Merge pull request #8265 from nupplaphil/task/add_license
[friendica.git/.git] / mod / wall_upload.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
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  * Module for uploading a picture to the profile wall
21  *
22  * By default the picture will be stored in the photo album with the name Wall Photos.
23  * You can specify a different album by adding an optional query string "album="
24  * to the url
25  *
26  */
27
28 use Friendica\App;
29 use Friendica\Core\Logger;
30 use Friendica\Core\Session;
31 use Friendica\Database\DBA;
32 use Friendica\DI;
33 use Friendica\Model\Photo;
34 use Friendica\Model\User;
35 use Friendica\Object\Image;
36 use Friendica\Util\Images;
37 use Friendica\Util\Strings;
38
39 function wall_upload_post(App $a, $desktopmode = true)
40 {
41         Logger::log("wall upload: starting new upload", Logger::DEBUG);
42
43         $r_json = (!empty($_GET['response']) && $_GET['response'] == 'json');
44         $album = (!empty($_GET['album']) ? Strings::escapeTags(trim($_GET['album'])) : '');
45
46         if ($a->argc > 1) {
47                 if (empty($_FILES['media'])) {
48                         $nick = $a->argv[1];
49                         $r = q("SELECT `user`.*, `contact`.`id` FROM `user`
50                                 INNER JOIN `contact` on `user`.`uid` = `contact`.`uid`
51                                 WHERE `user`.`nickname` = '%s' AND `user`.`blocked` = 0
52                                 AND `contact`.`self` = 1 LIMIT 1",
53                                 DBA::escape($nick)
54                         );
55
56                         if (!DBA::isResult($r)) {
57                                 if ($r_json) {
58                                         echo json_encode(['error' => DI::l10n()->t('Invalid request.')]);
59                                         exit();
60                                 }
61                                 return;
62                         }
63                 } else {
64                         $user_info = api_get_user($a);
65                         $r = q("SELECT `user`.*, `contact`.`id` FROM `user`
66                                 INNER JOIN `contact` on `user`.`uid` = `contact`.`uid`
67                                 WHERE `user`.`nickname` = '%s' AND `user`.`blocked` = 0
68                                 AND `contact`.`self` = 1 LIMIT 1",
69                                 DBA::escape($user_info['screen_name'])
70                         );
71                 }
72         } else {
73                 if ($r_json) {
74                         echo json_encode(['error' => DI::l10n()->t('Invalid request.')]);
75                         exit();
76                 }
77                 return;
78         }
79
80         /*
81          * Setup permissions structures
82          */
83         $can_post  = false;
84         $visitor   = 0;
85
86         $page_owner_uid   = $r[0]['uid'];
87         $default_cid      = $r[0]['id'];
88         $page_owner_nick  = $r[0]['nickname'];
89         $community_page   = (($r[0]['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? true : false);
90
91         if ((local_user()) && (local_user() == $page_owner_uid)) {
92                 $can_post = true;
93         } elseif ($community_page && !empty(Session::getRemoteContactID($page_owner_uid))) {
94                 $contact_id = Session::getRemoteContactID($page_owner_uid);
95
96                 $r = q("SELECT `uid` FROM `contact`
97                         WHERE `blocked` = 0 AND `pending` = 0
98                         AND `id` = %d AND `uid` = %d LIMIT 1",
99                         intval($contact_id),
100                         intval($page_owner_uid)
101                 );
102                 if (DBA::isResult($r)) {
103                         $can_post = true;
104                         $visitor = $contact_id;
105                 }
106         }
107
108         if (!$can_post) {
109                 if ($r_json) {
110                         echo json_encode(['error' => DI::l10n()->t('Permission denied.')]);
111                         exit();
112                 }
113                 notice(DI::l10n()->t('Permission denied.') . EOL);
114                 exit();
115         }
116
117         if (empty($_FILES['userfile']) && empty($_FILES['media'])) {
118                 if ($r_json) {
119                         echo json_encode(['error' => DI::l10n()->t('Invalid request.')]);
120                 }
121                 exit();
122         }
123
124         $src = '';
125         $filename = '';
126         $filesize = 0;
127         $filetype = '';
128         if (!empty($_FILES['userfile'])) {
129                 $src      = $_FILES['userfile']['tmp_name'];
130                 $filename = basename($_FILES['userfile']['name']);
131                 $filesize = intval($_FILES['userfile']['size']);
132                 $filetype = $_FILES['userfile']['type'];
133
134         } elseif (!empty($_FILES['media'])) {
135                 if (!empty($_FILES['media']['tmp_name'])) {
136                         if (is_array($_FILES['media']['tmp_name'])) {
137                                 $src = $_FILES['media']['tmp_name'][0];
138                         } else {
139                                 $src = $_FILES['media']['tmp_name'];
140                         }
141                 }
142
143                 if (!empty($_FILES['media']['name'])) {
144                         if (is_array($_FILES['media']['name'])) {
145                                 $filename = basename($_FILES['media']['name'][0]);
146                         } else {
147                                 $filename = basename($_FILES['media']['name']);
148                         }
149                 }
150
151                 if (!empty($_FILES['media']['size'])) {
152                         if (is_array($_FILES['media']['size'])) {
153                                 $filesize = intval($_FILES['media']['size'][0]);
154                         } else {
155                                 $filesize = intval($_FILES['media']['size']);
156                         }
157                 }
158
159                 if (!empty($_FILES['media']['type'])) {
160                         if (is_array($_FILES['media']['type'])) {
161                                 $filetype = $_FILES['media']['type'][0];
162                         } else {
163                                 $filetype = $_FILES['media']['type'];
164                         }
165                 }
166         }
167
168         if ($src == "") {
169                 if ($r_json) {
170                         echo json_encode(['error' => DI::l10n()->t('Invalid request.')]);
171                         exit();
172                 }
173                 notice(DI::l10n()->t('Invalid request.').EOL);
174                 exit();
175         }
176
177         // This is a special treatment for picture upload from Twidere
178         if (($filename == "octet-stream") && ($filetype != "")) {
179                 $filename = $filetype;
180                 $filetype = "";
181         }
182
183         if ($filetype == "") {
184                 $filetype = Images::guessType($filename);
185         }
186
187         // If there is a temp name, then do a manual check
188         // This is more reliable than the provided value
189
190         $imagedata = getimagesize($src);
191         if ($imagedata) {
192                 $filetype = $imagedata['mime'];
193         }
194
195         Logger::log("File upload src: " . $src . " - filename: " . $filename .
196                 " - size: " . $filesize . " - type: " . $filetype, Logger::DEBUG);
197
198         $maximagesize = DI::config()->get('system', 'maximagesize');
199
200         if (($maximagesize) && ($filesize > $maximagesize)) {
201                 $msg = DI::l10n()->t('Image exceeds size limit of %s', Strings::formatBytes($maximagesize));
202                 if ($r_json) {
203                         echo json_encode(['error' => $msg]);
204                 } else {
205                         echo  $msg. EOL;
206                 }
207                 @unlink($src);
208                 exit();
209         }
210
211         $imagedata = @file_get_contents($src);
212         $Image = new Image($imagedata, $filetype);
213
214         if (!$Image->isValid()) {
215                 $msg = DI::l10n()->t('Unable to process image.');
216                 if ($r_json) {
217                         echo json_encode(['error' => $msg]);
218                 } else {
219                         echo  $msg. EOL;
220                 }
221                 @unlink($src);
222                 exit();
223         }
224
225         $Image->orient($src);
226         @unlink($src);
227
228         $max_length = DI::config()->get('system', 'max_image_length');
229         if (!$max_length) {
230                 $max_length = MAX_IMAGE_LENGTH;
231         }
232         if ($max_length > 0) {
233                 $Image->scaleDown($max_length);
234                 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
235         }
236
237         $width = $Image->getWidth();
238         $height = $Image->getHeight();
239
240         $resource_id = Photo::newResource();
241
242         $smallest = 0;
243
244         // If we don't have an album name use the Wall Photos album
245         if (!strlen($album)) {
246                 $album = DI::l10n()->t('Wall Photos');
247         }
248
249         $defperm = '<' . $default_cid . '>';
250
251         $r = Photo::store($Image, $page_owner_uid, $visitor, $resource_id, $filename, $album, 0, 0, $defperm);
252
253         if (!$r) {
254                 $msg = DI::l10n()->t('Image upload failed.');
255                 if ($r_json) {
256                         echo json_encode(['error' => $msg]);
257                 } else {
258                         echo  $msg. EOL;
259                 }
260                 exit();
261         }
262
263         if ($width > 640 || $height > 640) {
264                 $Image->scaleDown(640);
265                 $r = Photo::store($Image, $page_owner_uid, $visitor, $resource_id, $filename, $album, 1, 0, $defperm);
266                 if ($r) {
267                         $smallest = 1;
268                 }
269         }
270
271         if ($width > 320 || $height > 320) {
272                 $Image->scaleDown(320);
273                 $r = Photo::store($Image, $page_owner_uid, $visitor, $resource_id, $filename, $album, 2, 0, $defperm);
274                 if ($r && ($smallest == 0)) {
275                         $smallest = 2;
276                 }
277         }
278
279         if (!$desktopmode) {
280                 $r = q("SELECT `id`, `datasize`, `width`, `height`, `type` FROM `photo`
281                         WHERE `resource-id` = '%s'
282                         ORDER BY `width` DESC LIMIT 1",
283                         $resource_id
284                 );
285                 if (!$r) {
286                         if ($r_json) {
287                                 echo json_encode(['error' => '']);
288                                 exit();
289                         }
290                         return false;
291                 }
292                 $picture = [];
293
294                 $picture["id"]        = $r[0]["id"];
295                 $picture["size"]      = $r[0]["datasize"];
296                 $picture["width"]     = $r[0]["width"];
297                 $picture["height"]    = $r[0]["height"];
298                 $picture["type"]      = $r[0]["type"];
299                 $picture["albumpage"] = DI::baseUrl() . '/photos/' . $page_owner_nick . '/image/' . $resource_id;
300                 $picture["picture"]   = DI::baseUrl() . "/photo/{$resource_id}-0." . $Image->getExt();
301                 $picture["preview"]   = DI::baseUrl() . "/photo/{$resource_id}-{$smallest}." . $Image->getExt();
302
303                 if ($r_json) {
304                         echo json_encode(['picture' => $picture]);
305                         exit();
306                 }
307                 Logger::log("upload done", Logger::DEBUG);
308                 return $picture;
309         }
310
311         Logger::log("upload done", Logger::DEBUG);
312
313         if ($r_json) {
314                 echo json_encode(['ok' => true]);
315                 exit();
316         }
317
318         echo  "\n\n" . '[url=' . DI::baseUrl() . '/photos/' . $page_owner_nick . '/image/' . $resource_id . '][img]' . DI::baseUrl() . "/photo/{$resource_id}-{$smallest}.".$Image->getExt()."[/img][/url]\n\n";
319         exit();
320         // NOTREACHED
321 }