]> git.mxchange.org Git - friendica.git/blob - include/api.php
ET translation updated THX Rain Hawk
[friendica.git] / include / api.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  * Friendica implementation of statusnet/twitter API
21  *
22  * @file include/api.php
23  * @todo Automatically detect if incoming data is HTML or BBCode
24  */
25
26 use Friendica\App;
27 use Friendica\Content\Text\BBCode;
28 use Friendica\Content\Text\HTML;
29 use Friendica\Core\Logger;
30 use Friendica\Core\System;
31 use Friendica\Database\DBA;
32 use Friendica\DI;
33 use Friendica\Model\Contact;
34 use Friendica\Model\Group;
35 use Friendica\Model\Item;
36 use Friendica\Model\Mail;
37 use Friendica\Model\Photo;
38 use Friendica\Model\Post;
39 use Friendica\Model\Profile;
40 use Friendica\Module\BaseApi;
41 use Friendica\Network\HTTPException;
42 use Friendica\Network\HTTPException\BadRequestException;
43 use Friendica\Network\HTTPException\ForbiddenException;
44 use Friendica\Network\HTTPException\InternalServerErrorException;
45 use Friendica\Network\HTTPException\NotFoundException;
46 use Friendica\Network\HTTPException\UnauthorizedException;
47 use Friendica\Object\Image;
48 use Friendica\Util\DateTimeFormat;
49 use Friendica\Util\Images;
50 use Friendica\Util\Strings;
51
52 $API = [];
53
54 /**
55  * Register a function to be the endpoint for defined API path.
56  *
57  * @param string $path   API URL path, relative to DI::baseUrl()
58  * @param string $func   Function name to call on path request
59  */
60 function api_register_func($path, $func)
61 {
62         global $API;
63
64         $API[$path] = [
65                 'func'   => $func,
66         ];
67
68         // Workaround for hotot
69         $path = str_replace("api/", "api/1.1/", $path);
70
71         $API[$path] = [
72                 'func'   => $func,
73         ];
74 }
75
76 /**
77  * Main API entry point
78  *
79  * Authenticate user, call registered API function, set HTTP headers
80  *
81  * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
82  * @return string|array API call result
83  * @throws Exception
84  */
85 function api_call($command, $extension)
86 {
87         global $API;
88
89         Logger::info('Legacy API call', ['command' => $command, 'extension' => $extension]);
90
91         try {
92                 foreach ($API as $p => $info) {
93                         if (strpos($command, $p) === 0) {
94                                 Logger::debug(BaseApi::LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
95
96                                 $stamp =  microtime(true);
97                                 $return = call_user_func($info['func'], $extension);
98                                 $duration = floatval(microtime(true) - $stamp);
99
100                                 Logger::info(BaseApi::LOG_PREFIX . 'duration {duration}', ['module' => 'api', 'action' => 'call', 'duration' => round($duration, 2)]);
101
102                                 DI::profiler()->saveLog(DI::logger(), BaseApi::LOG_PREFIX . 'performance');
103
104                                 if (false === $return) {
105                                         /*
106                                                 * api function returned false withour throw an
107                                                 * exception. This should not happend, throw a 500
108                                                 */
109                                         throw new InternalServerErrorException();
110                                 }
111
112                                 switch ($extension) {
113                                         case "xml":
114                                                 header("Content-Type: text/xml");
115                                                 break;
116                                         case "json":
117                                                 header("Content-Type: application/json");
118                                                 if (!empty($return)) {
119                                                         $json = json_encode(end($return));
120                                                         if (!empty($_GET['callback'])) {
121                                                                 $json = $_GET['callback'] . "(" . $json . ")";
122                                                         }
123                                                         $return = $json;
124                                                 }
125                                                 break;
126                                         case "rss":
127                                                 header("Content-Type: application/rss+xml");
128                                                 $return  = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
129                                                 break;
130                                         case "atom":
131                                                 header("Content-Type: application/atom+xml");
132                                                 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
133                                                 break;
134                                 }
135                                 return $return;
136                         }
137                 }
138
139                 Logger::warning(BaseApi::LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
140                 throw new NotFoundException();
141         } catch (HTTPException $e) {
142                 Logger::notice(BaseApi::LOG_PREFIX . 'got exception', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString(), 'error' => $e]);
143                 DI::apiResponse()->error($e->getCode(), $e->getDescription(), $e->getMessage(), $extension);
144         }
145 }
146
147 /**
148  *
149  * @param array $item
150  * @param array $recipient
151  * @param array $sender
152  *
153  * @return array
154  * @throws InternalServerErrorException
155  */
156 function api_format_messages($item, $recipient, $sender)
157 {
158         // standard meta information
159         $ret = [
160                 'id'                    => $item['id'],
161                 'sender_id'             => $sender['id'],
162                 'text'                  => "",
163                 'recipient_id'          => $recipient['id'],
164                 'created_at'            => DateTimeFormat::utc($item['created'] ?? 'now', DateTimeFormat::API),
165                 'sender_screen_name'    => $sender['screen_name'],
166                 'recipient_screen_name' => $recipient['screen_name'],
167                 'sender'                => $sender,
168                 'recipient'             => $recipient,
169                 'title'                 => "",
170                 'friendica_seen'        => $item['seen'] ?? 0,
171                 'friendica_parent_uri'  => $item['parent-uri'] ?? '',
172         ];
173
174         // "uid" is only needed for some internal stuff, so remove it from here
175         if (isset($ret['sender']['uid'])) {
176                 unset($ret['sender']['uid']);
177         }
178         if (isset($ret['recipient']['uid'])) {
179                 unset($ret['recipient']['uid']);
180         }
181
182         //don't send title to regular StatusNET requests to avoid confusing these apps
183         if (!empty($_GET['getText'])) {
184                 $ret['title'] = $item['title'];
185                 if ($_GET['getText'] == 'html') {
186                         $ret['text'] = BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::API);
187                 } elseif ($_GET['getText'] == 'plain') {
188                         $ret['text'] = trim(HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0));
189                 }
190         } else {
191                 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0);
192         }
193         if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
194                 unset($ret['sender']);
195                 unset($ret['recipient']);
196         }
197
198         return $ret;
199 }
200
201 /**
202  *
203  * @param string $acl_string
204  * @param int    $uid
205  * @return bool
206  * @throws Exception
207  */
208 function check_acl_input($acl_string, $uid)
209 {
210         if (empty($acl_string)) {
211                 return false;
212         }
213
214         $contact_not_found = false;
215
216         // split <x><y><z> into array of cid's
217         preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
218
219         // check for each cid if it is available on server
220         $cid_array = $array[0];
221         foreach ($cid_array as $cid) {
222                 $cid = str_replace("<", "", $cid);
223                 $cid = str_replace(">", "", $cid);
224                 $condition = ['id' => $cid, 'uid' => $uid];
225                 $contact_not_found |= !DBA::exists('contact', $condition);
226         }
227         return $contact_not_found;
228 }
229
230 /**
231  * @param string  $mediatype
232  * @param array   $media
233  * @param string  $type
234  * @param string  $album
235  * @param string  $allow_cid
236  * @param string  $deny_cid
237  * @param string  $allow_gid
238  * @param string  $deny_gid
239  * @param string  $desc
240  * @param integer $phototype
241  * @param boolean $visibility
242  * @param string  $photo_id
243  * @param int     $uid
244  * @return array
245  * @throws BadRequestException
246  * @throws ForbiddenException
247  * @throws ImagickException
248  * @throws InternalServerErrorException
249  * @throws NotFoundException
250  * @throws UnauthorizedException
251  */
252 function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, $phototype, $visibility, $photo_id, $uid)
253 {
254         $visitor   = 0;
255         $src = "";
256         $filetype = "";
257         $filename = "";
258         $filesize = 0;
259
260         if (is_array($media)) {
261                 if (is_array($media['tmp_name'])) {
262                         $src = $media['tmp_name'][0];
263                 } else {
264                         $src = $media['tmp_name'];
265                 }
266                 if (is_array($media['name'])) {
267                         $filename = basename($media['name'][0]);
268                 } else {
269                         $filename = basename($media['name']);
270                 }
271                 if (is_array($media['size'])) {
272                         $filesize = intval($media['size'][0]);
273                 } else {
274                         $filesize = intval($media['size']);
275                 }
276                 if (is_array($media['type'])) {
277                         $filetype = $media['type'][0];
278                 } else {
279                         $filetype = $media['type'];
280                 }
281         }
282
283         $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
284
285         logger::info(
286                 "File upload src: " . $src . " - filename: " . $filename .
287                 " - size: " . $filesize . " - type: " . $filetype);
288
289         // check if there was a php upload error
290         if ($filesize == 0 && $media['error'] == 1) {
291                 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
292         }
293         // check against max upload size within Friendica instance
294         $maximagesize = DI::config()->get('system', 'maximagesize');
295         if ($maximagesize && ($filesize > $maximagesize)) {
296                 $formattedBytes = Strings::formatBytes($maximagesize);
297                 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
298         }
299
300         // create Photo instance with the data of the image
301         $imagedata = @file_get_contents($src);
302         $Image = new Image($imagedata, $filetype);
303         if (!$Image->isValid()) {
304                 throw new InternalServerErrorException("unable to process image data");
305         }
306
307         // check orientation of image
308         $Image->orient($src);
309         @unlink($src);
310
311         // check max length of images on server
312         $max_length = DI::config()->get('system', 'max_image_length');
313         if ($max_length > 0) {
314                 $Image->scaleDown($max_length);
315                 logger::info("File upload: Scaling picture to new size " . $max_length);
316         }
317         $width = $Image->getWidth();
318         $height = $Image->getHeight();
319
320         // create a new resource-id if not already provided
321         $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
322
323         if ($mediatype == "photo") {
324                 // upload normal image (scales 0, 1, 2)
325                 logger::info("photo upload: starting new photo upload");
326
327                 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
328                 if (!$r) {
329                         logger::notice("photo upload: image upload with scale 0 (original size) failed");
330                 }
331                 if ($width > 640 || $height > 640) {
332                         $Image->scaleDown(640);
333                         $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
334                         if (!$r) {
335                                 logger::notice("photo upload: image upload with scale 1 (640x640) failed");
336                         }
337                 }
338
339                 if ($width > 320 || $height > 320) {
340                         $Image->scaleDown(320);
341                         $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
342                         if (!$r) {
343                                 logger::notice("photo upload: image upload with scale 2 (320x320) failed");
344                         }
345                 }
346                 logger::info("photo upload: new photo upload ended");
347         } elseif ($mediatype == "profileimage") {
348                 // upload profile image (scales 4, 5, 6)
349                 logger::info("photo upload: starting new profile image upload");
350
351                 if ($width > 300 || $height > 300) {
352                         $Image->scaleDown(300);
353                         $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 4, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
354                         if (!$r) {
355                                 logger::notice("photo upload: profile image upload with scale 4 (300x300) failed");
356                         }
357                 }
358
359                 if ($width > 80 || $height > 80) {
360                         $Image->scaleDown(80);
361                         $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 5, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
362                         if (!$r) {
363                                 logger::notice("photo upload: profile image upload with scale 5 (80x80) failed");
364                         }
365                 }
366
367                 if ($width > 48 || $height > 48) {
368                         $Image->scaleDown(48);
369                         $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 6, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
370                         if (!$r) {
371                                 logger::notice("photo upload: profile image upload with scale 6 (48x48) failed");
372                         }
373                 }
374                 $Image->__destruct();
375                 logger::info("photo upload: new profile image upload ended");
376         }
377
378         if (!empty($r)) {
379                 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
380                 if ($photo_id == null && $mediatype == "photo") {
381                         post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility, $uid);
382                 }
383                 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
384                 return prepare_photo_data($type, false, $resource_id, $uid);
385         } else {
386                 throw new InternalServerErrorException("image upload failed");
387                 DI::page()->exit(DI::apiResponse());
388         }
389 }
390
391 /**
392  *
393  * @param string  $hash
394  * @param string  $allow_cid
395  * @param string  $deny_cid
396  * @param string  $allow_gid
397  * @param string  $deny_gid
398  * @param string  $filetype
399  * @param boolean $visibility
400  * @param int     $uid
401  * @throws InternalServerErrorException
402  */
403 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility, $uid)
404 {
405         // get data about the api authenticated user
406         $uri = Item::newURI(intval($uid));
407         $owner_record = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
408
409         $arr = [];
410         $arr['guid']          = System::createUUID();
411         $arr['uid']           = $uid;
412         $arr['uri']           = $uri;
413         $arr['post-type']     = Item::PT_IMAGE;
414         $arr['wall']          = 1;
415         $arr['resource-id']   = $hash;
416         $arr['contact-id']    = $owner_record['id'];
417         $arr['owner-name']    = $owner_record['name'];
418         $arr['owner-link']    = $owner_record['url'];
419         $arr['owner-avatar']  = $owner_record['thumb'];
420         $arr['author-name']   = $owner_record['name'];
421         $arr['author-link']   = $owner_record['url'];
422         $arr['author-avatar'] = $owner_record['thumb'];
423         $arr['title']         = '';
424         $arr['allow_cid']     = $allow_cid;
425         $arr['allow_gid']     = $allow_gid;
426         $arr['deny_cid']      = $deny_cid;
427         $arr['deny_gid']      = $deny_gid;
428         $arr['visible']       = $visibility;
429         $arr['origin']        = 1;
430
431         $typetoext = Images::supportedTypes();
432
433         // adds link to the thumbnail scale photo
434         $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
435                                 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
436                                 . '[/url]';
437
438         // do the magic for storing the item in the database and trigger the federation to other contacts
439         Item::insert($arr);
440 }
441
442 /**
443  *
444  * @param string $type
445  * @param int    $scale
446  * @param string $photo_id
447  *
448  * @return array
449  * @throws BadRequestException
450  * @throws ForbiddenException
451  * @throws ImagickException
452  * @throws InternalServerErrorException
453  * @throws NotFoundException
454  * @throws UnauthorizedException
455  */
456 function prepare_photo_data($type, $scale, $photo_id, $uid)
457 {
458         $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
459         $data_sql = ($scale === false ? "" : "data, ");
460
461         // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
462         // clients needs to convert this in their way for further processing
463         $r = DBA::toArray(DBA::p(
464                 "SELECT $data_sql `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
465                                         `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
466                                         MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
467                         FROM `photo` WHERE `uid` = ? AND `resource-id` = ? $scale_sql GROUP BY
468                                    `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
469                                    `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
470                 $uid,
471                 $photo_id
472         ));
473
474         $typetoext = [
475                 'image/jpeg' => 'jpg',
476                 'image/png' => 'png',
477                 'image/gif' => 'gif'
478         ];
479
480         // prepare output data for photo
481         if (DBA::isResult($r)) {
482                 $data = ['photo' => $r[0]];
483                 $data['photo']['id'] = $data['photo']['resource-id'];
484                 if ($scale !== false) {
485                         $data['photo']['data'] = base64_encode($data['photo']['data']);
486                 } else {
487                         unset($data['photo']['datasize']); //needed only with scale param
488                 }
489                 if ($type == "xml") {
490                         $data['photo']['links'] = [];
491                         for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
492                                 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
493                                                                                 "scale" => $k,
494                                                                                 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
495                         }
496                 } else {
497                         $data['photo']['link'] = [];
498                         // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
499                         $i = 0;
500                         for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
501                                 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
502                                 $i++;
503                         }
504                 }
505                 unset($data['photo']['resource-id']);
506                 unset($data['photo']['minscale']);
507                 unset($data['photo']['maxscale']);
508         } else {
509                 throw new NotFoundException();
510         }
511
512         // retrieve item element for getting activities (like, dislike etc.) related to photo
513         $condition = ['uid' => $uid, 'resource-id' => $photo_id];
514         $item = Post::selectFirst(['id', 'uid', 'uri', 'uri-id', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
515         if (!DBA::isResult($item)) {
516                 throw new NotFoundException('Photo-related item not found.');
517         }
518
519         $data['photo']['friendica_activities'] = DI::friendicaActivities()->createFromUriId($item['uri-id'], $item['uid'], $type);
520
521         // retrieve comments on photo
522         $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
523                 $item['parent'], $uid, GRAVITY_PARENT, GRAVITY_COMMENT];
524
525         $statuses = Post::selectForUser($uid, [], $condition);
526
527         // prepare output of comments
528         $commentData = [];
529         while ($status = DBA::fetch($statuses)) {
530                 $commentData[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'])->toArray();
531         }
532         DBA::close($statuses);
533
534         $comments = [];
535         if ($type == "xml") {
536                 $k = 0;
537                 foreach ($commentData as $comment) {
538                         $comments[$k++ . ":comment"] = $comment;
539                 }
540         } else {
541                 foreach ($commentData as $comment) {
542                         $comments[] = $comment;
543                 }
544         }
545         $data['photo']['friendica_comments'] = $comments;
546
547         // include info if rights on photo and rights on item are mismatching
548         $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
549                 $data['photo']['deny_cid'] != $item['deny_cid'] ||
550                 $data['photo']['allow_gid'] != $item['allow_gid'] ||
551                 $data['photo']['deny_gid'] != $item['deny_gid'];
552         $data['photo']['rights_mismatch'] = $rights_mismatch;
553
554         return $data;
555 }
556
557 /**
558  *
559  * @param string $text
560  *
561  * @return string
562  * @throws InternalServerErrorException
563  */
564 function api_clean_plain_items($text)
565 {
566         $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
567
568         $text = BBCode::cleanPictureLinks($text);
569         $URLSearchString = "^\[\]";
570
571         $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
572
573         if ($include_entities == "true") {
574                 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
575         }
576
577         // Simplify "attachment" element
578         $text = BBCode::removeAttachment($text);
579
580         return $text;
581 }
582
583 /**
584  * Add a new group to the database.
585  *
586  * @param  string $name  Group name
587  * @param  int    $uid   User ID
588  * @param  array  $users List of users to add to the group
589  *
590  * @return array
591  * @throws BadRequestException
592  */
593 function group_create($name, $uid, $users = [])
594 {
595         // error if no name specified
596         if ($name == "") {
597                 throw new BadRequestException('group name not specified');
598         }
599
600         // error message if specified group name already exists
601         if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => false])) {
602                 throw new BadRequestException('group name already exists');
603         }
604
605         // Check if the group needs to be reactivated
606         if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => true])) {
607                 $reactivate_group = true;
608         }
609
610         // create group
611         $ret = Group::create($uid, $name);
612         if ($ret) {
613                 $gid = Group::getIdByName($uid, $name);
614         } else {
615                 throw new BadRequestException('other API error');
616         }
617
618         // add members
619         $erroraddinguser = false;
620         $errorusers = [];
621         foreach ($users as $user) {
622                 $cid = $user['cid'];
623                 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
624                         Group::addMember($gid, $cid);
625                 } else {
626                         $erroraddinguser = true;
627                         $errorusers[] = $cid;
628                 }
629         }
630
631         // return success message incl. missing users in array
632         $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
633
634         return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
635 }
636
637 /**
638  * TWITTER API
639  */
640
641 /**
642  * Returns all lists the user subscribes to.
643  *
644  * @param string $type Return type (atom, rss, xml, json)
645  *
646  * @return array|string
647  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
648  */
649 function api_lists_list($type)
650 {
651         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
652         $ret = [];
653         /// @TODO $ret is not filled here?
654         return DI::apiResponse()->formatData('lists', $type, ["lists_list" => $ret]);
655 }
656
657 api_register_func('api/lists/list', 'api_lists_list', true);
658 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
659
660 /**
661  * Returns all groups the user owns.
662  *
663  * @param string $type Return type (atom, rss, xml, json)
664  *
665  * @return array|string
666  * @throws BadRequestException
667  * @throws ForbiddenException
668  * @throws ImagickException
669  * @throws InternalServerErrorException
670  * @throws UnauthorizedException
671  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
672  */
673 function api_lists_ownerships($type)
674 {
675         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
676         $uid = BaseApi::getCurrentUserID();
677
678         // params
679         $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
680
681         $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
682
683         // loop through all groups
684         $lists = [];
685         foreach ($groups as $group) {
686                 if ($group['visible']) {
687                         $mode = 'public';
688                 } else {
689                         $mode = 'private';
690                 }
691                 $lists[] = [
692                         'name' => $group['name'],
693                         'id' => intval($group['id']),
694                         'id_str' => (string) $group['id'],
695                         'user' => $user_info,
696                         'mode' => $mode
697                 ];
698         }
699         return DI::apiResponse()->formatData("lists", $type, ['lists' => ['lists' => $lists]]);
700 }
701
702 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
703
704 /**
705  * Sends a new direct message.
706  *
707  * @param string $type Return type (atom, rss, xml, json)
708  *
709  * @return array|string
710  * @throws BadRequestException
711  * @throws ForbiddenException
712  * @throws ImagickException
713  * @throws InternalServerErrorException
714  * @throws NotFoundException
715  * @throws UnauthorizedException
716  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
717  */
718 function api_direct_messages_new($type)
719 {
720         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
721         $uid = BaseApi::getCurrentUserID();
722
723         if (empty($_POST["text"]) || empty($_REQUEST['screen_name']) && empty($_REQUEST['user_id'])) {
724                 return;
725         }
726
727         $sender = DI::twitterUser()->createFromUserId($uid, true)->toArray();
728
729         $cid = BaseApi::getContactIDForSearchterm($_REQUEST['screen_name'] ?? '', $_REQUEST['profileurl'] ?? '', $_REQUEST['user_id'] ?? 0, 0);
730         if (empty($cid)) {
731                 throw new NotFoundException('Recipient not found');
732         }
733
734         $replyto = '';
735         if (!empty($_REQUEST['replyto'])) {
736                 $mail    = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => $uid, 'id' => $_REQUEST['replyto']]);
737                 $replyto = $mail['parent-uri'];
738                 $sub     = $mail['title'];
739         } else {
740                 if (!empty($_REQUEST['title'])) {
741                         $sub = $_REQUEST['title'];
742                 } else {
743                         $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
744                 }
745         }
746
747         $cdata = Contact::getPublicAndUserContactID($cid, $uid);
748
749         $id = Mail::send($cdata['user'], $_POST['text'], $sub, $replyto);
750
751         if ($id > -1) {
752                 $mail = DBA::selectFirst('mail', [], ['id' => $id]);
753                 $ret = api_format_messages($mail, DI::twitterUser()->createFromContactId($cid, $uid, true)->toArray(), $sender);
754         } else {
755                 $ret = ["error" => $id];
756         }
757
758         return DI::apiResponse()->formatData("direct-messages", $type, ['direct_message' => $ret], Contact::getPublicIdByUserId($uid));
759 }
760
761 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true);
762
763 /**
764  * delete a direct_message from mail table through api
765  *
766  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
767  * @return string|array
768  * @throws BadRequestException
769  * @throws ForbiddenException
770  * @throws ImagickException
771  * @throws InternalServerErrorException
772  * @throws UnauthorizedException
773  * @see   https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
774  */
775 function api_direct_messages_destroy($type)
776 {
777         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
778         $uid = BaseApi::getCurrentUserID();
779
780         //required
781         $id = $_REQUEST['id'] ?? 0;
782         // optional
783         $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
784         $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
785         /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
786
787         // error if no id or parenturi specified (for clients posting parent-uri as well)
788         if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
789                 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
790                 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
791         }
792
793         // BadRequestException if no id specified (for clients using Twitter API)
794         if ($id == 0) {
795                 throw new BadRequestException('Message id not specified');
796         }
797
798         // add parent-uri to sql command if specified by calling app
799         $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
800
801         // error message if specified id is not in database
802         if (!DBA::exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) {
803                 if ($verbose == "true") {
804                         $answer = ['result' => 'error', 'message' => 'message id not in database'];
805                         return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
806                 }
807                 /// @todo BadRequestException ok for Twitter API clients?
808                 throw new BadRequestException('message id not in database');
809         }
810
811         // delete message
812         $result = DBA::delete('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id]);
813
814         if ($verbose == "true") {
815                 if ($result) {
816                         // return success
817                         $answer = ['result' => 'ok', 'message' => 'message deleted'];
818                         return DI::apiResponse()->formatData("direct_message_delete", $type, ['$result' => $answer]);
819                 } else {
820                         $answer = ['result' => 'error', 'message' => 'unknown error'];
821                         return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
822                 }
823         }
824         /// @todo return JSON data like Twitter API not yet implemented
825 }
826
827 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true);
828
829 /**
830  *
831  * @param string $type Return type (atom, rss, xml, json)
832  * @param string $box
833  * @param string $verbose
834  *
835  * @return array|string
836  * @throws BadRequestException
837  * @throws ForbiddenException
838  * @throws ImagickException
839  * @throws InternalServerErrorException
840  * @throws UnauthorizedException
841  */
842 function api_direct_messages_box($type, $box, $verbose)
843 {
844         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
845         $uid = BaseApi::getCurrentUserID();
846
847         // params
848         $count = $_GET['count'] ?? 20;
849         $page = $_REQUEST['page'] ?? 1;
850
851         $since_id = $_REQUEST['since_id'] ?? 0;
852         $max_id = $_REQUEST['max_id'] ?? 0;
853
854         $user_id = $_REQUEST['user_id'] ?? '';
855         $screen_name = $_REQUEST['screen_name'] ?? '';
856
857         $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
858
859         $profile_url = $user_info["url"];
860
861         // pagination
862         $start = max(0, ($page - 1) * $count);
863
864         $sql_extra = "";
865
866         // filters
867         if ($box=="sentbox") {
868                 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
869         } elseif ($box == "conversation") {
870                 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '')  . "'";
871         } elseif ($box == "all") {
872                 $sql_extra = "true";
873         } elseif ($box == "inbox") {
874                 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
875         }
876
877         if ($max_id > 0) {
878                 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
879         }
880
881         if ($user_id != "") {
882                 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
883         } elseif ($screen_name !="") {
884                 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
885         }
886
887         $r = DBA::toArray(DBA::p(
888                 "SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid` = ? AND $sql_extra AND `mail`.`id` > ? ORDER BY `mail`.`id` DESC LIMIT ?,?",
889                 $uid,
890                 $since_id,
891                 $start,
892                 $count
893         ));
894         if ($verbose == "true" && !DBA::isResult($r)) {
895                 $answer = ['result' => 'error', 'message' => 'no mails available'];
896                 return DI::apiResponse()->formatData("direct_messages_all", $type, ['$result' => $answer]);
897         }
898
899         $ret = [];
900         foreach ($r as $item) {
901                 if ($box == "inbox" || $item['from-url'] != $profile_url) {
902                         $recipient = $user_info;
903                         $sender = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
904                 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
905                         $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
906                         $sender = $user_info;
907                 }
908
909                 if (isset($recipient) && isset($sender)) {
910                         $ret[] = api_format_messages($item, $recipient, $sender);
911                 }
912         }
913
914         return DI::apiResponse()->formatData("direct-messages", $type, ['direct_message' => $ret], Contact::getPublicIdByUserId($uid));
915 }
916
917 /**
918  * Returns the most recent direct messages sent by the user.
919  *
920  * @param string $type Return type (atom, rss, xml, json)
921  *
922  * @return array|string
923  * @throws BadRequestException
924  * @throws ForbiddenException
925  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
926  */
927 function api_direct_messages_sentbox($type)
928 {
929         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
930         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
931         return api_direct_messages_box($type, "sentbox", $verbose);
932 }
933
934 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
935
936 /**
937  * Returns the most recent direct messages sent to the user.
938  *
939  * @param string $type Return type (atom, rss, xml, json)
940  *
941  * @return array|string
942  * @throws BadRequestException
943  * @throws ForbiddenException
944  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
945  */
946 function api_direct_messages_inbox($type)
947 {
948         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
949         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
950         return api_direct_messages_box($type, "inbox", $verbose);
951 }
952
953 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
954
955 /**
956  *
957  * @param string $type Return type (atom, rss, xml, json)
958  *
959  * @return array|string
960  * @throws BadRequestException
961  * @throws ForbiddenException
962  */
963 function api_direct_messages_all($type)
964 {
965         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
966         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
967         return api_direct_messages_box($type, "all", $verbose);
968 }
969
970 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
971
972 /**
973  *
974  * @param string $type Return type (atom, rss, xml, json)
975  *
976  * @return array|string
977  * @throws BadRequestException
978  * @throws ForbiddenException
979  */
980 function api_direct_messages_conversation($type)
981 {
982         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
983         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
984         return api_direct_messages_box($type, "conversation", $verbose);
985 }
986
987 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
988
989 /**
990  * list all photos of the authenticated user
991  *
992  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
993  * @return string|array
994  * @throws ForbiddenException
995  * @throws InternalServerErrorException
996  */
997 function api_fr_photos_list($type)
998 {
999         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1000         $uid = BaseApi::getCurrentUserID();
1001
1002         $r = DBA::toArray(DBA::p(
1003                 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
1004                 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
1005                 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
1006                 $uid, Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
1007         ));
1008         $typetoext = [
1009                 'image/jpeg' => 'jpg',
1010                 'image/png' => 'png',
1011                 'image/gif' => 'gif'
1012         ];
1013         $data = ['photo'=>[]];
1014         if (DBA::isResult($r)) {
1015                 foreach ($r as $rr) {
1016                         $photo = [];
1017                         $photo['id'] = $rr['resource-id'];
1018                         $photo['album'] = $rr['album'];
1019                         $photo['filename'] = $rr['filename'];
1020                         $photo['type'] = $rr['type'];
1021                         $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
1022                         $photo['created'] = $rr['created'];
1023                         $photo['edited'] = $rr['edited'];
1024                         $photo['desc'] = $rr['desc'];
1025
1026                         if ($type == "xml") {
1027                                 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
1028                         } else {
1029                                 $photo['thumb'] = $thumb;
1030                                 $data['photo'][] = $photo;
1031                         }
1032                 }
1033         }
1034         return DI::apiResponse()->formatData("photos", $type, $data);
1035 }
1036
1037 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
1038
1039 /**
1040  * upload a new photo or change an existing photo
1041  *
1042  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1043  * @return string|array
1044  * @throws BadRequestException
1045  * @throws ForbiddenException
1046  * @throws ImagickException
1047  * @throws InternalServerErrorException
1048  * @throws NotFoundException
1049  */
1050 function api_fr_photo_create_update($type)
1051 {
1052         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1053         $uid = BaseApi::getCurrentUserID();
1054
1055         // input params
1056         $photo_id  = $_REQUEST['photo_id']  ?? null;
1057         $desc      = $_REQUEST['desc']      ?? null;
1058         $album     = $_REQUEST['album']     ?? null;
1059         $album_new = $_REQUEST['album_new'] ?? null;
1060         $allow_cid = $_REQUEST['allow_cid'] ?? null;
1061         $deny_cid  = $_REQUEST['deny_cid' ] ?? null;
1062         $allow_gid = $_REQUEST['allow_gid'] ?? null;
1063         $deny_gid  = $_REQUEST['deny_gid' ] ?? null;
1064         // Pictures uploaded via API never get posted as a visible status
1065         // See https://github.com/friendica/friendica/issues/10990
1066         $visibility = false;
1067
1068         // do several checks on input parameters
1069         // we do not allow calls without album string
1070         if ($album == null) {
1071                 throw new BadRequestException("no albumname specified");
1072         }
1073         // if photo_id == null --> we are uploading a new photo
1074         if ($photo_id == null) {
1075                 $mode = "create";
1076
1077                 // error if no media posted in create-mode
1078                 if (empty($_FILES['media'])) {
1079                         // Output error
1080                         throw new BadRequestException("no media data submitted");
1081                 }
1082
1083                 // album_new will be ignored in create-mode
1084                 $album_new = "";
1085         } else {
1086                 $mode = "update";
1087
1088                 // check if photo is existing in databasei
1089                 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => $uid, 'album' => $album])) {
1090                         throw new BadRequestException("photo not available");
1091                 }
1092         }
1093
1094         // checks on acl strings provided by clients
1095         $acl_input_error = false;
1096         $acl_input_error |= check_acl_input($allow_cid, $uid);
1097         $acl_input_error |= check_acl_input($deny_cid, $uid);
1098         $acl_input_error |= check_acl_input($allow_gid, $uid);
1099         $acl_input_error |= check_acl_input($deny_gid, $uid);
1100         if ($acl_input_error) {
1101                 throw new BadRequestException("acl data invalid");
1102         }
1103         // now let's upload the new media in create-mode
1104         if ($mode == "create") {
1105                 $media = $_FILES['media'];
1106                 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, Photo::DEFAULT, $visibility, null, $uid);
1107
1108                 // return success of updating or error message
1109                 if (!is_null($data)) {
1110                         return DI::apiResponse()->formatData("photo_create", $type, $data);
1111                 } else {
1112                         throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
1113                 }
1114         }
1115
1116         // now let's do the changes in update-mode
1117         if ($mode == "update") {
1118                 $updated_fields = [];
1119
1120                 if (!is_null($desc)) {
1121                         $updated_fields['desc'] = $desc;
1122                 }
1123
1124                 if (!is_null($album_new)) {
1125                         $updated_fields['album'] = $album_new;
1126                 }
1127
1128                 if (!is_null($allow_cid)) {
1129                         $allow_cid = trim($allow_cid);
1130                         $updated_fields['allow_cid'] = $allow_cid;
1131                 }
1132
1133                 if (!is_null($deny_cid)) {
1134                         $deny_cid = trim($deny_cid);
1135                         $updated_fields['deny_cid'] = $deny_cid;
1136                 }
1137
1138                 if (!is_null($allow_gid)) {
1139                         $allow_gid = trim($allow_gid);
1140                         $updated_fields['allow_gid'] = $allow_gid;
1141                 }
1142
1143                 if (!is_null($deny_gid)) {
1144                         $deny_gid = trim($deny_gid);
1145                         $updated_fields['deny_gid'] = $deny_gid;
1146                 }
1147
1148                 $result = false;
1149                 if (count($updated_fields) > 0) {
1150                         $nothingtodo = false;
1151                         $result = Photo::update($updated_fields, ['uid' => $uid, 'resource-id' => $photo_id, 'album' => $album]);
1152                 } else {
1153                         $nothingtodo = true;
1154                 }
1155
1156                 if (!empty($_FILES['media'])) {
1157                         $nothingtodo = false;
1158                         $media = $_FILES['media'];
1159                         $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id, $uid);
1160                         if (!is_null($data)) {
1161                                 return DI::apiResponse()->formatData("photo_update", $type, $data);
1162                         }
1163                 }
1164
1165                 // return success of updating or error message
1166                 if ($result) {
1167                         $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
1168                         return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
1169                 } else {
1170                         if ($nothingtodo) {
1171                                 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
1172                                 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
1173                         }
1174                         throw new InternalServerErrorException("unknown error - update photo entry in database failed");
1175                 }
1176         }
1177         throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
1178 }
1179
1180 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true);
1181 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true);
1182
1183 /**
1184  * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
1185  *
1186  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1187  * @return string|array
1188  * @throws BadRequestException
1189  * @throws ForbiddenException
1190  * @throws InternalServerErrorException
1191  * @throws NotFoundException
1192  */
1193 function api_fr_photo_detail($type)
1194 {
1195         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1196         $uid = BaseApi::getCurrentUserID();
1197
1198         if (empty($_REQUEST['photo_id'])) {
1199                 throw new BadRequestException("No photo id.");
1200         }
1201
1202         $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
1203         $photo_id = $_REQUEST['photo_id'];
1204
1205         // prepare json/xml output with data from database for the requested photo
1206         $data = prepare_photo_data($type, $scale, $photo_id, $uid);
1207
1208         return DI::apiResponse()->formatData("photo_detail", $type, $data);
1209 }
1210
1211 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
1212
1213 /**
1214  * updates the profile image for the user (either a specified profile or the default profile)
1215  *
1216  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1217  *
1218  * @return string|array
1219  * @throws BadRequestException
1220  * @throws ForbiddenException
1221  * @throws ImagickException
1222  * @throws InternalServerErrorException
1223  * @throws NotFoundException
1224  * @see   https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
1225  */
1226 function api_account_update_profile_image($type)
1227 {
1228         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1229         $uid = BaseApi::getCurrentUserID();
1230
1231         // input params
1232         $profile_id = $_REQUEST['profile_id'] ?? 0;
1233
1234         // error if image data is missing
1235         if (empty($_FILES['image'])) {
1236                 throw new BadRequestException("no media data submitted");
1237         }
1238
1239         // check if specified profile id is valid
1240         if ($profile_id != 0) {
1241                 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => $uid, 'id' => $profile_id]);
1242                 // error message if specified profile id is not in database
1243                 if (!DBA::isResult($profile)) {
1244                         throw new BadRequestException("profile_id not available");
1245                 }
1246                 $is_default_profile = $profile['is-default'];
1247         } else {
1248                 $is_default_profile = 1;
1249         }
1250
1251         // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
1252         $media = null;
1253         if (!empty($_FILES['image'])) {
1254                 $media = $_FILES['image'];
1255         } elseif (!empty($_FILES['media'])) {
1256                 $media = $_FILES['media'];
1257         }
1258         // save new profile image
1259         $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR, false, null, $uid);
1260
1261         // get filetype
1262         if (is_array($media['type'])) {
1263                 $filetype = $media['type'][0];
1264         } else {
1265                 $filetype = $media['type'];
1266         }
1267         if ($filetype == "image/jpeg") {
1268                 $fileext = "jpg";
1269         } elseif ($filetype == "image/png") {
1270                 $fileext = "png";
1271         } else {
1272                 throw new InternalServerErrorException('Unsupported filetype');
1273         }
1274
1275         // change specified profile or all profiles to the new resource-id
1276         if ($is_default_profile) {
1277                 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], $uid];
1278                 Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
1279         } else {
1280                 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
1281                         'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
1282                 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => $uid]);
1283         }
1284
1285         Contact::updateSelfFromUserID($uid, true);
1286
1287         // Update global directory in background
1288         Profile::publishUpdate($uid);
1289
1290         // output for client
1291         if ($data) {
1292                 $skip_status = $_REQUEST['skip_status'] ?? false;
1293
1294                 $user_info = DI::twitterUser()->createFromUserId($uid, $skip_status)->toArray();
1295
1296                 // "verified" isn't used here in the standard
1297                 unset($user_info["verified"]);
1298
1299                 // "uid" is only needed for some internal stuff, so remove it from here
1300                 unset($user_info['uid']);
1301
1302                 return DI::apiResponse()->formatData("user", $type, ['user' => $user_info]);
1303         } else {
1304                 // SaveMediaToDatabase failed for some reason
1305                 throw new InternalServerErrorException("image upload failed");
1306         }
1307 }
1308
1309 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true);
1310
1311 /**
1312  * Return all or a specified group of the user with the containing contacts.
1313  *
1314  * @param string $type Return type (atom, rss, xml, json)
1315  *
1316  * @return array|string
1317  * @throws BadRequestException
1318  * @throws ForbiddenException
1319  * @throws ImagickException
1320  * @throws InternalServerErrorException
1321  * @throws UnauthorizedException
1322  */
1323 function api_friendica_group_show($type)
1324 {
1325         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1326         $uid = BaseApi::getCurrentUserID();
1327
1328         // params
1329         $gid = $_REQUEST['gid'] ?? 0;
1330
1331         // get data of the specified group id or all groups if not specified
1332         if ($gid != 0) {
1333                 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
1334
1335                 // error message if specified gid is not in database
1336                 if (!DBA::isResult($groups)) {
1337                         throw new BadRequestException("gid not available");
1338                 }
1339         } else {
1340                 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
1341         }
1342
1343         // loop through all groups and retrieve all members for adding data in the user array
1344         $grps = [];
1345         foreach ($groups as $rr) {
1346                 $members = Contact\Group::getById($rr['id']);
1347                 $users = [];
1348
1349                 if ($type == "xml") {
1350                         $user_element = "users";
1351                         $k = 0;
1352                         foreach ($members as $member) {
1353                                 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid, true)->toArray();
1354                                 $users[$k++.":user"] = $user;
1355                         }
1356                 } else {
1357                         $user_element = "user";
1358                         foreach ($members as $member) {
1359                                 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid, true)->toArray();
1360                                 $users[] = $user;
1361                         }
1362                 }
1363                 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
1364         }
1365         return DI::apiResponse()->formatData("groups", $type, ['group' => $grps]);
1366 }
1367
1368 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
1369
1370 /**
1371  * Delete a group.
1372  *
1373  * @param string $type Return type (atom, rss, xml, json)
1374  *
1375  * @return array|string
1376  * @throws BadRequestException
1377  * @throws ForbiddenException
1378  * @throws ImagickException
1379  * @throws InternalServerErrorException
1380  * @throws UnauthorizedException
1381  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
1382  */
1383 function api_lists_destroy($type)
1384 {
1385         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1386         $uid = BaseApi::getCurrentUserID();
1387
1388         // params
1389         $gid = $_REQUEST['list_id'] ?? 0;
1390
1391         // error if no gid specified
1392         if ($gid == 0) {
1393                 throw new BadRequestException('gid not specified');
1394         }
1395
1396         // get data of the specified group id
1397         $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
1398         // error message if specified gid is not in database
1399         if (!$group) {
1400                 throw new BadRequestException('gid not available');
1401         }
1402
1403         if (Group::remove($gid)) {
1404                 $list = [
1405                         'name' => $group['name'],
1406                         'id' => intval($gid),
1407                         'id_str' => (string) $gid,
1408                         'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
1409                 ];
1410
1411                 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
1412         }
1413 }
1414
1415 api_register_func('api/lists/destroy', 'api_lists_destroy', true);
1416
1417 /**
1418  * Create the specified group with the posted array of contacts.
1419  *
1420  * @param string $type Return type (atom, rss, xml, json)
1421  *
1422  * @return array|string
1423  * @throws BadRequestException
1424  * @throws ForbiddenException
1425  * @throws ImagickException
1426  * @throws InternalServerErrorException
1427  * @throws UnauthorizedException
1428  */
1429 function api_friendica_group_create($type)
1430 {
1431         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1432         $uid = BaseApi::getCurrentUserID();
1433
1434         // params
1435         $name = $_REQUEST['name'] ?? '';
1436         $json = json_decode($_POST['json'], true);
1437         $users = $json['user'];
1438
1439         $success = group_create($name, $uid, $users);
1440
1441         return DI::apiResponse()->formatData("group_create", $type, ['result' => $success]);
1442 }
1443
1444 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true);
1445
1446 /**
1447  * Create a new group.
1448  *
1449  * @param string $type Return type (atom, rss, xml, json)
1450  *
1451  * @return array|string
1452  * @throws BadRequestException
1453  * @throws ForbiddenException
1454  * @throws ImagickException
1455  * @throws InternalServerErrorException
1456  * @throws UnauthorizedException
1457  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
1458  */
1459 function api_lists_create($type)
1460 {
1461         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1462         $uid = BaseApi::getCurrentUserID();
1463
1464         // params
1465         $name = $_REQUEST['name'] ?? '';
1466
1467         $success = group_create($name, $uid);
1468         if ($success['success']) {
1469                 $grp = [
1470                         'name' => $success['name'],
1471                         'id' => intval($success['gid']),
1472                         'id_str' => (string) $success['gid'],
1473                         'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
1474                 ];
1475
1476                 return DI::apiResponse()->formatData("lists", $type, ['lists' => $grp]);
1477         }
1478 }
1479
1480 api_register_func('api/lists/create', 'api_lists_create', true);
1481
1482 /**
1483  * Update information about a group.
1484  *
1485  * @param string $type Return type (atom, rss, xml, json)
1486  *
1487  * @return array|string
1488  * @throws BadRequestException
1489  * @throws ForbiddenException
1490  * @throws ImagickException
1491  * @throws InternalServerErrorException
1492  * @throws UnauthorizedException
1493  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
1494  */
1495 function api_lists_update($type)
1496 {
1497         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1498         $uid = BaseApi::getCurrentUserID();
1499
1500         // params
1501         $gid = $_REQUEST['list_id'] ?? 0;
1502         $name = $_REQUEST['name'] ?? '';
1503
1504         // error if no gid specified
1505         if ($gid == 0) {
1506                 throw new BadRequestException('gid not specified');
1507         }
1508
1509         // get data of the specified group id
1510         $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
1511         // error message if specified gid is not in database
1512         if (!$group) {
1513                 throw new BadRequestException('gid not available');
1514         }
1515
1516         if (Group::update($gid, $name)) {
1517                 $list = [
1518                         'name' => $name,
1519                         'id' => intval($gid),
1520                         'id_str' => (string) $gid,
1521                         'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
1522                 ];
1523
1524                 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
1525         }
1526 }
1527
1528 api_register_func('api/lists/update', 'api_lists_update', true);
1529
1530 /**
1531  * search for direct_messages containing a searchstring through api
1532  *
1533  * @param string $type      Known types are 'atom', 'rss', 'xml' and 'json'
1534  * @param string $box
1535  * @return string|array (success: success=true if found and search_result contains found messages,
1536  *                          success=false if nothing was found, search_result='nothing found',
1537  *                          error: result=error with error message)
1538  * @throws BadRequestException
1539  * @throws ForbiddenException
1540  * @throws ImagickException
1541  * @throws InternalServerErrorException
1542  * @throws UnauthorizedException
1543  */
1544 function api_friendica_direct_messages_search($type, $box = "")
1545 {
1546         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1547         $uid = BaseApi::getCurrentUserID();
1548
1549         // params
1550         $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
1551         $searchstring = $_REQUEST['searchstring'] ?? '';
1552
1553         // error if no searchstring specified
1554         if ($searchstring == "") {
1555                 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
1556                 return DI::apiResponse()->formatData("direct_messages_search", $type, ['$result' => $answer]);
1557         }
1558
1559         // get data for the specified searchstring
1560         $r = DBA::toArray(DBA::p(
1561                 "SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid` = ? AND `body` LIKE ? ORDER BY `mail`.`id` DESC",
1562                 $uid,
1563                 '%'.$searchstring.'%'
1564         ));
1565
1566         $profile_url = $user_info["url"];
1567
1568         // message if nothing was found
1569         if (!DBA::isResult($r)) {
1570                 $success = ['success' => false, 'search_results' => 'problem with query'];
1571         } elseif (count($r) == 0) {
1572                 $success = ['success' => false, 'search_results' => 'nothing found'];
1573         } else {
1574                 $ret = [];
1575                 foreach ($r as $item) {
1576                         if ($box == "inbox" || $item['from-url'] != $profile_url) {
1577                                 $recipient = $user_info;
1578                                 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
1579                         } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
1580                                 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
1581                                 $sender = $user_info;
1582                         }
1583
1584                         if (isset($recipient) && isset($sender)) {
1585                                 $ret[] = api_format_messages($item, $recipient, $sender);
1586                         }
1587                 }
1588                 $success = ['success' => true, 'search_results' => $ret];
1589         }
1590
1591         return DI::apiResponse()->formatData("direct_message_search", $type, ['$result' => $success]);
1592 }
1593
1594 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);