]> git.mxchange.org Git - friendica.git/blob - include/api.php
Merge pull request #11149 from nupplaphil/bug/friendica-11144
[friendica.git] / include / api.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, 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\Core\ACL;
28 use Friendica\Core\Logger;
29 use Friendica\Database\DBA;
30 use Friendica\DI;
31 use Friendica\Model\Contact;
32 use Friendica\Model\Group;
33 use Friendica\Model\Photo;
34 use Friendica\Model\Post;
35 use Friendica\Module\BaseApi;
36 use Friendica\Network\HTTPException;
37
38 $API = [];
39
40 /**
41  * Register a function to be the endpoint for defined API path.
42  *
43  * @param string $path   API URL path, relative to DI::baseUrl()
44  * @param string $func   Function name to call on path request
45  */
46 function api_register_func($path, $func)
47 {
48         global $API;
49
50         $API[$path] = [
51                 'func'   => $func,
52         ];
53
54         // Workaround for hotot
55         $path = str_replace("api/", "api/1.1/", $path);
56
57         $API[$path] = [
58                 'func'   => $func,
59         ];
60 }
61
62 /**
63  * Main API entry point
64  *
65  * Authenticate user, call registered API function, set HTTP headers
66  *
67  * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
68  * @return string|array API call result
69  * @throws Exception
70  */
71 function api_call($command, $extension)
72 {
73         global $API;
74
75         Logger::info('Legacy API call', ['command' => $command, 'extension' => $extension]);
76
77         try {
78                 foreach ($API as $p => $info) {
79                         if (strpos($command, $p) === 0) {
80                                 Logger::debug(BaseApi::LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
81
82                                 $stamp =  microtime(true);
83                                 $return = call_user_func($info['func'], $extension);
84                                 $duration = floatval(microtime(true) - $stamp);
85
86                                 Logger::info(BaseApi::LOG_PREFIX . 'duration {duration}', ['module' => 'api', 'action' => 'call', 'duration' => round($duration, 2)]);
87
88                                 DI::profiler()->saveLog(DI::logger(), BaseApi::LOG_PREFIX . 'performance');
89
90                                 if (false === $return) {
91                                         /*
92                                                 * api function returned false withour throw an
93                                                 * exception. This should not happend, throw a 500
94                                                 */
95                                         throw new HTTPException\InternalServerErrorException();
96                                 }
97
98                                 switch ($extension) {
99                                         case "xml":
100                                                 header("Content-Type: text/xml");
101                                                 break;
102                                         case "json":
103                                                 header("Content-Type: application/json");
104                                                 if (!empty($return)) {
105                                                         $json = json_encode(end($return));
106                                                         if (!empty($_GET['callback'])) {
107                                                                 $json = $_GET['callback'] . "(" . $json . ")";
108                                                         }
109                                                         $return = $json;
110                                                 }
111                                                 break;
112                                         case "rss":
113                                                 header("Content-Type: application/rss+xml");
114                                                 $return  = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
115                                                 break;
116                                         case "atom":
117                                                 header("Content-Type: application/atom+xml");
118                                                 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
119                                                 break;
120                                 }
121                                 return $return;
122                         }
123                 }
124
125                 Logger::warning(BaseApi::LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
126                 throw new HTTPException\NotFoundException();
127         } catch (HTTPException $e) {
128                 Logger::notice(BaseApi::LOG_PREFIX . 'got exception', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString(), 'error' => $e]);
129                 DI::apiResponse()->error($e->getCode(), $e->getDescription(), $e->getMessage(), $extension);
130         }
131 }
132
133 /**
134  *
135  * @param string $type
136  * @param int    $scale
137  * @param string $photo_id
138  *
139  * @return array
140  * @throws HTTPException\BadRequestException
141  * @throws HTTPException\ForbiddenException
142  * @throws ImagickException
143  * @throws HTTPException\InternalServerErrorException
144  * @throws HTTPException\NotFoundException
145  * @throws HTTPException\UnauthorizedException
146  */
147 function prepare_photo_data($type, $scale, $photo_id, $uid)
148 {
149         $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
150         $data_sql = ($scale === false ? "" : "data, ");
151
152         // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
153         // clients needs to convert this in their way for further processing
154         $r = DBA::toArray(DBA::p(
155                 "SELECT $data_sql `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
156                                         `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
157                                         MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
158                         FROM `photo` WHERE `uid` = ? AND `resource-id` = ? $scale_sql GROUP BY
159                                    `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
160                                    `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
161                 $uid,
162                 $photo_id
163         ));
164
165         $typetoext = [
166                 'image/jpeg' => 'jpg',
167                 'image/png' => 'png',
168                 'image/gif' => 'gif'
169         ];
170
171         // prepare output data for photo
172         if (DBA::isResult($r)) {
173                 $data = ['photo' => $r[0]];
174                 $data['photo']['id'] = $data['photo']['resource-id'];
175                 if ($scale !== false) {
176                         $data['photo']['data'] = base64_encode($data['photo']['data']);
177                 } else {
178                         unset($data['photo']['datasize']); //needed only with scale param
179                 }
180                 if ($type == "xml") {
181                         $data['photo']['links'] = [];
182                         for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
183                                 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
184                                                                                 "scale" => $k,
185                                                                                 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
186                         }
187                 } else {
188                         $data['photo']['link'] = [];
189                         // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
190                         $i = 0;
191                         for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
192                                 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
193                                 $i++;
194                         }
195                 }
196                 unset($data['photo']['resource-id']);
197                 unset($data['photo']['minscale']);
198                 unset($data['photo']['maxscale']);
199         } else {
200                 throw new HTTPException\NotFoundException();
201         }
202
203         // retrieve item element for getting activities (like, dislike etc.) related to photo
204         $condition = ['uid' => $uid, 'resource-id' => $photo_id];
205         $item = Post::selectFirst(['id', 'uid', 'uri', 'uri-id', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
206         if (!DBA::isResult($item)) {
207                 throw new HTTPException\NotFoundException('Photo-related item not found.');
208         }
209
210         $data['photo']['friendica_activities'] = DI::friendicaActivities()->createFromUriId($item['uri-id'], $item['uid'], $type);
211
212         // retrieve comments on photo
213         $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
214                 $item['parent'], $uid, GRAVITY_PARENT, GRAVITY_COMMENT];
215
216         $statuses = Post::selectForUser($uid, [], $condition);
217
218         // prepare output of comments
219         $commentData = [];
220         while ($status = DBA::fetch($statuses)) {
221                 $commentData[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'])->toArray();
222         }
223         DBA::close($statuses);
224
225         $comments = [];
226         if ($type == "xml") {
227                 $k = 0;
228                 foreach ($commentData as $comment) {
229                         $comments[$k++ . ":comment"] = $comment;
230                 }
231         } else {
232                 foreach ($commentData as $comment) {
233                         $comments[] = $comment;
234                 }
235         }
236         $data['photo']['friendica_comments'] = $comments;
237
238         // include info if rights on photo and rights on item are mismatching
239         $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
240                 $data['photo']['deny_cid'] != $item['deny_cid'] ||
241                 $data['photo']['allow_gid'] != $item['allow_gid'] ||
242                 $data['photo']['deny_gid'] != $item['deny_gid'];
243         $data['photo']['rights_mismatch'] = $rights_mismatch;
244
245         return $data;
246 }
247
248 /**
249  * TWITTER API
250  */
251
252 /**
253  * Returns all lists the user subscribes to.
254  *
255  * @param string $type Return type (atom, rss, xml, json)
256  *
257  * @return array|string
258  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
259  */
260 function api_lists_list($type)
261 {
262         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
263         $ret = [];
264         /// @TODO $ret is not filled here?
265         return DI::apiResponse()->formatData('lists', $type, ["lists_list" => $ret]);
266 }
267
268 api_register_func('api/lists/list', 'api_lists_list', true);
269 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
270
271 /**
272  * Returns all groups the user owns.
273  *
274  * @param string $type Return type (atom, rss, xml, json)
275  *
276  * @return array|string
277  * @throws HTTPException\BadRequestException
278  * @throws HTTPException\ForbiddenException
279  * @throws ImagickException
280  * @throws HTTPException\InternalServerErrorException
281  * @throws HTTPException\UnauthorizedException
282  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
283  */
284 function api_lists_ownerships($type)
285 {
286         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
287         $uid = BaseApi::getCurrentUserID();
288
289         // params
290         $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
291
292         $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
293
294         // loop through all groups
295         $lists = [];
296         foreach ($groups as $group) {
297                 if ($group['visible']) {
298                         $mode = 'public';
299                 } else {
300                         $mode = 'private';
301                 }
302                 $lists[] = [
303                         'name' => $group['name'],
304                         'id' => intval($group['id']),
305                         'id_str' => (string) $group['id'],
306                         'user' => $user_info,
307                         'mode' => $mode
308                 ];
309         }
310         return DI::apiResponse()->formatData("lists", $type, ['lists' => ['lists' => $lists]]);
311 }
312
313 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
314
315 /**
316  * list all photos of the authenticated user
317  *
318  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
319  * @return string|array
320  * @throws HTTPException\ForbiddenException
321  * @throws HTTPException\InternalServerErrorException
322  */
323 function api_fr_photos_list($type)
324 {
325         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
326         $uid = BaseApi::getCurrentUserID();
327
328         $r = DBA::toArray(DBA::p(
329                 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
330                 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
331                 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
332                 $uid, Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
333         ));
334         $typetoext = [
335                 'image/jpeg' => 'jpg',
336                 'image/png' => 'png',
337                 'image/gif' => 'gif'
338         ];
339         $data = ['photo'=>[]];
340         if (DBA::isResult($r)) {
341                 foreach ($r as $rr) {
342                         $photo = [];
343                         $photo['id'] = $rr['resource-id'];
344                         $photo['album'] = $rr['album'];
345                         $photo['filename'] = $rr['filename'];
346                         $photo['type'] = $rr['type'];
347                         $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
348                         $photo['created'] = $rr['created'];
349                         $photo['edited'] = $rr['edited'];
350                         $photo['desc'] = $rr['desc'];
351
352                         if ($type == "xml") {
353                                 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
354                         } else {
355                                 $photo['thumb'] = $thumb;
356                                 $data['photo'][] = $photo;
357                         }
358                 }
359         }
360         return DI::apiResponse()->formatData("photos", $type, $data);
361 }
362
363 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
364
365 /**
366  * upload a new photo or change an existing photo
367  *
368  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
369  * @return string|array
370  * @throws HTTPException\BadRequestException
371  * @throws HTTPException\ForbiddenException
372  * @throws ImagickException
373  * @throws HTTPException\InternalServerErrorException
374  * @throws HTTPException\NotFoundException
375  */
376 function api_fr_photo_create_update($type)
377 {
378         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
379         $uid = BaseApi::getCurrentUserID();
380
381         // input params
382         $photo_id  = $_REQUEST['photo_id']  ?? null;
383         $desc      = $_REQUEST['desc']      ?? null;
384         $album     = $_REQUEST['album']     ?? null;
385         $album_new = $_REQUEST['album_new'] ?? null;
386         $allow_cid = $_REQUEST['allow_cid'] ?? null;
387         $deny_cid  = $_REQUEST['deny_cid' ] ?? null;
388         $allow_gid = $_REQUEST['allow_gid'] ?? null;
389         $deny_gid  = $_REQUEST['deny_gid' ] ?? null;
390
391         // do several checks on input parameters
392         // we do not allow calls without album string
393         if ($album == null) {
394                 throw new HTTPException\BadRequestException("no albumname specified");
395         }
396         // if photo_id == null --> we are uploading a new photo
397         if ($photo_id == null) {
398                 $mode = "create";
399
400                 // error if no media posted in create-mode
401                 if (empty($_FILES['media'])) {
402                         // Output error
403                         throw new HTTPException\BadRequestException("no media data submitted");
404                 }
405
406                 // album_new will be ignored in create-mode
407                 $album_new = "";
408         } else {
409                 $mode = "update";
410
411                 // check if photo is existing in databasei
412                 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => $uid, 'album' => $album])) {
413                         throw new HTTPException\BadRequestException("photo not available");
414                 }
415         }
416
417         // checks on acl strings provided by clients
418         $acl_input_error = false;
419         $acl_input_error |= !ACL::isValidContact($allow_cid, $uid);
420         $acl_input_error |= !ACL::isValidContact($deny_cid, $uid);
421         $acl_input_error |= !ACL::isValidGroup($allow_gid, $uid);
422         $acl_input_error |= !ACL::isValidGroup($deny_gid, $uid);
423         if ($acl_input_error) {
424                 throw new HTTPException\BadRequestException("acl data invalid");
425         }
426         // now let's upload the new media in create-mode
427         if ($mode == "create") {
428                 $photo = Photo::upload($uid, $_FILES['media'], $album, trim($allow_cid), trim($allow_gid), trim($deny_cid), trim($deny_gid), $desc);
429
430                 // return success of updating or error message
431                 if (!empty($photo)) {
432                         $data = prepare_photo_data($type, false, $photo['resource_id'], $uid);
433                         return DI::apiResponse()->formatData("photo_create", $type, $data);
434                 } else {
435                         throw new HTTPException\InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
436                 }
437         }
438
439         // now let's do the changes in update-mode
440         if ($mode == "update") {
441                 $updated_fields = [];
442
443                 if (!is_null($desc)) {
444                         $updated_fields['desc'] = $desc;
445                 }
446
447                 if (!is_null($album_new)) {
448                         $updated_fields['album'] = $album_new;
449                 }
450
451                 if (!is_null($allow_cid)) {
452                         $allow_cid = trim($allow_cid);
453                         $updated_fields['allow_cid'] = $allow_cid;
454                 }
455
456                 if (!is_null($deny_cid)) {
457                         $deny_cid = trim($deny_cid);
458                         $updated_fields['deny_cid'] = $deny_cid;
459                 }
460
461                 if (!is_null($allow_gid)) {
462                         $allow_gid = trim($allow_gid);
463                         $updated_fields['allow_gid'] = $allow_gid;
464                 }
465
466                 if (!is_null($deny_gid)) {
467                         $deny_gid = trim($deny_gid);
468                         $updated_fields['deny_gid'] = $deny_gid;
469                 }
470
471                 $result = false;
472                 if (count($updated_fields) > 0) {
473                         $nothingtodo = false;
474                         $result = Photo::update($updated_fields, ['uid' => $uid, 'resource-id' => $photo_id, 'album' => $album]);
475                 } else {
476                         $nothingtodo = true;
477                 }
478
479                 if (!empty($_FILES['media'])) {
480                         $nothingtodo = false;
481                         $photo = Photo::upload($uid, $_FILES['media'], $album, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc, $photo_id);
482                         if (!empty($photo)) {
483                                 $data = prepare_photo_data($type, false, $photo['resource_id'], $uid);
484                                 return DI::apiResponse()->formatData("photo_update", $type, $data);
485                         }
486                 }
487
488                 // return success of updating or error message
489                 if ($result) {
490                         $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
491                         return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
492                 } else {
493                         if ($nothingtodo) {
494                                 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
495                                 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
496                         }
497                         throw new HTTPException\InternalServerErrorException("unknown error - update photo entry in database failed");
498                 }
499         }
500         throw new HTTPException\InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
501 }
502
503 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true);
504 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true);
505
506 /**
507  * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
508  *
509  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
510  * @return string|array
511  * @throws HTTPException\BadRequestException
512  * @throws HTTPException\ForbiddenException
513  * @throws HTTPException\InternalServerErrorException
514  * @throws HTTPException\NotFoundException
515  */
516 function api_fr_photo_detail($type)
517 {
518         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
519         $uid = BaseApi::getCurrentUserID();
520
521         if (empty($_REQUEST['photo_id'])) {
522                 throw new HTTPException\BadRequestException("No photo id.");
523         }
524
525         $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
526         $photo_id = $_REQUEST['photo_id'];
527
528         // prepare json/xml output with data from database for the requested photo
529         $data = prepare_photo_data($type, $scale, $photo_id, $uid);
530
531         return DI::apiResponse()->formatData("photo_detail", $type, $data);
532 }
533
534 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
535
536 /**
537  * updates the profile image for the user (either a specified profile or the default profile)
538  *
539  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
540  *
541  * @return string|array
542  * @throws HTTPException\BadRequestException
543  * @throws HTTPException\ForbiddenException
544  * @throws ImagickException
545  * @throws HTTPException\InternalServerErrorException
546  * @throws HTTPException\NotFoundException
547  * @see   https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
548  */
549 function api_account_update_profile_image($type)
550 {
551         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
552         $uid = BaseApi::getCurrentUserID();
553
554         // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
555         if (!empty($_FILES['image'])) {
556                 $media = $_FILES['image'];
557         } elseif (!empty($_FILES['media'])) {
558                 $media = $_FILES['media'];
559         }
560
561         // error if image data is missing
562         if (empty($media)) {
563                 throw new HTTPException\BadRequestException("no media data submitted");
564         }
565         
566         // save new profile image
567         $resource_id = Photo::uploadAvatar($uid, $media);
568         if (empty($resource_id)) {
569                 throw new HTTPException\InternalServerErrorException("image upload failed");
570         }
571
572         // output for client
573         $skip_status = $_REQUEST['skip_status'] ?? false;
574
575         $user_info = DI::twitterUser()->createFromUserId($uid, $skip_status)->toArray();
576
577         // "verified" isn't used here in the standard
578         unset($user_info["verified"]);
579
580         // "uid" is only needed for some internal stuff, so remove it from here
581         unset($user_info['uid']);
582
583         return DI::apiResponse()->formatData("user", $type, ['user' => $user_info]);
584 }
585
586 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true);
587
588 /**
589  * Return all or a specified group of the user with the containing contacts.
590  *
591  * @param string $type Return type (atom, rss, xml, json)
592  *
593  * @return array|string
594  * @throws HTTPException\BadRequestException
595  * @throws HTTPException\ForbiddenException
596  * @throws ImagickException
597  * @throws HTTPException\InternalServerErrorException
598  * @throws HTTPException\UnauthorizedException
599  */
600 function api_friendica_group_show($type)
601 {
602         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
603         $uid = BaseApi::getCurrentUserID();
604
605         // params
606         $gid = $_REQUEST['gid'] ?? 0;
607
608         // get data of the specified group id or all groups if not specified
609         if ($gid != 0) {
610                 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
611
612                 // error message if specified gid is not in database
613                 if (!DBA::isResult($groups)) {
614                         throw new HTTPException\BadRequestException("gid not available");
615                 }
616         } else {
617                 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
618         }
619
620         // loop through all groups and retrieve all members for adding data in the user array
621         $grps = [];
622         foreach ($groups as $rr) {
623                 $members = Contact\Group::getById($rr['id']);
624                 $users = [];
625
626                 if ($type == "xml") {
627                         $user_element = "users";
628                         $k = 0;
629                         foreach ($members as $member) {
630                                 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid, true)->toArray();
631                                 $users[$k++.":user"] = $user;
632                         }
633                 } else {
634                         $user_element = "user";
635                         foreach ($members as $member) {
636                                 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid, true)->toArray();
637                                 $users[] = $user;
638                         }
639                 }
640                 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
641         }
642         return DI::apiResponse()->formatData("groups", $type, ['group' => $grps]);
643 }
644
645 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
646
647 /**
648  * Delete a group.
649  *
650  * @param string $type Return type (atom, rss, xml, json)
651  *
652  * @return array|string
653  * @throws HTTPException\BadRequestException
654  * @throws HTTPException\ForbiddenException
655  * @throws ImagickException
656  * @throws HTTPException\InternalServerErrorException
657  * @throws HTTPException\UnauthorizedException
658  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
659  */
660 function api_lists_destroy($type)
661 {
662         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
663         $uid = BaseApi::getCurrentUserID();
664
665         // params
666         $gid = $_REQUEST['list_id'] ?? 0;
667
668         // error if no gid specified
669         if ($gid == 0) {
670                 throw new HTTPException\BadRequestException('gid not specified');
671         }
672
673         // get data of the specified group id
674         $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
675         // error message if specified gid is not in database
676         if (!$group) {
677                 throw new HTTPException\BadRequestException('gid not available');
678         }
679
680         if (Group::remove($gid)) {
681                 $list = [
682                         'name' => $group['name'],
683                         'id' => intval($gid),
684                         'id_str' => (string) $gid,
685                         'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
686                 ];
687
688                 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
689         }
690 }
691
692 api_register_func('api/lists/destroy', 'api_lists_destroy', true);
693
694 /**
695  * Create the specified group with the posted array of contacts.
696  *
697  * @param string $type Return type (atom, rss, xml, json)
698  *
699  * @return array|string
700  * @throws HTTPException\BadRequestException
701  * @throws HTTPException\ForbiddenException
702  * @throws ImagickException
703  * @throws HTTPException\InternalServerErrorException
704  * @throws HTTPException\UnauthorizedException
705  */
706 function api_friendica_group_create($type)
707 {
708         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
709         $uid = BaseApi::getCurrentUserID();
710
711         // params
712         $name = $_REQUEST['name'] ?? '';
713         $json = json_decode($_POST['json'], true);
714         $users = $json['user'];
715
716         // error if no name specified
717         if ($name == "") {
718                 throw new HTTPException\BadRequestException('group name not specified');
719         }
720
721         // error message if specified group name already exists
722         if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => false])) {
723                 throw new HTTPException\BadRequestException('group name already exists');
724         }
725
726         // Check if the group needs to be reactivated
727         if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => true])) {
728                 $reactivate_group = true;
729         }
730
731         // create group
732         $ret = Group::create($uid, $name);
733         if ($ret) {
734                 $gid = Group::getIdByName($uid, $name);
735         } else {
736                 throw new HTTPException\BadRequestException('other API error');
737         }
738
739         // add members
740         $erroraddinguser = false;
741         $errorusers = [];
742         foreach ($users as $user) {
743                 $cid = $user['cid'];
744                 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
745                         Group::addMember($gid, $cid);
746                 } else {
747                         $erroraddinguser = true;
748                         $errorusers[] = $cid;
749                 }
750         }
751
752         // return success message incl. missing users in array
753         $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
754
755         $result = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
756
757         return DI::apiResponse()->formatData("group_create", $type, ['result' => $result]);
758 }
759
760 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true);
761
762 /**
763  * Create a new group.
764  *
765  * @param string $type Return type (atom, rss, xml, json)
766  *
767  * @return array|string
768  * @throws HTTPException\BadRequestException
769  * @throws HTTPException\ForbiddenException
770  * @throws ImagickException
771  * @throws HTTPException\InternalServerErrorException
772  * @throws HTTPException\UnauthorizedException
773  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
774  */
775 function api_lists_create($type)
776 {
777         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
778         $uid = BaseApi::getCurrentUserID();
779
780         // params
781         $name = $_REQUEST['name'] ?? '';
782
783         if ($name == "") {
784                 throw new HTTPException\BadRequestException('group name not specified');
785         }
786
787         // error message if specified group name already exists
788         if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => false])) {
789                 throw new HTTPException\BadRequestException('group name already exists');
790         }
791
792         $ret = Group::create($uid, $name);
793         if ($ret) {
794                 $gid = Group::getIdByName($uid, $name);
795         } else {
796                 throw new HTTPException\BadRequestException('other API error');
797         }
798
799         $grp = [
800                 'name' => $name,
801                 'id' => intval($gid),
802                 'id_str' => (string) $gid,
803                 'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
804         ];
805
806         return DI::apiResponse()->formatData("lists", $type, ['lists' => $grp]);
807 }
808
809 api_register_func('api/lists/create', 'api_lists_create', true);
810
811 /**
812  * Update information about a group.
813  *
814  * @param string $type Return type (atom, rss, xml, json)
815  *
816  * @return array|string
817  * @throws HTTPException\BadRequestException
818  * @throws HTTPException\ForbiddenException
819  * @throws ImagickException
820  * @throws HTTPException\InternalServerErrorException
821  * @throws HTTPException\UnauthorizedException
822  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
823  */
824 function api_lists_update($type)
825 {
826         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
827         $uid = BaseApi::getCurrentUserID();
828
829         // params
830         $gid = $_REQUEST['list_id'] ?? 0;
831         $name = $_REQUEST['name'] ?? '';
832
833         // error if no gid specified
834         if ($gid == 0) {
835                 throw new HTTPException\BadRequestException('gid not specified');
836         }
837
838         // get data of the specified group id
839         $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
840         // error message if specified gid is not in database
841         if (!$group) {
842                 throw new HTTPException\BadRequestException('gid not available');
843         }
844
845         if (Group::update($gid, $name)) {
846                 $list = [
847                         'name' => $name,
848                         'id' => intval($gid),
849                         'id_str' => (string) $gid,
850                         'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
851                 ];
852
853                 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
854         }
855 }
856
857 api_register_func('api/lists/update', 'api_lists_update', true);