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