]> git.mxchange.org Git - friendica.git/blob - include/api.php
Merge branch 'develop' of https://github.com/gerhard6380/friendica into develop
[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         }\r
2466 \r
2467         /**\r
2468          * @brief format items to be returned by api\r
2469          *\r
2470          * @param array $r array of items\r
2471          * @param array $user_info\r
2472          * @param bool $filter_user filter items by $user_info\r
2473          */\r
2474         function api_format_items($r,$user_info, $filter_user = false, $type = "json") {\r
2475 \r
2476                 $a = get_app();\r
2477 \r
2478                 $ret = Array();\r
2479 \r
2480                 foreach($r as $item) {\r
2481 \r
2482                         localize_item($item);\r
2483                         list($status_user, $owner_user) = api_item_get_user($a,$item);\r
2484 \r
2485                         // Look if the posts are matching if they should be filtered by user id\r
2486                         if ($filter_user AND ($status_user["id"] != $user_info["id"]))\r
2487                                 continue;\r
2488 \r
2489                         if ($item['thr-parent'] != $item['uri']) {\r
2490                                 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",\r
2491                                         intval(api_user()),\r
2492                                         dbesc($item['thr-parent']));\r
2493                                 if ($r)\r
2494                                         $in_reply_to_status_id = intval($r[0]['id']);\r
2495                                 else\r
2496                                         $in_reply_to_status_id = intval($item['parent']);\r
2497 \r
2498                                 $in_reply_to_status_id_str = (string) intval($item['parent']);\r
2499 \r
2500                                 $in_reply_to_screen_name = NULL;\r
2501                                 $in_reply_to_user_id = NULL;\r
2502                                 $in_reply_to_user_id_str = NULL;\r
2503 \r
2504                                 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",\r
2505                                         intval(api_user()),\r
2506                                         intval($in_reply_to_status_id));\r
2507                                 if ($r) {\r
2508                                         $r = q("SELECT * FROM `gcontact` WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));\r
2509 \r
2510                                         if ($r) {\r
2511                                                 if ($r[0]['nick'] == "")\r
2512                                                         $r[0]['nick'] = api_get_nick($r[0]["url"]);\r
2513 \r
2514                                                 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);\r
2515                                                 $in_reply_to_user_id = intval($r[0]['id']);\r
2516                                                 $in_reply_to_user_id_str = (string) intval($r[0]['id']);\r
2517                                         }\r
2518                                 }\r
2519                         } else {\r
2520                                 $in_reply_to_screen_name = NULL;\r
2521                                 $in_reply_to_user_id = NULL;\r
2522                                 $in_reply_to_status_id = NULL;\r
2523                                 $in_reply_to_user_id_str = NULL;\r
2524                                 $in_reply_to_status_id_str = NULL;\r
2525                         }\r
2526 \r
2527                         $converted = api_convert_item($item);\r
2528 \r
2529                         if ($type == "xml")\r
2530                                 $geo = "georss:point";\r
2531                         else\r
2532                                 $geo = "geo";\r
2533 \r
2534                         $status = array(\r
2535                                 'text'          => $converted["text"],\r
2536                                 'truncated' => False,\r
2537                                 'created_at'=> api_date($item['created']),\r
2538                                 'in_reply_to_status_id' => $in_reply_to_status_id,\r
2539                                 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,\r
2540                                 'source'    => (($item['app']) ? $item['app'] : 'web'),\r
2541                                 'id'            => intval($item['id']),\r
2542                                 'id_str'        => (string) intval($item['id']),\r
2543                                 'in_reply_to_user_id' => $in_reply_to_user_id,\r
2544                                 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,\r
2545                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,\r
2546                                 $geo => NULL,\r
2547                                 'favorited' => $item['starred'] ? true : false,\r
2548                                 'user' =>  $status_user ,\r
2549                                 'friendica_owner' => $owner_user,\r
2550                                 //'entities' => NULL,\r
2551                                 'statusnet_html'                => $converted["html"],\r
2552                                 'statusnet_conversation_id'     => $item['parent'],\r
2553                                 'friendica_activities' => api_format_items_activities($item, $type),\r
2554                         );\r
2555 \r
2556                         if (count($converted["attachments"]) > 0)\r
2557                                 $status["attachments"] = $converted["attachments"];\r
2558 \r
2559                         if (count($converted["entities"]) > 0)\r
2560                                 $status["entities"] = $converted["entities"];\r
2561 \r
2562                         if (($item['item_network'] != "") AND ($status["source"] == 'web'))\r
2563                                 $status["source"] = network_to_name($item['item_network'], $user_info['url']);\r
2564                         else if (($item['item_network'] != "") AND (network_to_name($item['item_network'], $user_info['url']) != $status["source"]))\r
2565                                 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');\r
2566 \r
2567 \r
2568                         // Retweets are only valid for top postings\r
2569                         // It doesn't work reliable with the link if its a feed\r
2570                         #$IsRetweet = ($item['owner-link'] != $item['author-link']);\r
2571                         #if ($IsRetweet)\r
2572                         #       $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));\r
2573 \r
2574 \r
2575                         if ($item["id"] == $item["parent"]) {\r
2576                                 $retweeted_item = api_share_as_retweet($item);\r
2577                                 if ($retweeted_item !== false) {\r
2578                                         $retweeted_status = $status;\r
2579                                         try {\r
2580                                                 $retweeted_status["user"] = api_get_user($a,$retweeted_item["author-link"]);\r
2581                                         } catch( BadRequestException $e ) {\r
2582                                                 // user not found. should be found?\r
2583                                                 /// @todo check if the user should be always found\r
2584                                                 $retweeted_status["user"] = array();\r
2585                                         }\r
2586 \r
2587                                         $rt_converted = api_convert_item($retweeted_item);\r
2588 \r
2589                                         $retweeted_status['text'] = $rt_converted["text"];\r
2590                                         $retweeted_status['statusnet_html'] = $rt_converted["html"];\r
2591                                         $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);\r
2592                                         $retweeted_status['created_at'] =  api_date($retweeted_item['created']);\r
2593                                         $status['retweeted_status'] = $retweeted_status;\r
2594                                 }\r
2595                         }\r
2596 \r
2597                         // "uid" and "self" are only needed for some internal stuff, so remove it from here\r
2598                         unset($status["user"]["uid"]);\r
2599                         unset($status["user"]["self"]);\r
2600 \r
2601                         if ($item["coord"] != "") {\r
2602                                 $coords = explode(' ',$item["coord"]);\r
2603                                 if (count($coords) == 2) {\r
2604                                         if ($type == "json")\r
2605                                                 $status["geo"] = array('type' => 'Point',\r
2606                                                                 'coordinates' => array((float) $coords[0],\r
2607                                                                                         (float) $coords[1]));\r
2608                                         else // Not sure if this is the official format - if someone founds a documentation we can check\r
2609                                                 $status["georss:point"] = $item["coord"];\r
2610                                 }\r
2611                         }\r
2612                         $ret[] = $status;\r
2613                 };\r
2614                 return $ret;\r
2615         }\r
2616 \r
2617 \r
2618         function api_account_rate_limit_status($type) {\r
2619 \r
2620                 if ($type == "xml")\r
2621                         $hash = array(\r
2622                                         'remaining-hits' => (string) 150,\r
2623                                         '@attributes' => array("type" => "integer"),\r
2624                                         'hourly-limit' => (string) 150,\r
2625                                         '@attributes2' => array("type" => "integer"),\r
2626                                         'reset-time' => datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME),\r
2627                                         '@attributes3' => array("type" => "datetime"),\r
2628                                         'reset_time_in_seconds' => strtotime('now + 1 hour'),\r
2629                                         '@attributes4' => array("type" => "integer"),\r
2630                                 );\r
2631                 else\r
2632                         $hash = array(\r
2633                                         'reset_time_in_seconds' => strtotime('now + 1 hour'),\r
2634                                         'remaining_hits' => (string) 150,\r
2635                                         'hourly_limit' => (string) 150,\r
2636                                         'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),\r
2637                                 );\r
2638 \r
2639                 return api_format_data('hash', $type, array('hash' => $hash));\r
2640         }\r
2641         api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);\r
2642 \r
2643         function api_help_test($type) {\r
2644                 if ($type == 'xml')\r
2645                         $ok = "true";\r
2646                 else\r
2647                         $ok = "ok";\r
2648 \r
2649                 return api_format_data('ok', $type, array("ok" => $ok));\r
2650         }\r
2651         api_register_func('api/help/test','api_help_test',false);\r
2652 \r
2653         function api_lists($type) {\r
2654                 $ret = array();\r
2655                 return api_format_data('lists', $type, array("lists_list" => $ret));\r
2656         }\r
2657         api_register_func('api/lists','api_lists',true);\r
2658 \r
2659         function api_lists_list($type) {\r
2660                 $ret = array();\r
2661                 return api_format_data('lists', $type, array("lists_list" => $ret));\r
2662         }\r
2663         api_register_func('api/lists/list','api_lists_list',true);\r
2664 \r
2665         /**\r
2666          *  https://dev.twitter.com/docs/api/1/get/statuses/friends\r
2667          *  This function is deprecated by Twitter\r
2668          *  returns: json, xml\r
2669          **/\r
2670         function api_statuses_f($type, $qtype) {\r
2671 \r
2672                 $a = get_app();\r
2673 \r
2674                 if (api_user()===false) throw new ForbiddenException();\r
2675                 $user_info = api_get_user($a);\r
2676 \r
2677                 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){\r
2678                         /* this is to stop Hotot to load friends multiple times\r
2679                         *  I'm not sure if I'm missing return something or\r
2680                         *  is a bug in hotot. Workaround, meantime\r
2681                         */\r
2682 \r
2683                         /*$ret=Array();\r
2684                         return array('$users' => $ret);*/\r
2685                         return false;\r
2686                 }\r
2687 \r
2688                 if($qtype == 'friends')\r
2689                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));\r
2690                 if($qtype == 'followers')\r
2691                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));\r
2692 \r
2693                 // friends and followers only for self\r
2694                 if ($user_info['self'] == 0)\r
2695                         $sql_extra = " AND false ";\r
2696 \r
2697                 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",\r
2698                         intval(api_user())\r
2699                 );\r
2700 \r
2701                 $ret = array();\r
2702                 foreach($r as $cid){\r
2703                         $user = api_get_user($a, $cid['nurl']);\r
2704                         // "uid" and "self" are only needed for some internal stuff, so remove it from here\r
2705                         unset($user["uid"]);\r
2706                         unset($user["self"]);\r
2707 \r
2708                         if ($user)\r
2709                                 $ret[] = $user;\r
2710                 }\r
2711 \r
2712                 return array('user' => $ret);\r
2713 \r
2714         }\r
2715         function api_statuses_friends($type){\r
2716                 $data =  api_statuses_f($type, "friends");\r
2717                 if ($data===false) return false;\r
2718                 return  api_format_data("users", $type, $data);\r
2719         }\r
2720         function api_statuses_followers($type){\r
2721                 $data = api_statuses_f($type, "followers");\r
2722                 if ($data===false) return false;\r
2723                 return  api_format_data("users", $type, $data);\r
2724         }\r
2725         api_register_func('api/statuses/friends','api_statuses_friends',true);\r
2726         api_register_func('api/statuses/followers','api_statuses_followers',true);\r
2727 \r
2728 \r
2729 \r
2730 \r
2731 \r
2732 \r
2733         function api_statusnet_config($type) {\r
2734 \r
2735                 $a = get_app();\r
2736 \r
2737                 $name = $a->config['sitename'];\r
2738                 $server = $a->get_hostname();\r
2739                 $logo = App::get_baseurl() . '/images/friendica-64.png';\r
2740                 $email = $a->config['admin_email'];\r
2741                 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');\r
2742                 $private = (($a->config['system']['block_public']) ? 'true' : 'false');\r
2743                 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);\r
2744                 if($a->config['api_import_size'])\r
2745                         $texlimit = string($a->config['api_import_size']);\r
2746                 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');\r
2747                 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',App::get_baseurl()) : '');\r
2748 \r
2749                 $config = array(\r
2750                         'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',\r
2751                                 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',\r
2752                                 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,\r
2753                                 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,\r
2754                                 'shorturllength' => '30',\r
2755                                 'friendica' => array(\r
2756                                                 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,\r
2757                                                 'FRIENDICA_VERSION' => FRIENDICA_VERSION,\r
2758                                                 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,\r
2759                                                 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION\r
2760                                                 )\r
2761                         ),\r
2762                 );\r
2763 \r
2764                 return api_format_data('config', $type, array('config' => $config));\r
2765 \r
2766         }\r
2767         api_register_func('api/statusnet/config','api_statusnet_config',false);\r
2768 \r
2769         function api_statusnet_version($type) {\r
2770                 // liar\r
2771                 $fake_statusnet_version = "0.9.7";\r
2772 \r
2773                 return api_format_data('version', $type, array('version' => $fake_statusnet_version));\r
2774         }\r
2775         api_register_func('api/statusnet/version','api_statusnet_version',false);\r
2776 \r
2777         /**\r
2778          * @todo use api_format_data() to return data\r
2779          */\r
2780         function api_ff_ids($type,$qtype) {\r
2781 \r
2782                 $a = get_app();\r
2783 \r
2784                 if(! api_user()) throw new ForbiddenException();\r
2785 \r
2786                 $user_info = api_get_user($a);\r
2787 \r
2788                 if($qtype == 'friends')\r
2789                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));\r
2790                 if($qtype == 'followers')\r
2791                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));\r
2792 \r
2793                 if (!$user_info["self"])\r
2794                         $sql_extra = " AND false ";\r
2795 \r
2796                 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);\r
2797 \r
2798                 $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
2799                         intval(api_user())\r
2800                 );\r
2801 \r
2802                 if(!dbm::is_result($r))\r
2803                         return;\r
2804 \r
2805                 $ids = array();\r
2806                 foreach($r as $rr)\r
2807                         if ($stringify_ids)\r
2808                                 $ids[] = $rr['id'];\r
2809                         else\r
2810                                 $ids[] = intval($rr['id']);\r
2811 \r
2812                 return api_format_data("ids", $type, array('id' => $ids));\r
2813         }\r
2814 \r
2815         function api_friends_ids($type) {\r
2816                 return api_ff_ids($type,'friends');\r
2817         }\r
2818         function api_followers_ids($type) {\r
2819                 return api_ff_ids($type,'followers');\r
2820         }\r
2821         api_register_func('api/friends/ids','api_friends_ids',true);\r
2822         api_register_func('api/followers/ids','api_followers_ids',true);\r
2823 \r
2824 \r
2825         function api_direct_messages_new($type) {\r
2826 \r
2827                 $a = get_app();\r
2828 \r
2829                 if (api_user()===false) throw new ForbiddenException();\r
2830 \r
2831                 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;\r
2832 \r
2833                 $sender = api_get_user($a);\r
2834 \r
2835                 if ($_POST['screen_name']) {\r
2836                         $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",\r
2837                                         intval(api_user()),\r
2838                                         dbesc($_POST['screen_name']));\r
2839 \r
2840                         // Selecting the id by priority, friendica first\r
2841                         api_best_nickname($r);\r
2842 \r
2843                         $recipient = api_get_user($a, $r[0]['nurl']);\r
2844                 } else\r
2845                         $recipient = api_get_user($a, $_POST['user_id']);\r
2846 \r
2847                 $replyto = '';\r
2848                 $sub     = '';\r
2849                 if (x($_REQUEST,'replyto')) {\r
2850                         $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',\r
2851                                         intval(api_user()),\r
2852                                         intval($_REQUEST['replyto']));\r
2853                         $replyto = $r[0]['parent-uri'];\r
2854                         $sub     = $r[0]['title'];\r
2855                 }\r
2856                 else {\r
2857                         if (x($_REQUEST,'title')) {\r
2858                                 $sub = $_REQUEST['title'];\r
2859                         }\r
2860                         else {\r
2861                                 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);\r
2862                         }\r
2863                 }\r
2864 \r
2865                 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);\r
2866 \r
2867                 if ($id>-1) {\r
2868                         $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));\r
2869                         $ret = api_format_messages($r[0], $recipient, $sender);\r
2870 \r
2871                 } else {\r
2872                         $ret = array("error"=>$id);\r
2873                 }\r
2874 \r
2875                 $data = Array('direct_message'=>$ret);\r
2876 \r
2877                 switch($type){\r
2878                         case "atom":\r
2879                         case "rss":\r
2880                                 $data = api_rss_extra($a, $data, $user_info);\r
2881                 }\r
2882 \r
2883                 return  api_format_data("direct-messages", $type, $data);\r
2884 \r
2885         }\r
2886         api_register_func('api/direct_messages/new','api_direct_messages_new',true, API_METHOD_POST);\r
2887 \r
2888 \r
2889         /**\r
2890          * @brief delete a direct_message from mail table through api\r
2891          *\r
2892          * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'\r
2893          * @return string\r
2894          */\r
2895         function api_direct_messages_destroy($type){\r
2896                 $a = get_app();\r
2897 \r
2898                 if (api_user()===false) throw new ForbiddenException();\r
2899 \r
2900                 // params\r
2901                 $user_info = api_get_user($a);\r
2902                 //required\r
2903                 $id = (x($_REQUEST,'id') ? $_REQUEST['id'] : 0);\r
2904                 // optional\r
2905                 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");\r
2906                 $verbose = (x($_GET,'friendica_verbose')?strtolower($_GET['friendica_verbose']):"false");\r
2907                 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented\r
2908 \r
2909                 $uid = $user_info['uid'];\r
2910                 // error if no id or parenturi specified (for clients posting parent-uri as well)\r
2911                 if ($verbose == "true") {\r
2912                         if ($id == 0 || $parenturi == "") {\r
2913                                 $answer = array('result' => 'error', 'message' => 'message id or parenturi not specified');\r
2914                                 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));\r
2915                         }\r
2916                 }\r
2917 \r
2918                 // BadRequestException if no id specified (for clients using Twitter API)\r
2919                 if ($id == 0) throw new BadRequestException('Message id not specified');\r
2920 \r
2921                 // add parent-uri to sql command if specified by calling app\r
2922                 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");\r
2923 \r
2924                 // get data of the specified message id\r
2925                 $r = q("SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,\r
2926                         intval($uid),\r
2927                         intval($id));\r
2928 \r
2929                 // error message if specified id is not in database\r
2930                 if (!dbm::is_result($r)) {\r
2931                         if ($verbose == "true") {\r
2932                                 $answer = array('result' => 'error', 'message' => 'message id not in database');\r
2933                                 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));\r
2934                         }\r
2935                         /// @todo BadRequestException ok for Twitter API clients?\r
2936                         throw new BadRequestException('message id not in database');\r
2937                 }\r
2938 \r
2939                 // delete message\r
2940                 $result = q("DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,\r
2941                         intval($uid),\r
2942                         intval($id));\r
2943 \r
2944                 if ($verbose == "true") {\r
2945                         if ($result) {\r
2946                                 // return success\r
2947                                 $answer = array('result' => 'ok', 'message' => 'message deleted');\r
2948                                 return api_format_data("direct_message_delete", $type, array('$result' => $answer));\r
2949                         }\r
2950                         else {\r
2951                                 $answer = array('result' => 'error', 'message' => 'unknown error');\r
2952                                 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));\r
2953                         }\r
2954                 }\r
2955                 /// @todo return JSON data like Twitter API not yet implemented\r
2956 \r
2957         }\r
2958         api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);\r
2959 \r
2960 \r
2961         function api_direct_messages_box($type, $box, $verbose) {\r
2962 \r
2963                 $a = get_app();\r
2964 \r
2965                 if (api_user()===false) throw new ForbiddenException();\r
2966 \r
2967                 // params\r
2968                 $count = (x($_GET,'count')?$_GET['count']:20);\r
2969                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);\r
2970                 if ($page<0) $page=0;\r
2971 \r
2972                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);\r
2973                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);\r
2974 \r
2975                 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");\r
2976                 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");\r
2977 \r
2978                 //  caller user info\r
2979                 unset($_REQUEST["user_id"]);\r
2980                 unset($_GET["user_id"]);\r
2981 \r
2982                 unset($_REQUEST["screen_name"]);\r
2983                 unset($_GET["screen_name"]);\r
2984 \r
2985                 $user_info = api_get_user($a);\r
2986                 $profile_url = $user_info["url"];\r
2987 \r
2988 \r
2989                 // pagination\r
2990                 $start = $page*$count;\r
2991 \r
2992                 // filters\r
2993                 if ($box=="sentbox") {\r
2994                         $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";\r
2995                 }\r
2996                 elseif ($box=="conversation") {\r
2997                         $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] )  ."'";\r
2998                 }\r
2999                 elseif ($box=="all") {\r
3000                         $sql_extra = "true";\r
3001                 }\r
3002                 elseif ($box=="inbox") {\r
3003                         $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";\r
3004                 }\r
3005 \r
3006                 if ($max_id > 0)\r
3007                         $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);\r
3008 \r
3009                 if ($user_id !="") {\r
3010                         $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);\r
3011                 }\r
3012                 elseif($screen_name !=""){\r
3013                         $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";\r
3014                 }\r
3015 \r
3016                 $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
3017                                 intval(api_user()),\r
3018                                 intval($since_id),\r
3019                                 intval($start), intval($count)\r
3020                 );\r
3021                 if ($verbose == "true") {\r
3022                         // stop execution and return error message if no mails available\r
3023                         if($r == null) {\r
3024                                 $answer = array('result' => 'error', 'message' => 'no mails available');\r
3025                                 return api_format_data("direct_messages_all", $type, array('$result' => $answer));\r
3026                         }\r
3027                 }\r
3028 \r
3029                 $ret = Array();\r
3030                 foreach($r as $item) {\r
3031                         if ($box == "inbox" || $item['from-url'] != $profile_url){\r
3032                                 $recipient = $user_info;\r
3033                                 $sender = api_get_user($a,normalise_link($item['contact-url']));\r
3034                         }\r
3035                         elseif ($box == "sentbox" || $item['from-url'] == $profile_url){\r
3036                                 $recipient = api_get_user($a,normalise_link($item['contact-url']));\r
3037                                 $sender = $user_info;\r
3038 \r
3039                         }\r
3040                         $ret[]=api_format_messages($item, $recipient, $sender);\r
3041                 }\r
3042 \r
3043 \r
3044                 $data = array('direct_message' => $ret);\r
3045                 switch($type){\r
3046                         case "atom":\r
3047                         case "rss":\r
3048                                 $data = api_rss_extra($a, $data, $user_info);\r
3049                 }\r
3050 \r
3051                 return  api_format_data("direct-messages", $type, $data);\r
3052 \r
3053         }\r
3054 \r
3055         function api_direct_messages_sentbox($type){\r
3056                 $verbose = (x($_GET,'friendica_verbose')?strtolower($_GET['friendica_verbose']):"false");\r
3057                 return api_direct_messages_box($type, "sentbox", $verbose);\r
3058         }\r
3059         function api_direct_messages_inbox($type){\r
3060                 $verbose = (x($_GET,'friendica_verbose')?strtolower($_GET['friendica_verbose']):"false");\r
3061                 return api_direct_messages_box($type, "inbox", $verbose);\r
3062         }\r
3063         function api_direct_messages_all($type){\r
3064                 $verbose = (x($_GET,'friendica_verbose')?strtolower($_GET['friendica_verbose']):"false");\r
3065                 return api_direct_messages_box($type, "all", $verbose);\r
3066         }\r
3067         function api_direct_messages_conversation($type){\r
3068                 $verbose = (x($_GET,'friendica_verbose')?strtolower($_GET['friendica_verbose']):"false");\r
3069                 return api_direct_messages_box($type, "conversation", $verbose);\r
3070         }\r
3071         api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);\r
3072         api_register_func('api/direct_messages/all','api_direct_messages_all',true);\r
3073         api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);\r
3074         api_register_func('api/direct_messages','api_direct_messages_inbox',true);\r
3075 \r
3076 \r
3077 \r
3078         function api_oauth_request_token($type){\r
3079                 try{\r
3080                         $oauth = new FKOAuth1();\r
3081                         $r = $oauth->fetch_request_token(OAuthRequest::from_request());\r
3082                 }catch(Exception $e){\r
3083                         echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();\r
3084                 }\r
3085                 echo $r;\r
3086                 killme();\r
3087         }\r
3088         function api_oauth_access_token($type){\r
3089                 try{\r
3090                         $oauth = new FKOAuth1();\r
3091                         $r = $oauth->fetch_access_token(OAuthRequest::from_request());\r
3092                 }catch(Exception $e){\r
3093                         echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();\r
3094                 }\r
3095                 echo $r;\r
3096                 killme();\r
3097         }\r
3098 \r
3099         api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);\r
3100         api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);\r
3101 \r
3102 \r
3103         function api_fr_photos_list($type) {\r
3104                 if (api_user()===false) throw new ForbiddenException();\r
3105                 $r = q("select `resource-id`, max(scale) as scale, album, filename, type from photo\r
3106                                 where uid = %d and album != 'Contact Photos' group by `resource-id`",\r
3107                         intval(local_user())\r
3108                 );\r
3109                 $typetoext = array(\r
3110                 'image/jpeg' => 'jpg',\r
3111                 'image/png' => 'png',\r
3112                 'image/gif' => 'gif'\r
3113                 );\r
3114                 $data = array('photo'=>array());\r
3115                 if($r) {\r
3116                         foreach($r as $rr) {\r
3117                                 $photo = array();\r
3118                                 $photo['id'] = $rr['resource-id'];\r
3119                                 $photo['album'] = $rr['album'];\r
3120                                 $photo['filename'] = $rr['filename'];\r
3121                                 $photo['type'] = $rr['type'];\r
3122                                 $thumb = App::get_baseurl()."/photo/".$rr['resource-id']."-".$rr['scale'].".".$typetoext[$rr['type']];\r
3123 \r
3124                                 if ($type == "xml")\r
3125                                         $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);\r
3126                                 else {\r
3127                                         $photo['thumb'] = $thumb;\r
3128                                         $data['photo'][] = $photo;\r
3129                                 }\r
3130                         }\r
3131                 }\r
3132                 return  api_format_data("photos", $type, $data);\r
3133         }\r
3134 \r
3135         function api_fr_photo_detail($type) {\r
3136                 if (api_user()===false) throw new ForbiddenException();\r
3137                 if(!x($_REQUEST,'photo_id')) throw new BadRequestException("No photo id.");\r
3138 \r
3139                 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);\r
3140                 $scale_sql = ($scale === false ? "" : sprintf("and scale=%d",intval($scale)));\r
3141                 $data_sql = ($scale === false ? "" : "data, ");\r
3142 \r
3143                 $r = q("select %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,\r
3144                                                 `type`, `height`, `width`, `datasize`, `profile`, min(`scale`) as minscale, max(`scale`) as maxscale\r
3145                                 from photo where `uid` = %d and `resource-id` = '%s' %s group by `resource-id`",\r
3146                         $data_sql,\r
3147                         intval(local_user()),\r
3148                         dbesc($_REQUEST['photo_id']),\r
3149                         $scale_sql\r
3150                 );\r
3151 \r
3152                 $typetoext = array(\r
3153                 'image/jpeg' => 'jpg',\r
3154                 'image/png' => 'png',\r
3155                 'image/gif' => 'gif'\r
3156                 );\r
3157 \r
3158                 if ($r) {\r
3159                         $data = array('photo' => $r[0]);\r
3160                         $data['photo']['id'] = $data['photo']['resource-id'];\r
3161                         if ($scale !== false) {\r
3162                                 $data['photo']['data'] = base64_encode($data['photo']['data']);\r
3163                         } else {\r
3164                                 unset($data['photo']['datasize']); //needed only with scale param\r
3165                         }\r
3166                         if ($type == "xml") {\r
3167                                 $data['photo']['links'] = array();\r
3168                                 for ($k=intval($data['photo']['minscale']); $k<=intval($data['photo']['maxscale']); $k++)\r
3169                                         $data['photo']['links'][$k.":link"]["@attributes"] = array("type" => $data['photo']['type'],\r
3170                                                                                         "scale" => $k,\r
3171                                                                                         "href" => App::get_baseurl()."/photo/".$data['photo']['resource-id']."-".$k.".".$typetoext[$data['photo']['type']]);\r
3172                         } else {\r
3173                                 $data['photo']['link'] = array();\r
3174                                 for ($k=intval($data['photo']['minscale']); $k<=intval($data['photo']['maxscale']); $k++) {\r
3175                                         $data['photo']['link'][$k] = App::get_baseurl()."/photo/".$data['photo']['resource-id']."-".$k.".".$typetoext[$data['photo']['type']];\r
3176                                 }\r
3177                         }\r
3178                         unset($data['photo']['resource-id']);\r
3179                         unset($data['photo']['minscale']);\r
3180                         unset($data['photo']['maxscale']);\r
3181 \r
3182                 } else {\r
3183                         throw new NotFoundException();\r
3184                 }\r
3185 \r
3186                 return api_format_data("photo_detail", $type, $data);\r
3187         }\r
3188 \r
3189         api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);\r
3190         api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);\r
3191 \r
3192 \r
3193 \r
3194         /**\r
3195          * similar as /mod/redir.php\r
3196          * redirect to 'url' after dfrn auth\r
3197          *\r
3198          * why this when there is mod/redir.php already?\r
3199          * This use api_user() and api_login()\r
3200          *\r
3201          * params\r
3202          *              c_url: url of remote contact to auth to\r
3203          *              url: string, url to redirect after auth\r
3204          */\r
3205         function api_friendica_remoteauth() {\r
3206                 $url = ((x($_GET,'url')) ? $_GET['url'] : '');\r
3207                 $c_url = ((x($_GET,'c_url')) ? $_GET['c_url'] : '');\r
3208 \r
3209                 if ($url === '' || $c_url === '')\r
3210                         throw new BadRequestException("Wrong parameters.");\r
3211 \r
3212                 $c_url = normalise_link($c_url);\r
3213 \r
3214                 // traditional DFRN\r
3215 \r
3216                 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",\r
3217                         dbesc($c_url),\r
3218                         intval(api_user())\r
3219                 );\r
3220 \r
3221                 if ((! count($r)) || ($r[0]['network'] !== NETWORK_DFRN))\r
3222                         throw new BadRequestException("Unknown contact");\r
3223 \r
3224                 $cid = $r[0]['id'];\r
3225 \r
3226                 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);\r
3227 \r
3228                 if($r[0]['duplex'] && $r[0]['issued-id']) {\r
3229                         $orig_id = $r[0]['issued-id'];\r
3230                         $dfrn_id = '1:' . $orig_id;\r
3231                 }\r
3232                 if($r[0]['duplex'] && $r[0]['dfrn-id']) {\r
3233                         $orig_id = $r[0]['dfrn-id'];\r
3234                         $dfrn_id = '0:' . $orig_id;\r
3235                 }\r
3236 \r
3237                 $sec = random_string();\r
3238 \r
3239                 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)\r
3240                         VALUES( %d, %s, '%s', '%s', %d )",\r
3241                         intval(api_user()),\r
3242                         intval($cid),\r
3243                         dbesc($dfrn_id),\r
3244                         dbesc($sec),\r
3245                         intval(time() + 45)\r
3246                 );\r
3247 \r
3248                 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);\r
3249                 $dest = (($url) ? '&destination_url=' . $url : '');\r
3250                 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id\r
3251                                 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION\r
3252                                 . '&type=profile&sec=' . $sec . $dest . $quiet );\r
3253         }\r
3254         api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);\r
3255 \r
3256         /**\r
3257          * @brief Return the item shared, if the item contains only the [share] tag\r
3258          *\r
3259          * @param array $item Sharer item\r
3260          * @return array Shared item or false if not a reshare\r
3261          */\r
3262         function api_share_as_retweet(&$item) {\r
3263                 $body = trim($item["body"]);\r
3264 \r
3265                 if (diaspora::is_reshare($body, false)===false) {\r
3266                         return false;\r
3267                 }\r
3268 \r
3269                 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);\r
3270                 // Skip if there is no shared message in there\r
3271                 // we already checked this in diaspora::is_reshare()\r
3272                 // but better one more than one less...\r
3273                 if ($body == $attributes)\r
3274                         return false;\r
3275 \r
3276 \r
3277                 // build the fake reshared item\r
3278                 $reshared_item = $item;\r
3279 \r
3280                 $author = "";\r
3281                 preg_match("/author='(.*?)'/ism", $attributes, $matches);\r
3282                 if ($matches[1] != "")\r
3283                         $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');\r
3284 \r
3285                 preg_match('/author="(.*?)"/ism', $attributes, $matches);\r
3286                 if ($matches[1] != "")\r
3287                         $author = $matches[1];\r
3288 \r
3289                 $profile = "";\r
3290                 preg_match("/profile='(.*?)'/ism", $attributes, $matches);\r
3291                 if ($matches[1] != "")\r
3292                         $profile = $matches[1];\r
3293 \r
3294                 preg_match('/profile="(.*?)"/ism', $attributes, $matches);\r
3295                 if ($matches[1] != "")\r
3296                         $profile = $matches[1];\r
3297 \r
3298                 $avatar = "";\r
3299                 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);\r
3300                 if ($matches[1] != "")\r
3301                         $avatar = $matches[1];\r
3302 \r
3303                 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);\r
3304                 if ($matches[1] != "")\r
3305                         $avatar = $matches[1];\r
3306 \r
3307                 $link = "";\r
3308                 preg_match("/link='(.*?)'/ism", $attributes, $matches);\r
3309                 if ($matches[1] != "")\r
3310                         $link = $matches[1];\r
3311 \r
3312                 preg_match('/link="(.*?)"/ism', $attributes, $matches);\r
3313                 if ($matches[1] != "")\r
3314                         $link = $matches[1];\r
3315 \r
3316                 $posted = "";\r
3317                 preg_match("/posted='(.*?)'/ism", $attributes, $matches);\r
3318                 if ($matches[1] != "")\r
3319                         $posted= $matches[1];\r
3320 \r
3321                 preg_match('/posted="(.*?)"/ism', $attributes, $matches);\r
3322                 if ($matches[1] != "")\r
3323                         $posted = $matches[1];\r
3324 \r
3325                 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);\r
3326 \r
3327                 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == ""))\r
3328                         return false;\r
3329 \r
3330 \r
3331 \r
3332                 $reshared_item["body"] = $shared_body;\r
3333                 $reshared_item["author-name"] = $author;\r
3334                 $reshared_item["author-link"] = $profile;\r
3335                 $reshared_item["author-avatar"] = $avatar;\r
3336                 $reshared_item["plink"] = $link;\r
3337                 $reshared_item["created"] = $posted;\r
3338                 $reshared_item["edited"] = $posted;\r
3339 \r
3340                 return $reshared_item;\r
3341 \r
3342         }\r
3343 \r
3344         function api_get_nick($profile) {\r
3345                 /* To-Do:\r
3346                  - remove trailing junk from profile url\r
3347                  - pump.io check has to check the website\r
3348                 */\r
3349 \r
3350                 $nick = "";\r
3351 \r
3352                 $r = q("SELECT `nick` FROM `gcontact` WHERE `nurl` = '%s'",\r
3353                         dbesc(normalise_link($profile)));\r
3354                 if ($r)\r
3355                         $nick = $r[0]["nick"];\r
3356 \r
3357                 if (!$nick == "") {\r
3358                         $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",\r
3359                                 dbesc(normalise_link($profile)));\r
3360                         if ($r)\r
3361                                 $nick = $r[0]["nick"];\r
3362                 }\r
3363 \r
3364                 if (!$nick == "") {\r
3365                         $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);\r
3366                         if ($friendica != $profile)\r
3367                                 $nick = $friendica;\r
3368                 }\r
3369 \r
3370                 if (!$nick == "") {\r
3371                         $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);\r
3372                         if ($diaspora != $profile)\r
3373                                 $nick = $diaspora;\r
3374                 }\r
3375 \r
3376                 if (!$nick == "") {\r
3377                         $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);\r
3378                         if ($twitter != $profile)\r
3379                                 $nick = $twitter;\r
3380                 }\r
3381 \r
3382 \r
3383                 if (!$nick == "") {\r
3384                         $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);\r
3385                         if ($StatusnetHost != $profile) {\r
3386                                 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);\r
3387                                 if ($StatusnetUser != $profile) {\r
3388                                         $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);\r
3389                                         $user = json_decode($UserData);\r
3390                                         if ($user)\r
3391                                                 $nick = $user->screen_name;\r
3392                                 }\r
3393                         }\r
3394                 }\r
3395 \r
3396                 // To-Do: look at the page if its really a pumpio site\r
3397                 //if (!$nick == "") {\r
3398                 //      $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");\r
3399                 //      if ($pumpio != $profile)\r
3400                 //              $nick = $pumpio;\r
3401                         //      <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">\r
3402 \r
3403                 //}\r
3404 \r
3405                 if ($nick != "")\r
3406                         return($nick);\r
3407 \r
3408                 return(false);\r
3409         }\r
3410 \r
3411         function api_clean_plain_items($Text) {\r
3412                 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");\r
3413 \r
3414                 $Text = bb_CleanPictureLinks($Text);\r
3415                 $URLSearchString = "^\[\]";\r
3416 \r
3417                 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);\r
3418 \r
3419                 if ($include_entities == "true") {\r
3420                         $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);\r
3421                 }\r
3422 \r
3423                 // Simplify "attachment" element\r
3424                 $Text = api_clean_attachments($Text);\r
3425 \r
3426                 return($Text);\r
3427         }\r
3428 \r
3429         /**\r
3430          * @brief Removes most sharing information for API text export\r
3431          *\r
3432          * @param string $body The original body\r
3433          *\r
3434          * @return string Cleaned body\r
3435          */\r
3436         function api_clean_attachments($body) {\r
3437                 $data = get_attachment_data($body);\r
3438 \r
3439                 if (!$data)\r
3440                         return $body;\r
3441 \r
3442                 $body = "";\r
3443 \r
3444                 if (isset($data["text"]))\r
3445                         $body = $data["text"];\r
3446 \r
3447                 if (($body == "") AND (isset($data["title"])))\r
3448                         $body = $data["title"];\r
3449 \r
3450                 if (isset($data["url"]))\r
3451                         $body .= "\n".$data["url"];\r
3452 \r
3453                 $body .= $data["after"];\r
3454 \r
3455                 return $body;\r
3456         }\r
3457 \r
3458         function api_best_nickname(&$contacts) {\r
3459                 $best_contact = array();\r
3460 \r
3461                 if (count($contact) == 0)\r
3462                         return;\r
3463 \r
3464                 foreach ($contacts AS $contact)\r
3465                         if ($contact["network"] == "") {\r
3466                                 $contact["network"] = "dfrn";\r
3467                                 $best_contact = array($contact);\r
3468                         }\r
3469 \r
3470                 if (sizeof($best_contact) == 0)\r
3471                         foreach ($contacts AS $contact)\r
3472                                 if ($contact["network"] == "dfrn")\r
3473                                         $best_contact = array($contact);\r
3474 \r
3475                 if (sizeof($best_contact) == 0)\r
3476                         foreach ($contacts AS $contact)\r
3477                                 if ($contact["network"] == "dspr")\r
3478                                         $best_contact = array($contact);\r
3479 \r
3480                 if (sizeof($best_contact) == 0)\r
3481                         foreach ($contacts AS $contact)\r
3482                                 if ($contact["network"] == "stat")\r
3483                                         $best_contact = array($contact);\r
3484 \r
3485                 if (sizeof($best_contact) == 0)\r
3486                         foreach ($contacts AS $contact)\r
3487                                 if ($contact["network"] == "pump")\r
3488                                         $best_contact = array($contact);\r
3489 \r
3490                 if (sizeof($best_contact) == 0)\r
3491                         foreach ($contacts AS $contact)\r
3492                                 if ($contact["network"] == "twit")\r
3493                                         $best_contact = array($contact);\r
3494 \r
3495                 if (sizeof($best_contact) == 1)\r
3496                         $contacts = $best_contact;\r
3497                 else\r
3498                         $contacts = array($contacts[0]);\r
3499         }\r
3500 \r
3501         // return all or a specified group of the user with the containing contacts\r
3502         function api_friendica_group_show($type) {\r
3503 \r
3504                 $a = get_app();\r
3505 \r
3506                 if (api_user()===false) throw new ForbiddenException();\r
3507 \r
3508                 // params\r
3509                 $user_info = api_get_user($a);\r
3510                 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);\r
3511                 $uid = $user_info['uid'];\r
3512 \r
3513                 // get data of the specified group id or all groups if not specified\r
3514                 if ($gid != 0) {\r
3515                         $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",\r
3516                                 intval($uid),\r
3517                                 intval($gid));\r
3518                         // error message if specified gid is not in database\r
3519                         if (count($r) == 0)\r
3520                                 throw new BadRequestException("gid not available");\r
3521                 }\r
3522                 else\r
3523                         $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",\r
3524                                 intval($uid));\r
3525 \r
3526                 // loop through all groups and retrieve all members for adding data in the user array\r
3527                 foreach ($r as $rr) {\r
3528                         $members = group_get_members($rr['id']);\r
3529                         $users = array();\r
3530 \r
3531                         if ($type == "xml") {\r
3532                                 $user_element = "users";\r
3533                                 $k = 0;\r
3534                                 foreach ($members as $member) {\r
3535                                         $user = api_get_user($a, $member['nurl']);\r
3536                                         $users[$k++.":user"] = $user;\r
3537                                 }\r
3538                         } else {\r
3539                                 $user_element = "user";\r
3540                                 foreach ($members as $member) {\r
3541                                         $user = api_get_user($a, $member['nurl']);\r
3542                                         $users[] = $user;\r
3543                                 }\r
3544                         }\r
3545                         $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);\r
3546                 }\r
3547                 return api_format_data("groups", $type, array('group' => $grps));\r
3548         }\r
3549         api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);\r
3550 \r
3551 \r
3552         // delete the specified group of the user\r
3553         function api_friendica_group_delete($type) {\r
3554 \r
3555                 $a = get_app();\r
3556 \r
3557                 if (api_user()===false) throw new ForbiddenException();\r
3558 \r
3559                 // params\r
3560                 $user_info = api_get_user($a);\r
3561                 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);\r
3562                 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");\r
3563                 $uid = $user_info['uid'];\r
3564 \r
3565                 // error if no gid specified\r
3566                 if ($gid == 0 || $name == "")\r
3567                         throw new BadRequestException('gid or name not specified');\r
3568 \r
3569                 // get data of the specified group id\r
3570                 $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",\r
3571                         intval($uid),\r
3572                         intval($gid));\r
3573                 // error message if specified gid is not in database\r
3574                 if (count($r) == 0)\r
3575                         throw new BadRequestException('gid not available');\r
3576 \r
3577                 // get data of the specified group id and group name\r
3578                 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",\r
3579                         intval($uid),\r
3580                         intval($gid),\r
3581                         dbesc($name));\r
3582                 // error message if specified gid is not in database\r
3583                 if (count($rname) == 0)\r
3584                         throw new BadRequestException('wrong group name');\r
3585 \r
3586                 // delete group\r
3587                 $ret = group_rmv($uid, $name);\r
3588                 if ($ret) {\r
3589                         // return success\r
3590                         $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());\r
3591                         return api_format_data("group_delete", $type, array('result' => $success));\r
3592                 }\r
3593                 else\r
3594                         throw new BadRequestException('other API error');\r
3595         }\r
3596         api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);\r
3597 \r
3598 \r
3599         // create the specified group with the posted array of contacts\r
3600         function api_friendica_group_create($type) {\r
3601 \r
3602                 $a = get_app();\r
3603 \r
3604                 if (api_user()===false) throw new ForbiddenException();\r
3605 \r
3606                 // params\r
3607                 $user_info = api_get_user($a);\r
3608                 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");\r
3609                 $uid = $user_info['uid'];\r
3610                 $json = json_decode($_POST['json'], true);\r
3611                 $users = $json['user'];\r
3612 \r
3613                 // error if no name specified\r
3614                 if ($name == "")\r
3615                         throw new BadRequestException('group name not specified');\r
3616 \r
3617                 // get data of the specified group name\r
3618                 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",\r
3619                         intval($uid),\r
3620                         dbesc($name));\r
3621                 // error message if specified group name already exists\r
3622                 if (count($rname) != 0)\r
3623                         throw new BadRequestException('group name already exists');\r
3624 \r
3625                 // check if specified group name is a deleted group\r
3626                 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",\r
3627                         intval($uid),\r
3628                         dbesc($name));\r
3629                 // error message if specified group name already exists\r
3630                 if (count($rname) != 0)\r
3631                         $reactivate_group = true;\r
3632 \r
3633                 // create group\r
3634                 $ret = group_add($uid, $name);\r
3635                 if ($ret)\r
3636                         $gid = group_byname($uid, $name);\r
3637                 else\r
3638                         throw new BadRequestException('other API error');\r
3639 \r
3640                 // add members\r
3641                 $erroraddinguser = false;\r
3642                 $errorusers = array();\r
3643                 foreach ($users as $user) {\r
3644                         $cid = $user['cid'];\r
3645                         // check if user really exists as contact\r
3646                         $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",\r
3647                                 intval($cid),\r
3648                                 intval($uid));\r
3649                         if (count($contact))\r
3650                                 $result = group_add_member($uid, $name, $cid, $gid);\r
3651                         else {\r
3652                                 $erroraddinguser = true;\r
3653                                 $errorusers[] = $cid;\r
3654                         }\r
3655                 }\r
3656 \r
3657                 // return success message incl. missing users in array\r
3658                 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));\r
3659                 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);\r
3660                 return api_format_data("group_create", $type, array('result' => $success));\r
3661         }\r
3662         api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);\r
3663 \r
3664 \r
3665         // update the specified group with the posted array of contacts\r
3666         function api_friendica_group_update($type) {\r
3667 \r
3668                 $a = get_app();\r
3669 \r
3670                 if (api_user()===false) throw new ForbiddenException();\r
3671 \r
3672                 // params\r
3673                 $user_info = api_get_user($a);\r
3674                 $uid = $user_info['uid'];\r
3675                 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);\r
3676                 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");\r
3677                 $json = json_decode($_POST['json'], true);\r
3678                 $users = $json['user'];\r
3679 \r
3680                 // error if no name specified\r
3681                 if ($name == "")\r
3682                         throw new BadRequestException('group name not specified');\r
3683 \r
3684                 // error if no gid specified\r
3685                 if ($gid == "")\r
3686                         throw new BadRequestException('gid not specified');\r
3687 \r
3688                 // remove members\r
3689                 $members = group_get_members($gid);\r
3690                 foreach ($members as $member) {\r
3691                         $cid = $member['id'];\r
3692                         foreach ($users as $user) {\r
3693                                 $found = ($user['cid'] == $cid ? true : false);\r
3694                         }\r
3695                         if (!$found) {\r
3696                                 $ret = group_rmv_member($uid, $name, $cid);\r
3697                         }\r
3698                 }\r
3699 \r
3700                 // add members\r
3701                 $erroraddinguser = false;\r
3702                 $errorusers = array();\r
3703                 foreach ($users as $user) {\r
3704                         $cid = $user['cid'];\r
3705                         // check if user really exists as contact\r
3706                         $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",\r
3707                                 intval($cid),\r
3708                                 intval($uid));\r
3709                         if (count($contact))\r
3710                                 $result = group_add_member($uid, $name, $cid, $gid);\r
3711                         else {\r
3712                                 $erroraddinguser = true;\r
3713                                 $errorusers[] = $cid;\r
3714                         }\r
3715                 }\r
3716 \r
3717                 // return success message incl. missing users in array\r
3718                 $status = ($erroraddinguser ? "missing user" : "ok");\r
3719                 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);\r
3720                 return api_format_data("group_update", $type, array('result' => $success));\r
3721         }\r
3722         api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);\r
3723 \r
3724 \r
3725         function api_friendica_activity($type) {\r
3726 \r
3727                 $a = get_app();\r
3728 \r
3729                 if (api_user()===false) throw new ForbiddenException();\r
3730                 $verb = strtolower($a->argv[3]);\r
3731                 $verb = preg_replace("|\..*$|", "", $verb);\r
3732 \r
3733                 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);\r
3734 \r
3735                 $res = do_like($id, $verb);\r
3736 \r
3737                 if ($res) {\r
3738                         if ($type == "xml")\r
3739                                 $ok = "true";\r
3740                         else\r
3741                                 $ok = "ok";\r
3742                         return api_format_data('ok', $type, array('ok' => $ok));\r
3743                 } else {\r
3744                         throw new BadRequestException('Error adding activity');\r
3745                 }\r
3746 \r
3747         }\r
3748         api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);\r
3749         api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);\r
3750         api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);\r
3751         api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);\r
3752         api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);\r
3753         api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);\r
3754         api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);\r
3755         api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);\r
3756         api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);\r
3757         api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);\r
3758 \r
3759         /**\r
3760          * @brief Returns notifications\r
3761          *\r
3762          * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'\r
3763          * @return string\r
3764         */\r
3765         function api_friendica_notification($type) {\r
3766 \r
3767                 $a = get_app();\r
3768 \r
3769                 if (api_user()===false) throw new ForbiddenException();\r
3770                 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");\r
3771                 $nm = new NotificationsManager();\r
3772 \r
3773                 $notes = $nm->getAll(array(), "+seen -date", 50);\r
3774 \r
3775                 if ($type == "xml") {\r
3776                         $xmlnotes = array();\r
3777                         foreach ($notes AS $note)\r
3778                                 $xmlnotes[] = array("@attributes" => $note);\r
3779 \r
3780                         $notes = $xmlnotes;\r
3781                 }\r
3782 \r
3783                 return api_format_data("notes", $type, array('note' => $notes));\r
3784         }\r
3785 \r
3786         /**\r
3787          * @brief Set notification as seen and returns associated item (if possible)\r
3788          *\r
3789          * POST request with 'id' param as notification id\r
3790          *\r
3791          * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'\r
3792          * @return string\r
3793          */\r
3794         function api_friendica_notification_seen($type){\r
3795 \r
3796                 $a = get_app();\r
3797 \r
3798                 if (api_user()===false) throw new ForbiddenException();\r
3799                 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");\r
3800 \r
3801                 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);\r
3802 \r
3803                 $nm = new NotificationsManager();\r
3804                 $note = $nm->getByID($id);\r
3805                 if (is_null($note)) throw new BadRequestException("Invalid argument");\r
3806 \r
3807                 $nm->setSeen($note);\r
3808                 if ($note['otype']=='item') {\r
3809                         // would be really better with an ItemsManager and $im->getByID() :-P\r
3810                         $r = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",\r
3811                                 intval($note['iid']),\r
3812                                 intval(local_user())\r
3813                         );\r
3814                         if ($r!==false) {\r
3815                                 // we found the item, return it to the user\r
3816                                 $user_info = api_get_user($a);\r
3817                                 $ret = api_format_items($r,$user_info, false, $type);\r
3818                                 $data = array('status' => $ret);\r
3819                                 return api_format_data("status", $type, $data);\r
3820                         }\r
3821                         // the item can't be found, but we set the note as seen, so we count this as a success\r
3822                 }\r
3823                 return api_format_data('result', $type, array('result' => "success"));\r
3824         }\r
3825 \r
3826         api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);\r
3827         api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);\r
3828 \r
3829 \r
3830         /**\r
3831          * @brief update a direct_message to seen state\r
3832          *\r
3833          * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'\r
3834          * @return string (success result=ok, error result=error with error message)\r
3835          */\r
3836         function api_friendica_direct_messages_setseen($type){\r
3837                 $a = get_app();\r
3838                 if (api_user()===false) throw new ForbiddenException();\r
3839 \r
3840                 // params\r
3841                 $user_info = api_get_user($a);\r
3842                 $uid = $user_info['uid'];\r
3843                 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);\r
3844 \r
3845                 // return error if id is zero\r
3846                 if ($id == "") {\r
3847                         $answer = array('result' => 'error', 'message' => 'message id not specified');\r
3848                         return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));\r
3849                 }\r
3850 \r
3851                 // get data of the specified message id\r
3852                 $r = q("SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",\r
3853                         intval($id),\r
3854                         intval($uid));\r
3855                 // error message if specified id is not in database\r
3856                 if (!dbm::is_result($r)) {\r
3857                         $answer = array('result' => 'error', 'message' => 'message id not in database');\r
3858                         return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));\r
3859                 }\r
3860 \r
3861                 // update seen indicator\r
3862                 $result = q("UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",\r
3863                         intval($id),\r
3864                         intval($uid));\r
3865 \r
3866                 if ($result) {\r
3867                         // return success\r
3868                         $answer = array('result' => 'ok', 'message' => 'message set to seen');\r
3869                         return api_format_data("direct_message_setseen", $type, array('$result' => $answer));\r
3870                 } else {\r
3871                         $answer = array('result' => 'error', 'message' => 'unknown error');\r
3872                         return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));\r
3873                 }\r
3874         }\r
3875         api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);\r
3876 \r
3877 \r
3878 \r
3879 \r
3880         /**\r
3881          * @brief search for direct_messages containing a searchstring through api\r
3882          *\r
3883          * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'\r
3884          * @return string (success: success=true if found and search_result contains found messages\r
3885          *                          success=false if nothing was found, search_result='nothing found',\r
3886          *                 error: result=error with error message)\r
3887          */\r
3888         function api_friendica_direct_messages_search($type){\r
3889                 $a = get_app();\r
3890 \r
3891                 if (api_user()===false) throw new ForbiddenException();\r
3892 \r
3893                 // params\r
3894                 $user_info = api_get_user($a);\r
3895                 $searchstring = (x($_REQUEST,'searchstring') ? $_REQUEST['searchstring'] : "");\r
3896                 $uid = $user_info['uid'];\r
3897 \r
3898                 // error if no searchstring specified\r
3899                 if ($searchstring == "") {\r
3900                         $answer = array('result' => 'error', 'message' => 'searchstring not specified');\r
3901                         return api_format_data("direct_messages_search", $type, array('$result' => $answer));\r
3902                 }\r
3903 \r
3904                 // get data for the specified searchstring\r
3905                 $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
3906                         intval($uid),\r
3907                         dbesc('%'.$searchstring.'%')\r
3908                 );\r
3909 \r
3910                 $profile_url = $user_info["url"];\r
3911                 // message if nothing was found\r
3912                 if (count($r) == 0)\r
3913                         $success = array('success' => false, 'search_results' => 'nothing found');\r
3914                 else {\r
3915                         $ret = Array();\r
3916                         foreach($r as $item) {\r
3917                                 if ($box == "inbox" || $item['from-url'] != $profile_url){\r
3918                                         $recipient = $user_info;\r
3919                                         $sender = api_get_user($a,normalise_link($item['contact-url']));\r
3920                                 }\r
3921                                 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){\r
3922                                         $recipient = api_get_user($a,normalise_link($item['contact-url']));\r
3923                                         $sender = $user_info;\r
3924                                 }\r
3925                                 $ret[]=api_format_messages($item, $recipient, $sender);\r
3926                         }\r
3927                         $success = array('success' => true, 'search_results' => $ret);\r
3928                 }\r
3929 \r
3930                 return api_format_data("direct_message_search", $type, array('$result' => $success));\r
3931         }\r
3932         api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);\r
3933 \r
3934 \r
3935         /**\r
3936          * @brief return data of all the profiles a user has to the client\r
3937          *\r
3938      * @param string $profile_id optional parameter to provide the id of the profile to be returned\r
3939          * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'\r
3940          * @return string\r
3941          */\r
3942     function api_friendica_profile_show($type){\r
3943         $a = get_app();\r
3944 \r
3945         if (api_user()===false) throw new ForbiddenException();\r
3946 \r
3947         // input params\r
3948                 $profileid = (x($_REQUEST,'profile_id') ? $_REQUEST['profile_id'] : 0);\r
3949 \r
3950         // retrieve general information about profiles for user\r
3951         $multi_profiles = feature_enabled(api_user(),'multi_profiles');\r
3952         $directory = get_config('system', 'directory');\r
3953 \r
3954                 // get data of the specified profile id or all profiles of the user if not specified\r
3955                 if ($profileid != 0) {\r
3956                         $r = q("SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",\r
3957                                 intval(api_user()),\r
3958                                 intval($profileid));\r
3959                         // error message if specified gid is not in database\r
3960                         if (count($r) == 0)\r
3961                                 throw new BadRequestException("profile_id not available");\r
3962                 }\r
3963                 else\r
3964                         $r = q("SELECT * FROM `profile` WHERE `uid` = %d",\r
3965                                 intval(api_user()));\r
3966 \r
3967         // loop through all returned profiles and retrieve data and users\r
3968         $k = 0;\r
3969                 foreach ($r as $rr) {\r
3970                         $profile = api_format_items_profiles($rr, $type);\r
3971 \r
3972             // select all users from contact table, loop and prepare standard return for user data\r
3973             $users = array();\r
3974             $r = q("SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",\r
3975                                 intval(api_user()),\r
3976                                 intval($rr['profile_id']));\r
3977 \r
3978                 foreach ($r as $rr) {\r
3979                 $user = api_get_user($a, $rr['nurl']);\r
3980                 ($type == "xml") ? $users[$k++.":user"] = $user : $users[] = $user;\r
3981             }\r
3982             $profile['users'] = $users;\r
3983 \r
3984             // add prepared profile data to array for final return\r
3985             if ($type == "xml") {\r
3986                 $profiles[$k++.":profile"] = $profile;\r
3987             } else {\r
3988                 $profiles[] = $profile;\r
3989             }\r
3990                 }\r
3991 \r
3992         // return settings, authenticated user and profiles data\r
3993         $result = array('multi_profiles' => $multi_profiles ? true : false,\r
3994                         'global_dir' => $directory,\r
3995                         'friendica_owner' => api_get_user($a, intval(api_user())),\r
3996                         'profiles' => $profiles);\r
3997         return api_format_data("friendica_profiles", $type, array('$result' => $result));\r
3998     }\r
3999     api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);\r
4000 \r
4001 /*\r
4002 To.Do:\r
4003     [pagename] => api/1.1/statuses/lookup.json\r
4004     [id] => 605138389168451584\r
4005     [include_cards] => true\r
4006     [cards_platform] => Android-12\r
4007     [include_entities] => true\r
4008     [include_my_retweet] => 1\r
4009     [include_rts] => 1\r
4010     [include_reply_count] => true\r
4011     [include_descendent_reply_count] => true\r
4012 (?)\r
4013 \r
4014 \r
4015 Not implemented by now:\r
4016 statuses/retweets_of_me\r
4017 friendships/create\r
4018 friendships/destroy\r
4019 friendships/exists\r
4020 friendships/show\r
4021 account/update_location\r
4022 account/update_profile_background_image\r
4023 account/update_profile_image\r
4024 blocks/create\r
4025 blocks/destroy\r
4026 friendica/profile/update\r
4027 friendica/profile/create\r
4028 friendica/profile/delete\r
4029 \r
4030 Not implemented in status.net:\r
4031 statuses/retweeted_to_me\r
4032 statuses/retweeted_by_me\r
4033 direct_messages/destroy\r
4034 account/end_session\r
4035 account/update_delivery_device\r
4036 notifications/follow\r
4037 notifications/leave\r
4038 blocks/exists\r
4039 blocks/blocking\r
4040 lists\r
4041 */\r