]> git.mxchange.org Git - friendica.git/blob - include/api.php
3441f91158fa110eaf6e4d8c0756eeff4050d721
[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']           = $uid;
415         $arr['uri']           = $uri;
416         $arr['post-type']     = Item::PT_IMAGE;
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 = Images::supportedTypes();
435
436         // adds link to the thumbnail scale photo
437         $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
438                                 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
439                                 . '[/url]';
440
441         // do the magic for storing the item in the database and trigger the federation to other contacts
442         Item::insert($arr);
443 }
444
445 /**
446  *
447  * @param string $type
448  * @param int    $scale
449  * @param string $photo_id
450  *
451  * @return array
452  * @throws BadRequestException
453  * @throws ForbiddenException
454  * @throws ImagickException
455  * @throws InternalServerErrorException
456  * @throws NotFoundException
457  * @throws UnauthorizedException
458  */
459 function prepare_photo_data($type, $scale, $photo_id, $uid)
460 {
461         $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
462         $data_sql = ($scale === false ? "" : "data, ");
463
464         // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
465         // clients needs to convert this in their way for further processing
466         $r = DBA::toArray(DBA::p(
467                 "SELECT $data_sql `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
468                                         `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
469                                         MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
470                         FROM `photo` WHERE `uid` = ? AND `resource-id` = ? $scale_sql GROUP BY
471                                    `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
472                                    `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
473                 $uid,
474                 $photo_id
475         ));
476
477         $typetoext = [
478                 'image/jpeg' => 'jpg',
479                 'image/png' => 'png',
480                 'image/gif' => 'gif'
481         ];
482
483         // prepare output data for photo
484         if (DBA::isResult($r)) {
485                 $data = ['photo' => $r[0]];
486                 $data['photo']['id'] = $data['photo']['resource-id'];
487                 if ($scale !== false) {
488                         $data['photo']['data'] = base64_encode($data['photo']['data']);
489                 } else {
490                         unset($data['photo']['datasize']); //needed only with scale param
491                 }
492                 if ($type == "xml") {
493                         $data['photo']['links'] = [];
494                         for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
495                                 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
496                                                                                 "scale" => $k,
497                                                                                 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
498                         }
499                 } else {
500                         $data['photo']['link'] = [];
501                         // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
502                         $i = 0;
503                         for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
504                                 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
505                                 $i++;
506                         }
507                 }
508                 unset($data['photo']['resource-id']);
509                 unset($data['photo']['minscale']);
510                 unset($data['photo']['maxscale']);
511         } else {
512                 throw new NotFoundException();
513         }
514
515         // retrieve item element for getting activities (like, dislike etc.) related to photo
516         $condition = ['uid' => $uid, 'resource-id' => $photo_id];
517         $item = Post::selectFirst(['id', 'uid', 'uri', 'uri-id', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
518         if (!DBA::isResult($item)) {
519                 throw new NotFoundException('Photo-related item not found.');
520         }
521
522         $data['photo']['friendica_activities'] = DI::friendicaActivities()->createFromUriId($item['uri-id'], $item['uid'], $type);
523
524         // retrieve comments on photo
525         $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
526                 $item['parent'], $uid, GRAVITY_PARENT, GRAVITY_COMMENT];
527
528         $statuses = Post::selectForUser($uid, [], $condition);
529
530         // prepare output of comments
531         $commentData = [];
532         while ($status = DBA::fetch($statuses)) {
533                 $commentData[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'])->toArray();
534         }
535         DBA::close($statuses);
536
537         $comments = [];
538         if ($type == "xml") {
539                 $k = 0;
540                 foreach ($commentData as $comment) {
541                         $comments[$k++ . ":comment"] = $comment;
542                 }
543         } else {
544                 foreach ($commentData as $comment) {
545                         $comments[] = $comment;
546                 }
547         }
548         $data['photo']['friendica_comments'] = $comments;
549
550         // include info if rights on photo and rights on item are mismatching
551         $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
552                 $data['photo']['deny_cid'] != $item['deny_cid'] ||
553                 $data['photo']['allow_gid'] != $item['allow_gid'] ||
554                 $data['photo']['deny_gid'] != $item['deny_gid'];
555         $data['photo']['rights_mismatch'] = $rights_mismatch;
556
557         return $data;
558 }
559
560 /**
561  *
562  * @param string $text
563  *
564  * @return string
565  * @throws InternalServerErrorException
566  */
567 function api_clean_plain_items($text)
568 {
569         $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
570
571         $text = BBCode::cleanPictureLinks($text);
572         $URLSearchString = "^\[\]";
573
574         $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
575
576         if ($include_entities == "true") {
577                 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
578         }
579
580         // Simplify "attachment" element
581         $text = BBCode::removeAttachment($text);
582
583         return $text;
584 }
585
586 /**
587  * Add a new group to the database.
588  *
589  * @param  string $name  Group name
590  * @param  int    $uid   User ID
591  * @param  array  $users List of users to add to the group
592  *
593  * @return array
594  * @throws BadRequestException
595  */
596 function group_create($name, $uid, $users = [])
597 {
598         // error if no name specified
599         if ($name == "") {
600                 throw new BadRequestException('group name not specified');
601         }
602
603         // error message if specified group name already exists
604         if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => false])) {
605                 throw new BadRequestException('group name already exists');
606         }
607
608         // Check if the group needs to be reactivated
609         if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => true])) {
610                 $reactivate_group = true;
611         }
612
613         // create group
614         $ret = Group::create($uid, $name);
615         if ($ret) {
616                 $gid = Group::getIdByName($uid, $name);
617         } else {
618                 throw new BadRequestException('other API error');
619         }
620
621         // add members
622         $erroraddinguser = false;
623         $errorusers = [];
624         foreach ($users as $user) {
625                 $cid = $user['cid'];
626                 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
627                         Group::addMember($gid, $cid);
628                 } else {
629                         $erroraddinguser = true;
630                         $errorusers[] = $cid;
631                 }
632         }
633
634         // return success message incl. missing users in array
635         $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
636
637         return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
638 }
639
640 /**
641  * TWITTER API
642  */
643
644 /**
645  * Returns all lists the user subscribes to.
646  *
647  * @param string $type Return type (atom, rss, xml, json)
648  *
649  * @return array|string
650  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
651  */
652 function api_lists_list($type)
653 {
654         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
655         $ret = [];
656         /// @TODO $ret is not filled here?
657         return DI::apiResponse()->formatData('lists', $type, ["lists_list" => $ret]);
658 }
659
660 api_register_func('api/lists/list', 'api_lists_list', true);
661 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
662
663 /**
664  * Returns all groups the user owns.
665  *
666  * @param string $type Return type (atom, rss, xml, json)
667  *
668  * @return array|string
669  * @throws BadRequestException
670  * @throws ForbiddenException
671  * @throws ImagickException
672  * @throws InternalServerErrorException
673  * @throws UnauthorizedException
674  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
675  */
676 function api_lists_ownerships($type)
677 {
678         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
679         $uid = BaseApi::getCurrentUserID();
680
681         // params
682         $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
683
684         $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
685
686         // loop through all groups
687         $lists = [];
688         foreach ($groups as $group) {
689                 if ($group['visible']) {
690                         $mode = 'public';
691                 } else {
692                         $mode = 'private';
693                 }
694                 $lists[] = [
695                         'name' => $group['name'],
696                         'id' => intval($group['id']),
697                         'id_str' => (string) $group['id'],
698                         'user' => $user_info,
699                         'mode' => $mode
700                 ];
701         }
702         return DI::apiResponse()->formatData("lists", $type, ['lists' => ['lists' => $lists]]);
703 }
704
705 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
706
707 /**
708  * Sends a new direct message.
709  *
710  * @param string $type Return type (atom, rss, xml, json)
711  *
712  * @return array|string
713  * @throws BadRequestException
714  * @throws ForbiddenException
715  * @throws ImagickException
716  * @throws InternalServerErrorException
717  * @throws NotFoundException
718  * @throws UnauthorizedException
719  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
720  */
721 function api_direct_messages_new($type)
722 {
723         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
724         $uid = BaseApi::getCurrentUserID();
725
726         if (empty($_POST["text"]) || empty($_REQUEST['screen_name']) && empty($_REQUEST['user_id'])) {
727                 return;
728         }
729
730         $sender = DI::twitterUser()->createFromUserId($uid, true)->toArray();
731
732         $cid = BaseApi::getContactIDForSearchterm($_REQUEST['screen_name'] ?? '', $_REQUEST['profileurl'] ?? '', $_REQUEST['user_id'] ?? 0, 0);
733         if (empty($cid)) {
734                 throw new NotFoundException('Recipient not found');
735         }
736
737         $replyto = '';
738         if (!empty($_REQUEST['replyto'])) {
739                 $mail    = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => $uid, 'id' => $_REQUEST['replyto']]);
740                 $replyto = $mail['parent-uri'];
741                 $sub     = $mail['title'];
742         } else {
743                 if (!empty($_REQUEST['title'])) {
744                         $sub = $_REQUEST['title'];
745                 } else {
746                         $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
747                 }
748         }
749
750         $cdata = Contact::getPublicAndUserContactID($cid, $uid);
751
752         $id = Mail::send($cdata['user'], $_POST['text'], $sub, $replyto);
753
754         if ($id > -1) {
755                 $mail = DBA::selectFirst('mail', [], ['id' => $id]);
756                 $ret = api_format_messages($mail, DI::twitterUser()->createFromContactId($cid, $uid, true)->toArray(), $sender);
757         } else {
758                 $ret = ["error" => $id];
759         }
760
761         return DI::apiResponse()->formatData("direct-messages", $type, ['direct_message' => $ret], Contact::getPublicIdByUserId($uid));
762 }
763
764 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true);
765
766 /**
767  * delete a direct_message from mail table through api
768  *
769  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
770  * @return string|array
771  * @throws BadRequestException
772  * @throws ForbiddenException
773  * @throws ImagickException
774  * @throws InternalServerErrorException
775  * @throws UnauthorizedException
776  * @see   https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
777  */
778 function api_direct_messages_destroy($type)
779 {
780         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
781         $uid = BaseApi::getCurrentUserID();
782
783         //required
784         $id = $_REQUEST['id'] ?? 0;
785         // optional
786         $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
787         $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
788         /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
789
790         // error if no id or parenturi specified (for clients posting parent-uri as well)
791         if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
792                 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
793                 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
794         }
795
796         // BadRequestException if no id specified (for clients using Twitter API)
797         if ($id == 0) {
798                 throw new BadRequestException('Message id not specified');
799         }
800
801         // add parent-uri to sql command if specified by calling app
802         $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
803
804         // error message if specified id is not in database
805         if (!DBA::exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) {
806                 if ($verbose == "true") {
807                         $answer = ['result' => 'error', 'message' => 'message id not in database'];
808                         return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
809                 }
810                 /// @todo BadRequestException ok for Twitter API clients?
811                 throw new BadRequestException('message id not in database');
812         }
813
814         // delete message
815         $result = DBA::delete('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id]);
816
817         if ($verbose == "true") {
818                 if ($result) {
819                         // return success
820                         $answer = ['result' => 'ok', 'message' => 'message deleted'];
821                         return DI::apiResponse()->formatData("direct_message_delete", $type, ['$result' => $answer]);
822                 } else {
823                         $answer = ['result' => 'error', 'message' => 'unknown error'];
824                         return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
825                 }
826         }
827         /// @todo return JSON data like Twitter API not yet implemented
828 }
829
830 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true);
831
832 /**
833  *
834  * @param string $type Return type (atom, rss, xml, json)
835  * @param string $box
836  * @param string $verbose
837  *
838  * @return array|string
839  * @throws BadRequestException
840  * @throws ForbiddenException
841  * @throws ImagickException
842  * @throws InternalServerErrorException
843  * @throws UnauthorizedException
844  */
845 function api_direct_messages_box($type, $box, $verbose)
846 {
847         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
848         $uid = BaseApi::getCurrentUserID();
849
850         // params
851         $count = $_GET['count'] ?? 20;
852         $page = $_REQUEST['page'] ?? 1;
853
854         $since_id = $_REQUEST['since_id'] ?? 0;
855         $max_id = $_REQUEST['max_id'] ?? 0;
856
857         $user_id = $_REQUEST['user_id'] ?? '';
858         $screen_name = $_REQUEST['screen_name'] ?? '';
859
860         $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
861
862         $profile_url = $user_info["url"];
863
864         // pagination
865         $start = max(0, ($page - 1) * $count);
866
867         $sql_extra = "";
868
869         // filters
870         if ($box=="sentbox") {
871                 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
872         } elseif ($box == "conversation") {
873                 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '')  . "'";
874         } elseif ($box == "all") {
875                 $sql_extra = "true";
876         } elseif ($box == "inbox") {
877                 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
878         }
879
880         if ($max_id > 0) {
881                 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
882         }
883
884         if ($user_id != "") {
885                 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
886         } elseif ($screen_name !="") {
887                 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
888         }
889
890         $r = DBA::toArray(DBA::p(
891                 "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 ?,?",
892                 $uid,
893                 $since_id,
894                 $start,
895                 $count
896         ));
897         if ($verbose == "true" && !DBA::isResult($r)) {
898                 $answer = ['result' => 'error', 'message' => 'no mails available'];
899                 return DI::apiResponse()->formatData("direct_messages_all", $type, ['$result' => $answer]);
900         }
901
902         $ret = [];
903         foreach ($r as $item) {
904                 if ($box == "inbox" || $item['from-url'] != $profile_url) {
905                         $recipient = $user_info;
906                         $sender = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
907                 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
908                         $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
909                         $sender = $user_info;
910                 }
911
912                 if (isset($recipient) && isset($sender)) {
913                         $ret[] = api_format_messages($item, $recipient, $sender);
914                 }
915         }
916
917         return DI::apiResponse()->formatData("direct-messages", $type, ['direct_message' => $ret], Contact::getPublicIdByUserId($uid));
918 }
919
920 /**
921  * Returns the most recent direct messages sent by the user.
922  *
923  * @param string $type Return type (atom, rss, xml, json)
924  *
925  * @return array|string
926  * @throws BadRequestException
927  * @throws ForbiddenException
928  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
929  */
930 function api_direct_messages_sentbox($type)
931 {
932         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
933         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
934         return api_direct_messages_box($type, "sentbox", $verbose);
935 }
936
937 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
938
939 /**
940  * Returns the most recent direct messages sent to the user.
941  *
942  * @param string $type Return type (atom, rss, xml, json)
943  *
944  * @return array|string
945  * @throws BadRequestException
946  * @throws ForbiddenException
947  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
948  */
949 function api_direct_messages_inbox($type)
950 {
951         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
952         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
953         return api_direct_messages_box($type, "inbox", $verbose);
954 }
955
956 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
957
958 /**
959  *
960  * @param string $type Return type (atom, rss, xml, json)
961  *
962  * @return array|string
963  * @throws BadRequestException
964  * @throws ForbiddenException
965  */
966 function api_direct_messages_all($type)
967 {
968         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
969         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
970         return api_direct_messages_box($type, "all", $verbose);
971 }
972
973 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
974
975 /**
976  *
977  * @param string $type Return type (atom, rss, xml, json)
978  *
979  * @return array|string
980  * @throws BadRequestException
981  * @throws ForbiddenException
982  */
983 function api_direct_messages_conversation($type)
984 {
985         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
986         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
987         return api_direct_messages_box($type, "conversation", $verbose);
988 }
989
990 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
991
992 /**
993  * list all photos of the authenticated user
994  *
995  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
996  * @return string|array
997  * @throws ForbiddenException
998  * @throws InternalServerErrorException
999  */
1000 function api_fr_photos_list($type)
1001 {
1002         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1003         $uid = BaseApi::getCurrentUserID();
1004
1005         $r = DBA::toArray(DBA::p(
1006                 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
1007                 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
1008                 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
1009                 $uid, Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
1010         ));
1011         $typetoext = [
1012                 'image/jpeg' => 'jpg',
1013                 'image/png' => 'png',
1014                 'image/gif' => 'gif'
1015         ];
1016         $data = ['photo'=>[]];
1017         if (DBA::isResult($r)) {
1018                 foreach ($r as $rr) {
1019                         $photo = [];
1020                         $photo['id'] = $rr['resource-id'];
1021                         $photo['album'] = $rr['album'];
1022                         $photo['filename'] = $rr['filename'];
1023                         $photo['type'] = $rr['type'];
1024                         $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
1025                         $photo['created'] = $rr['created'];
1026                         $photo['edited'] = $rr['edited'];
1027                         $photo['desc'] = $rr['desc'];
1028
1029                         if ($type == "xml") {
1030                                 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
1031                         } else {
1032                                 $photo['thumb'] = $thumb;
1033                                 $data['photo'][] = $photo;
1034                         }
1035                 }
1036         }
1037         return DI::apiResponse()->formatData("photos", $type, $data);
1038 }
1039
1040 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
1041
1042 /**
1043  * upload a new photo or change an existing photo
1044  *
1045  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1046  * @return string|array
1047  * @throws BadRequestException
1048  * @throws ForbiddenException
1049  * @throws ImagickException
1050  * @throws InternalServerErrorException
1051  * @throws NotFoundException
1052  */
1053 function api_fr_photo_create_update($type)
1054 {
1055         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1056         $uid = BaseApi::getCurrentUserID();
1057
1058         // input params
1059         $photo_id  = $_REQUEST['photo_id']  ?? null;
1060         $desc      = $_REQUEST['desc']      ?? null;
1061         $album     = $_REQUEST['album']     ?? null;
1062         $album_new = $_REQUEST['album_new'] ?? null;
1063         $allow_cid = $_REQUEST['allow_cid'] ?? null;
1064         $deny_cid  = $_REQUEST['deny_cid' ] ?? null;
1065         $allow_gid = $_REQUEST['allow_gid'] ?? null;
1066         $deny_gid  = $_REQUEST['deny_gid' ] ?? null;
1067         $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
1068
1069         // do several checks on input parameters
1070         // we do not allow calls without album string
1071         if ($album == null) {
1072                 throw new BadRequestException("no albumname specified");
1073         }
1074         // if photo_id == null --> we are uploading a new photo
1075         if ($photo_id == null) {
1076                 $mode = "create";
1077
1078                 // error if no media posted in create-mode
1079                 if (empty($_FILES['media'])) {
1080                         // Output error
1081                         throw new BadRequestException("no media data submitted");
1082                 }
1083
1084                 // album_new will be ignored in create-mode
1085                 $album_new = "";
1086         } else {
1087                 $mode = "update";
1088
1089                 // check if photo is existing in databasei
1090                 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => $uid, 'album' => $album])) {
1091                         throw new BadRequestException("photo not available");
1092                 }
1093         }
1094
1095         // checks on acl strings provided by clients
1096         $acl_input_error = false;
1097         $acl_input_error |= check_acl_input($allow_cid, $uid);
1098         $acl_input_error |= check_acl_input($deny_cid, $uid);
1099         $acl_input_error |= check_acl_input($allow_gid, $uid);
1100         $acl_input_error |= check_acl_input($deny_gid, $uid);
1101         if ($acl_input_error) {
1102                 throw new BadRequestException("acl data invalid");
1103         }
1104         // now let's upload the new media in create-mode
1105         if ($mode == "create") {
1106                 $media = $_FILES['media'];
1107                 $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);
1108
1109                 // return success of updating or error message
1110                 if (!is_null($data)) {
1111                         return DI::apiResponse()->formatData("photo_create", $type, $data);
1112                 } else {
1113                         throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
1114                 }
1115         }
1116
1117         // now let's do the changes in update-mode
1118         if ($mode == "update") {
1119                 $updated_fields = [];
1120
1121                 if (!is_null($desc)) {
1122                         $updated_fields['desc'] = $desc;
1123                 }
1124
1125                 if (!is_null($album_new)) {
1126                         $updated_fields['album'] = $album_new;
1127                 }
1128
1129                 if (!is_null($allow_cid)) {
1130                         $allow_cid = trim($allow_cid);
1131                         $updated_fields['allow_cid'] = $allow_cid;
1132                 }
1133
1134                 if (!is_null($deny_cid)) {
1135                         $deny_cid = trim($deny_cid);
1136                         $updated_fields['deny_cid'] = $deny_cid;
1137                 }
1138
1139                 if (!is_null($allow_gid)) {
1140                         $allow_gid = trim($allow_gid);
1141                         $updated_fields['allow_gid'] = $allow_gid;
1142                 }
1143
1144                 if (!is_null($deny_gid)) {
1145                         $deny_gid = trim($deny_gid);
1146                         $updated_fields['deny_gid'] = $deny_gid;
1147                 }
1148
1149                 $result = false;
1150                 if (count($updated_fields) > 0) {
1151                         $nothingtodo = false;
1152                         $result = Photo::update($updated_fields, ['uid' => $uid, 'resource-id' => $photo_id, 'album' => $album]);
1153                 } else {
1154                         $nothingtodo = true;
1155                 }
1156
1157                 if (!empty($_FILES['media'])) {
1158                         $nothingtodo = false;
1159                         $media = $_FILES['media'];
1160                         $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id, $uid);
1161                         if (!is_null($data)) {
1162                                 return DI::apiResponse()->formatData("photo_update", $type, $data);
1163                         }
1164                 }
1165
1166                 // return success of updating or error message
1167                 if ($result) {
1168                         $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
1169                         return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
1170                 } else {
1171                         if ($nothingtodo) {
1172                                 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
1173                                 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
1174                         }
1175                         throw new InternalServerErrorException("unknown error - update photo entry in database failed");
1176                 }
1177         }
1178         throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
1179 }
1180
1181 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true);
1182 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true);
1183
1184 /**
1185  * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
1186  *
1187  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1188  * @return string|array
1189  * @throws BadRequestException
1190  * @throws ForbiddenException
1191  * @throws InternalServerErrorException
1192  * @throws NotFoundException
1193  */
1194 function api_fr_photo_detail($type)
1195 {
1196         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1197         $uid = BaseApi::getCurrentUserID();
1198
1199         if (empty($_REQUEST['photo_id'])) {
1200                 throw new BadRequestException("No photo id.");
1201         }
1202
1203         $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
1204         $photo_id = $_REQUEST['photo_id'];
1205
1206         // prepare json/xml output with data from database for the requested photo
1207         $data = prepare_photo_data($type, $scale, $photo_id, $uid);
1208
1209         return DI::apiResponse()->formatData("photo_detail", $type, $data);
1210 }
1211
1212 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
1213
1214 /**
1215  * updates the profile image for the user (either a specified profile or the default profile)
1216  *
1217  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1218  *
1219  * @return string|array
1220  * @throws BadRequestException
1221  * @throws ForbiddenException
1222  * @throws ImagickException
1223  * @throws InternalServerErrorException
1224  * @throws NotFoundException
1225  * @see   https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
1226  */
1227 function api_account_update_profile_image($type)
1228 {
1229         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1230         $uid = BaseApi::getCurrentUserID();
1231
1232         // input params
1233         $profile_id = $_REQUEST['profile_id'] ?? 0;
1234
1235         // error if image data is missing
1236         if (empty($_FILES['image'])) {
1237                 throw new BadRequestException("no media data submitted");
1238         }
1239
1240         // check if specified profile id is valid
1241         if ($profile_id != 0) {
1242                 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => $uid, 'id' => $profile_id]);
1243                 // error message if specified profile id is not in database
1244                 if (!DBA::isResult($profile)) {
1245                         throw new BadRequestException("profile_id not available");
1246                 }
1247                 $is_default_profile = $profile['is-default'];
1248         } else {
1249                 $is_default_profile = 1;
1250         }
1251
1252         // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
1253         $media = null;
1254         if (!empty($_FILES['image'])) {
1255                 $media = $_FILES['image'];
1256         } elseif (!empty($_FILES['media'])) {
1257                 $media = $_FILES['media'];
1258         }
1259         // save new profile image
1260         $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR, false, null, $uid);
1261
1262         // get filetype
1263         if (is_array($media['type'])) {
1264                 $filetype = $media['type'][0];
1265         } else {
1266                 $filetype = $media['type'];
1267         }
1268         if ($filetype == "image/jpeg") {
1269                 $fileext = "jpg";
1270         } elseif ($filetype == "image/png") {
1271                 $fileext = "png";
1272         } else {
1273                 throw new InternalServerErrorException('Unsupported filetype');
1274         }
1275
1276         // change specified profile or all profiles to the new resource-id
1277         if ($is_default_profile) {
1278                 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], $uid];
1279                 Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
1280         } else {
1281                 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
1282                         'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
1283                 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => $uid]);
1284         }
1285
1286         Contact::updateSelfFromUserID($uid, true);
1287
1288         // Update global directory in background
1289         Profile::publishUpdate($uid);
1290
1291         // output for client
1292         if ($data) {
1293                 $skip_status = $_REQUEST['skip_status'] ?? false;
1294
1295                 $user_info = DI::twitterUser()->createFromUserId($uid, $skip_status)->toArray();
1296
1297                 // "verified" isn't used here in the standard
1298                 unset($user_info["verified"]);
1299
1300                 // "uid" is only needed for some internal stuff, so remove it from here
1301                 unset($user_info['uid']);
1302
1303                 return DI::apiResponse()->formatData("user", $type, ['user' => $user_info]);
1304         } else {
1305                 // SaveMediaToDatabase failed for some reason
1306                 throw new InternalServerErrorException("image upload failed");
1307         }
1308 }
1309
1310 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true);
1311
1312 /**
1313  * Return all or a specified group of the user with the containing contacts.
1314  *
1315  * @param string $type Return type (atom, rss, xml, json)
1316  *
1317  * @return array|string
1318  * @throws BadRequestException
1319  * @throws ForbiddenException
1320  * @throws ImagickException
1321  * @throws InternalServerErrorException
1322  * @throws UnauthorizedException
1323  */
1324 function api_friendica_group_show($type)
1325 {
1326         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1327         $uid = BaseApi::getCurrentUserID();
1328
1329         // params
1330         $gid = $_REQUEST['gid'] ?? 0;
1331
1332         // get data of the specified group id or all groups if not specified
1333         if ($gid != 0) {
1334                 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
1335
1336                 // error message if specified gid is not in database
1337                 if (!DBA::isResult($groups)) {
1338                         throw new BadRequestException("gid not available");
1339                 }
1340         } else {
1341                 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
1342         }
1343
1344         // loop through all groups and retrieve all members for adding data in the user array
1345         $grps = [];
1346         foreach ($groups as $rr) {
1347                 $members = Contact\Group::getById($rr['id']);
1348                 $users = [];
1349
1350                 if ($type == "xml") {
1351                         $user_element = "users";
1352                         $k = 0;
1353                         foreach ($members as $member) {
1354                                 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid, true)->toArray();
1355                                 $users[$k++.":user"] = $user;
1356                         }
1357                 } else {
1358                         $user_element = "user";
1359                         foreach ($members as $member) {
1360                                 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid, true)->toArray();
1361                                 $users[] = $user;
1362                         }
1363                 }
1364                 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
1365         }
1366         return DI::apiResponse()->formatData("groups", $type, ['group' => $grps]);
1367 }
1368
1369 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
1370
1371 /**
1372  * Delete a group.
1373  *
1374  * @param string $type Return type (atom, rss, xml, json)
1375  *
1376  * @return array|string
1377  * @throws BadRequestException
1378  * @throws ForbiddenException
1379  * @throws ImagickException
1380  * @throws InternalServerErrorException
1381  * @throws UnauthorizedException
1382  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
1383  */
1384 function api_lists_destroy($type)
1385 {
1386         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1387         $uid = BaseApi::getCurrentUserID();
1388
1389         // params
1390         $gid = $_REQUEST['list_id'] ?? 0;
1391
1392         // error if no gid specified
1393         if ($gid == 0) {
1394                 throw new BadRequestException('gid not specified');
1395         }
1396
1397         // get data of the specified group id
1398         $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
1399         // error message if specified gid is not in database
1400         if (!$group) {
1401                 throw new BadRequestException('gid not available');
1402         }
1403
1404         if (Group::remove($gid)) {
1405                 $list = [
1406                         'name' => $group['name'],
1407                         'id' => intval($gid),
1408                         'id_str' => (string) $gid,
1409                         'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
1410                 ];
1411
1412                 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
1413         }
1414 }
1415
1416 api_register_func('api/lists/destroy', 'api_lists_destroy', true);
1417
1418 /**
1419  * Create the specified group with the posted array of contacts.
1420  *
1421  * @param string $type Return type (atom, rss, xml, json)
1422  *
1423  * @return array|string
1424  * @throws BadRequestException
1425  * @throws ForbiddenException
1426  * @throws ImagickException
1427  * @throws InternalServerErrorException
1428  * @throws UnauthorizedException
1429  */
1430 function api_friendica_group_create($type)
1431 {
1432         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1433         $uid = BaseApi::getCurrentUserID();
1434
1435         // params
1436         $name = $_REQUEST['name'] ?? '';
1437         $json = json_decode($_POST['json'], true);
1438         $users = $json['user'];
1439
1440         $success = group_create($name, $uid, $users);
1441
1442         return DI::apiResponse()->formatData("group_create", $type, ['result' => $success]);
1443 }
1444
1445 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true);
1446
1447 /**
1448  * Create a new group.
1449  *
1450  * @param string $type Return type (atom, rss, xml, json)
1451  *
1452  * @return array|string
1453  * @throws BadRequestException
1454  * @throws ForbiddenException
1455  * @throws ImagickException
1456  * @throws InternalServerErrorException
1457  * @throws UnauthorizedException
1458  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
1459  */
1460 function api_lists_create($type)
1461 {
1462         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1463         $uid = BaseApi::getCurrentUserID();
1464
1465         // params
1466         $name = $_REQUEST['name'] ?? '';
1467
1468         $success = group_create($name, $uid);
1469         if ($success['success']) {
1470                 $grp = [
1471                         'name' => $success['name'],
1472                         'id' => intval($success['gid']),
1473                         'id_str' => (string) $success['gid'],
1474                         'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
1475                 ];
1476
1477                 return DI::apiResponse()->formatData("lists", $type, ['lists' => $grp]);
1478         }
1479 }
1480
1481 api_register_func('api/lists/create', 'api_lists_create', true);
1482
1483 /**
1484  * Update information about a group.
1485  *
1486  * @param string $type Return type (atom, rss, xml, json)
1487  *
1488  * @return array|string
1489  * @throws BadRequestException
1490  * @throws ForbiddenException
1491  * @throws ImagickException
1492  * @throws InternalServerErrorException
1493  * @throws UnauthorizedException
1494  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
1495  */
1496 function api_lists_update($type)
1497 {
1498         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1499         $uid = BaseApi::getCurrentUserID();
1500
1501         // params
1502         $gid = $_REQUEST['list_id'] ?? 0;
1503         $name = $_REQUEST['name'] ?? '';
1504
1505         // error if no gid specified
1506         if ($gid == 0) {
1507                 throw new BadRequestException('gid not specified');
1508         }
1509
1510         // get data of the specified group id
1511         $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
1512         // error message if specified gid is not in database
1513         if (!$group) {
1514                 throw new BadRequestException('gid not available');
1515         }
1516
1517         if (Group::update($gid, $name)) {
1518                 $list = [
1519                         'name' => $name,
1520                         'id' => intval($gid),
1521                         'id_str' => (string) $gid,
1522                         'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
1523                 ];
1524
1525                 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
1526         }
1527 }
1528
1529 api_register_func('api/lists/update', 'api_lists_update', true);
1530
1531 /**
1532  * search for direct_messages containing a searchstring through api
1533  *
1534  * @param string $type      Known types are 'atom', 'rss', 'xml' and 'json'
1535  * @param string $box
1536  * @return string|array (success: success=true if found and search_result contains found messages,
1537  *                          success=false if nothing was found, search_result='nothing found',
1538  *                          error: result=error with error message)
1539  * @throws BadRequestException
1540  * @throws ForbiddenException
1541  * @throws ImagickException
1542  * @throws InternalServerErrorException
1543  * @throws UnauthorizedException
1544  */
1545 function api_friendica_direct_messages_search($type, $box = "")
1546 {
1547         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1548         $uid = BaseApi::getCurrentUserID();
1549
1550         // params
1551         $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
1552         $searchstring = $_REQUEST['searchstring'] ?? '';
1553
1554         // error if no searchstring specified
1555         if ($searchstring == "") {
1556                 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
1557                 return DI::apiResponse()->formatData("direct_messages_search", $type, ['$result' => $answer]);
1558         }
1559
1560         // get data for the specified searchstring
1561         $r = DBA::toArray(DBA::p(
1562                 "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",
1563                 $uid,
1564                 '%'.$searchstring.'%'
1565         ));
1566
1567         $profile_url = $user_info["url"];
1568
1569         // message if nothing was found
1570         if (!DBA::isResult($r)) {
1571                 $success = ['success' => false, 'search_results' => 'problem with query'];
1572         } elseif (count($r) == 0) {
1573                 $success = ['success' => false, 'search_results' => 'nothing found'];
1574         } else {
1575                 $ret = [];
1576                 foreach ($r as $item) {
1577                         if ($box == "inbox" || $item['from-url'] != $profile_url) {
1578                                 $recipient = $user_info;
1579                                 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
1580                         } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
1581                                 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
1582                                 $sender = $user_info;
1583                         }
1584
1585                         if (isset($recipient) && isset($sender)) {
1586                                 $ret[] = api_format_messages($item, $recipient, $sender);
1587                         }
1588                 }
1589                 $success = ['success' => true, 'search_results' => $ret];
1590         }
1591
1592         return DI::apiResponse()->formatData("direct_message_search", $type, ['$result' => $success]);
1593 }
1594
1595 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);