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