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