]> git.mxchange.org Git - friendica.git/blob - include/api.php
de7195dbb6db9426788d90da01adb9b3dba20761
[friendica.git] / include / api.php
1 <?php\r
2 /**\r
3  * @file include/api.php\r
4  * Friendica implementation of statusnet/twitter API\r
5  *\r
6  * @todo Automatically detect if incoming data is HTML or BBCode\r
7  */\r
8         require_once('include/HTTPExceptions.php');\r
9 \r
10         require_once('include/bbcode.php');\r
11         require_once('include/datetime.php');\r
12         require_once('include/conversation.php');\r
13         require_once('include/oauth.php');\r
14         require_once('include/html2plain.php');\r
15         require_once('mod/share.php');\r
16         require_once('include/Photo.php');\r
17         require_once('mod/item.php');\r
18         require_once('include/security.php');\r
19         require_once('include/contact_selectors.php');\r
20         require_once('include/html2bbcode.php');\r
21         require_once('mod/wall_upload.php');\r
22         require_once('mod/proxy.php');\r
23         require_once('include/message.php');\r
24         require_once('include/group.php');\r
25         require_once('include/like.php');\r
26         require_once('include/NotificationsManager.php');\r
27         require_once('include/plaintext.php');\r
28         require_once('include/xml.php');\r
29 \r
30 \r
31         define('API_METHOD_ANY','*');\r
32         define('API_METHOD_GET','GET');\r
33         define('API_METHOD_POST','POST,PUT');\r
34         define('API_METHOD_DELETE','POST,DELETE');\r
35 \r
36 \r
37 \r
38         $API = Array();\r
39         $called_api = Null;\r
40 \r
41         /**\r
42          * @brief Auth API user\r
43          *\r
44          * It is not sufficient to use local_user() to check whether someone is allowed to use the API,\r
45          * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF\r
46          * into a page, and visitors will post something without noticing it).\r
47          */\r
48         function api_user() {\r
49                 if ($_SESSION['allow_api'])\r
50                         return local_user();\r
51 \r
52                 return false;\r
53         }\r
54 \r
55         /**\r
56          * @brief Get source name from API client\r
57          *\r
58          * Clients can send 'source' parameter to be show in post metadata\r
59          * as "sent via <source>".\r
60          * Some clients doesn't send a source param, we support ones we know\r
61          * (only Twidere, atm)\r
62          *\r
63          * @return string\r
64          *              Client source name, default to "api" if unset/unknown\r
65          */\r
66         function api_source() {\r
67                 if (requestdata('source'))\r
68                         return (requestdata('source'));\r
69 \r
70                 // Support for known clients that doesn't send a source name\r
71                 if (strstr($_SERVER['HTTP_USER_AGENT'], "Twidere"))\r
72                         return ("Twidere");\r
73 \r
74                 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);\r
75 \r
76                 return ("api");\r
77         }\r
78 \r
79         /**\r
80          * @brief Format date for API\r
81          *\r
82          * @param string $str Source date, as UTC\r
83          * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"\r
84          */\r
85         function api_date($str){\r
86                 //Wed May 23 06:01:13 +0000 2007\r
87                 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );\r
88         }\r
89 \r
90         /**\r
91          * @brief Register API endpoint\r
92          *\r
93          * Register a function to be the endpont for defined API path.\r
94          *\r
95          * @param string $path API URL path, relative to App::get_baseurl()\r
96          * @param string $func Function name to call on path request\r
97          * @param bool $auth API need logged user\r
98          * @param string $method\r
99          *      HTTP method reqiured to call this endpoint.\r
100          *      One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.\r
101          *  Default to API_METHOD_ANY\r
102          */\r
103         function api_register_func($path, $func, $auth=false, $method=API_METHOD_ANY){\r
104                 global $API;\r
105                 $API[$path] = array(\r
106                         'func'=>$func,\r
107                         'auth'=>$auth,\r
108                         'method'=> $method\r
109                 );\r
110 \r
111                 // Workaround for hotot\r
112                 $path = str_replace("api/", "api/1.1/", $path);\r
113                 $API[$path] = array(\r
114                         'func'=>$func,\r
115                         'auth'=>$auth,\r
116                         'method'=> $method\r
117                 );\r
118         }\r
119 \r
120         /**\r
121          * @brief Login API user\r
122          *\r
123          * Log in user via OAuth1 or Simple HTTP Auth.\r
124          * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part\r
125          *\r
126          * @param App $a\r
127          * @hook 'authenticate'\r
128          *              array $addon_auth\r
129          *                      'username' => username from login form\r
130          *                      'password' => password from login form\r
131          *                      'authenticated' => return status,\r
132          *                      'user_record' => return authenticated user record\r
133          * @hook 'logged_in'\r
134          *              array $user     logged user record\r
135          */\r
136         function api_login(&$a){\r
137                 // login with oauth\r
138                 try{\r
139                         $oauth = new FKOAuth1();\r
140                         list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());\r
141                         if (!is_null($token)){\r
142                                 $oauth->loginUser($token->uid);\r
143                                 call_hooks('logged_in', $a->user);\r
144                                 return;\r
145                         }\r
146                         echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();\r
147                 }catch(Exception $e){\r
148                         logger($e);\r
149                 }\r
150 \r
151 \r
152 \r
153                 // workaround for HTTP-auth in CGI mode\r
154                 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {\r
155                         $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;\r
156                         if(strlen($userpass)) {\r
157                                 list($name, $password) = explode(':', $userpass);\r
158                                 $_SERVER['PHP_AUTH_USER'] = $name;\r
159                                 $_SERVER['PHP_AUTH_PW'] = $password;\r
160                         }\r
161                 }\r
162 \r
163                 if (!isset($_SERVER['PHP_AUTH_USER'])) {\r
164                         logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);\r
165                         header('WWW-Authenticate: Basic realm="Friendica"');\r
166                         throw new UnauthorizedException("This API requires login");\r
167                 }\r
168 \r
169                 $user = $_SERVER['PHP_AUTH_USER'];\r
170                 $password = $_SERVER['PHP_AUTH_PW'];\r
171                 $encrypted = hash('whirlpool',trim($password));\r
172 \r
173                 // allow "user@server" login (but ignore 'server' part)\r
174                 $at=strstr($user, "@", true);\r
175                 if ( $at ) $user=$at;\r
176 \r
177                 /**\r
178                  *  next code from mod/auth.php. needs better solution\r
179                  */\r
180                 $record = null;\r
181 \r
182                 $addon_auth = array(\r
183                         'username' => trim($user),\r
184                         'password' => trim($password),\r
185                         'authenticated' => 0,\r
186                         'user_record' => null\r
187                 );\r
188 \r
189                 /**\r
190                  *\r
191                  * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record\r
192                  * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained\r
193                  * and later plugins should not interfere with an earlier one that succeeded.\r
194                  *\r
195                  */\r
196 \r
197                 call_hooks('authenticate', $addon_auth);\r
198 \r
199                 if(($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {\r
200                         $record = $addon_auth['user_record'];\r
201                 }\r
202                 else {\r
203                         // process normal login request\r
204 \r
205                         $r = q("SELECT * FROM `user` WHERE (`email` = '%s' OR `nickname` = '%s')\r
206                                 AND `password` = '%s' AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified` LIMIT 1",\r
207                                 dbesc(trim($user)),\r
208                                 dbesc(trim($user)),\r
209                                 dbesc($encrypted)\r
210                         );\r
211                         if(count($r))\r
212                                 $record = $r[0];\r
213                 }\r
214 \r
215                 if((! $record) || (! count($record))) {\r
216                         logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);\r
217                         header('WWW-Authenticate: Basic realm="Friendica"');\r
218                         #header('HTTP/1.0 401 Unauthorized');\r
219                         #die('This api requires login');\r
220                         throw new UnauthorizedException("This API requires login");\r
221                 }\r
222 \r
223                 authenticate_success($record);\r
224 \r
225                 $_SESSION["allow_api"] = true;\r
226 \r
227                 call_hooks('logged_in', $a->user);\r
228 \r
229         }\r
230 \r
231         /**\r
232          * @brief Check HTTP method of called API\r
233          *\r
234          * API endpoints can define which HTTP method to accept when called.\r
235          * This function check the current HTTP method agains endpoint\r
236          * registered method.\r
237          *\r
238          * @param string $method Required methods, uppercase, separated by comma\r
239          * @return bool\r
240          */\r
241          function api_check_method($method) {\r
242                 if ($method=="*") return True;\r
243                 return strpos($method, $_SERVER['REQUEST_METHOD']) !== false;\r
244          }\r
245 \r
246         /**\r
247          * @brief Main API entry point\r
248          *\r
249          * Authenticate user, call registered API function, set HTTP headers\r
250          *\r
251          * @param App $a\r
252          * @return string API call result\r
253          */\r
254         function api_call(&$a){\r
255                 GLOBAL $API, $called_api;\r
256 \r
257                 $type="json";\r
258                 if (strpos($a->query_string, ".xml")>0) $type="xml";\r
259                 if (strpos($a->query_string, ".json")>0) $type="json";\r
260                 if (strpos($a->query_string, ".rss")>0) $type="rss";\r
261                 if (strpos($a->query_string, ".atom")>0) $type="atom";\r
262                 try {\r
263                         foreach ($API as $p=>$info){\r
264                                 if (strpos($a->query_string, $p)===0){\r
265                                         if (!api_check_method($info['method'])){\r
266                                                 throw new MethodNotAllowedException();\r
267                                         }\r
268 \r
269                                         $called_api= explode("/",$p);\r
270                                         //unset($_SERVER['PHP_AUTH_USER']);\r
271                                         if ($info['auth']===true && api_user()===false) {\r
272                                                         api_login($a);\r
273                                         }\r
274 \r
275                                         logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);\r
276                                         logger('API parameters: ' . print_r($_REQUEST,true));\r
277 \r
278                                         $stamp =  microtime(true);\r
279                                         $r = call_user_func($info['func'], $type);\r
280                                         $duration = (float)(microtime(true)-$stamp);\r
281                                         logger("API call duration: ".round($duration, 2)."\t".$a->query_string, LOGGER_DEBUG);\r
282 \r
283                                         if ($r===false) {\r
284                                                 // api function returned false withour throw an\r
285                                                 // exception. This should not happend, throw a 500\r
286                                                 throw new InternalServerErrorException();\r
287                                         }\r
288 \r
289                                         switch($type){\r
290                                                 case "xml":\r
291                                                         header ("Content-Type: text/xml");\r
292                                                         return $r;\r
293                                                         break;\r
294                                                 case "json":\r
295                                                         header ("Content-Type: application/json");\r
296                                                         foreach($r as $rr)\r
297                                                                 $json = json_encode($rr);\r
298                                                                 if ($_GET['callback'])\r
299                                                                         $json = $_GET['callback']."(".$json.")";\r
300                                                                 return $json;\r
301                                                         break;\r
302                                                 case "rss":\r
303                                                         header ("Content-Type: application/rss+xml");\r
304                                                         return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;\r
305                                                         break;\r
306                                                 case "atom":\r
307                                                         header ("Content-Type: application/atom+xml");\r
308                                                         return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;\r
309                                                         break;\r
310 \r
311                                         }\r
312                                 }\r
313                         }\r
314                         throw new NotImplementedException();\r
315                 } catch (HTTPException $e) {\r
316                         header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");\r
317                         return api_error($type, $e);\r
318                 }\r
319         }\r
320 \r
321         /**\r
322          * @brief Format API error string\r
323          *\r
324          * @param string $type Return type (xml, json, rss, as)\r
325          * @param HTTPException $error Error object\r
326          * @return strin error message formatted as $type\r
327          */\r
328         function api_error($type, $e) {\r
329 \r
330                 $a = get_app();\r
331 \r
332                 $error = ($e->getMessage()!==""?$e->getMessage():$e->httpdesc);\r
333                 # TODO:  https://dev.twitter.com/overview/api/response-codes\r
334 \r
335                 $error = array("error" => $error,\r
336                                 "code" => $e->httpcode." ".$e->httpdesc,\r
337                                 "request" => $a->query_string);\r
338 \r
339                 $ret = api_format_data('status', $type, array('status' => $error));\r
340 \r
341                 switch($type){\r
342                         case "xml":\r
343                                 header ("Content-Type: text/xml");\r
344                                 return $ret;\r
345                                 break;\r
346                         case "json":\r
347                                 header ("Content-Type: application/json");\r
348                                 return json_encode($ret);\r
349                                 break;\r
350                         case "rss":\r
351                                 header ("Content-Type: application/rss+xml");\r
352                                 return $ret;\r
353                                 break;\r
354                         case "atom":\r
355                                 header ("Content-Type: application/atom+xml");\r
356                                 return $ret;\r
357                                 break;\r
358                 }\r
359         }\r
360 \r
361         /**\r
362          * @brief Set values for RSS template\r
363          *\r
364          * @param App $a\r
365          * @param array $arr Array to be passed to template\r
366          * @param array $user_info\r
367          * @return array\r
368          */\r
369         function api_rss_extra(&$a, $arr, $user_info){\r
370                 if (is_null($user_info)) $user_info = api_get_user($a);\r
371                 $arr['$user'] = $user_info;\r
372                 $arr['$rss'] = array(\r
373                         'alternate' => $user_info['url'],\r
374                         'self' => App::get_baseurl(). "/". $a->query_string,\r
375                         'base' => App::get_baseurl(),\r
376                         'updated' => api_date(null),\r
377                         'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),\r
378                         'language' => $user_info['language'],\r
379                         'logo'  => App::get_baseurl()."/images/friendica-32.png",\r
380                 );\r
381 \r
382                 return $arr;\r
383         }\r
384 \r
385 \r
386         /**\r
387          * @brief Unique contact to contact url.\r
388          *\r
389          * @param int $id Contact id\r
390          * @return bool|string\r
391          *              Contact url or False if contact id is unknown\r
392          */\r
393         function api_unique_id_to_url($id){\r
394                 $r = q("SELECT `url` FROM `gcontact` WHERE `id`=%d LIMIT 1",\r
395                         intval($id));\r
396                 if ($r)\r
397                         return ($r[0]["url"]);\r
398                 else\r
399                         return false;\r
400         }\r
401 \r
402         /**\r
403          * @brief Get user info array.\r
404          *\r
405          * @param Api $a\r
406          * @param int|string $contact_id Contact ID or URL\r
407          * @param string $type Return type (for errors)\r
408          */\r
409         function api_get_user(&$a, $contact_id = Null, $type = "json"){\r
410                 global $called_api;\r
411                 $user = null;\r
412                 $extra_query = "";\r
413                 $url = "";\r
414                 $nick = "";\r
415 \r
416                 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);\r
417 \r
418                 // Searching for contact URL\r
419                 if(!is_null($contact_id) AND (intval($contact_id) == 0)){\r
420                         $user = dbesc(normalise_link($contact_id));\r
421                         $url = $user;\r
422                         $extra_query = "AND `contact`.`nurl` = '%s' ";\r
423                         if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());\r
424                 }\r
425 \r
426                 // Searching for unique contact id\r
427                 if(!is_null($contact_id) AND (intval($contact_id) != 0)){\r
428                         $user = dbesc(api_unique_id_to_url($contact_id));\r
429 \r
430                         if ($user == "")\r
431                                 throw new BadRequestException("User not found.");\r
432 \r
433                         $url = $user;\r
434                         $extra_query = "AND `contact`.`nurl` = '%s' ";\r
435                         if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());\r
436                 }\r
437 \r
438                 if(is_null($user) && x($_GET, 'user_id')) {\r
439                         $user = dbesc(api_unique_id_to_url($_GET['user_id']));\r
440 \r
441                         if ($user == "")\r
442                                 throw new BadRequestException("User not found.");\r
443 \r
444                         $url = $user;\r
445                         $extra_query = "AND `contact`.`nurl` = '%s' ";\r
446                         if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());\r
447                 }\r
448                 if(is_null($user) && x($_GET, 'screen_name')) {\r
449                         $user = dbesc($_GET['screen_name']);\r
450                         $nick = $user;\r
451                         $extra_query = "AND `contact`.`nick` = '%s' ";\r
452                         if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());\r
453                 }\r
454 \r
455                 if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){\r
456                         $argid = count($called_api);\r
457                         list($user, $null) = explode(".",$a->argv[$argid]);\r
458                         if(is_numeric($user)){\r
459                                 $user = dbesc(api_unique_id_to_url($user));\r
460 \r
461                                 if ($user == "")\r
462                                         return false;\r
463 \r
464                                 $url = $user;\r
465                                 $extra_query = "AND `contact`.`nurl` = '%s' ";\r
466                                 if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());\r
467                         } else {\r
468                                 $user = dbesc($user);\r
469                                 $nick = $user;\r
470                                 $extra_query = "AND `contact`.`nick` = '%s' ";\r
471                                 if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());\r
472                         }\r
473                 }\r
474 \r
475                 logger("api_get_user: user ".$user, LOGGER_DEBUG);\r
476 \r
477                 if (!$user) {\r
478                         if (api_user()===false) {\r
479                                 api_login($a);\r
480                                 return False;\r
481                         } else {\r
482                                 $user = $_SESSION['uid'];\r
483                                 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";\r
484                         }\r
485 \r
486                 }\r
487 \r
488                 logger('api_user: ' . $extra_query . ', user: ' . $user);\r
489                 // user info\r
490                 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`\r
491                                 WHERE 1\r
492                                 $extra_query",\r
493                                 $user\r
494                 );\r
495 \r
496                 // Selecting the id by priority, friendica first\r
497                 api_best_nickname($uinfo);\r
498 \r
499                 // if the contact wasn't found, fetch it from the unique contacts\r
500                 if (count($uinfo)==0) {\r
501                         $r = array();\r
502 \r
503                         if ($url != "")\r
504                                 $r = q("SELECT * FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($url)));\r
505 \r
506                         if ($r) {\r
507                                 // If no nick where given, extract it from the address\r
508                                 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick']))\r
509                                         $r[0]['nick'] = api_get_nick($r[0]["url"]);\r
510 \r
511                                 $ret = array(\r
512                                         'id' => $r[0]["id"],\r
513                                         'id_str' => (string) $r[0]["id"],\r
514                                         'name' => $r[0]["name"],\r
515                                         'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),\r
516                                         'location' => $r[0]["location"],\r
517                                         'description' => $r[0]["about"],\r
518                                         'url' => $r[0]["url"],\r
519                                         'protected' => false,\r
520                                         'followers_count' => 0,\r
521                                         'friends_count' => 0,\r
522                                         'listed_count' => 0,\r
523                                         'created_at' => api_date($r[0]["created"]),\r
524                                         'favourites_count' => 0,\r
525                                         'utc_offset' => 0,\r
526                                         'time_zone' => 'UTC',\r
527                                         'geo_enabled' => false,\r
528                                         'verified' => false,\r
529                                         'statuses_count' => 0,\r
530                                         'lang' => '',\r
531                                         'contributors_enabled' => false,\r
532                                         'is_translator' => false,\r
533                                         'is_translation_enabled' => false,\r
534                                         'profile_image_url' => $r[0]["photo"],\r
535                                         'profile_image_url_https' => $r[0]["photo"],\r
536                                         'following' => false,\r
537                                         'follow_request_sent' => false,\r
538                                         'notifications' => false,\r
539                                         'statusnet_blocking' => false,\r
540                                         'notifications' => false,\r
541                                         'statusnet_profile_url' => $r[0]["url"],\r
542                                         'uid' => 0,\r
543                                         'cid' => get_contact($r[0]["url"], api_user()),\r
544                                         'self' => 0,\r
545                                         'network' => $r[0]["network"],\r
546                                 );\r
547 \r
548                                 return $ret;\r
549                         } else {\r
550                                 throw new BadRequestException("User not found.");\r
551                         }\r
552                 }\r
553 \r
554                 if($uinfo[0]['self']) {\r
555 \r
556                         if ($uinfo[0]['network'] == "")\r
557                                 $uinfo[0]['network'] = NETWORK_DFRN;\r
558 \r
559                         $usr = q("select * from user where uid = %d limit 1",\r
560                                 intval(api_user())\r
561                         );\r
562                         $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",\r
563                                 intval(api_user())\r
564                         );\r
565 \r
566                         //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",\r
567                         // count public wall messages\r
568                         $r = q("SELECT count(*) as `count` FROM `item`\r
569                                         WHERE  `uid` = %d\r
570                                         AND `type`='wall'",\r
571                                         intval($uinfo[0]['uid'])\r
572                         );\r
573                         $countitms = $r[0]['count'];\r
574                 }\r
575                 else {\r
576                         //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",\r
577                         $r = q("SELECT count(*) as `count` FROM `item`\r
578                                         WHERE  `contact-id` = %d",\r
579                                         intval($uinfo[0]['id'])\r
580                         );\r
581                         $countitms = $r[0]['count'];\r
582                 }\r
583 \r
584                 // count friends\r
585                 $r = q("SELECT count(*) as `count` FROM `contact`\r
586                                 WHERE  `uid` = %d AND `rel` IN ( %d, %d )\r
587                                 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",\r
588                                 intval($uinfo[0]['uid']),\r
589                                 intval(CONTACT_IS_SHARING),\r
590                                 intval(CONTACT_IS_FRIEND)\r
591                 );\r
592                 $countfriends = $r[0]['count'];\r
593 \r
594                 $r = q("SELECT count(*) as `count` FROM `contact`\r
595                                 WHERE  `uid` = %d AND `rel` IN ( %d, %d )\r
596                                 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",\r
597                                 intval($uinfo[0]['uid']),\r
598                                 intval(CONTACT_IS_FOLLOWER),\r
599                                 intval(CONTACT_IS_FRIEND)\r
600                 );\r
601                 $countfollowers = $r[0]['count'];\r
602 \r
603                 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",\r
604                         intval($uinfo[0]['uid'])\r
605                 );\r
606                 $starred = $r[0]['count'];\r
607 \r
608 \r
609                 if(! $uinfo[0]['self']) {\r
610                         $countfriends = 0;\r
611                         $countfollowers = 0;\r
612                         $starred = 0;\r
613                 }\r
614 \r
615                 // Add a nick if it isn't present there\r
616                 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {\r
617                         $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);\r
618                 }\r
619 \r
620                 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);\r
621 \r
622                 $gcontact_id  = get_gcontact_id(array("url" => $uinfo[0]['url'], "network" => $uinfo[0]['network'],\r
623                                                         "photo" => $uinfo[0]['micro'], "name" => $uinfo[0]['name']));\r
624 \r
625                 $ret = Array(\r
626                         'id' => intval($gcontact_id),\r
627                         'id_str' => (string) intval($gcontact_id),\r
628                         'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),\r
629                         'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),\r
630                         'location' => ($usr) ? $usr[0]['default-location'] : $network_name,\r
631                         'description' => (($profile) ? $profile[0]['pdesc'] : NULL),\r
632                         'profile_image_url' => $uinfo[0]['micro'],\r
633                         'profile_image_url_https' => $uinfo[0]['micro'],\r
634                         'url' => $uinfo[0]['url'],\r
635                         'protected' => false,\r
636                         'followers_count' => intval($countfollowers),\r
637                         'friends_count' => intval($countfriends),\r
638                         'created_at' => api_date($uinfo[0]['created']),\r
639                         'favourites_count' => intval($starred),\r
640                         'utc_offset' => "0",\r
641                         'time_zone' => 'UTC',\r
642                         'statuses_count' => intval($countitms),\r
643                         'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),\r
644                         'verified' => true,\r
645                         'statusnet_blocking' => false,\r
646                         'notifications' => false,\r
647                         //'statusnet_profile_url' => App::get_baseurl()."/contacts/".$uinfo[0]['cid'],\r
648                         'statusnet_profile_url' => $uinfo[0]['url'],\r
649                         'uid' => intval($uinfo[0]['uid']),\r
650                         'cid' => intval($uinfo[0]['cid']),\r
651                         'self' => $uinfo[0]['self'],\r
652                         'network' => $uinfo[0]['network'],\r
653                 );\r
654 \r
655                 return $ret;\r
656 \r
657         }\r
658 \r
659         /**\r
660          * @brief return api-formatted array for item's author and owner\r
661          *\r
662          * @param App $a\r
663          * @param array $item : item from db\r
664          * @return array(array:author, array:owner)\r
665          */\r
666         function api_item_get_user(&$a, $item) {\r
667 \r
668                 // Make sure that there is an entry in the global contacts for author and owner\r
669                 get_gcontact_id(array("url" => $item['author-link'], "network" => $item['network'],\r
670                                         "photo" => $item['author-avatar'], "name" => $item['author-name']));\r
671 \r
672                 get_gcontact_id(array("url" => $item['owner-link'], "network" => $item['network'],\r
673                                         "photo" => $item['owner-avatar'], "name" => $item['owner-name']));\r
674 \r
675                 $status_user = api_get_user($a,$item["author-link"]);\r
676                 $status_user["protected"] = (($item["allow_cid"] != "") OR\r
677                                                 ($item["allow_gid"] != "") OR\r
678                                                 ($item["deny_cid"] != "") OR\r
679                                                 ($item["deny_gid"] != "") OR\r
680                                                 $item["private"]);\r
681 \r
682                 $owner_user = api_get_user($a,$item["owner-link"]);\r
683 \r
684                 return (array($status_user, $owner_user));\r
685         }\r
686 \r
687         /**\r
688          * @brief walks recursively through an array with the possibility to change value and key\r
689          *\r
690          * @param array $array The array to walk through\r
691          * @param string $callback The callback function\r
692          *\r
693          * @return array the transformed array\r
694          */\r
695         function api_walk_recursive(array &$array, callable $callback) {\r
696 \r
697                 $new_array = array();\r
698 \r
699                 foreach ($array as $k => $v) {\r
700                         if (is_array($v)) {\r
701                                 if ($callback($v, $k))\r
702                                         $new_array[$k] = api_walk_recursive($v, $callback);\r
703                         } else {\r
704                                 if ($callback($v, $k))\r
705                                         $new_array[$k] = $v;\r
706                         }\r
707                 }\r
708                 $array = $new_array;\r
709 \r
710                 return $array;\r
711         }\r
712 \r
713         /**\r
714          * @brief Callback function to transform the array in an array that can be transformed in a XML file\r
715          *\r
716          * @param variant $item Array item value\r
717          * @param string $key Array key\r
718          *\r
719          * @return boolean Should the array item be deleted?\r
720          */\r
721         function api_reformat_xml(&$item, &$key) {\r
722                 if (is_bool($item))\r
723                         $item = ($item ? "true" : "false");\r
724 \r
725                 if (substr($key, 0, 10) == "statusnet_")\r
726                         $key = "statusnet:".substr($key, 10);\r
727                 elseif (substr($key, 0, 10) == "friendica_")\r
728                         $key = "friendica:".substr($key, 10);\r
729                 //else\r
730                 //      $key = "default:".$key;\r
731 \r
732                 return true;\r
733         }\r
734 \r
735         /**\r
736          * @brief Creates the XML from a JSON style array\r
737          *\r
738          * @param array $data JSON style array\r
739          * @param string $root_element Name of the root element\r
740          *\r
741          * @return string The XML data\r
742          */\r
743         function api_create_xml($data, $root_element) {\r
744                 $childname = key($data);\r
745                 $data2 = array_pop($data);\r
746                 $key = key($data2);\r
747 \r
748                 $namespaces = array("" => "http://api.twitter.com",\r
749                                         "statusnet" => "http://status.net/schema/api/1/",\r
750                                         "friendica" => "http://friendi.ca/schema/api/1/",\r
751                                         "georss" => "http://www.georss.org/georss");\r
752 \r
753                 /// @todo Auto detection of needed namespaces\r
754                 if (in_array($root_element, array("ok", "hash", "config", "version", "ids", "notes", "photos")))\r
755                         $namespaces = array();\r
756 \r
757                 if (is_array($data2))\r
758                         api_walk_recursive($data2, "api_reformat_xml");\r
759 \r
760                 if ($key == "0") {\r
761                         $data4 = array();\r
762                         $i = 1;\r
763 \r
764                         foreach ($data2 AS $item)\r
765                                 $data4[$i++.":".$childname] = $item;\r
766 \r
767                         $data2 = $data4;\r
768                 }\r
769 \r
770                 $data3 = array($root_element => $data2);\r
771 \r
772                 $ret = xml::from_array($data3, $xml, false, $namespaces);\r
773                 return $ret;\r
774         }\r
775 \r
776         /**\r
777          * @brief Formats the data according to the data type\r
778          *\r
779          * @param string $root_element Name of the root element\r
780          * @param string $type Return type (atom, rss, xml, json)\r
781          * @param array $data JSON style array\r
782          *\r
783          * @return (string|object) XML data or JSON data\r
784          */\r
785         function api_format_data($root_element, $type, $data){\r
786 \r
787                 $a = get_app();\r
788 \r
789                 switch($type){\r
790                         case "atom":\r
791                         case "rss":\r
792                         case "xml":\r
793                                 $ret = api_create_xml($data, $root_element);\r
794                                 break;\r
795                         case "json":\r
796                                 $ret = $data;\r
797                                 break;\r
798                 }\r
799 \r
800                 return $ret;\r
801         }\r
802 \r
803         /**\r
804          ** TWITTER API\r
805          */\r
806 \r
807         /**\r
808          * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;\r
809          * returns a 401 status code and an error message if not.\r
810          * http://developer.twitter.com/doc/get/account/verify_credentials\r
811          */\r
812         function api_account_verify_credentials($type){\r
813 \r
814                 $a = get_app();\r
815 \r
816                 if (api_user()===false) throw new ForbiddenException();\r
817 \r
818                 unset($_REQUEST["user_id"]);\r
819                 unset($_GET["user_id"]);\r
820 \r
821                 unset($_REQUEST["screen_name"]);\r
822                 unset($_GET["screen_name"]);\r
823 \r
824                 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);\r
825 \r
826                 $user_info = api_get_user($a);\r
827 \r
828                 // "verified" isn't used here in the standard\r
829                 unset($user_info["verified"]);\r
830 \r
831                 // - Adding last status\r
832                 if (!$skip_status) {\r
833                         $user_info["status"] = api_status_show("raw");\r
834                         if (!count($user_info["status"]))\r
835                                 unset($user_info["status"]);\r
836                         else\r
837                                 unset($user_info["status"]["user"]);\r
838                 }\r
839 \r
840                 // "uid" and "self" are only needed for some internal stuff, so remove it from here\r
841                 unset($user_info["uid"]);\r
842                 unset($user_info["self"]);\r
843 \r
844                 return api_format_data("user", $type, array('user' => $user_info));\r
845 \r
846         }\r
847         api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);\r
848 \r
849 \r
850         /**\r
851          * get data from $_POST or $_GET\r
852          */\r
853         function requestdata($k){\r
854                 if (isset($_POST[$k])){\r
855                         return $_POST[$k];\r
856                 }\r
857                 if (isset($_GET[$k])){\r
858                         return $_GET[$k];\r
859                 }\r
860                 return null;\r
861         }\r
862 \r
863 /*Waitman Gobble Mod*/\r
864         function api_statuses_mediap($type) {\r
865 \r
866                 $a = get_app();\r
867 \r
868                 if (api_user()===false) {\r
869                         logger('api_statuses_update: no user');\r
870                         throw new ForbiddenException();\r
871                 }\r
872                 $user_info = api_get_user($a);\r
873 \r
874                 $_REQUEST['type'] = 'wall';\r
875                 $_REQUEST['profile_uid'] = api_user();\r
876                 $_REQUEST['api_source'] = true;\r
877                 $txt = requestdata('status');\r
878                 //$txt = urldecode(requestdata('status'));\r
879 \r
880                 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {\r
881 \r
882                         $txt = html2bb_video($txt);\r
883                         $config = HTMLPurifier_Config::createDefault();\r
884                         $config->set('Cache.DefinitionImpl', null);\r
885                         $purifier = new HTMLPurifier($config);\r
886                         $txt = $purifier->purify($txt);\r
887                 }\r
888                 $txt = html2bbcode($txt);\r
889 \r
890                 $a->argv[1]=$user_info['screen_name']; //should be set to username?\r
891 \r
892                 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo\r
893                 $bebop = wall_upload_post($a);\r
894 \r
895                 //now that we have the img url in bbcode we can add it to the status and insert the wall item.\r
896                 $_REQUEST['body']=$txt."\n\n".$bebop;\r
897                 item_post($a);\r
898 \r
899                 // this should output the last post (the one we just posted).\r
900                 return api_status_show($type);\r
901         }\r
902         api_register_func('api/statuses/mediap','api_statuses_mediap', true, API_METHOD_POST);\r
903 /*Waitman Gobble Mod*/\r
904 \r
905 \r
906         function api_statuses_update($type) {\r
907 \r
908                 $a = get_app();\r
909 \r
910                 if (api_user()===false) {\r
911                         logger('api_statuses_update: no user');\r
912                         throw new ForbiddenException();\r
913                 }\r
914 \r
915                 $user_info = api_get_user($a);\r
916 \r
917                 // convert $_POST array items to the form we use for web posts.\r
918 \r
919                 // logger('api_post: ' . print_r($_POST,true));\r
920 \r
921                 if(requestdata('htmlstatus')) {\r
922                         $txt = requestdata('htmlstatus');\r
923                         if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {\r
924                                 $txt = html2bb_video($txt);\r
925 \r
926                                 $config = HTMLPurifier_Config::createDefault();\r
927                                 $config->set('Cache.DefinitionImpl', null);\r
928 \r
929                                 $purifier = new HTMLPurifier($config);\r
930                                 $txt = $purifier->purify($txt);\r
931 \r
932                                 $_REQUEST['body'] = html2bbcode($txt);\r
933                         }\r
934 \r
935                 } else\r
936                         $_REQUEST['body'] = requestdata('status');\r
937 \r
938                 $_REQUEST['title'] = requestdata('title');\r
939 \r
940                 $parent = requestdata('in_reply_to_status_id');\r
941 \r
942                 // Twidere sends "-1" if it is no reply ...\r
943                 if ($parent == -1)\r
944                         $parent = "";\r
945 \r
946                 if(ctype_digit($parent))\r
947                         $_REQUEST['parent'] = $parent;\r
948                 else\r
949                         $_REQUEST['parent_uri'] = $parent;\r
950 \r
951                 if(requestdata('lat') && requestdata('long'))\r
952                         $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));\r
953                 $_REQUEST['profile_uid'] = api_user();\r
954 \r
955                 if($parent)\r
956                         $_REQUEST['type'] = 'net-comment';\r
957                 else {\r
958                         // Check for throttling (maximum posts per day, week and month)\r
959                         $throttle_day = get_config('system','throttle_limit_day');\r
960                         if ($throttle_day > 0) {\r
961                                 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);\r
962 \r
963                                 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`\r
964                                         AND `created` > '%s' AND `id` = `parent`",\r
965                                         intval(api_user()), dbesc($datefrom));\r
966 \r
967                                 if ($r)\r
968                                         $posts_day = $r[0]["posts_day"];\r
969                                 else\r
970                                         $posts_day = 0;\r
971 \r
972                                 if ($posts_day > $throttle_day) {\r
973                                         logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);\r
974                                         #die(api_error($type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));\r
975                                         throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));\r
976                                 }\r
977                         }\r
978 \r
979                         $throttle_week = get_config('system','throttle_limit_week');\r
980                         if ($throttle_week > 0) {\r
981                                 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);\r
982 \r
983                                 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`\r
984                                         AND `created` > '%s' AND `id` = `parent`",\r
985                                         intval(api_user()), dbesc($datefrom));\r
986 \r
987                                 if ($r)\r
988                                         $posts_week = $r[0]["posts_week"];\r
989                                 else\r
990                                         $posts_week = 0;\r
991 \r
992                                 if ($posts_week > $throttle_week) {\r
993                                         logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);\r
994                                         #die(api_error($type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));\r
995                                         throw new TooManyRequestsException(sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week));\r
996 \r
997                                 }\r
998                         }\r
999 \r
1000                         $throttle_month = get_config('system','throttle_limit_month');\r
1001                         if ($throttle_month > 0) {\r
1002                                 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);\r
1003 \r
1004                                 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`\r
1005                                         AND `created` > '%s' AND `id` = `parent`",\r
1006                                         intval(api_user()), dbesc($datefrom));\r
1007 \r
1008                                 if ($r)\r
1009                                         $posts_month = $r[0]["posts_month"];\r
1010                                 else\r
1011                                         $posts_month = 0;\r
1012 \r
1013                                 if ($posts_month > $throttle_month) {\r
1014                                         logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);\r
1015                                         #die(api_error($type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));\r
1016                                         throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));\r
1017                                 }\r
1018                         }\r
1019 \r
1020                         $_REQUEST['type'] = 'wall';\r
1021                 }\r
1022 \r
1023                 if(x($_FILES,'media')) {\r
1024                         // upload the image if we have one\r
1025                         $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo\r
1026                         $media = wall_upload_post($a);\r
1027                         if(strlen($media)>0)\r
1028                                 $_REQUEST['body'] .= "\n\n".$media;\r
1029                 }\r
1030 \r
1031                 // To-Do: Multiple IDs\r
1032                 if (requestdata('media_ids')) {\r
1033                         $r = q("SELECT `resource-id`, `scale`, `nickname`, `type` FROM `photo` INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN (SELECT `resource-id` FROM `photo` WHERE `id` = %d) AND `scale` > 0 AND `photo`.`uid` = %d ORDER BY `photo`.`width` DESC LIMIT 1",\r
1034                                 intval(requestdata('media_ids')), api_user());\r
1035                         if ($r) {\r
1036                                 $phototypes = Photo::supportedTypes();\r
1037                                 $ext = $phototypes[$r[0]['type']];\r
1038                                 $_REQUEST['body'] .= "\n\n".'[url='.App::get_baseurl().'/photos/'.$r[0]['nickname'].'/image/'.$r[0]['resource-id'].']';\r
1039                                 $_REQUEST['body'] .= '[img]'.App::get_baseurl()."/photo/".$r[0]['resource-id']."-".$r[0]['scale'].".".$ext."[/img][/url]";\r
1040                         }\r
1041                 }\r
1042 \r
1043                 // set this so that the item_post() function is quiet and doesn't redirect or emit json\r
1044 \r
1045                 $_REQUEST['api_source'] = true;\r
1046 \r
1047                 if (!x($_REQUEST, "source"))\r
1048                         $_REQUEST["source"] = api_source();\r
1049 \r
1050                 // call out normal post function\r
1051 \r
1052                 item_post($a);\r
1053 \r
1054                 // this should output the last post (the one we just posted).\r
1055                 return api_status_show($type);\r
1056         }\r
1057         api_register_func('api/statuses/update','api_statuses_update', true, API_METHOD_POST);\r
1058         api_register_func('api/statuses/update_with_media','api_statuses_update', true, API_METHOD_POST);\r
1059 \r
1060 \r
1061         function api_media_upload($type) {\r
1062 \r
1063                 $a = get_app();\r
1064 \r
1065                 if (api_user()===false) {\r
1066                         logger('no user');\r
1067                         throw new ForbiddenException();\r
1068                 }\r
1069 \r
1070                 $user_info = api_get_user($a);\r
1071 \r
1072                 if(!x($_FILES,'media')) {\r
1073                         // Output error\r
1074                         throw new BadRequestException("No media.");\r
1075                 }\r
1076 \r
1077                 $media = wall_upload_post($a, false);\r
1078                 if(!$media) {\r
1079                         // Output error\r
1080                         throw new InternalServerErrorException();\r
1081                 }\r
1082 \r
1083                 $returndata = array();\r
1084                 $returndata["media_id"] = $media["id"];\r
1085                 $returndata["media_id_string"] = (string)$media["id"];\r
1086                 $returndata["size"] = $media["size"];\r
1087                 $returndata["image"] = array("w" => $media["width"],\r
1088                                                 "h" => $media["height"],\r
1089                                                 "image_type" => $media["type"]);\r
1090 \r
1091                 logger("Media uploaded: ".print_r($returndata, true), LOGGER_DEBUG);\r
1092 \r
1093                 return array("media" => $returndata);\r
1094         }\r
1095         api_register_func('api/media/upload','api_media_upload', true, API_METHOD_POST);\r
1096 \r
1097         function api_status_show($type){\r
1098 \r
1099                 $a = get_app();\r
1100 \r
1101                 $user_info = api_get_user($a);\r
1102 \r
1103                 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);\r
1104 \r
1105                 if ($type == "raw")\r
1106                         $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";\r
1107                 else\r
1108                         $privacy_sql = "";\r
1109 \r
1110                 // get last public wall message\r
1111                 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`\r
1112                                 FROM `item`, `item` as `i`\r
1113                                 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d\r
1114                                         AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))\r
1115                                         AND `i`.`id` = `item`.`parent`\r
1116                                         AND `item`.`type`!='activity' $privacy_sql\r
1117                                 ORDER BY `item`.`id` DESC\r
1118                                 LIMIT 1",\r
1119                                 intval($user_info['cid']),\r
1120                                 intval(api_user()),\r
1121                                 dbesc($user_info['url']),\r
1122                                 dbesc(normalise_link($user_info['url'])),\r
1123                                 dbesc($user_info['url']),\r
1124                                 dbesc(normalise_link($user_info['url']))\r
1125                 );\r
1126 \r
1127                 if (count($lastwall)>0){\r
1128                         $lastwall = $lastwall[0];\r
1129 \r
1130                         $in_reply_to_status_id = NULL;\r
1131                         $in_reply_to_user_id = NULL;\r
1132                         $in_reply_to_status_id_str = NULL;\r
1133                         $in_reply_to_user_id_str = NULL;\r
1134                         $in_reply_to_screen_name = NULL;\r
1135                         if (intval($lastwall['parent']) != intval($lastwall['id'])) {\r
1136                                 $in_reply_to_status_id= intval($lastwall['parent']);\r
1137                                 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);\r
1138 \r
1139                                 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($lastwall['item-author'])));\r
1140                                 if ($r) {\r
1141                                         if ($r[0]['nick'] == "")\r
1142                                                 $r[0]['nick'] = api_get_nick($r[0]["url"]);\r
1143 \r
1144                                         $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);\r
1145                                         $in_reply_to_user_id = intval($r[0]['id']);\r
1146                                         $in_reply_to_user_id_str = (string) intval($r[0]['id']);\r
1147                                 }\r
1148                         }\r
1149 \r
1150                         // There seems to be situation, where both fields are identical:\r
1151                         // https://github.com/friendica/friendica/issues/1010\r
1152                         // This is a bugfix for that.\r
1153                         if (intval($in_reply_to_status_id) == intval($lastwall['id'])) {\r
1154                                 logger('api_status_show: this message should never appear: id: '.$lastwall['id'].' similar to reply-to: '.$in_reply_to_status_id, LOGGER_DEBUG);\r
1155                                 $in_reply_to_status_id = NULL;\r
1156                                 $in_reply_to_user_id = NULL;\r
1157                                 $in_reply_to_status_id_str = NULL;\r
1158                                 $in_reply_to_user_id_str = NULL;\r
1159                                 $in_reply_to_screen_name = NULL;\r
1160                         }\r
1161 \r
1162                         $converted = api_convert_item($lastwall);\r
1163 \r
1164                         if ($type == "xml")\r
1165                                 $geo = "georss:point";\r
1166                         else\r
1167                                 $geo = "geo";\r
1168 \r
1169                         $status_info = array(\r
1170                                 'created_at' => api_date($lastwall['created']),\r
1171                                 'id' => intval($lastwall['id']),\r
1172                                 'id_str' => (string) $lastwall['id'],\r
1173                                 'text' => $converted["text"],\r
1174                                 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),\r
1175                                 'truncated' => false,\r
1176                                 'in_reply_to_status_id' => $in_reply_to_status_id,\r
1177                                 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,\r
1178                                 'in_reply_to_user_id' => $in_reply_to_user_id,\r
1179                                 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,\r
1180                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,\r
1181                                 'user' => $user_info,\r
1182                                 $geo => NULL,\r
1183                                 'coordinates' => "",\r
1184                                 'place' => "",\r
1185                                 'contributors' => "",\r
1186                                 'is_quote_status' => false,\r
1187                                 'retweet_count' => 0,\r
1188                                 'favorite_count' => 0,\r
1189                                 'favorited' => $lastwall['starred'] ? true : false,\r
1190                                 'retweeted' => false,\r
1191                                 'possibly_sensitive' => false,\r
1192                                 'lang' => "",\r
1193                                 'statusnet_html'                => $converted["html"],\r
1194                                 'statusnet_conversation_id'     => $lastwall['parent'],\r
1195                         );\r
1196 \r
1197                         if (count($converted["attachments"]) > 0)\r
1198                                 $status_info["attachments"] = $converted["attachments"];\r
1199 \r
1200                         if (count($converted["entities"]) > 0)\r
1201                                 $status_info["entities"] = $converted["entities"];\r
1202 \r
1203                         if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))\r
1204                                 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);\r
1205                         elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"]))\r
1206                                 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');\r
1207 \r
1208                         // "uid" and "self" are only needed for some internal stuff, so remove it from here\r
1209                         unset($status_info["user"]["uid"]);\r
1210                         unset($status_info["user"]["self"]);\r
1211                 }\r
1212 \r
1213                 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);\r
1214 \r
1215                 if ($type == "raw")\r
1216                         return($status_info);\r
1217 \r
1218                 return  api_format_data("statuses", $type, array('status' => $status_info));\r
1219 \r
1220         }\r
1221 \r
1222 \r
1223 \r
1224 \r
1225 \r
1226         /**\r
1227          * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.\r
1228          * The author's most recent status will be returned inline.\r
1229          * http://developer.twitter.com/doc/get/users/show\r
1230          */\r
1231         function api_users_show($type){\r
1232 \r
1233                 $a = get_app();\r
1234 \r
1235                 $user_info = api_get_user($a);\r
1236                 $lastwall = q("SELECT `item`.*\r
1237                                 FROM `item`\r
1238                                 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`\r
1239                                 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d\r
1240                                         AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))\r
1241                                         AND `type`!='activity'\r
1242                                         AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''\r
1243                                 ORDER BY `id` DESC\r
1244                                 LIMIT 1",\r
1245                                 intval(api_user()),\r
1246                                 dbesc(ACTIVITY_POST),\r
1247                                 intval($user_info['cid']),\r
1248                                 dbesc($user_info['url']),\r
1249                                 dbesc(normalise_link($user_info['url'])),\r
1250                                 dbesc($user_info['url']),\r
1251                                 dbesc(normalise_link($user_info['url']))\r
1252                 );\r
1253 \r
1254                 if (count($lastwall)>0){\r
1255                         $lastwall = $lastwall[0];\r
1256 \r
1257                         $in_reply_to_status_id = NULL;\r
1258                         $in_reply_to_user_id = NULL;\r
1259                         $in_reply_to_status_id_str = NULL;\r
1260                         $in_reply_to_user_id_str = NULL;\r
1261                         $in_reply_to_screen_name = NULL;\r
1262                         if ($lastwall['parent']!=$lastwall['id']) {\r
1263                                 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`\r
1264                                                 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));\r
1265                                 if (count($reply)>0) {\r
1266                                         $in_reply_to_status_id = intval($lastwall['parent']);\r
1267                                         $in_reply_to_status_id_str = (string) intval($lastwall['parent']);\r
1268 \r
1269                                         $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));\r
1270                                         if ($r) {\r
1271                                                 if ($r[0]['nick'] == "")\r
1272                                                         $r[0]['nick'] = api_get_nick($r[0]["url"]);\r
1273 \r
1274                                                 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);\r
1275                                                 $in_reply_to_user_id = intval($r[0]['id']);\r
1276                                                 $in_reply_to_user_id_str = (string) intval($r[0]['id']);\r
1277                                         }\r
1278                                 }\r
1279                         }\r
1280 \r
1281                         $converted = api_convert_item($lastwall);\r
1282 \r
1283                         if ($type == "xml")\r
1284                                 $geo = "georss:point";\r
1285                         else\r
1286                                 $geo = "geo";\r
1287 \r
1288                         $user_info['status'] = array(\r
1289                                 'text' => $converted["text"],\r
1290                                 'truncated' => false,\r
1291                                 'created_at' => api_date($lastwall['created']),\r
1292                                 'in_reply_to_status_id' => $in_reply_to_status_id,\r
1293                                 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,\r
1294                                 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),\r
1295                                 'id' => intval($lastwall['contact-id']),\r
1296                                 'id_str' => (string) $lastwall['contact-id'],\r
1297                                 'in_reply_to_user_id' => $in_reply_to_user_id,\r
1298                                 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,\r
1299                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,\r
1300                                 $geo => NULL,\r
1301                                 'favorited' => $lastwall['starred'] ? true : false,\r
1302                                 'statusnet_html'                => $converted["html"],\r
1303                                 'statusnet_conversation_id'     => $lastwall['parent'],\r
1304                         );\r
1305 \r
1306                         if (count($converted["attachments"]) > 0)\r
1307                                 $user_info["status"]["attachments"] = $converted["attachments"];\r
1308 \r
1309                         if (count($converted["entities"]) > 0)\r
1310                                 $user_info["status"]["entities"] = $converted["entities"];\r
1311 \r
1312                         if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))\r
1313                                 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);\r
1314                         if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"]))\r
1315                                 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');\r
1316 \r
1317                 }\r
1318 \r
1319                 // "uid" and "self" are only needed for some internal stuff, so remove it from here\r
1320                 unset($user_info["uid"]);\r
1321                 unset($user_info["self"]);\r
1322 \r
1323                 return  api_format_data("user", $type, array('user' => $user_info));\r
1324 \r
1325         }\r
1326         api_register_func('api/users/show','api_users_show');\r
1327 \r
1328 \r
1329         function api_users_search($type) {\r
1330 \r
1331                 $a = get_app();\r
1332 \r
1333                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);\r
1334 \r
1335                 $userlist = array();\r
1336 \r
1337                 if (isset($_GET["q"])) {\r
1338                         $r = q("SELECT id FROM `gcontact` WHERE `name`='%s'", dbesc($_GET["q"]));\r
1339                         if (!count($r))\r
1340                                 $r = q("SELECT `id` FROM `gcontact` WHERE `nick`='%s'", dbesc($_GET["q"]));\r
1341 \r
1342                         if (count($r)) {\r
1343                                 $k = 0;\r
1344                                 foreach ($r AS $user) {\r
1345                                         $user_info = api_get_user($a, $user["id"], "json");\r
1346 \r
1347                                         if ($type == "xml")\r
1348                                                 $userlist[$k++.":user"] = $user_info;\r
1349                                         else\r
1350                                                 $userlist[] = $user_info;\r
1351                                 }\r
1352                                 $userlist = array("users" => $userlist);\r
1353                         } else {\r
1354                                 throw new BadRequestException("User not found.");\r
1355                         }\r
1356                 } else {\r
1357                         throw new BadRequestException("User not found.");\r
1358                 }\r
1359                 return api_format_data("users", $type, $userlist);\r
1360         }\r
1361 \r
1362         api_register_func('api/users/search','api_users_search');\r
1363 \r
1364         /**\r
1365          *\r
1366          * http://developer.twitter.com/doc/get/statuses/home_timeline\r
1367          *\r
1368          * TODO: Optional parameters\r
1369          * TODO: Add reply info\r
1370          */\r
1371         function api_statuses_home_timeline($type){\r
1372 \r
1373                 $a = get_app();\r
1374 \r
1375                 if (api_user()===false) throw new ForbiddenException();\r
1376 \r
1377                 unset($_REQUEST["user_id"]);\r
1378                 unset($_GET["user_id"]);\r
1379 \r
1380                 unset($_REQUEST["screen_name"]);\r
1381                 unset($_GET["screen_name"]);\r
1382 \r
1383                 $user_info = api_get_user($a);\r
1384                 // get last newtork messages\r
1385 \r
1386 \r
1387                 // params\r
1388                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);\r
1389                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);\r
1390                 if ($page<0) $page=0;\r
1391                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);\r
1392                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);\r
1393                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);\r
1394                 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);\r
1395                 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);\r
1396 \r
1397                 $start = $page*$count;\r
1398 \r
1399                 $sql_extra = '';\r
1400                 if ($max_id > 0)\r
1401                         $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);\r
1402                 if ($exclude_replies > 0)\r
1403                         $sql_extra .= ' AND `item`.`parent` = `item`.`id`';\r
1404                 if ($conversation_id > 0)\r
1405                         $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);\r
1406 \r
1407                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,\r
1408                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,\r
1409                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,\r
1410                         `contact`.`id` AS `cid`\r
1411                         FROM `item`\r
1412                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`\r
1413                                 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`\r
1414                         WHERE `item`.`uid` = %d AND `verb` = '%s'\r
1415                         AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`\r
1416                         $sql_extra\r
1417                         AND `item`.`id`>%d\r
1418                         ORDER BY `item`.`id` DESC LIMIT %d ,%d ",\r
1419                         intval(api_user()),\r
1420                         dbesc(ACTIVITY_POST),\r
1421                         intval($since_id),\r
1422                         intval($start), intval($count)\r
1423                 );\r
1424 \r
1425                 $ret = api_format_items($r,$user_info, false, $type);\r
1426 \r
1427                 // Set all posts from the query above to seen\r
1428                 $idarray = array();\r
1429                 foreach ($r AS $item)\r
1430                         $idarray[] = intval($item["id"]);\r
1431 \r
1432                 $idlist = implode(",", $idarray);\r
1433 \r
1434                 if ($idlist != "") {\r
1435                         $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);\r
1436 \r
1437                         if ($unseen)\r
1438                                 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);\r
1439                 }\r
1440 \r
1441                 $data = array('status' => $ret);\r
1442                 switch($type){\r
1443                         case "atom":\r
1444                         case "rss":\r
1445                                 $data = api_rss_extra($a, $data, $user_info);\r
1446                                 break;\r
1447                 }\r
1448 \r
1449                 return  api_format_data("statuses", $type, $data);\r
1450         }\r
1451         api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);\r
1452         api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);\r
1453 \r
1454         function api_statuses_public_timeline($type){\r
1455 \r
1456                 $a = get_app();\r
1457 \r
1458                 if (api_user()===false) throw new ForbiddenException();\r
1459 \r
1460                 $user_info = api_get_user($a);\r
1461                 // get last newtork messages\r
1462 \r
1463 \r
1464                 // params\r
1465                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);\r
1466                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);\r
1467                 if ($page<0) $page=0;\r
1468                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);\r
1469                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);\r
1470                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);\r
1471                 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);\r
1472                 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);\r
1473 \r
1474                 $start = $page*$count;\r
1475 \r
1476                 if ($max_id > 0)\r
1477                         $sql_extra = 'AND `item`.`id` <= '.intval($max_id);\r
1478                 if ($exclude_replies > 0)\r
1479                         $sql_extra .= ' AND `item`.`parent` = `item`.`id`';\r
1480                 if ($conversation_id > 0)\r
1481                         $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);\r
1482 \r
1483                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,\r
1484                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,\r
1485                         `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,\r
1486                         `contact`.`id` AS `cid`,\r
1487                         `user`.`nickname`, `user`.`hidewall`\r
1488                         FROM `item`\r
1489                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`\r
1490                                 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`\r
1491                         STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`\r
1492                                 AND NOT `user`.`hidewall`\r
1493                         WHERE `verb` = '%s' AND `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`\r
1494                         AND `item`.`allow_cid` = ''  AND `item`.`allow_gid` = ''\r
1495                         AND `item`.`deny_cid`  = '' AND `item`.`deny_gid`  = ''\r
1496                         AND NOT `item`.`private` AND `item`.`wall`\r
1497                         $sql_extra\r
1498                         AND `item`.`id`>%d\r
1499                         ORDER BY `item`.`id` DESC LIMIT %d, %d ",\r
1500                         dbesc(ACTIVITY_POST),\r
1501                         intval($since_id),\r
1502                         intval($start),\r
1503                         intval($count));\r
1504 \r
1505                 $ret = api_format_items($r,$user_info, false, $type);\r
1506 \r
1507 \r
1508                 $data = array('status' => $ret);\r
1509                 switch($type){\r
1510                         case "atom":\r
1511                         case "rss":\r
1512                                 $data = api_rss_extra($a, $data, $user_info);\r
1513                                 break;\r
1514                 }\r
1515 \r
1516                 return  api_format_data("statuses", $type, $data);\r
1517         }\r
1518         api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);\r
1519 \r
1520         /**\r
1521          *\r
1522          */\r
1523         function api_statuses_show($type){\r
1524 \r
1525                 $a = get_app();\r
1526 \r
1527                 if (api_user()===false) throw new ForbiddenException();\r
1528 \r
1529                 $user_info = api_get_user($a);\r
1530 \r
1531                 // params\r
1532                 $id = intval($a->argv[3]);\r
1533 \r
1534                 if ($id == 0)\r
1535                         $id = intval($_REQUEST["id"]);\r
1536 \r
1537                 // Hotot workaround\r
1538                 if ($id == 0)\r
1539                         $id = intval($a->argv[4]);\r
1540 \r
1541                 logger('API: api_statuses_show: '.$id);\r
1542 \r
1543                 $conversation = (x($_REQUEST,'conversation')?1:0);\r
1544 \r
1545                 $sql_extra = '';\r
1546                 if ($conversation)\r
1547                         $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";\r
1548                 else\r
1549                         $sql_extra .= " AND `item`.`id` = %d";\r
1550 \r
1551                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,\r
1552                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,\r
1553                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,\r
1554                         `contact`.`id` AS `cid`\r
1555                         FROM `item`\r
1556                         INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`\r
1557                                 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`\r
1558                         WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`\r
1559                         AND `item`.`uid` = %d AND `item`.`verb` = '%s'\r
1560                         $sql_extra",\r
1561                         intval(api_user()),\r
1562                         dbesc(ACTIVITY_POST),\r
1563                         intval($id)\r
1564                 );\r
1565 \r
1566                 if (!$r) {\r
1567                         throw new BadRequestException("There is no status with this id.");\r
1568                 }\r
1569 \r
1570                 $ret = api_format_items($r,$user_info, false, $type);\r
1571 \r
1572                 if ($conversation) {\r
1573                         $data = array('status' => $ret);\r
1574                         return api_format_data("statuses", $type, $data);\r
1575                 } else {\r
1576                         $data = array('status' => $ret[0]);\r
1577                         return  api_format_data("status", $type, $data);\r
1578                 }\r
1579         }\r
1580         api_register_func('api/statuses/show','api_statuses_show', true);\r
1581 \r
1582 \r
1583         /**\r
1584          *\r
1585          */\r
1586         function api_conversation_show($type){\r
1587 \r
1588                 $a = get_app();\r
1589 \r
1590                 if (api_user()===false) throw new ForbiddenException();\r
1591 \r
1592                 $user_info = api_get_user($a);\r
1593 \r
1594                 // params\r
1595                 $id = intval($a->argv[3]);\r
1596                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);\r
1597                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);\r
1598                 if ($page<0) $page=0;\r
1599                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);\r
1600                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);\r
1601 \r
1602                 $start = $page*$count;\r
1603 \r
1604                 if ($id == 0)\r
1605                         $id = intval($_REQUEST["id"]);\r
1606 \r
1607                 // Hotot workaround\r
1608                 if ($id == 0)\r
1609                         $id = intval($a->argv[4]);\r
1610 \r
1611                 logger('API: api_conversation_show: '.$id);\r
1612 \r
1613                 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));\r
1614                 if ($r)\r
1615                         $id = $r[0]["parent"];\r
1616 \r
1617                 $sql_extra = '';\r
1618 \r
1619                 if ($max_id > 0)\r
1620                         $sql_extra = ' AND `item`.`id` <= '.intval($max_id);\r
1621 \r
1622                 // Not sure why this query was so complicated. We should keep it here for a while,\r
1623                 // just to make sure that we really don't need it.\r
1624                 //      FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`\r
1625                 //      ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)\r
1626 \r
1627                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,\r
1628                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,\r
1629                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,\r
1630                         `contact`.`id` AS `cid`\r
1631                         FROM `item`\r
1632                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`\r
1633                                 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`\r
1634                         WHERE `item`.`parent` = %d AND `item`.`visible`\r
1635                         AND NOT `item`.`moderated` AND NOT `item`.`deleted`\r
1636                         AND `item`.`uid` = %d AND `item`.`verb` = '%s'\r
1637                         AND `item`.`id`>%d $sql_extra\r
1638                         ORDER BY `item`.`id` DESC LIMIT %d ,%d",\r
1639                         intval($id), intval(api_user()),\r
1640                         dbesc(ACTIVITY_POST),\r
1641                         intval($since_id),\r
1642                         intval($start), intval($count)\r
1643                 );\r
1644 \r
1645                 if (!$r)\r
1646                         throw new BadRequestException("There is no conversation with this id.");\r
1647 \r
1648                 $ret = api_format_items($r,$user_info, false, $type);\r
1649 \r
1650                 $data = array('status' => $ret);\r
1651                 return api_format_data("statuses", $type, $data);\r
1652         }\r
1653         api_register_func('api/conversation/show','api_conversation_show', true);\r
1654         api_register_func('api/statusnet/conversation','api_conversation_show', true);\r
1655 \r
1656 \r
1657         /**\r
1658          *\r
1659          */\r
1660         function api_statuses_repeat($type){\r
1661                 global $called_api;\r
1662 \r
1663                 $a = get_app();\r
1664 \r
1665                 if (api_user()===false) throw new ForbiddenException();\r
1666 \r
1667                 $user_info = api_get_user($a);\r
1668 \r
1669                 // params\r
1670                 $id = intval($a->argv[3]);\r
1671 \r
1672                 if ($id == 0)\r
1673                         $id = intval($_REQUEST["id"]);\r
1674 \r
1675                 // Hotot workaround\r
1676                 if ($id == 0)\r
1677                         $id = intval($a->argv[4]);\r
1678 \r
1679                 logger('API: api_statuses_repeat: '.$id);\r
1680 \r
1681                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,\r
1682                         `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,\r
1683                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,\r
1684                         `contact`.`id` AS `cid`\r
1685                         FROM `item`\r
1686                         INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`\r
1687                                 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`\r
1688                         WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`\r
1689                         AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow`.`gid` = ''\r
1690                         AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''\r
1691                         $sql_extra\r
1692                         AND `item`.`id`=%d",\r
1693                         intval($id)\r
1694                 );\r
1695 \r
1696                 if ($r[0]['body'] != "") {\r
1697                         if (!intval(get_config('system','old_share'))) {\r
1698                                 if (strpos($r[0]['body'], "[/share]") !== false) {\r
1699                                         $pos = strpos($r[0]['body'], "[share");\r
1700                                         $post = substr($r[0]['body'], $pos);\r
1701                                 } else {\r
1702                                         $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);\r
1703 \r
1704                                         $post .= $r[0]['body'];\r
1705                                         $post .= "[/share]";\r
1706                                 }\r
1707                                 $_REQUEST['body'] = $post;\r
1708                         } else\r
1709                                 $_REQUEST['body'] = html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];\r
1710 \r
1711                         $_REQUEST['profile_uid'] = api_user();\r
1712                         $_REQUEST['type'] = 'wall';\r
1713                         $_REQUEST['api_source'] = true;\r
1714 \r
1715                         if (!x($_REQUEST, "source"))\r
1716                                 $_REQUEST["source"] = api_source();\r
1717 \r
1718                         item_post($a);\r
1719                 } else\r
1720                         throw new ForbiddenException();\r
1721 \r
1722                 // this should output the last post (the one we just posted).\r
1723                 $called_api = null;\r
1724                 return(api_status_show($type));\r
1725         }\r
1726         api_register_func('api/statuses/retweet','api_statuses_repeat', true, API_METHOD_POST);\r
1727 \r
1728         /**\r
1729          *\r
1730          */\r
1731         function api_statuses_destroy($type){\r
1732 \r
1733                 $a = get_app();\r
1734 \r
1735                 if (api_user()===false) throw new ForbiddenException();\r
1736 \r
1737                 $user_info = api_get_user($a);\r
1738 \r
1739                 // params\r
1740                 $id = intval($a->argv[3]);\r
1741 \r
1742                 if ($id == 0)\r
1743                         $id = intval($_REQUEST["id"]);\r
1744 \r
1745                 // Hotot workaround\r
1746                 if ($id == 0)\r
1747                         $id = intval($a->argv[4]);\r
1748 \r
1749                 logger('API: api_statuses_destroy: '.$id);\r
1750 \r
1751                 $ret = api_statuses_show($type);\r
1752 \r
1753                 drop_item($id, false);\r
1754 \r
1755                 return($ret);\r
1756         }\r
1757         api_register_func('api/statuses/destroy','api_statuses_destroy', true, API_METHOD_DELETE);\r
1758 \r
1759         /**\r
1760          *\r
1761          * http://developer.twitter.com/doc/get/statuses/mentions\r
1762          *\r
1763          */\r
1764         function api_statuses_mentions($type){\r
1765 \r
1766                 $a = get_app();\r
1767 \r
1768                 if (api_user()===false) throw new ForbiddenException();\r
1769 \r
1770                 unset($_REQUEST["user_id"]);\r
1771                 unset($_GET["user_id"]);\r
1772 \r
1773                 unset($_REQUEST["screen_name"]);\r
1774                 unset($_GET["screen_name"]);\r
1775 \r
1776                 $user_info = api_get_user($a);\r
1777                 // get last newtork messages\r
1778 \r
1779 \r
1780                 // params\r
1781                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);\r
1782                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);\r
1783                 if ($page<0) $page=0;\r
1784                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);\r
1785                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);\r
1786                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);\r
1787 \r
1788                 $start = $page*$count;\r
1789 \r
1790                 // Ugly code - should be changed\r
1791                 $myurl = App::get_baseurl() . '/profile/'. $a->user['nickname'];\r
1792                 $myurl = substr($myurl,strpos($myurl,'://')+3);\r
1793                 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);\r
1794                 $myurl = str_replace('www.','',$myurl);\r
1795                 $diasp_url = str_replace('/profile/','/u/',$myurl);\r
1796 \r
1797                 if ($max_id > 0)\r
1798                         $sql_extra = ' AND `item`.`id` <= '.intval($max_id);\r
1799 \r
1800                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,\r
1801                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,\r
1802                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,\r
1803                         `contact`.`id` AS `cid`\r
1804                         FROM `item` FORCE INDEX (`uid_id`)\r
1805                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`\r
1806                                 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`\r
1807                         WHERE `item`.`uid` = %d AND `verb` = '%s'\r
1808                         AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))\r
1809                         AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`\r
1810                         AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)\r
1811                         $sql_extra\r
1812                         AND `item`.`id`>%d\r
1813                         ORDER BY `item`.`id` DESC LIMIT %d ,%d ",\r
1814                         intval(api_user()),\r
1815                         dbesc(ACTIVITY_POST),\r
1816                         dbesc(protect_sprintf($myurl)),\r
1817                         dbesc(protect_sprintf($myurl)),\r
1818                         intval(api_user()),\r
1819                         intval($since_id),\r
1820                         intval($start), intval($count)\r
1821                 );\r
1822 \r
1823                 $ret = api_format_items($r,$user_info, false, $type);\r
1824 \r
1825 \r
1826                 $data = array('status' => $ret);\r
1827                 switch($type){\r
1828                         case "atom":\r
1829                         case "rss":\r
1830                                 $data = api_rss_extra($a, $data, $user_info);\r
1831                                 break;\r
1832                 }\r
1833 \r
1834                 return  api_format_data("statuses", $type, $data);\r
1835         }\r
1836         api_register_func('api/statuses/mentions','api_statuses_mentions', true);\r
1837         api_register_func('api/statuses/replies','api_statuses_mentions', true);\r
1838 \r
1839 \r
1840         function api_statuses_user_timeline($type){\r
1841 \r
1842                 $a = get_app();\r
1843 \r
1844                 if (api_user()===false) throw new ForbiddenException();\r
1845 \r
1846                 $user_info = api_get_user($a);\r
1847                 // get last network messages\r
1848 \r
1849                 logger("api_statuses_user_timeline: api_user: ". api_user() .\r
1850                            "\nuser_info: ".print_r($user_info, true) .\r
1851                            "\n_REQUEST:  ".print_r($_REQUEST, true),\r
1852                            LOGGER_DEBUG);\r
1853 \r
1854                 // params\r
1855                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);\r
1856                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);\r
1857                 if ($page<0) $page=0;\r
1858                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);\r
1859                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);\r
1860                 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);\r
1861                 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);\r
1862 \r
1863                 $start = $page*$count;\r
1864 \r
1865                 $sql_extra = '';\r
1866                 if ($user_info['self']==1)\r
1867                         $sql_extra .= " AND `item`.`wall` = 1 ";\r
1868 \r
1869                 if ($exclude_replies > 0)\r
1870                         $sql_extra .= ' AND `item`.`parent` = `item`.`id`';\r
1871                 if ($conversation_id > 0)\r
1872                         $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);\r
1873 \r
1874                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,\r
1875                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,\r
1876                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,\r
1877                         `contact`.`id` AS `cid`\r
1878                         FROM `item` FORCE INDEX (`uid_contactid_id`)\r
1879                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`\r
1880                                 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`\r
1881                         WHERE `item`.`uid` = %d AND `verb` = '%s'\r
1882                         AND `item`.`contact-id` = %d\r
1883                         AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`\r
1884                         $sql_extra\r
1885                         AND `item`.`id`>%d\r
1886                         ORDER BY `item`.`id` DESC LIMIT %d ,%d ",\r
1887                         intval(api_user()),\r
1888                         dbesc(ACTIVITY_POST),\r
1889                         intval($user_info['cid']),\r
1890                         intval($since_id),\r
1891                         intval($start), intval($count)\r
1892                 );\r
1893 \r
1894                 $ret = api_format_items($r,$user_info, true, $type);\r
1895 \r
1896                 $data = array('status' => $ret);\r
1897                 switch($type){\r
1898                         case "atom":\r
1899                         case "rss":\r
1900                                 $data = api_rss_extra($a, $data, $user_info);\r
1901                 }\r
1902 \r
1903                 return  api_format_data("statuses", $type, $data);\r
1904         }\r
1905         api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);\r
1906 \r
1907 \r
1908         /**\r
1909          * Star/unstar an item\r
1910          * param: id : id of the item\r
1911          *\r
1912          * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid\r
1913          */\r
1914         function api_favorites_create_destroy($type){\r
1915 \r
1916                 $a = get_app();\r
1917 \r
1918                 if (api_user()===false) throw new ForbiddenException();\r
1919 \r
1920                 // for versioned api.\r
1921                 /// @TODO We need a better global soluton\r
1922                 $action_argv_id=2;\r
1923                 if ($a->argv[1]=="1.1") $action_argv_id=3;\r
1924 \r
1925                 if ($a->argc<=$action_argv_id) throw new BadRequestException("Invalid request.");\r
1926                 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);\r
1927                 if ($a->argc==$action_argv_id+2) {\r
1928                         $itemid = intval($a->argv[$action_argv_id+1]);\r
1929                 } else {\r
1930                         $itemid = intval($_REQUEST['id']);\r
1931                 }\r
1932 \r
1933                 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",\r
1934                                 $itemid, api_user());\r
1935 \r
1936                 if ($item===false || count($item)==0)\r
1937                         throw new BadRequestException("Invalid item.");\r
1938 \r
1939                 switch($action){\r
1940                         case "create":\r
1941                                 $item[0]['starred']=1;\r
1942                                 break;\r
1943                         case "destroy":\r
1944                                 $item[0]['starred']=0;\r
1945                                 break;\r
1946                         default:\r
1947                                 throw new BadRequestException("Invalid action ".$action);\r
1948                 }\r
1949                 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",\r
1950                                 $item[0]['starred'], $itemid, api_user());\r
1951 \r
1952                 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",\r
1953                         $item[0]['starred'], $itemid, api_user());\r
1954 \r
1955                 if ($r===false)\r
1956                         throw InternalServerErrorException("DB error");\r
1957 \r
1958 \r
1959                 $user_info = api_get_user($a);\r
1960                 $rets = api_format_items($item, $user_info, false, $type);\r
1961                 $ret = $rets[0];\r
1962 \r
1963                 $data = array('status' => $ret);\r
1964                 switch($type){\r
1965                         case "atom":\r
1966                         case "rss":\r
1967                                 $data = api_rss_extra($a, $data, $user_info);\r
1968                 }\r
1969 \r
1970                 return api_format_data("status", $type, $data);\r
1971         }\r
1972         api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);\r
1973         api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);\r
1974 \r
1975         function api_favorites($type){\r
1976                 global $called_api;\r
1977 \r
1978                 $a = get_app();\r
1979 \r
1980                 if (api_user()===false) throw new ForbiddenException();\r
1981 \r
1982                 $called_api= array();\r
1983 \r
1984                 $user_info = api_get_user($a);\r
1985 \r
1986                 // in friendica starred item are private\r
1987                 // return favorites only for self\r
1988                 logger('api_favorites: self:' . $user_info['self']);\r
1989 \r
1990                 if ($user_info['self']==0) {\r
1991                         $ret = array();\r
1992                 } else {\r
1993                         $sql_extra = "";\r
1994 \r
1995                         // params\r
1996                         $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);\r
1997                         $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);\r
1998                         $count = (x($_GET,'count')?$_GET['count']:20);\r
1999                         $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);\r
2000                         if ($page<0) $page=0;\r
2001 \r
2002                         $start = $page*$count;\r
2003 \r
2004                         if ($max_id > 0)\r
2005                                 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);\r
2006 \r
2007                         $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,\r
2008                                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,\r
2009                                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,\r
2010                                 `contact`.`id` AS `cid`\r
2011                                 FROM `item`, `contact`\r
2012                                 WHERE `item`.`uid` = %d\r
2013                                 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0\r
2014                                 AND `item`.`starred` = 1\r
2015                                 AND `contact`.`id` = `item`.`contact-id`\r
2016                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0\r
2017                                 $sql_extra\r
2018                                 AND `item`.`id`>%d\r
2019                                 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",\r
2020                                 intval(api_user()),\r
2021                                 intval($since_id),\r
2022                                 intval($start), intval($count)\r
2023                         );\r
2024 \r
2025                         $ret = api_format_items($r,$user_info, false, $type);\r
2026 \r
2027                 }\r
2028 \r
2029                 $data = array('status' => $ret);\r
2030                 switch($type){\r
2031                         case "atom":\r
2032                         case "rss":\r
2033                                 $data = api_rss_extra($a, $data, $user_info);\r
2034                 }\r
2035 \r
2036                 return  api_format_data("statuses", $type, $data);\r
2037         }\r
2038         api_register_func('api/favorites','api_favorites', true);\r
2039 \r
2040         function api_format_messages($item, $recipient, $sender) {\r
2041                 // standard meta information\r
2042                 $ret=Array(\r
2043                                 'id'                    => $item['id'],\r
2044                                 'sender_id'             => $sender['id'] ,\r
2045                                 'text'                  => "",\r
2046                                 'recipient_id'          => $recipient['id'],\r
2047                                 'created_at'            => api_date($item['created']),\r
2048                                 'sender_screen_name'    => $sender['screen_name'],\r
2049                                 'recipient_screen_name' => $recipient['screen_name'],\r
2050                                 'sender'                => $sender,\r
2051                                 'recipient'             => $recipient,\r
2052                                 'title'                 => "",\r
2053                                 'friendica_seen'        => $item['seen'],\r
2054                                 'friendica_parent_uri'  => $item['parent-uri'],\r
2055                 );\r
2056 \r
2057                 // "uid" and "self" are only needed for some internal stuff, so remove it from here\r
2058                 unset($ret["sender"]["uid"]);\r
2059                 unset($ret["sender"]["self"]);\r
2060                 unset($ret["recipient"]["uid"]);\r
2061                 unset($ret["recipient"]["self"]);\r
2062 \r
2063                 //don't send title to regular StatusNET requests to avoid confusing these apps\r
2064                 if (x($_GET, 'getText')) {\r
2065                         $ret['title'] = $item['title'] ;\r
2066                         if ($_GET["getText"] == "html") {\r
2067                                 $ret['text'] = bbcode($item['body'], false, false);\r
2068                         }\r
2069                         elseif ($_GET["getText"] == "plain") {\r
2070                                 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);\r
2071                                 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));\r
2072                         }\r
2073                 }\r
2074                 else {\r
2075                         $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);\r
2076                 }\r
2077                 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {\r
2078                         unset($ret['sender']);\r
2079                         unset($ret['recipient']);\r
2080                 }\r
2081 \r
2082                 return $ret;\r
2083         }\r
2084 \r
2085         function api_convert_item($item) {\r
2086                 $body = $item['body'];\r
2087                 $attachments = api_get_attachments($body);\r
2088 \r
2089                 // Workaround for ostatus messages where the title is identically to the body\r
2090                 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);\r
2091                 $statusbody = trim(html2plain($html, 0));\r
2092 \r
2093                 // handle data: images\r
2094                 $statusbody = api_format_items_embeded_images($item,$statusbody);\r
2095 \r
2096                 $statustitle = trim($item['title']);\r
2097 \r
2098                 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))\r
2099                         $statustext = trim($statusbody);\r
2100                 else\r
2101                         $statustext = trim($statustitle."\n\n".$statusbody);\r
2102 \r
2103                 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))\r
2104                         $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];\r
2105 \r
2106                 $statushtml = trim(bbcode($body, false, false));\r
2107 \r
2108                 $search = array("<br>", "<blockquote>", "</blockquote>",\r
2109                                 "<h1>", "</h1>", "<h2>", "</h2>",\r
2110                                 "<h3>", "</h3>", "<h4>", "</h4>",\r
2111                                 "<h5>", "</h5>", "<h6>", "</h6>");\r
2112                 $replace = array("<br>\n", "\n<blockquote>", "</blockquote>\n",\r
2113                                 "\n<h1>", "</h1>\n", "\n<h2>", "</h2>\n",\r
2114                                 "\n<h3>", "</h3>\n", "\n<h4>", "</h4>\n",\r
2115                                 "\n<h5>", "</h5>\n", "\n<h6>", "</h6>\n");\r
2116                 $statushtml = str_replace($search, $replace, $statushtml);\r
2117 \r
2118                 if ($item['title'] != "")\r
2119                         $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;\r
2120 \r
2121                 $entities = api_get_entitities($statustext, $body);\r
2122 \r
2123                 return array(\r
2124                         "text" => $statustext,\r
2125                         "html" => $statushtml,\r
2126                         "attachments" => $attachments,\r
2127                         "entities" => $entities\r
2128                 );\r
2129         }\r
2130 \r
2131         function api_get_attachments(&$body) {\r
2132 \r
2133                 $text = $body;\r
2134                 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);\r
2135 \r
2136                 $URLSearchString = "^\[\]";\r
2137                 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);\r
2138 \r
2139                 if (!$ret)\r
2140                         return false;\r
2141 \r
2142                 $attachments = array();\r
2143 \r
2144                 foreach ($images[1] AS $image) {\r
2145                         $imagedata = get_photo_info($image);\r
2146 \r
2147                         if ($imagedata)\r
2148                                 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);\r
2149                 }\r
2150 \r
2151                 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))\r
2152                         foreach ($images[0] AS $orig)\r
2153                                 $body = str_replace($orig, "", $body);\r
2154 \r
2155                 return $attachments;\r
2156         }\r
2157 \r
2158         function api_get_entitities(&$text, $bbcode) {\r
2159                 /*\r
2160                 To-Do:\r
2161                 * Links at the first character of the post\r
2162                 */\r
2163 \r
2164                 $a = get_app();\r
2165 \r
2166                 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");\r
2167 \r
2168                 if ($include_entities != "true") {\r
2169 \r
2170                         preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);\r
2171 \r
2172                         foreach ($images[1] AS $image) {\r
2173                                 $replace = proxy_url($image);\r
2174                                 $text = str_replace($image, $replace, $text);\r
2175                         }\r
2176                         return array();\r
2177                 }\r
2178 \r
2179                 $bbcode = bb_CleanPictureLinks($bbcode);\r
2180 \r
2181                 // Change pure links in text to bbcode uris\r
2182                 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);\r
2183 \r
2184                 $entities = array();\r
2185                 $entities["hashtags"] = array();\r
2186                 $entities["symbols"] = array();\r
2187                 $entities["urls"] = array();\r
2188                 $entities["user_mentions"] = array();\r
2189 \r
2190                 $URLSearchString = "^\[\]";\r
2191 \r
2192                 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);\r
2193 \r
2194                 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);\r
2195                 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);\r
2196                 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);\r
2197 \r
2198                 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",\r
2199                                         '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);\r
2200                 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);\r
2201 \r
2202                 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",\r
2203                                         '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);\r
2204                 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);\r
2205 \r
2206                 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);\r
2207 \r
2208                 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);\r
2209                 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);\r
2210 \r
2211                 $ordered_urls = array();\r
2212                 foreach ($urls[1] AS $id=>$url) {\r
2213                         //$start = strpos($text, $url, $offset);\r
2214                         $start = iconv_strpos($text, $url, 0, "UTF-8");\r
2215                         if (!($start === false))\r
2216                                 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);\r
2217                 }\r
2218 \r
2219                 ksort($ordered_urls);\r
2220 \r
2221                 $offset = 0;\r
2222                 //foreach ($urls[1] AS $id=>$url) {\r
2223                 foreach ($ordered_urls AS $url) {\r
2224                         if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND\r
2225                                 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))\r
2226                                 $display_url = $url["title"];\r
2227                         else {\r
2228                                 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);\r
2229                                 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);\r
2230 \r
2231                                 if (strlen($display_url) > 26)\r
2232                                         $display_url = substr($display_url, 0, 25)."…";\r
2233                         }\r
2234 \r
2235                         //$start = strpos($text, $url, $offset);\r
2236                         $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");\r
2237                         if (!($start === false)) {\r
2238                                 $entities["urls"][] = array("url" => $url["url"],\r
2239                                                                 "expanded_url" => $url["url"],\r
2240                                                                 "display_url" => $display_url,\r
2241                                                                 "indices" => array($start, $start+strlen($url["url"])));\r
2242                                 $offset = $start + 1;\r
2243                         }\r
2244                 }\r
2245 \r
2246                 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);\r
2247                 $ordered_images = array();\r
2248                 foreach ($images[1] AS $image) {\r
2249                         //$start = strpos($text, $url, $offset);\r
2250                         $start = iconv_strpos($text, $image, 0, "UTF-8");\r
2251                         if (!($start === false))\r
2252                                 $ordered_images[$start] = $image;\r
2253                 }\r
2254                 //$entities["media"] = array();\r
2255                 $offset = 0;\r
2256 \r
2257                 foreach ($ordered_images AS $url) {\r
2258                         $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);\r
2259                         $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);\r
2260 \r
2261                         if (strlen($display_url) > 26)\r
2262                                 $display_url = substr($display_url, 0, 25)."…";\r
2263 \r
2264                         $start = iconv_strpos($text, $url, $offset, "UTF-8");\r
2265                         if (!($start === false)) {\r
2266                                 $image = get_photo_info($url);\r
2267                                 if ($image) {\r
2268                                         // If image cache is activated, then use the following sizes:\r
2269                                         // thumb  (150), small (340), medium (600) and large (1024)\r
2270                                         if (!get_config("system", "proxy_disabled")) {\r
2271                                                 $media_url = proxy_url($url);\r
2272 \r
2273                                                 $sizes = array();\r
2274                                                 $scale = scale_image($image[0], $image[1], 150);\r
2275                                                 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");\r
2276 \r
2277                                                 if (($image[0] > 150) OR ($image[1] > 150)) {\r
2278                                                         $scale = scale_image($image[0], $image[1], 340);\r
2279                                                         $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");\r
2280                                                 }\r
2281 \r
2282                                                 $scale = scale_image($image[0], $image[1], 600);\r
2283                                                 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");\r
2284 \r
2285                                                 if (($image[0] > 600) OR ($image[1] > 600)) {\r
2286                                                         $scale = scale_image($image[0], $image[1], 1024);\r
2287                                                         $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");\r
2288                                                 }\r
2289                                         } else {\r
2290                                                 $media_url = $url;\r
2291                                                 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");\r
2292                                         }\r
2293 \r
2294                                         $entities["media"][] = array(\r
2295                                                                 "id" => $start+1,\r
2296                                                                 "id_str" => (string)$start+1,\r
2297                                                                 "indices" => array($start, $start+strlen($url)),\r
2298                                                                 "media_url" => normalise_link($media_url),\r
2299                                                                 "media_url_https" => $media_url,\r
2300                                                                 "url" => $url,\r
2301                                                                 "display_url" => $display_url,\r
2302                                                                 "expanded_url" => $url,\r
2303                                                                 "type" => "photo",\r
2304                                                                 "sizes" => $sizes);\r
2305                                 }\r
2306                                 $offset = $start + 1;\r
2307                         }\r
2308                 }\r
2309 \r
2310                 return($entities);\r
2311         }\r
2312         function api_format_items_embeded_images(&$item, $text){\r
2313                 $text = preg_replace_callback(\r
2314                                 "|data:image/([^;]+)[^=]+=*|m",\r
2315                                 function($match) use ($item) {\r
2316                                         return App::get_baseurl()."/display/".$item['guid'];\r
2317                                 },\r
2318                                 $text);\r
2319                 return $text;\r
2320         }\r
2321 \r
2322 \r
2323         /**\r
2324          * @brief return <a href='url'>name</a> as array\r
2325          *\r
2326          * @param string $txt\r
2327          * @return array\r
2328          *                      name => 'name'\r
2329          *                      'url => 'url'\r
2330          */\r
2331         function api_contactlink_to_array($txt) {\r
2332                 $match = array();\r
2333                 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);\r
2334                 if ($r && count($match)==3) {\r
2335                         $res = array(\r
2336                                 'name' => $match[2],\r
2337                                 'url' => $match[1]\r
2338                         );\r
2339                 } else {\r
2340                         $res = array(\r
2341                                 'name' => $text,\r
2342                                 'url' => ""\r
2343                         );\r
2344                 }\r
2345                 return $res;\r
2346         }\r
2347 \r
2348 \r
2349         /**\r
2350          * @brief return likes, dislikes and attend status for item\r
2351          *\r
2352          * @param array $item\r
2353          * @return array\r
2354          *                      likes => int count\r
2355          *                      dislikes => int count\r
2356          */\r
2357         function api_format_items_activities(&$item, $type = "json") {\r
2358                 $activities = array(\r
2359                         'like' => array(),\r
2360                         'dislike' => array(),\r
2361                         'attendyes' => array(),\r
2362                         'attendno' => array(),\r
2363                         'attendmaybe' => array()\r
2364                 );\r
2365 \r
2366                 $items = q('SELECT * FROM item\r
2367                                         WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',\r
2368                                         intval($item['uid']),\r
2369                                         dbesc($item['uri']));\r
2370 \r
2371                 foreach ($items as $i){\r
2372                         // not used as result should be structured like other user data\r
2373                         //builtin_activity_puller($i, $activities);\r
2374 \r
2375                         // get user data and add it to the array of the activity\r
2376                         $user = api_get_user($a, $i['author-link']);\r
2377                         switch($i['verb']) {\r
2378                                 case ACTIVITY_LIKE:\r
2379                                         $activities['like'][] = $user;\r
2380                                         break;\r
2381                                 case ACTIVITY_DISLIKE:\r
2382                                         $activities['dislike'][] = $user;\r
2383                                         break;\r
2384                                 case ACTIVITY_ATTEND:\r
2385                                         $activities['attendyes'][] = $user;\r
2386                                         break;\r
2387                                 case ACTIVITY_ATTENDNO:\r
2388                                         $activities['attendno'][] = $user;\r
2389                                         break;\r
2390                                 case ACTIVITY_ATTENDMAYBE:\r
2391                                         $activities['attendmaybe'][] = $user;\r
2392                                         break;\r
2393                                 default:\r
2394                                         break;\r
2395                         }\r
2396                 }\r
2397 \r
2398                 if ($type == "xml") {\r
2399                         $xml_activities = array();\r
2400                         foreach ($activities as $k => $v) {\r
2401                                 // change xml element from "like" to "friendica:like"\r
2402                                 $xml_activities["friendica:".$k] = $v;\r
2403                                 // add user data into xml output\r
2404                                 $k_user = 0;\r
2405                                 foreach ($v as $user)\r
2406                                         $xml_activities["friendica:".$k][$k_user++.":user"] = $user;\r
2407                         }\r
2408                         $activities = $xml_activities;\r
2409                 }\r
2410 \r
2411                 return $activities;\r
2412 \r
2413         }\r
2414 \r
2415 \r
2416     /**\r
2417      * @brief return data from profiles\r
2418      *\r
2419      * @param array $profile\r
2420      * @return array\r
2421      */\r
2422         function api_format_items_profiles(&$profile = null, $type = "json") {\r
2423         if ($profile != null) {\r
2424         $profile = array('profile_id' => $profile['id'],\r
2425                         'profile_name' => $profile['profile-name'],\r
2426                         'is_default' => $profile['is-default'] ? true : false,\r
2427                         'hide_friends'=> $profile['hide-friends'] ? true : false,\r
2428                         'profile_photo' => $profile['photo'],\r
2429                         'profile_thumb' => $profile['thumb'],\r
2430                         'publish' => $profile['publish'] ? true : false,\r
2431                         'net_publish' => $profile['net-publish'] ? true : false,\r
2432                         'description' => $profile['pdesc'],\r
2433                         'date_of_birth' => $profile['dob'],\r
2434                         'address' => $profile['address'],\r
2435                         'city' => $profile['locality'],\r
2436                         'region' => $profile['region'],\r
2437                         'postal_code' => $profile['postal-code'],\r
2438                         'country' => $profile['country-name'],\r
2439                         'hometown' => $profile['hometown'],\r
2440                         'gender' => $profile['gender'],\r
2441                         'marital' => $profile['marital'],\r
2442                         'marital_with' => $profile['with'],\r
2443                         'marital_since' => $profile['howlong'],\r
2444                         'sexual' => $profile['sexual'],\r
2445                         'politic' => $profile['politic'],\r
2446                         'religion' => $profile['religion'],\r
2447                         'public_keywords' => $profile['pub_keywords'],\r
2448                         'private_keywords' => $profile['prv_keywords'],\r
2449                         'likes' => bbcode(api_clean_plain_items($profile['likes']), false, false, 2, true),\r
2450                         'dislikes' => bbcode(api_clean_plain_items($profile['dislikes']), false, false, 2, true),\r
2451                         'about' => bbcode(api_clean_plain_items($profile['about']), false, false, 2, true),\r
2452                         'music' => bbcode(api_clean_plain_items($profile['music']), false, false, 2, true),\r
2453                         'book' => bbcode(api_clean_plain_items($profile['book']), false, false, 2, true),\r
2454                         'tv' => bbcode(api_clean_plain_items($profile['tv']), false, false, 2, true),\r
2455                         'film' => bbcode(api_clean_plain_items($profile['film']), false, false, 2, true),\r
2456                         'interest' => bbcode(api_clean_plain_items($profile['interest']), false, false, 2, true),\r
2457                         'romance' => bbcode(api_clean_plain_items($profile['romance']), false, false, 2, true),\r
2458                         'work' => bbcode(api_clean_plain_items($profile['work']), false, false, 2, true),\r
2459                         'education' => bbcode(api_clean_plain_items($profile['education']), false, false, 2, true),\r
2460                         'social_networks' => bbcode(api_clean_plain_items($profile['contact']), false, false, 2, true),\r
2461                         'homepage' => $profile['homepage'],\r
2462                         'users' => null);\r
2463         return $profile;\r
2464         }\r
2465                 if ($type == "xml") {\r
2466                         $xml_activities = array();\r
2467                         foreach ($activities as $k => $v) {\r
2468                                 // change xml element from "like" to "friendica:like"\r
2469                                 $xml_activities["friendica:".$k] = $v;\r
2470                                 // add user data into xml output\r
2471                                 $k_user = 0;\r
2472                                 foreach ($v as $user)\r
2473                                         $xml_activities["friendica:".$k][$k_user++.":user"] = $user;\r
2474                         }\r
2475                         $activities = $xml_activities;\r
2476                 }\r
2477 \r
2478                 return $activities;\r
2479         }\r
2480 \r
2481         /**\r
2482          * @brief format items to be returned by api\r
2483          *\r
2484          * @param array $r array of items\r
2485          * @param array $user_info\r
2486          * @param bool $filter_user filter items by $user_info\r
2487          */\r
2488         function api_format_items($r,$user_info, $filter_user = false, $type = "json") {\r
2489 \r
2490                 $a = get_app();\r
2491 \r
2492                 $ret = Array();\r
2493 \r
2494                 foreach($r as $item) {\r
2495 \r
2496                         localize_item($item);\r
2497                         list($status_user, $owner_user) = api_item_get_user($a,$item);\r
2498 \r
2499                         // Look if the posts are matching if they should be filtered by user id\r
2500                         if ($filter_user AND ($status_user["id"] != $user_info["id"]))\r
2501                                 continue;\r
2502 \r
2503                         if ($item['thr-parent'] != $item['uri']) {\r
2504                                 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",\r
2505                                         intval(api_user()),\r
2506                                         dbesc($item['thr-parent']));\r
2507                                 if ($r)\r
2508                                         $in_reply_to_status_id = intval($r[0]['id']);\r
2509                                 else\r
2510                                         $in_reply_to_status_id = intval($item['parent']);\r
2511 \r
2512                                 $in_reply_to_status_id_str = (string) intval($item['parent']);\r
2513 \r
2514                                 $in_reply_to_screen_name = NULL;\r
2515                                 $in_reply_to_user_id = NULL;\r
2516                                 $in_reply_to_user_id_str = NULL;\r
2517 \r
2518                                 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",\r
2519                                         intval(api_user()),\r
2520                                         intval($in_reply_to_status_id));\r
2521                                 if ($r) {\r
2522                                         $r = q("SELECT * FROM `gcontact` WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));\r
2523 \r
2524                                         if ($r) {\r
2525                                                 if ($r[0]['nick'] == "")\r
2526                                                         $r[0]['nick'] = api_get_nick($r[0]["url"]);\r
2527 \r
2528                                                 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);\r
2529                                                 $in_reply_to_user_id = intval($r[0]['id']);\r
2530                                                 $in_reply_to_user_id_str = (string) intval($r[0]['id']);\r
2531                                         }\r
2532                                 }\r
2533                         } else {\r
2534                                 $in_reply_to_screen_name = NULL;\r
2535                                 $in_reply_to_user_id = NULL;\r
2536                                 $in_reply_to_status_id = NULL;\r
2537                                 $in_reply_to_user_id_str = NULL;\r
2538                                 $in_reply_to_status_id_str = NULL;\r
2539                         }\r
2540 \r
2541                         $converted = api_convert_item($item);\r
2542 \r
2543                         if ($type == "xml")\r
2544                                 $geo = "georss:point";\r
2545                         else\r
2546                                 $geo = "geo";\r
2547 \r
2548                         $status = array(\r
2549                                 'text'          => $converted["text"],\r
2550                                 'truncated' => False,\r
2551                                 'created_at'=> api_date($item['created']),\r
2552                                 'in_reply_to_status_id' => $in_reply_to_status_id,\r
2553                                 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,\r
2554                                 'source'    => (($item['app']) ? $item['app'] : 'web'),\r
2555                                 'id'            => intval($item['id']),\r
2556                                 'id_str'        => (string) intval($item['id']),\r
2557                                 'in_reply_to_user_id' => $in_reply_to_user_id,\r
2558                                 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,\r
2559                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,\r
2560                                 $geo => NULL,\r
2561                                 'favorited' => $item['starred'] ? true : false,\r
2562                                 'user' =>  $status_user ,\r
2563                                 'friendica_owner' => $owner_user,\r
2564                                 //'entities' => NULL,\r
2565                                 'statusnet_html'                => $converted["html"],\r
2566                                 'statusnet_conversation_id'     => $item['parent'],\r
2567                                 'friendica_activities' => api_format_items_activities($item, $type),\r
2568                         );\r
2569 \r
2570                         if (count($converted["attachments"]) > 0)\r
2571                                 $status["attachments"] = $converted["attachments"];\r
2572 \r
2573                         if (count($converted["entities"]) > 0)\r
2574                                 $status["entities"] = $converted["entities"];\r
2575 \r
2576                         if (($item['item_network'] != "") AND ($status["source"] == 'web'))\r
2577                                 $status["source"] = network_to_name($item['item_network'], $user_info['url']);\r
2578                         else if (($item['item_network'] != "") AND (network_to_name($item['item_network'], $user_info['url']) != $status["source"]))\r
2579                                 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');\r
2580 \r
2581 \r
2582                         // Retweets are only valid for top postings\r
2583                         // It doesn't work reliable with the link if its a feed\r
2584                         #$IsRetweet = ($item['owner-link'] != $item['author-link']);\r
2585                         #if ($IsRetweet)\r
2586                         #       $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));\r
2587 \r
2588 \r
2589                         if ($item["id"] == $item["parent"]) {\r
2590                                 $retweeted_item = api_share_as_retweet($item);\r
2591                                 if ($retweeted_item !== false) {\r
2592                                         $retweeted_status = $status;\r
2593                                         try {\r
2594                                                 $retweeted_status["user"] = api_get_user($a,$retweeted_item["author-link"]);\r
2595                                         } catch( BadRequestException $e ) {\r
2596                                                 // user not found. should be found?\r
2597                                                 /// @todo check if the user should be always found\r
2598                                                 $retweeted_status["user"] = array();\r
2599                                         }\r
2600 \r
2601                                         $rt_converted = api_convert_item($retweeted_item);\r
2602 \r
2603                                         $retweeted_status['text'] = $rt_converted["text"];\r
2604                                         $retweeted_status['statusnet_html'] = $rt_converted["html"];\r
2605                                         $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);\r
2606                                         $retweeted_status['created_at'] =  api_date($retweeted_item['created']);\r
2607                                         $status['retweeted_status'] = $retweeted_status;\r
2608                                 }\r
2609                         }\r
2610 \r
2611                         // "uid" and "self" are only needed for some internal stuff, so remove it from here\r
2612                         unset($status["user"]["uid"]);\r
2613                         unset($status["user"]["self"]);\r
2614 \r
2615                         if ($item["coord"] != "") {\r
2616                                 $coords = explode(' ',$item["coord"]);\r
2617                                 if (count($coords) == 2) {\r
2618                                         if ($type == "json")\r
2619                                                 $status["geo"] = array('type' => 'Point',\r
2620                                                                 'coordinates' => array((float) $coords[0],\r
2621                                                                                         (float) $coords[1]));\r
2622                                         else // Not sure if this is the official format - if someone founds a documentation we can check\r
2623                                                 $status["georss:point"] = $item["coord"];\r
2624                                 }\r
2625                         }\r
2626                         $ret[] = $status;\r
2627                 };\r
2628                 return $ret;\r
2629         }\r
2630 \r
2631 \r
2632         function api_account_rate_limit_status($type) {\r
2633 \r
2634                 if ($type == "xml")\r
2635                         $hash = array(\r
2636                                         'remaining-hits' => (string) 150,\r
2637                                         '@attributes' => array("type" => "integer"),\r
2638                                         'hourly-limit' => (string) 150,\r
2639                                         '@attributes2' => array("type" => "integer"),\r
2640                                         'reset-time' => datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME),\r
2641                                         '@attributes3' => array("type" => "datetime"),\r
2642                                         'reset_time_in_seconds' => strtotime('now + 1 hour'),\r
2643                                         '@attributes4' => array("type" => "integer"),\r
2644                                 );\r
2645                 else\r
2646                         $hash = array(\r
2647                                         'reset_time_in_seconds' => strtotime('now + 1 hour'),\r
2648                                         'remaining_hits' => (string) 150,\r
2649                                         'hourly_limit' => (string) 150,\r
2650                                         'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),\r
2651                                 );\r
2652 \r
2653                 return api_format_data('hash', $type, array('hash' => $hash));\r
2654         }\r
2655         api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);\r
2656 \r
2657         function api_help_test($type) {\r
2658                 if ($type == 'xml')\r
2659                         $ok = "true";\r
2660                 else\r
2661                         $ok = "ok";\r
2662 \r
2663                 return api_format_data('ok', $type, array("ok" => $ok));\r
2664         }\r
2665         api_register_func('api/help/test','api_help_test',false);\r
2666 \r
2667         function api_lists($type) {\r
2668                 $ret = array();\r
2669                 return api_format_data('lists', $type, array("lists_list" => $ret));\r
2670         }\r
2671         api_register_func('api/lists','api_lists',true);\r
2672 \r
2673         function api_lists_list($type) {\r
2674                 $ret = array();\r
2675                 return api_format_data('lists', $type, array("lists_list" => $ret));\r
2676         }\r
2677         api_register_func('api/lists/list','api_lists_list',true);\r
2678 \r
2679         /**\r
2680          *  https://dev.twitter.com/docs/api/1/get/statuses/friends\r
2681          *  This function is deprecated by Twitter\r
2682          *  returns: json, xml\r
2683          **/\r
2684         function api_statuses_f($type, $qtype) {\r
2685 \r
2686                 $a = get_app();\r
2687 \r
2688                 if (api_user()===false) throw new ForbiddenException();\r
2689                 $user_info = api_get_user($a);\r
2690 \r
2691                 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){\r
2692                         /* this is to stop Hotot to load friends multiple times\r
2693                         *  I'm not sure if I'm missing return something or\r
2694                         *  is a bug in hotot. Workaround, meantime\r
2695                         */\r
2696 \r
2697                         /*$ret=Array();\r
2698                         return array('$users' => $ret);*/\r
2699                         return false;\r
2700                 }\r
2701 \r
2702                 if($qtype == 'friends')\r
2703                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));\r
2704                 if($qtype == 'followers')\r
2705                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));\r
2706 \r
2707                 // friends and followers only for self\r
2708                 if ($user_info['self'] == 0)\r
2709                         $sql_extra = " AND false ";\r
2710 \r
2711                 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",\r
2712                         intval(api_user())\r
2713                 );\r
2714 \r
2715                 $ret = array();\r
2716                 foreach($r as $cid){\r
2717                         $user = api_get_user($a, $cid['nurl']);\r
2718                         // "uid" and "self" are only needed for some internal stuff, so remove it from here\r
2719                         unset($user["uid"]);\r
2720                         unset($user["self"]);\r
2721 \r
2722                         if ($user)\r
2723                                 $ret[] = $user;\r
2724                 }\r
2725 \r
2726                 return array('user' => $ret);\r
2727 \r
2728         }\r
2729         function api_statuses_friends($type){\r
2730                 $data =  api_statuses_f($type, "friends");\r
2731                 if ($data===false) return false;\r
2732                 return  api_format_data("users", $type, $data);\r
2733         }\r
2734         function api_statuses_followers($type){\r
2735                 $data = api_statuses_f($type, "followers");\r
2736                 if ($data===false) return false;\r
2737                 return  api_format_data("users", $type, $data);\r
2738         }\r
2739         api_register_func('api/statuses/friends','api_statuses_friends',true);\r
2740         api_register_func('api/statuses/followers','api_statuses_followers',true);\r
2741 \r
2742 \r
2743 \r
2744 \r
2745 \r
2746 \r
2747         function api_statusnet_config($type) {\r
2748 \r
2749                 $a = get_app();\r
2750 \r
2751                 $name = $a->config['sitename'];\r
2752                 $server = $a->get_hostname();\r
2753                 $logo = App::get_baseurl() . '/images/friendica-64.png';\r
2754                 $email = $a->config['admin_email'];\r
2755                 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');\r
2756                 $private = (($a->config['system']['block_public']) ? 'true' : 'false');\r
2757                 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);\r
2758                 if($a->config['api_import_size'])\r
2759                         $texlimit = string($a->config['api_import_size']);\r
2760                 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');\r
2761                 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',App::get_baseurl()) : '');\r
2762 \r
2763                 $config = array(\r
2764                         'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',\r
2765                                 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',\r
2766                                 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,\r
2767                                 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,\r
2768                                 'shorturllength' => '30',\r
2769                                 'friendica' => array(\r
2770                                                 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,\r
2771                                                 'FRIENDICA_VERSION' => FRIENDICA_VERSION,\r
2772                                                 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,\r
2773                                                 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION\r
2774                                                 )\r
2775                         ),\r
2776                 );\r
2777 \r
2778                 return api_format_data('config', $type, array('config' => $config));\r
2779 \r
2780         }\r
2781         api_register_func('api/statusnet/config','api_statusnet_config',false);\r
2782 \r
2783         function api_statusnet_version($type) {\r
2784                 // liar\r
2785                 $fake_statusnet_version = "0.9.7";\r
2786 \r
2787                 return api_format_data('version', $type, array('version' => $fake_statusnet_version));\r
2788         }\r
2789         api_register_func('api/statusnet/version','api_statusnet_version',false);\r
2790 \r
2791         /**\r
2792          * @todo use api_format_data() to return data\r
2793          */\r
2794         function api_ff_ids($type,$qtype) {\r
2795 \r
2796                 $a = get_app();\r
2797 \r
2798                 if(! api_user()) throw new ForbiddenException();\r
2799 \r
2800                 $user_info = api_get_user($a);\r
2801 \r
2802                 if($qtype == 'friends')\r
2803                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));\r
2804                 if($qtype == 'followers')\r
2805                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));\r
2806 \r
2807                 if (!$user_info["self"])\r
2808                         $sql_extra = " AND false ";\r
2809 \r
2810                 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);\r
2811 \r
2812                 $r = q("SELECT `gcontact`.`id` FROM `contact`, `gcontact` WHERE `contact`.`nurl` = `gcontact`.`nurl` AND `uid` = %d AND NOT `self` AND NOT `blocked` AND NOT `pending` $sql_extra",\r
2813                         intval(api_user())\r
2814                 );\r
2815 \r
2816                 if(!dbm::is_result($r))\r
2817                         return;\r
2818 \r
2819                 $ids = array();\r
2820                 foreach($r as $rr)\r
2821                         if ($stringify_ids)\r
2822                                 $ids[] = $rr['id'];\r
2823                         else\r
2824                                 $ids[] = intval($rr['id']);\r
2825 \r
2826                 return api_format_data("ids", $type, array('id' => $ids));\r
2827         }\r
2828 \r
2829         function api_friends_ids($type) {\r
2830                 return api_ff_ids($type,'friends');\r
2831         }\r
2832         function api_followers_ids($type) {\r
2833                 return api_ff_ids($type,'followers');\r
2834         }\r
2835         api_register_func('api/friends/ids','api_friends_ids',true);\r
2836         api_register_func('api/followers/ids','api_followers_ids',true);\r
2837 \r
2838 \r
2839         function api_direct_messages_new($type) {\r
2840 \r
2841                 $a = get_app();\r
2842 \r
2843                 if (api_user()===false) throw new ForbiddenException();\r
2844 \r
2845                 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;\r
2846 \r
2847                 $sender = api_get_user($a);\r
2848 \r
2849                 if ($_POST['screen_name']) {\r
2850                         $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",\r
2851                                         intval(api_user()),\r
2852                                         dbesc($_POST['screen_name']));\r
2853 \r
2854                         // Selecting the id by priority, friendica first\r
2855                         api_best_nickname($r);\r
2856 \r
2857                         $recipient = api_get_user($a, $r[0]['nurl']);\r
2858                 } else\r
2859                         $recipient = api_get_user($a, $_POST['user_id']);\r
2860 \r
2861                 $replyto = '';\r
2862                 $sub     = '';\r
2863                 if (x($_REQUEST,'replyto')) {\r
2864                         $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',\r
2865                                         intval(api_user()),\r
2866                                         intval($_REQUEST['replyto']));\r
2867                         $replyto = $r[0]['parent-uri'];\r
2868                         $sub     = $r[0]['title'];\r
2869                 }\r
2870                 else {\r
2871                         if (x($_REQUEST,'title')) {\r
2872                                 $sub = $_REQUEST['title'];\r
2873                         }\r
2874                         else {\r
2875                                 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);\r
2876                         }\r
2877                 }\r
2878 \r
2879                 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);\r
2880 \r
2881                 if ($id>-1) {\r
2882                         $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));\r
2883                         $ret = api_format_messages($r[0], $recipient, $sender);\r
2884 \r
2885                 } else {\r
2886                         $ret = array("error"=>$id);\r
2887                 }\r
2888 \r
2889                 $data = Array('direct_message'=>$ret);\r
2890 \r
2891                 switch($type){\r
2892                         case "atom":\r
2893                         case "rss":\r
2894                                 $data = api_rss_extra($a, $data, $user_info);\r
2895                 }\r
2896 \r
2897                 return  api_format_data("direct-messages", $type, $data);\r
2898 \r
2899         }\r
2900         api_register_func('api/direct_messages/new','api_direct_messages_new',true, API_METHOD_POST);\r
2901 \r
2902 \r
2903         /**\r
2904          * @brief delete a direct_message from mail table through api\r
2905          *\r
2906          * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'\r
2907          * @return string\r
2908          */\r
2909         function api_direct_messages_destroy($type){\r
2910                 $a = get_app();\r
2911 \r
2912                 if (api_user()===false) throw new ForbiddenException();\r
2913 \r
2914                 // params\r
2915                 $user_info = api_get_user($a);\r
2916                 //required\r
2917                 $id = (x($_REQUEST,'id') ? $_REQUEST['id'] : 0);\r
2918                 // optional\r
2919                 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");\r
2920                 $verbose = (x($_GET,'friendica_verbose')?strtolower($_GET['friendica_verbose']):"false");\r
2921                 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented\r
2922 \r
2923                 $uid = $user_info['uid'];\r
2924                 // error if no id or parenturi specified (for clients posting parent-uri as well)\r
2925                 if ($verbose == "true") {\r
2926                         if ($id == 0 || $parenturi == "") {\r
2927                                 $answer = array('result' => 'error', 'message' => 'message id or parenturi not specified');\r
2928                                 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));\r
2929                         }\r
2930                 }\r
2931 \r
2932                 // BadRequestException if no id specified (for clients using Twitter API)\r
2933                 if ($id == 0) throw new BadRequestException('Message id not specified');\r
2934 \r
2935                 // add parent-uri to sql command if specified by calling app\r
2936                 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");\r
2937 \r
2938                 // get data of the specified message id\r
2939                 $r = q("SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,\r
2940                         intval($uid),\r
2941                         intval($id));\r
2942 \r
2943                 // error message if specified id is not in database\r
2944                 if (!dbm::is_result($r)) {\r
2945                         if ($verbose == "true") {\r
2946                                 $answer = array('result' => 'error', 'message' => 'message id not in database');\r
2947                                 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));\r
2948                         }\r
2949                         /// @todo BadRequestException ok for Twitter API clients?\r
2950                         throw new BadRequestException('message id not in database');\r
2951                 }\r
2952 \r
2953                 // delete message\r
2954                 $result = q("DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,\r
2955                         intval($uid),\r
2956                         intval($id));\r
2957 \r
2958                 if ($verbose == "true") {\r
2959                         if ($result) {\r
2960                                 // return success\r
2961                                 $answer = array('result' => 'ok', 'message' => 'message deleted');\r
2962                                 return api_format_data("direct_message_delete", $type, array('$result' => $answer));\r
2963                         }\r
2964                         else {\r
2965                                 $answer = array('result' => 'error', 'message' => 'unknown error');\r
2966                                 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));\r
2967                         }\r
2968                 }\r
2969                 /// @todo return JSON data like Twitter API not yet implemented\r
2970 \r
2971         }\r
2972         api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);\r
2973 \r
2974 \r
2975         function api_direct_messages_box($type, $box, $verbose) {\r
2976 \r
2977                 $a = get_app();\r
2978 \r
2979                 if (api_user()===false) throw new ForbiddenException();\r
2980 \r
2981                 // params\r
2982                 $count = (x($_GET,'count')?$_GET['count']:20);\r
2983                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);\r
2984                 if ($page<0) $page=0;\r
2985 \r
2986                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);\r
2987                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);\r
2988 \r
2989                 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");\r
2990                 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");\r
2991 \r
2992                 //  caller user info\r
2993                 unset($_REQUEST["user_id"]);\r
2994                 unset($_GET["user_id"]);\r
2995 \r
2996                 unset($_REQUEST["screen_name"]);\r
2997                 unset($_GET["screen_name"]);\r
2998 \r
2999                 $user_info = api_get_user($a);\r
3000                 $profile_url = $user_info["url"];\r
3001 \r
3002 \r
3003                 // pagination\r
3004                 $start = $page*$count;\r
3005 \r
3006                 // filters\r
3007                 if ($box=="sentbox") {\r
3008                         $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";\r
3009                 }\r
3010                 elseif ($box=="conversation") {\r
3011                         $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] )  ."'";\r
3012                 }\r
3013                 elseif ($box=="all") {\r
3014                         $sql_extra = "true";\r
3015                 }\r
3016                 elseif ($box=="inbox") {\r
3017                         $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";\r
3018                 }\r
3019 \r
3020                 if ($max_id > 0)\r
3021                         $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);\r
3022 \r
3023                 if ($user_id !="") {\r
3024                         $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);\r
3025                 }\r
3026                 elseif($screen_name !=""){\r
3027                         $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";\r
3028                 }\r
3029 \r
3030                 $r = q("SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid`=%d AND $sql_extra AND `mail`.`id` > %d ORDER BY `mail`.`id` DESC LIMIT %d,%d",\r
3031                                 intval(api_user()),\r
3032                                 intval($since_id),\r
3033                                 intval($start), intval($count)\r
3034                 );\r
3035                 if ($verbose == "true") {\r
3036                         // stop execution and return error message if no mails available\r
3037                         if($r == null) {\r
3038                                 $answer = array('result' => 'error', 'message' => 'no mails available');\r
3039                                 return api_format_data("direct_messages_all", $type, array('$result' => $answer));\r
3040                         }\r
3041                 }\r
3042 \r
3043                 $ret = Array();\r
3044                 foreach($r as $item) {\r
3045                         if ($box == "inbox" || $item['from-url'] != $profile_url){\r
3046                                 $recipient = $user_info;\r
3047                                 $sender = api_get_user($a,normalise_link($item['contact-url']));\r
3048                         }\r
3049                         elseif ($box == "sentbox" || $item['from-url'] == $profile_url){\r
3050                                 $recipient = api_get_user($a,normalise_link($item['contact-url']));\r
3051                                 $sender = $user_info;\r
3052 \r
3053                         }\r
3054                         $ret[]=api_format_messages($item, $recipient, $sender);\r
3055                 }\r
3056 \r
3057 \r
3058                 $data = array('direct_message' => $ret);\r
3059                 switch($type){\r
3060                         case "atom":\r
3061                         case "rss":\r
3062                                 $data = api_rss_extra($a, $data, $user_info);\r
3063                 }\r
3064 \r
3065                 return  api_format_data("direct-messages", $type, $data);\r
3066 \r
3067         }\r
3068 \r
3069         function api_direct_messages_sentbox($type){\r
3070                 $verbose = (x($_GET,'friendica_verbose')?strtolower($_GET['friendica_verbose']):"false");\r
3071                 return api_direct_messages_box($type, "sentbox", $verbose);\r
3072         }\r
3073         function api_direct_messages_inbox($type){\r
3074                 $verbose = (x($_GET,'friendica_verbose')?strtolower($_GET['friendica_verbose']):"false");\r
3075                 return api_direct_messages_box($type, "inbox", $verbose);\r
3076         }\r
3077         function api_direct_messages_all($type){\r
3078                 $verbose = (x($_GET,'friendica_verbose')?strtolower($_GET['friendica_verbose']):"false");\r
3079                 return api_direct_messages_box($type, "all", $verbose);\r
3080         }\r
3081         function api_direct_messages_conversation($type){\r
3082                 $verbose = (x($_GET,'friendica_verbose')?strtolower($_GET['friendica_verbose']):"false");\r
3083                 return api_direct_messages_box($type, "conversation", $verbose);\r
3084         }\r
3085         api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);\r
3086         api_register_func('api/direct_messages/all','api_direct_messages_all',true);\r
3087         api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);\r
3088         api_register_func('api/direct_messages','api_direct_messages_inbox',true);\r
3089 \r
3090 \r
3091 \r
3092         function api_oauth_request_token($type){\r
3093                 try{\r
3094                         $oauth = new FKOAuth1();\r
3095                         $r = $oauth->fetch_request_token(OAuthRequest::from_request());\r
3096                 }catch(Exception $e){\r
3097                         echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();\r
3098                 }\r
3099                 echo $r;\r
3100                 killme();\r
3101         }\r
3102         function api_oauth_access_token($type){\r
3103                 try{\r
3104                         $oauth = new FKOAuth1();\r
3105                         $r = $oauth->fetch_access_token(OAuthRequest::from_request());\r
3106                 }catch(Exception $e){\r
3107                         echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();\r
3108                 }\r
3109                 echo $r;\r
3110                 killme();\r
3111         }\r
3112 \r
3113         api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);\r
3114         api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);\r
3115 \r
3116 \r
3117         function api_fr_photos_list($type) {\r
3118                 if (api_user()===false) throw new ForbiddenException();\r
3119                 $r = q("select `resource-id`, max(scale) as scale, album, filename, type from photo\r
3120                                 where uid = %d and album != 'Contact Photos' group by `resource-id`",\r
3121                         intval(local_user())\r
3122                 );\r
3123                 $typetoext = array(\r
3124                 'image/jpeg' => 'jpg',\r
3125                 'image/png' => 'png',\r
3126                 'image/gif' => 'gif'\r
3127                 );\r
3128                 $data = array('photo'=>array());\r
3129                 if($r) {\r
3130                         foreach($r as $rr) {\r
3131                                 $photo = array();\r
3132                                 $photo['id'] = $rr['resource-id'];\r
3133                                 $photo['album'] = $rr['album'];\r
3134                                 $photo['filename'] = $rr['filename'];\r
3135                                 $photo['type'] = $rr['type'];\r
3136                                 $thumb = App::get_baseurl()."/photo/".$rr['resource-id']."-".$rr['scale'].".".$typetoext[$rr['type']];\r
3137 \r
3138                                 if ($type == "xml")\r
3139                                         $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);\r
3140                                 else {\r
3141                                         $photo['thumb'] = $thumb;\r
3142                                         $data['photo'][] = $photo;\r
3143                                 }\r
3144                         }\r
3145                 }\r
3146                 return  api_format_data("photos", $type, $data);\r
3147         }\r
3148 \r
3149         function api_fr_photo_detail($type) {\r
3150                 if (api_user()===false) throw new ForbiddenException();\r
3151                 if(!x($_REQUEST,'photo_id')) throw new BadRequestException("No photo id.");\r
3152 \r
3153                 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);\r
3154                 $scale_sql = ($scale === false ? "" : sprintf("and scale=%d",intval($scale)));\r
3155                 $data_sql = ($scale === false ? "" : "data, ");\r
3156 \r
3157                 $r = q("select %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,\r
3158                                                 `type`, `height`, `width`, `datasize`, `profile`, min(`scale`) as minscale, max(`scale`) as maxscale\r
3159                                 from photo where `uid` = %d and `resource-id` = '%s' %s group by `resource-id`",\r
3160                         $data_sql,\r
3161                         intval(local_user()),\r
3162                         dbesc($_REQUEST['photo_id']),\r
3163                         $scale_sql\r
3164                 );\r
3165 \r
3166                 $typetoext = array(\r
3167                 'image/jpeg' => 'jpg',\r
3168                 'image/png' => 'png',\r
3169                 'image/gif' => 'gif'\r
3170                 );\r
3171 \r
3172                 if ($r) {\r
3173                         $data = array('photo' => $r[0]);\r
3174                         $data['photo']['id'] = $data['photo']['resource-id'];\r
3175                         if ($scale !== false) {\r
3176                                 $data['photo']['data'] = base64_encode($data['photo']['data']);\r
3177                         } else {\r
3178                                 unset($data['photo']['datasize']); //needed only with scale param\r
3179                         }\r
3180                         if ($type == "xml") {\r
3181                                 $data['photo']['links'] = array();\r
3182                                 for ($k=intval($data['photo']['minscale']); $k<=intval($data['photo']['maxscale']); $k++)\r
3183                                         $data['photo']['links'][$k.":link"]["@attributes"] = array("type" => $data['photo']['type'],\r
3184                                                                                         "scale" => $k,\r
3185                                                                                         "href" => App::get_baseurl()."/photo/".$data['photo']['resource-id']."-".$k.".".$typetoext[$data['photo']['type']]);\r
3186                         } else {\r
3187                                 $data['photo']['link'] = array();\r
3188                                 for ($k=intval($data['photo']['minscale']); $k<=intval($data['photo']['maxscale']); $k++) {\r
3189                                         $data['photo']['link'][$k] = App::get_baseurl()."/photo/".$data['photo']['resource-id']."-".$k.".".$typetoext[$data['photo']['type']];\r
3190                                 }\r
3191                         }\r
3192                         unset($data['photo']['resource-id']);\r
3193                         unset($data['photo']['minscale']);\r
3194                         unset($data['photo']['maxscale']);\r
3195 \r
3196                 } else {\r
3197                         throw new NotFoundException();\r
3198                 }\r
3199 \r
3200                 return api_format_data("photo_detail", $type, $data);\r
3201         }\r
3202 \r
3203         api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);\r
3204         api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);\r
3205 \r
3206 \r
3207 \r
3208         /**\r
3209          * similar as /mod/redir.php\r
3210          * redirect to 'url' after dfrn auth\r
3211          *\r
3212          * why this when there is mod/redir.php already?\r
3213          * This use api_user() and api_login()\r
3214          *\r
3215          * params\r
3216          *              c_url: url of remote contact to auth to\r
3217          *              url: string, url to redirect after auth\r
3218          */\r
3219         function api_friendica_remoteauth() {\r
3220                 $url = ((x($_GET,'url')) ? $_GET['url'] : '');\r
3221                 $c_url = ((x($_GET,'c_url')) ? $_GET['c_url'] : '');\r
3222 \r
3223                 if ($url === '' || $c_url === '')\r
3224                         throw new BadRequestException("Wrong parameters.");\r
3225 \r
3226                 $c_url = normalise_link($c_url);\r
3227 \r
3228                 // traditional DFRN\r
3229 \r
3230                 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",\r
3231                         dbesc($c_url),\r
3232                         intval(api_user())\r
3233                 );\r
3234 \r
3235                 if ((! count($r)) || ($r[0]['network'] !== NETWORK_DFRN))\r
3236                         throw new BadRequestException("Unknown contact");\r
3237 \r
3238                 $cid = $r[0]['id'];\r
3239 \r
3240                 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);\r
3241 \r
3242                 if($r[0]['duplex'] && $r[0]['issued-id']) {\r
3243                         $orig_id = $r[0]['issued-id'];\r
3244                         $dfrn_id = '1:' . $orig_id;\r
3245                 }\r
3246                 if($r[0]['duplex'] && $r[0]['dfrn-id']) {\r
3247                         $orig_id = $r[0]['dfrn-id'];\r
3248                         $dfrn_id = '0:' . $orig_id;\r
3249                 }\r
3250 \r
3251                 $sec = random_string();\r
3252 \r
3253                 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)\r
3254                         VALUES( %d, %s, '%s', '%s', %d )",\r
3255                         intval(api_user()),\r
3256                         intval($cid),\r
3257                         dbesc($dfrn_id),\r
3258                         dbesc($sec),\r
3259                         intval(time() + 45)\r
3260                 );\r
3261 \r
3262                 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);\r
3263                 $dest = (($url) ? '&destination_url=' . $url : '');\r
3264                 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id\r
3265                                 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION\r
3266                                 . '&type=profile&sec=' . $sec . $dest . $quiet );\r
3267         }\r
3268         api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);\r
3269 \r
3270         /**\r
3271          * @brief Return the item shared, if the item contains only the [share] tag\r
3272          *\r
3273          * @param array $item Sharer item\r
3274          * @return array Shared item or false if not a reshare\r
3275          */\r
3276         function api_share_as_retweet(&$item) {\r
3277                 $body = trim($item["body"]);\r
3278 \r
3279                 if (diaspora::is_reshare($body, false)===false) {\r
3280                         return false;\r
3281                 }\r
3282 \r
3283                 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);\r
3284                 // Skip if there is no shared message in there\r
3285                 // we already checked this in diaspora::is_reshare()\r
3286                 // but better one more than one less...\r
3287                 if ($body == $attributes)\r
3288                         return false;\r
3289 \r
3290 \r
3291                 // build the fake reshared item\r
3292                 $reshared_item = $item;\r
3293 \r
3294                 $author = "";\r
3295                 preg_match("/author='(.*?)'/ism", $attributes, $matches);\r
3296                 if ($matches[1] != "")\r
3297                         $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');\r
3298 \r
3299                 preg_match('/author="(.*?)"/ism', $attributes, $matches);\r
3300                 if ($matches[1] != "")\r
3301                         $author = $matches[1];\r
3302 \r
3303                 $profile = "";\r
3304                 preg_match("/profile='(.*?)'/ism", $attributes, $matches);\r
3305                 if ($matches[1] != "")\r
3306                         $profile = $matches[1];\r
3307 \r
3308                 preg_match('/profile="(.*?)"/ism', $attributes, $matches);\r
3309                 if ($matches[1] != "")\r
3310                         $profile = $matches[1];\r
3311 \r
3312                 $avatar = "";\r
3313                 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);\r
3314                 if ($matches[1] != "")\r
3315                         $avatar = $matches[1];\r
3316 \r
3317                 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);\r
3318                 if ($matches[1] != "")\r
3319                         $avatar = $matches[1];\r
3320 \r
3321                 $link = "";\r
3322                 preg_match("/link='(.*?)'/ism", $attributes, $matches);\r
3323                 if ($matches[1] != "")\r
3324                         $link = $matches[1];\r
3325 \r
3326                 preg_match('/link="(.*?)"/ism', $attributes, $matches);\r
3327                 if ($matches[1] != "")\r
3328                         $link = $matches[1];\r
3329 \r
3330                 $posted = "";\r
3331                 preg_match("/posted='(.*?)'/ism", $attributes, $matches);\r
3332                 if ($matches[1] != "")\r
3333                         $posted= $matches[1];\r
3334 \r
3335                 preg_match('/posted="(.*?)"/ism', $attributes, $matches);\r
3336                 if ($matches[1] != "")\r
3337                         $posted = $matches[1];\r
3338 \r
3339                 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);\r
3340 \r
3341                 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == ""))\r
3342                         return false;\r
3343 \r
3344 \r
3345 \r
3346                 $reshared_item["body"] = $shared_body;\r
3347                 $reshared_item["author-name"] = $author;\r
3348                 $reshared_item["author-link"] = $profile;\r
3349                 $reshared_item["author-avatar"] = $avatar;\r
3350                 $reshared_item["plink"] = $link;\r
3351                 $reshared_item["created"] = $posted;\r
3352                 $reshared_item["edited"] = $posted;\r
3353 \r
3354                 return $reshared_item;\r
3355 \r
3356         }\r
3357 \r
3358         function api_get_nick($profile) {\r
3359                 /* To-Do:\r
3360                  - remove trailing junk from profile url\r
3361                  - pump.io check has to check the website\r
3362                 */\r
3363 \r
3364                 $nick = "";\r
3365 \r
3366                 $r = q("SELECT `nick` FROM `gcontact` WHERE `nurl` = '%s'",\r
3367                         dbesc(normalise_link($profile)));\r
3368                 if ($r)\r
3369                         $nick = $r[0]["nick"];\r
3370 \r
3371                 if (!$nick == "") {\r
3372                         $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",\r
3373                                 dbesc(normalise_link($profile)));\r
3374                         if ($r)\r
3375                                 $nick = $r[0]["nick"];\r
3376                 }\r
3377 \r
3378                 if (!$nick == "") {\r
3379                         $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);\r
3380                         if ($friendica != $profile)\r
3381                                 $nick = $friendica;\r
3382                 }\r
3383 \r
3384                 if (!$nick == "") {\r
3385                         $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);\r
3386                         if ($diaspora != $profile)\r
3387                                 $nick = $diaspora;\r
3388                 }\r
3389 \r
3390                 if (!$nick == "") {\r
3391                         $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);\r
3392                         if ($twitter != $profile)\r
3393                                 $nick = $twitter;\r
3394                 }\r
3395 \r
3396 \r
3397                 if (!$nick == "") {\r
3398                         $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);\r
3399                         if ($StatusnetHost != $profile) {\r
3400                                 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);\r
3401                                 if ($StatusnetUser != $profile) {\r
3402                                         $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);\r
3403                                         $user = json_decode($UserData);\r
3404                                         if ($user)\r
3405                                                 $nick = $user->screen_name;\r
3406                                 }\r
3407                         }\r
3408                 }\r
3409 \r
3410                 // To-Do: look at the page if its really a pumpio site\r
3411                 //if (!$nick == "") {\r
3412                 //      $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");\r
3413                 //      if ($pumpio != $profile)\r
3414                 //              $nick = $pumpio;\r
3415                         //      <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">\r
3416 \r
3417                 //}\r
3418 \r
3419                 if ($nick != "")\r
3420                         return($nick);\r
3421 \r
3422                 return(false);\r
3423         }\r
3424 \r
3425         function api_clean_plain_items($Text) {\r
3426                 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");\r
3427 \r
3428                 $Text = bb_CleanPictureLinks($Text);\r
3429                 $URLSearchString = "^\[\]";\r
3430 \r
3431                 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);\r
3432 \r
3433                 if ($include_entities == "true") {\r
3434                         $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);\r
3435                 }\r
3436 \r
3437                 // Simplify "attachment" element\r
3438                 $Text = api_clean_attachments($Text);\r
3439 \r
3440                 return($Text);\r
3441         }\r
3442 \r
3443         /**\r
3444          * @brief Removes most sharing information for API text export\r
3445          *\r
3446          * @param string $body The original body\r
3447          *\r
3448          * @return string Cleaned body\r
3449          */\r
3450         function api_clean_attachments($body) {\r
3451                 $data = get_attachment_data($body);\r
3452 \r
3453                 if (!$data)\r
3454                         return $body;\r
3455 \r
3456                 $body = "";\r
3457 \r
3458                 if (isset($data["text"]))\r
3459                         $body = $data["text"];\r
3460 \r
3461                 if (($body == "") AND (isset($data["title"])))\r
3462                         $body = $data["title"];\r
3463 \r
3464                 if (isset($data["url"]))\r
3465                         $body .= "\n".$data["url"];\r
3466 \r
3467                 $body .= $data["after"];\r
3468 \r
3469                 return $body;\r
3470         }\r
3471 \r
3472         function api_best_nickname(&$contacts) {\r
3473                 $best_contact = array();\r
3474 \r
3475                 if (count($contact) == 0)\r
3476                         return;\r
3477 \r
3478                 foreach ($contacts AS $contact)\r
3479                         if ($contact["network"] == "") {\r
3480                                 $contact["network"] = "dfrn";\r
3481                                 $best_contact = array($contact);\r
3482                         }\r
3483 \r
3484                 if (sizeof($best_contact) == 0)\r
3485                         foreach ($contacts AS $contact)\r
3486                                 if ($contact["network"] == "dfrn")\r
3487                                         $best_contact = array($contact);\r
3488 \r
3489                 if (sizeof($best_contact) == 0)\r
3490                         foreach ($contacts AS $contact)\r
3491                                 if ($contact["network"] == "dspr")\r
3492                                         $best_contact = array($contact);\r
3493 \r
3494                 if (sizeof($best_contact) == 0)\r
3495                         foreach ($contacts AS $contact)\r
3496                                 if ($contact["network"] == "stat")\r
3497                                         $best_contact = array($contact);\r
3498 \r
3499                 if (sizeof($best_contact) == 0)\r
3500                         foreach ($contacts AS $contact)\r
3501                                 if ($contact["network"] == "pump")\r
3502                                         $best_contact = array($contact);\r
3503 \r
3504                 if (sizeof($best_contact) == 0)\r
3505                         foreach ($contacts AS $contact)\r
3506                                 if ($contact["network"] == "twit")\r
3507                                         $best_contact = array($contact);\r
3508 \r
3509                 if (sizeof($best_contact) == 1)\r
3510                         $contacts = $best_contact;\r
3511                 else\r
3512                         $contacts = array($contacts[0]);\r
3513         }\r
3514 \r
3515         // return all or a specified group of the user with the containing contacts\r
3516         function api_friendica_group_show($type) {\r
3517 \r
3518                 $a = get_app();\r
3519 \r
3520                 if (api_user()===false) throw new ForbiddenException();\r
3521 \r
3522                 // params\r
3523                 $user_info = api_get_user($a);\r
3524                 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);\r
3525                 $uid = $user_info['uid'];\r
3526 \r
3527                 // get data of the specified group id or all groups if not specified\r
3528                 if ($gid != 0) {\r
3529                         $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",\r
3530                                 intval($uid),\r
3531                                 intval($gid));\r
3532                         // error message if specified gid is not in database\r
3533                         if (count($r) == 0)\r
3534                                 throw new BadRequestException("gid not available");\r
3535                 }\r
3536                 else\r
3537                         $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",\r
3538                                 intval($uid));\r
3539 \r
3540                 // loop through all groups and retrieve all members for adding data in the user array\r
3541                 foreach ($r as $rr) {\r
3542                         $members = group_get_members($rr['id']);\r
3543                         $users = array();\r
3544 \r
3545                         if ($type == "xml") {\r
3546                                 $user_element = "users";\r
3547                                 $k = 0;\r
3548                                 foreach ($members as $member) {\r
3549                                         $user = api_get_user($a, $member['nurl']);\r
3550                                         $users[$k++.":user"] = $user;\r
3551                                 }\r
3552                         } else {\r
3553                                 $user_element = "user";\r
3554                                 foreach ($members as $member) {\r
3555                                         $user = api_get_user($a, $member['nurl']);\r
3556                                         $users[] = $user;\r
3557                                 }\r
3558                         }\r
3559                         $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);\r
3560                 }\r
3561                 return api_format_data("groups", $type, array('group' => $grps));\r
3562         }\r
3563         api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);\r
3564 \r
3565 \r
3566         // delete the specified group of the user\r
3567         function api_friendica_group_delete($type) {\r
3568 \r
3569                 $a = get_app();\r
3570 \r
3571                 if (api_user()===false) throw new ForbiddenException();\r
3572 \r
3573                 // params\r
3574                 $user_info = api_get_user($a);\r
3575                 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);\r
3576                 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");\r
3577                 $uid = $user_info['uid'];\r
3578 \r
3579                 // error if no gid specified\r
3580                 if ($gid == 0 || $name == "")\r
3581                         throw new BadRequestException('gid or name not specified');\r
3582 \r
3583                 // get data of the specified group id\r
3584                 $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",\r
3585                         intval($uid),\r
3586                         intval($gid));\r
3587                 // error message if specified gid is not in database\r
3588                 if (count($r) == 0)\r
3589                         throw new BadRequestException('gid not available');\r
3590 \r
3591                 // get data of the specified group id and group name\r
3592                 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",\r
3593                         intval($uid),\r
3594                         intval($gid),\r
3595                         dbesc($name));\r
3596                 // error message if specified gid is not in database\r
3597                 if (count($rname) == 0)\r
3598                         throw new BadRequestException('wrong group name');\r
3599 \r
3600                 // delete group\r
3601                 $ret = group_rmv($uid, $name);\r
3602                 if ($ret) {\r
3603                         // return success\r
3604                         $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());\r
3605                         return api_format_data("group_delete", $type, array('result' => $success));\r
3606                 }\r
3607                 else\r
3608                         throw new BadRequestException('other API error');\r
3609         }\r
3610         api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);\r
3611 \r
3612 \r
3613         // create the specified group with the posted array of contacts\r
3614         function api_friendica_group_create($type) {\r
3615 \r
3616                 $a = get_app();\r
3617 \r
3618                 if (api_user()===false) throw new ForbiddenException();\r
3619 \r
3620                 // params\r
3621                 $user_info = api_get_user($a);\r
3622                 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");\r
3623                 $uid = $user_info['uid'];\r
3624                 $json = json_decode($_POST['json'], true);\r
3625                 $users = $json['user'];\r
3626 \r
3627                 // error if no name specified\r
3628                 if ($name == "")\r
3629                         throw new BadRequestException('group name not specified');\r
3630 \r
3631                 // get data of the specified group name\r
3632                 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",\r
3633                         intval($uid),\r
3634                         dbesc($name));\r
3635                 // error message if specified group name already exists\r
3636                 if (count($rname) != 0)\r
3637                         throw new BadRequestException('group name already exists');\r
3638 \r
3639                 // check if specified group name is a deleted group\r
3640                 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",\r
3641                         intval($uid),\r
3642                         dbesc($name));\r
3643                 // error message if specified group name already exists\r
3644                 if (count($rname) != 0)\r
3645                         $reactivate_group = true;\r
3646 \r
3647                 // create group\r
3648                 $ret = group_add($uid, $name);\r
3649                 if ($ret)\r
3650                         $gid = group_byname($uid, $name);\r
3651                 else\r
3652                         throw new BadRequestException('other API error');\r
3653 \r
3654                 // add members\r
3655                 $erroraddinguser = false;\r
3656                 $errorusers = array();\r
3657                 foreach ($users as $user) {\r
3658                         $cid = $user['cid'];\r
3659                         // check if user really exists as contact\r
3660                         $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",\r
3661                                 intval($cid),\r
3662                                 intval($uid));\r
3663                         if (count($contact))\r
3664                                 $result = group_add_member($uid, $name, $cid, $gid);\r
3665                         else {\r
3666                                 $erroraddinguser = true;\r
3667                                 $errorusers[] = $cid;\r
3668                         }\r
3669                 }\r
3670 \r
3671                 // return success message incl. missing users in array\r
3672                 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));\r
3673                 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);\r
3674                 return api_format_data("group_create", $type, array('result' => $success));\r
3675         }\r
3676         api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);\r
3677 \r
3678 \r
3679         // update the specified group with the posted array of contacts\r
3680         function api_friendica_group_update($type) {\r
3681 \r
3682                 $a = get_app();\r
3683 \r
3684                 if (api_user()===false) throw new ForbiddenException();\r
3685 \r
3686                 // params\r
3687                 $user_info = api_get_user($a);\r
3688                 $uid = $user_info['uid'];\r
3689                 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);\r
3690                 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");\r
3691                 $json = json_decode($_POST['json'], true);\r
3692                 $users = $json['user'];\r
3693 \r
3694                 // error if no name specified\r
3695                 if ($name == "")\r
3696                         throw new BadRequestException('group name not specified');\r
3697 \r
3698                 // error if no gid specified\r
3699                 if ($gid == "")\r
3700                         throw new BadRequestException('gid not specified');\r
3701 \r
3702                 // remove members\r
3703                 $members = group_get_members($gid);\r
3704                 foreach ($members as $member) {\r
3705                         $cid = $member['id'];\r
3706                         foreach ($users as $user) {\r
3707                                 $found = ($user['cid'] == $cid ? true : false);\r
3708                         }\r
3709                         if (!$found) {\r
3710                                 $ret = group_rmv_member($uid, $name, $cid);\r
3711                         }\r
3712                 }\r
3713 \r
3714                 // add members\r
3715                 $erroraddinguser = false;\r
3716                 $errorusers = array();\r
3717                 foreach ($users as $user) {\r
3718                         $cid = $user['cid'];\r
3719                         // check if user really exists as contact\r
3720                         $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",\r
3721                                 intval($cid),\r
3722                                 intval($uid));\r
3723                         if (count($contact))\r
3724                                 $result = group_add_member($uid, $name, $cid, $gid);\r
3725                         else {\r
3726                                 $erroraddinguser = true;\r
3727                                 $errorusers[] = $cid;\r
3728                         }\r
3729                 }\r
3730 \r
3731                 // return success message incl. missing users in array\r
3732                 $status = ($erroraddinguser ? "missing user" : "ok");\r
3733                 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);\r
3734                 return api_format_data("group_update", $type, array('result' => $success));\r
3735         }\r
3736         api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);\r
3737 \r
3738 \r
3739         function api_friendica_activity($type) {\r
3740 \r
3741                 $a = get_app();\r
3742 \r
3743                 if (api_user()===false) throw new ForbiddenException();\r
3744                 $verb = strtolower($a->argv[3]);\r
3745                 $verb = preg_replace("|\..*$|", "", $verb);\r
3746 \r
3747                 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);\r
3748 \r
3749                 $res = do_like($id, $verb);\r
3750 \r
3751                 if ($res) {\r
3752                         if ($type == "xml")\r
3753                                 $ok = "true";\r
3754                         else\r
3755                                 $ok = "ok";\r
3756                         return api_format_data('ok', $type, array('ok' => $ok));\r
3757                 } else {\r
3758                         throw new BadRequestException('Error adding activity');\r
3759                 }\r
3760 \r
3761         }\r
3762         api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);\r
3763         api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);\r
3764         api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);\r
3765         api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);\r
3766         api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);\r
3767         api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);\r
3768         api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);\r
3769         api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);\r
3770         api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);\r
3771         api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);\r
3772 \r
3773         /**\r
3774          * @brief Returns notifications\r
3775          *\r
3776          * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'\r
3777          * @return string\r
3778         */\r
3779         function api_friendica_notification($type) {\r
3780 \r
3781                 $a = get_app();\r
3782 \r
3783                 if (api_user()===false) throw new ForbiddenException();\r
3784                 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");\r
3785                 $nm = new NotificationsManager();\r
3786 \r
3787                 $notes = $nm->getAll(array(), "+seen -date", 50);\r
3788 \r
3789                 if ($type == "xml") {\r
3790                         $xmlnotes = array();\r
3791                         foreach ($notes AS $note)\r
3792                                 $xmlnotes[] = array("@attributes" => $note);\r
3793 \r
3794                         $notes = $xmlnotes;\r
3795                 }\r
3796 \r
3797                 return api_format_data("notes", $type, array('note' => $notes));\r
3798         }\r
3799 \r
3800         /**\r
3801          * @brief Set notification as seen and returns associated item (if possible)\r
3802          *\r
3803          * POST request with 'id' param as notification id\r
3804          *\r
3805          * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'\r
3806          * @return string\r
3807          */\r
3808         function api_friendica_notification_seen($type){\r
3809 \r
3810                 $a = get_app();\r
3811 \r
3812                 if (api_user()===false) throw new ForbiddenException();\r
3813                 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");\r
3814 \r
3815                 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);\r
3816 \r
3817                 $nm = new NotificationsManager();\r
3818                 $note = $nm->getByID($id);\r
3819                 if (is_null($note)) throw new BadRequestException("Invalid argument");\r
3820 \r
3821                 $nm->setSeen($note);\r
3822                 if ($note['otype']=='item') {\r
3823                         // would be really better with an ItemsManager and $im->getByID() :-P\r
3824                         $r = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",\r
3825                                 intval($note['iid']),\r
3826                                 intval(local_user())\r
3827                         );\r
3828                         if ($r!==false) {\r
3829                                 // we found the item, return it to the user\r
3830                                 $user_info = api_get_user($a);\r
3831                                 $ret = api_format_items($r,$user_info, false, $type);\r
3832                                 $data = array('status' => $ret);\r
3833                                 return api_format_data("status", $type, $data);\r
3834                         }\r
3835                         // the item can't be found, but we set the note as seen, so we count this as a success\r
3836                 }\r
3837                 return api_format_data('result', $type, array('result' => "success"));\r
3838         }\r
3839 \r
3840         api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);\r
3841         api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);\r
3842 \r
3843 \r
3844         /**\r
3845          * @brief update a direct_message to seen state\r
3846          *\r
3847          * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'\r
3848          * @return string (success result=ok, error result=error with error message)\r
3849          */\r
3850         function api_friendica_direct_messages_setseen($type){\r
3851                 $a = get_app();\r
3852                 if (api_user()===false) throw new ForbiddenException();\r
3853 \r
3854                 // params\r
3855                 $user_info = api_get_user($a);\r
3856                 $uid = $user_info['uid'];\r
3857                 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);\r
3858 \r
3859                 // return error if id is zero\r
3860                 if ($id == "") {\r
3861                         $answer = array('result' => 'error', 'message' => 'message id not specified');\r
3862                         return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));\r
3863                 }\r
3864 \r
3865                 // get data of the specified message id\r
3866                 $r = q("SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",\r
3867                         intval($id),\r
3868                         intval($uid));\r
3869                 // error message if specified id is not in database\r
3870                 if (!dbm::is_result($r)) {\r
3871                         $answer = array('result' => 'error', 'message' => 'message id not in database');\r
3872                         return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));\r
3873                 }\r
3874 \r
3875                 // update seen indicator\r
3876                 $result = q("UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",\r
3877                         intval($id),\r
3878                         intval($uid));\r
3879 \r
3880                 if ($result) {\r
3881                         // return success\r
3882                         $answer = array('result' => 'ok', 'message' => 'message set to seen');\r
3883                         return api_format_data("direct_message_setseen", $type, array('$result' => $answer));\r
3884                 } else {\r
3885                         $answer = array('result' => 'error', 'message' => 'unknown error');\r
3886                         return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));\r
3887                 }\r
3888         }\r
3889         api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);\r
3890 \r
3891 \r
3892 \r
3893 \r
3894         /**\r
3895          * @brief search for direct_messages containing a searchstring through api\r
3896          *\r
3897          * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'\r
3898          * @return string (success: success=true if found and search_result contains found messages\r
3899          *                          success=false if nothing was found, search_result='nothing found',\r
3900          *                 error: result=error with error message)\r
3901          */\r
3902         function api_friendica_direct_messages_search($type){\r
3903                 $a = get_app();\r
3904 \r
3905                 if (api_user()===false) throw new ForbiddenException();\r
3906 \r
3907                 // params\r
3908                 $user_info = api_get_user($a);\r
3909                 $searchstring = (x($_REQUEST,'searchstring') ? $_REQUEST['searchstring'] : "");\r
3910                 $uid = $user_info['uid'];\r
3911 \r
3912                 // error if no searchstring specified\r
3913                 if ($searchstring == "") {\r
3914                         $answer = array('result' => 'error', 'message' => 'searchstring not specified');\r
3915                         return api_format_data("direct_messages_search", $type, array('$result' => $answer));\r
3916                 }\r
3917 \r
3918                 // get data for the specified searchstring\r
3919                 $r = q("SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid`=%d AND `body` LIKE '%s' ORDER BY `mail`.`id` DESC",\r
3920                         intval($uid),\r
3921                         dbesc('%'.$searchstring.'%')\r
3922                 );\r
3923 \r
3924                 $profile_url = $user_info["url"];\r
3925                 // message if nothing was found\r
3926                 if (count($r) == 0)\r
3927                         $success = array('success' => false, 'search_results' => 'nothing found');\r
3928                 else {\r
3929                         $ret = Array();\r
3930                         foreach($r as $item) {\r
3931                                 if ($box == "inbox" || $item['from-url'] != $profile_url){\r
3932                                         $recipient = $user_info;\r
3933                                         $sender = api_get_user($a,normalise_link($item['contact-url']));\r
3934                                 }\r
3935                                 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){\r
3936                                         $recipient = api_get_user($a,normalise_link($item['contact-url']));\r
3937                                         $sender = $user_info;\r
3938                                 }\r
3939                                 $ret[]=api_format_messages($item, $recipient, $sender);\r
3940                         }\r
3941                         $success = array('success' => true, 'search_results' => $ret);\r
3942                 }\r
3943 \r
3944                 return api_format_data("direct_message_search", $type, array('$result' => $success));\r
3945         }\r
3946         api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);\r
3947 \r
3948 \r
3949         /**\r
3950          * @brief return data of all the profiles a user has to the client\r
3951          *\r
3952      * @param string $profile_id optional parameter to provide the id of the profile to be returned\r
3953          * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'\r
3954          * @return string\r
3955          */\r
3956     function api_friendica_profile_show($type){\r
3957         $a = get_app();\r
3958 \r
3959         if (api_user()===false) throw new ForbiddenException();\r
3960 \r
3961         // input params\r
3962                 $profileid = (x($_REQUEST,'profile_id') ? $_REQUEST['profile_id'] : 0);\r
3963 \r
3964         // retrieve general information about profiles for user\r
3965         $multi_profiles = feature_enabled(api_user(),'multi_profiles');\r
3966         $directory = get_config('system', 'directory');\r
3967 \r
3968                 // get data of the specified profile id or all profiles of the user if not specified\r
3969                 if ($profileid != 0) {\r
3970                         $r = q("SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",\r
3971                                 intval(api_user()),\r
3972                                 intval($profileid));\r
3973                         // error message if specified gid is not in database\r
3974                         if (count($r) == 0)\r
3975                                 throw new BadRequestException("profile_id not available");\r
3976                 }\r
3977                 else\r
3978                         $r = q("SELECT * FROM `profile` WHERE `uid` = %d",\r
3979                                 intval(api_user()));\r
3980 \r
3981         // loop through all returned profiles and retrieve data and users\r
3982         $k = 0;\r
3983                 foreach ($r as $rr) {\r
3984                         $profile = api_format_items_profiles($rr, $type);\r
3985 \r
3986             // select all users from contact table, loop and prepare standard return for user data\r
3987             $users = array();\r
3988             $r = q("SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",\r
3989                                 intval(api_user()),\r
3990                                 intval($rr['profile_id']));\r
3991 \r
3992                 foreach ($r as $rr) {\r
3993                 $user = api_get_user($a, $rr['nurl']);\r
3994                 ($type == "xml") ? $users[$k++.":user"] = $user : $users[] = $user;\r
3995             }\r
3996             $profile['users'] = $users;\r
3997 \r
3998             // add prepared profile data to array for final return\r
3999             if ($type == "xml") {\r
4000                 $profiles[$k++.":profile"] = $profile;\r
4001             } else {\r
4002                 $profiles[] = $profile;\r
4003             }\r
4004                 }\r
4005 \r
4006         // return settings, authenticated user and profiles data\r
4007         $result = array('multi_profiles' => $multi_profiles,\r
4008                         'global_dir' => $directory,\r
4009                         'friendica_owner' => api_get_user($a, intval(api_user())),\r
4010                         'profiles' => $profiles);\r
4011         return api_format_data("friendica_profiles", $type, array('$result' => $result));\r
4012     }\r
4013     api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);\r
4014 \r
4015 /*\r
4016 To.Do:\r
4017     [pagename] => api/1.1/statuses/lookup.json\r
4018     [id] => 605138389168451584\r
4019     [include_cards] => true\r
4020     [cards_platform] => Android-12\r
4021     [include_entities] => true\r
4022     [include_my_retweet] => 1\r
4023     [include_rts] => 1\r
4024     [include_reply_count] => true\r
4025     [include_descendent_reply_count] => true\r
4026 (?)\r
4027 \r
4028 \r
4029 Not implemented by now:\r
4030 statuses/retweets_of_me\r
4031 friendships/create\r
4032 friendships/destroy\r
4033 friendships/exists\r
4034 friendships/show\r
4035 account/update_location\r
4036 account/update_profile_background_image\r
4037 account/update_profile_image\r
4038 blocks/create\r
4039 blocks/destroy\r
4040 friendica/profile/update\r
4041 friendica/profile/create\r
4042 friendica/profile/delete\r
4043 \r
4044 Not implemented in status.net:\r
4045 statuses/retweeted_to_me\r
4046 statuses/retweeted_by_me\r
4047 direct_messages/destroy\r
4048 account/end_session\r
4049 account/update_delivery_device\r
4050 notifications/follow\r
4051 notifications/leave\r
4052 blocks/exists\r
4053 blocks/blocking\r
4054 lists\r
4055 */\r