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