]> git.mxchange.org Git - friendica.git/blob - include/ostatus.php
New OStatus implementation
[friendica.git] / include / ostatus.php
1 <?php
2 require_once("include/Contact.php");
3 require_once("include/threads.php");
4 require_once("include/html2bbcode.php");
5 require_once("include/bbcode.php");
6 require_once("include/items.php");
7 require_once("mod/share.php");
8 require_once("include/enotify.php");
9 require_once("include/socgraph.php");
10 require_once("include/Photo.php");
11 require_once("include/Scrape.php");
12 require_once("include/follow.php");
13 require_once("include/api.php");
14 require_once("mod/proxy.php");
15 require_once("include/ostatus2.php");
16
17 define('OSTATUS_DEFAULT_POLL_INTERVAL', 30); // given in minutes
18 define('OSTATUS_DEFAULT_POLL_TIMEFRAME', 1440); // given in minutes
19 define('OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS', 14400); // given in minutes
20
21 function ostatus_check_follow_friends() {
22         $r = q("SELECT `uid`,`v` FROM `pconfig` WHERE `cat`='system' AND `k`='ostatus_legacy_contact' AND `v` != ''");
23
24         if (!$r)
25                 return;
26
27         foreach ($r AS $contact) {
28                 ostatus_follow_friends($contact["uid"], $contact["v"]);
29                 set_pconfig($contact["uid"], "system", "ostatus_legacy_contact", "");
30         }
31 }
32
33 // This function doesn't work reliable by now.
34 function ostatus_follow_friends($uid, $url) {
35         $contact = probe_url($url);
36
37         if (!$contact)
38                 return;
39
40         $api = $contact["baseurl"]."/api/";
41
42         // Fetching friends
43         $data = z_fetch_url($api."statuses/friends.json?screen_name=".$contact["nick"]);
44
45         if (!$data["success"])
46                 return;
47
48         $friends = json_decode($data["body"]);
49
50         foreach ($friends AS $friend) {
51                 $url = $friend->statusnet_profile_url;
52                 $r = q("SELECT `url` FROM `contact` WHERE `uid` = %d AND
53                         (`nurl` = '%s' OR `alias` = '%s' OR `alias` = '%s') AND
54                         `network` != '%s' LIMIT 1",
55                         intval($uid), dbesc(normalise_link($url)),
56                         dbesc(normalise_link($url)), dbesc($url), dbesc(NETWORK_STATUSNET));
57                 if (!$r) {
58                         $data = probe_url($friend->statusnet_profile_url);
59                         if ($data["network"] == NETWORK_OSTATUS) {
60                                 $result = new_contact($uid,$friend->statusnet_profile_url);
61                                 if ($result["success"])
62                                         logger($friend->name." ".$url." - success", LOGGER_DEBUG);
63                                 else
64                                         logger($friend->name." ".$url." - failed", LOGGER_DEBUG);
65                         } else
66                                 logger($friend->name." ".$url." - not OStatus", LOGGER_DEBUG);
67                 }
68         }
69 }
70
71 function ostatus_fetchauthor($xpath, $context, $importer, &$contact, $onlyfetch) {
72
73         $author = array();
74         $author["author-link"] = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
75         $author["author-name"] = $xpath->evaluate('atom:author/atom:name/text()', $context)->item(0)->nodeValue;
76
77         // Preserve the value
78         $authorlink = $author["author-link"];
79
80         $alternate = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0)->attributes;
81         if (is_object($alternate))
82                 foreach($alternate AS $attributes)
83                         if ($attributes->name == "href")
84                                 $author["author-link"] = $attributes->textContent;
85
86         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` IN ('%s', '%s') AND `network` != '%s'",
87                 intval($importer["uid"]), dbesc(normalise_link($author["author-link"])),
88                 dbesc(normalise_link($authorlink)), dbesc(NETWORK_STATUSNET));
89         if ($r) {
90                 $contact = $r[0];
91                 $author["contact-id"] = $r[0]["id"];
92         } else
93                 $author["contact-id"] = $contact["id"];
94
95         $avatarlist = array();
96         $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
97         foreach($avatars AS $avatar) {
98                 $href = "";
99                 $width = 0;
100                 foreach($avatar->attributes AS $attributes) {
101                         if ($attributes->name == "href")
102                                 $href = $attributes->textContent;
103                         if ($attributes->name == "width")
104                                 $width = $attributes->textContent;
105                 }
106                 if (($width > 0) AND ($href != ""))
107                         $avatarlist[$width] = $href;
108         }
109         if (count($avatarlist) > 0) {
110                 krsort($avatarlist);
111                 $author["author-avatar"] = current($avatarlist);
112         }
113
114         $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
115         if ($displayname != "")
116                 $author["author-name"] = $displayname;
117
118         $author["owner-name"] = $author["author-name"];
119         $author["owner-link"] = $author["author-link"];
120         $author["owner-avatar"] = $author["author-avatar"];
121
122         // Only update the contacts if it is an OStatus contact
123         if ($r AND !$onlyfetch AND ($contact["network"] == NETWORK_OSTATUS)) {
124                 // Update contact data
125
126                 $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
127                 if ($value != "")
128                         $contact["notify"] = $value;
129
130                 $value = $xpath->evaluate('atom:author/uri/text()', $context)->item(0)->nodeValue;
131                 if ($value != "")
132                         $contact["alias"] = $value;
133
134                 $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
135                 if ($value != "")
136                         $contact["name"] = $value;
137
138                 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
139                 if ($value != "")
140                         $contact["nick"] = $value;
141
142                 $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
143                 if ($value != "")
144                         $contact["about"] = html2bbcode($value);
145
146                 $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
147                 if ($value != "")
148                         $contact["location"] = $value;
149
150                 if (($contact["name"] != $r[0]["name"]) OR ($contact["nick"] != $r[0]["nick"]) OR ($contact["about"] != $r[0]["about"]) OR ($contact["location"] != $r[0]["location"])) {
151
152                         logger("Update contact data for contact ".$contact["id"], LOGGER_DEBUG);
153
154                         q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s', `name-date` = '%s' WHERE `id` = %d",
155                                 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
156                                 dbesc(datetime_convert()), intval($contact["id"]));
157
158                         poco_check($contact["url"], $contact["name"], $contact["network"], $author["author-avatar"], $contact["about"], $contact["location"],
159                                                 "", "", "", datetime_convert(), 2, $contact["id"], $contact["uid"]);
160                 }
161
162                 if (isset($author["author-avatar"]) AND ($author["author-avatar"] != $r[0]['avatar'])) {
163                         logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
164
165                         update_contact_avatar($author["author-avatar"], $importer["uid"], $contact["id"]);
166                 }
167
168                 $contact["generation"] = 2;
169                 $contact["photo"] = $author["author-avatar"];
170                 update_gcontact($contact);
171         }
172
173         return($author);
174 }
175
176 function ostatus_salmon_author($xml, $importer) {
177         $a = get_app();
178
179         if ($xml == "")
180                 return;
181
182         $doc = new DOMDocument();
183         @$doc->loadXML($xml);
184
185         $xpath = new DomXPath($doc);
186         $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
187         $xpath->registerNamespace('thr', NAMESPACE_THREAD);
188         $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
189         $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
190         $xpath->registerNamespace('media', NAMESPACE_MEDIA);
191         $xpath->registerNamespace('poco', NAMESPACE_POCO);
192         $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
193         $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
194
195         $entries = $xpath->query('/atom:entry');
196
197         foreach ($entries AS $entry) {
198                 // fetch the author
199                 $author = ostatus_fetchauthor($xpath, $entry, $importer, $contact, true);
200                 return $author;
201         }
202 }
203
204 function ostatus_import($xml,$importer,&$contact, &$hub) {
205
206         $a = get_app();
207
208         logger("Import OStatus message", LOGGER_DEBUG);
209
210         if ($xml == "")
211                 return;
212
213         $doc = new DOMDocument();
214         @$doc->loadXML($xml);
215
216         $xpath = new DomXPath($doc);
217         $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
218         $xpath->registerNamespace('thr', NAMESPACE_THREAD);
219         $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
220         $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
221         $xpath->registerNamespace('media', NAMESPACE_MEDIA);
222         $xpath->registerNamespace('poco', NAMESPACE_POCO);
223         $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
224         $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
225
226         $gub = "";
227         $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
228         if (is_object($hub_attributes))
229                 foreach($hub_attributes AS $hub_attribute)
230                         if ($hub_attribute->name == "href") {
231                                 $hub = $hub_attribute->textContent;
232                                 logger("Found hub ".$hub, LOGGER_DEBUG);
233                         }
234
235         $header = array();
236         $header["uid"] = $importer["uid"];
237         $header["network"] = NETWORK_OSTATUS;
238         $header["type"] = "remote";
239         $header["wall"] = 0;
240         $header["origin"] = 0;
241         $header["gravity"] = GRAVITY_PARENT;
242
243         // it could either be a received post or a post we fetched by ourselves
244         // depending on that, the first node is different
245         $first_child = $doc->firstChild->tagName;
246
247         if ($first_child == "feed")
248                 $entries = $xpath->query('/atom:feed/atom:entry');
249         else
250                 $entries = $xpath->query('/atom:entry');
251
252         $conversation = "";
253         $conversationlist = array();
254         $item_id = 0;
255
256         // Reverse the order of the entries
257         $entrylist = array();
258
259         foreach ($entries AS $entry)
260                 $entrylist[] = $entry;
261
262         foreach (array_reverse($entrylist) AS $entry) {
263
264                 $mention = false;
265
266                 // fetch the author
267                 if ($first_child == "feed")
268                         $author = ostatus_fetchauthor($xpath, $doc->firstChild, $importer, $contact, false);
269                 else
270                         $author = ostatus_fetchauthor($xpath, $entry, $importer, $contact, false);
271
272                 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
273                 if ($value != "")
274                         $nickname = $value;
275                 else
276                         $nickname = $author["author-name"];
277
278                 $item = array_merge($header, $author);
279
280                 // Now get the item
281                 $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
282
283                 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
284                         intval($importer["uid"]), dbesc($item["uri"]));
285                 if ($r) {
286                         logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already existed under id ".$r[0]["id"], LOGGER_DEBUG);
287                         continue;
288                 }
289
290                 $item["body"] = add_page_info_to_body(html2bbcode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue));
291                 $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
292
293                 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) OR ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
294                         $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
295                         $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
296                 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION)
297                         $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
298
299                 $item["object"] = $xml;
300                 $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
301
302                 /// @TODO
303                 /// Delete a message
304                 if ($item["verb"] == "qvitter-delete-notice") {
305                         // ignore "Delete" messages (by now)
306                         logger("Ignore delete message ".print_r($item, true));
307                         continue;
308                 }
309
310                 if ($item["verb"] == ACTIVITY_JOIN) {
311                         // ignore "Join" messages
312                         logger("Ignore join message ".print_r($item, true));
313                         continue;
314                 }
315
316                 if ($item["verb"] == ACTIVITY_FOLLOW) {
317                         new_follower($importer, $contact, $item, $nickname);
318                         continue;
319                 }
320
321                 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
322                         lose_follower($importer, $contact, $item, $dummy);
323                         continue;
324                 }
325
326                 if ($item["verb"] == ACTIVITY_FAVORITE) {
327                         $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
328                         logger("Favorite ".$orig_uri." ".print_r($item, true));
329
330                         $item["verb"] = ACTIVITY_LIKE;
331                         $item["parent-uri"] = $orig_uri;
332                         $item["gravity"] = GRAVITY_LIKE;
333                 }
334
335                 if ($item["verb"] == NAMESPACE_OSTATUS."/unfavorite") {
336                         // Ignore "Unfavorite" message
337                         logger("Ignore unfavorite message ".print_r($item, true));
338                         continue;
339                 }
340
341                 // http://activitystrea.ms/schema/1.0/rsvp-yes
342                 if (!in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE)))
343                         logger("Unhandled verb ".$item["verb"]." ".print_r($item, true));
344
345                 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
346                 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
347                 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
348
349                 $related = "";
350
351                 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
352                 if (is_object($inreplyto->item(0))) {
353                         foreach($inreplyto->item(0)->attributes AS $attributes) {
354                                 if ($attributes->name == "ref")
355                                         $item["parent-uri"] = $attributes->textContent;
356                                 if ($attributes->name == "href")
357                                         $related = $attributes->textContent;
358                         }
359                 }
360
361                 $georsspoint = $xpath->query('georss:point', $entry);
362                 if ($georsspoint)
363                         $item["coord"] = $georsspoint->item(0)->nodeValue;
364
365                 /// @TODO
366                 /// $item["location"] =
367
368                 $categories = $xpath->query('atom:category', $entry);
369                 if ($categories) {
370                         foreach ($categories AS $category) {
371                                 foreach($category->attributes AS $attributes)
372                                         if ($attributes->name == "term") {
373                                                 $term = $attributes->textContent;
374                                                 if(strlen($item["tag"]))
375                                                         $item["tag"] .= ',';
376                                                 $item["tag"] .= "#[url=".$a->get_baseurl()."/search?tag=".$term."]".$term."[/url]";
377                                         }
378                         }
379                 }
380
381                 $self = "";
382                 $enclosure = "";
383
384                 $links = $xpath->query('atom:link', $entry);
385                 if ($links) {
386                         $rel = "";
387                         $href = "";
388                         $type = "";
389                         $length = "0";
390                         $title = "";
391                         foreach ($links AS $link) {
392                                 foreach($link->attributes AS $attributes) {
393                                         if ($attributes->name == "href")
394                                                 $href = $attributes->textContent;
395                                         if ($attributes->name == "rel")
396                                                 $rel = $attributes->textContent;
397                                         if ($attributes->name == "type")
398                                                 $type = $attributes->textContent;
399                                         if ($attributes->name == "length")
400                                                 $length = $attributes->textContent;
401                                         if ($attributes->name == "title")
402                                                 $title = $attributes->textContent;
403                                 }
404                                 if (($rel != "") AND ($href != ""))
405                                         switch($rel) {
406                                                 case "alternate":
407                                                         $item["plink"] = $href;
408                                                         if (($item["object-type"] == ACTIVITY_OBJ_QUESTION) OR
409                                                                 ($item["object-type"] == ACTIVITY_OBJ_EVENT))
410                                                                 $item["body"] .= add_page_info($href);
411                                                         break;
412                                                 case "ostatus:conversation":
413                                                         $conversation = $href;
414                                                         break;
415                                                 case "enclosure":
416                                                         $enclosure = $href;
417                                                         if(strlen($item["attach"]))
418                                                                 $item["attach"] .= ',';
419
420                                                         $item["attach"] .= '[attach]href="'.$href.'" length="'.$length.'" type="'.$type.'" title="'.$title.'"[/attach]';
421                                                         break;
422                                                 case "related":
423                                                         if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
424                                                                 if (!isset($item["parent-uri"]))
425                                                                         $item["parent-uri"] = $href;
426
427                                                                 if ($related == "")
428                                                                         $related = $href;
429                                                         } else
430                                                                 $item["body"] .= add_page_info($href);
431                                                         break;
432                                                 case "self":
433                                                         $self = $href;
434                                                         break;
435                                                 case "mentioned":
436                                                         // Notification check
437                                                         if ($importer["nurl"] == normalise_link($href))
438                                                                 $mention = true;
439                                                         break;
440                                         }
441                         }
442                 }
443
444                 $local_id = "";
445                 $repeat_of = "";
446
447                 $notice_info = $xpath->query('statusnet:notice_info', $entry);
448                 if ($notice_info AND ($notice_info->length > 0)) {
449                         foreach($notice_info->item(0)->attributes AS $attributes) {
450                                 if ($attributes->name == "source")
451                                         $item["app"] = strip_tags($attributes->textContent);
452                                 if ($attributes->name == "local_id")
453                                         $local_id = $attributes->textContent;
454                                 if ($attributes->name == "repeat_of")
455                                         $repeat_of = $attributes->textContent;
456                         }
457                 }
458
459                 // Is it a repeated post?
460                 if ($repeat_of != "") {
461                         $activityobjects = $xpath->query('activity:object', $entry)->item(0);
462
463                         if (is_object($activityobjects)) {
464
465                                 $orig_uri = $xpath->query("activity:object/atom:id", $activityobjects)->item(0)->nodeValue;
466                                 if (!isset($orig_uri))
467                                         $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
468
469                                 $orig_links = $xpath->query("activity:object/atom:link[@rel='alternate']", $activityobjects);
470                                 if ($orig_links AND ($orig_links->length > 0))
471                                         foreach($orig_links->item(0)->attributes AS $attributes)
472                                                 if ($attributes->name == "href")
473                                                         $orig_link = $attributes->textContent;
474
475                                 if (!isset($orig_link))
476                                         $orig_link = $xpath->query("atom:link[@rel='alternate']", $activityobjects)->item(0)->nodeValue;
477
478                                 if (!isset($orig_link))
479                                         $orig_link =  ostatus_convert_href($orig_uri);
480
481                                 $orig_body = $xpath->query('activity:object/atom:content/text()', $activityobjects)->item(0)->nodeValue;
482                                 if (!isset($orig_body))
483                                         $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
484
485                                 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
486
487                                 $orig_contact = $contact;
488                                 $orig_author = ostatus_fetchauthor($xpath, $activityobjects, $importer, $orig_contact, false);
489
490                                 //if (!intval(get_config('system','wall-to-wall_share'))) {
491                                 //      $prefix = share_header($orig_author['author-name'], $orig_author['author-link'], $orig_author['author-avatar'], "", $orig_created, $orig_link);
492                                 //      $item["body"] = $prefix.add_page_info_to_body(html2bbcode($orig_body))."[/share]";
493                                 //} else {
494                                         $item["author-name"] = $orig_author["author-name"];
495                                         $item["author-link"] = $orig_author["author-link"];
496                                         $item["author-avatar"] = $orig_author["author-avatar"];
497                                         $item["body"] = add_page_info_to_body(html2bbcode($orig_body));
498                                         $item["created"] = $orig_created;
499
500                                         $item["uri"] = $orig_uri;
501                                         $item["plink"] = $orig_link;
502                                 //}
503
504                                 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
505
506                                 $item["object-type"] = $xpath->query('activity:object/activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
507                                 if (!isset($item["object-type"]))
508                                         $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
509                         }
510                 }
511
512                 //if ($enclosure != "")
513                 //      $item["body"] .= add_page_info($enclosure);
514
515                 if (isset($item["parent-uri"])) {
516                         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
517                                 intval($importer["uid"]), dbesc($item["parent-uri"]));
518
519                         if (!$r AND ($related != "")) {
520                                 $reply_path = str_replace("/notice/", "/api/statuses/show/", $related).".atom";
521
522                                 if ($reply_path != $related) {
523                                         logger("Fetching related items for user ".$importer["uid"]." from ".$reply_path, LOGGER_DEBUG);
524                                         $reply_xml = fetch_url($reply_path);
525
526                                         $reply_contact = $contact;
527                                         ostatus_import($reply_xml,$importer,$reply_contact, $reply_hub);
528
529                                         // After the import try to fetch the parent item again
530                                         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
531                                                 intval($importer["uid"]), dbesc($item["parent-uri"]));
532                                 }
533                         }
534                         if ($r) {
535                                 $item["type"] = 'remote-comment';
536                                 $item["gravity"] = GRAVITY_COMMENT;
537                         }
538                 } else
539                         $item["parent-uri"] = $item["uri"];
540
541                 $item_id = ostatus_completion($conversation, $importer["uid"], $item, $self);
542
543                 if (!$item_id) {
544                         logger("Error storing item", LOGGER_DEBUG);
545                         continue;
546                 }
547
548                 logger("Item was stored with id ".$item_id, LOGGER_DEBUG);
549         }
550 }
551
552 function ostatus_convert_href($href) {
553         $elements = explode(":",$href);
554
555         if ((count($elements) <= 2) OR ($elements[0] != "tag"))
556                 return $href;
557
558         $server = explode(",", $elements[1]);
559         $conversation = explode("=", $elements[2]);
560
561         if ((count($elements) == 4) AND ($elements[2] == "post"))
562                 return "http://".$server[0]."/notice/".$elements[3];
563
564         if ((count($conversation) != 2) OR ($conversation[1] ==""))
565                 return $href;
566
567         if ($elements[3] == "objectType=thread")
568                 return "http://".$server[0]."/conversation/".$conversation[1];
569         else
570                 return "http://".$server[0]."/notice/".$conversation[1];
571
572         return $href;
573 }
574
575 function check_conversations($mentions = false, $override = false) {
576         $last = get_config('system','ostatus_last_poll');
577
578         $poll_interval = intval(get_config('system','ostatus_poll_interval'));
579         if(! $poll_interval)
580                 $poll_interval = OSTATUS_DEFAULT_POLL_INTERVAL;
581
582         // Don't poll if the interval is set negative
583         if (($poll_interval < 0) AND !$override)
584                 return;
585
586         if (!$mentions) {
587                 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
588                 if (!$poll_timeframe)
589                         $poll_timeframe = OSTATUS_DEFAULT_POLL_TIMEFRAME;
590         } else {
591                 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
592                 if (!$poll_timeframe)
593                         $poll_timeframe = OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS;
594         }
595
596
597         if ($last AND !$override) {
598                 $next = $last + ($poll_interval * 60);
599                 if ($next > time()) {
600                         logger('poll interval not reached');
601                         return;
602                 }
603         }
604
605         logger('cron_start');
606
607         $start = date("Y-m-d H:i:s", time() - ($poll_timeframe * 60));
608
609         if ($mentions)
610                 $conversations = q("SELECT `term`.`oid`, `term`.`url`, `term`.`uid` FROM `term`
611                                         STRAIGHT_JOIN `thread` ON `thread`.`iid` = `term`.`oid` AND `thread`.`uid` = `term`.`uid`
612                                         WHERE `term`.`type` = 7 AND `term`.`term` > '%s' AND `thread`.`mention`
613                                         GROUP BY `term`.`url`, `term`.`uid` ORDER BY `term`.`term` DESC", dbesc($start));
614         else
615                 $conversations = q("SELECT `oid`, `url`, `uid` FROM `term`
616                                         WHERE `type` = 7 AND `term` > '%s'
617                                         GROUP BY `url`, `uid` ORDER BY `term` DESC", dbesc($start));
618
619         foreach ($conversations AS $conversation) {
620                 ostatus_completion($conversation['url'], $conversation['uid']);
621         }
622
623         logger('cron_end');
624
625         set_config('system','ostatus_last_poll', time());
626 }
627
628 /**
629  * @brief Updates the gcontact table with actor data from the conversation
630  *
631  * @param object $actor The actor object that contains the contact data
632  */
633 function ostatus_conv_fetch_actor($actor) {
634
635         // We set the generation to "3" since the data here is not as reliable as the data we get on other occasions
636         $contact = array("network" => NETWORK_OSTATUS, "generation" => 3);
637
638         if (isset($actor->url))
639                 $contact["url"] = $actor->url;
640
641         if (isset($actor->displayName))
642                 $contact["name"] = $actor->displayName;
643
644         if (isset($actor->portablecontacts_net->displayName))
645                 $contact["name"] = $actor->portablecontacts_net->displayName;
646
647         if (isset($actor->portablecontacts_net->preferredUsername))
648                 $contact["nick"] = $actor->portablecontacts_net->preferredUsername;
649
650         if (isset($actor->id))
651                 $contact["alias"] = $actor->id;
652
653         if (isset($actor->summary))
654                 $contact["about"] = $actor->summary;
655
656         if (isset($actor->portablecontacts_net->note))
657                 $contact["about"] = $actor->portablecontacts_net->note;
658
659         if (isset($actor->portablecontacts_net->addresses->formatted))
660                 $contact["location"] = $actor->portablecontacts_net->addresses->formatted;
661
662
663         if (isset($actor->image->url))
664                 $contact["photo"] = $actor->image->url;
665
666         if (isset($actor->image->width))
667                 $avatarwidth = $actor->image->width;
668
669         if (is_array($actor->status_net->avatarLinks))
670                 foreach ($actor->status_net->avatarLinks AS $avatar) {
671                         if ($avatarsize < $avatar->width) {
672                                 $contact["photo"] = $avatar->url;
673                                 $avatarsize = $avatar->width;
674                         }
675                 }
676
677         update_gcontact($contact);
678 }
679
680 /**
681  * @brief Fetches the conversation url for a given item link or conversation id
682  *
683  * @param string $self The link to the posting
684  * @param string $conversation_id The conversation id
685  *
686  * @return string The conversation url
687  */
688 function ostatus_fetch_conversation($self, $conversation_id = "") {
689
690         if ($conversation_id != "") {
691                 $elements = explode(":", $conversation_id);
692
693                 if ((count($elements) <= 2) OR ($elements[0] != "tag"))
694                         return $conversation_id;
695         }
696
697         if ($self == "")
698                 return "";
699
700         $json = str_replace(".atom", ".json", $self);
701
702         $raw = fetch_url($json);
703         if ($raw == "")
704                 return "";
705
706         $data = json_decode($raw);
707         if (!is_object($data))
708                 return "";
709
710         $conversation_id = $data->statusnet_conversation_id;
711
712         $pos = strpos($self, "/api/statuses/show/");
713         $base_url = substr($self, 0, $pos);
714
715         return $base_url."/conversation/".$conversation_id;
716 }
717
718 /**
719  * @brief Fetches actor details of a given actor and user id
720  *
721  * @param string $actor The actor url
722  * @param int $uid The user id
723  * @param int $contact_id The default contact-id
724  *
725  * @return array Array with actor details
726  */
727 function ostatus_get_actor_details($actor, $uid, $contact_id) {
728
729         $details = array();
730
731         $contact = q("SELECT `id`, `rel`, `network` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
732                                 $uid, normalise_link($actor), NETWORK_STATUSNET);
733
734         if (!$contact)
735                 $contact = q("SELECT `id`, `rel`, `network` FROM `contact` WHERE `uid` = %d AND `alias` IN ('%s', '%s') AND `network` != '%s'",
736                                 $uid, $actor, normalise_link($actor), NETWORK_STATUSNET);
737
738         if ($contact) {
739                 logger("Found contact for url ".$actor, LOGGER_DEBUG);
740                 $details["contact_id"] = $contact[0]["id"];
741                 $details["network"] = $contact[0]["network"];
742
743                 $details["not_following"] = !in_array($contact[0]["rel"], array(CONTACT_IS_SHARING, CONTACT_IS_FRIEND));
744         } else {
745                 logger("No contact found for user ".$uid." and url ".$actor, LOGGER_DEBUG);
746
747                 // Adding a global contact
748                 /// @TODO Use this data for the post
749                 $details["global_contact_id"] = get_contact($actor, 0);
750
751                 logger("Global contact ".$global_contact_id." found for url ".$actor, LOGGER_DEBUG);
752
753                 $details["contact_id"] = $contact_id;
754                 $details["network"] = NETWORK_OSTATUS;
755
756                 $details["not_following"] = true;
757         }
758
759         return $details;
760 }
761
762 function ostatus_completion($conversation_url, $uid, $item = array(), $self = "") {
763
764         $a = get_app();
765
766         $item_stored = -1;
767
768         //$conversation_url = ostatus_convert_href($conversation_url);
769         $conversation_url = ostatus_fetch_conversation($self, $conversation_url);
770
771         // If the thread shouldn't be completed then store the item and go away
772         // Don't do a completion on liked content
773         if (((intval(get_config('system','ostatus_poll_interval')) == -2) AND (count($item) > 0)) OR
774                 ($item["verb"] == ACTIVITY_LIKE) OR ($conversation_url == "")) {
775                 //$arr["app"] .= " (OStatus-NoCompletion)";
776                 $item_stored = item_store($item, true);
777                 return($item_stored);
778         }
779
780         // Get the parent
781         $parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
782                         (SELECT `parent` FROM `item` WHERE `id` IN
783                                 (SELECT `oid` FROM `term` WHERE `uid` = %d AND `otype` = %d AND `type` = %d AND `url` = '%s'))",
784                         intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url));
785
786         if ($parents)
787                 $parent = $parents[0];
788         elseif (count($item) > 0) {
789                 $parent = $item;
790                 $parent["type"] = "remote";
791                 $parent["verb"] = ACTIVITY_POST;
792                 $parent["visible"] = 1;
793         } else {
794                 // Preset the parent
795                 $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid`=%d", $uid);
796                 if (!$r)
797                         return(-2);
798
799                 $parent = array();
800                 $parent["id"] = 0;
801                 $parent["parent"] = 0;
802                 $parent["uri"] = "";
803                 $parent["contact-id"] = $r[0]["id"];
804                 $parent["type"] = "remote";
805                 $parent["verb"] = ACTIVITY_POST;
806                 $parent["visible"] = 1;
807         }
808
809         $conv = str_replace("/conversation/", "/api/statusnet/conversation/", $conversation_url).".as";
810         $pageno = 1;
811         $items = array();
812
813         logger('fetching conversation url '.$conv.' (Self: '.$self.') for user '.$uid);
814
815         do {
816                 $conv_arr = z_fetch_url($conv."?page=".$pageno);
817
818                 // If it is a non-ssl site and there is an error, then try ssl or vice versa
819                 if (!$conv_arr["success"] AND (substr($conv, 0, 7) == "http://")) {
820                         $conv = str_replace("http://", "https://", $conv);
821                         $conv_as = fetch_url($conv."?page=".$pageno);
822                 } elseif (!$conv_arr["success"] AND (substr($conv, 0, 8) == "https://")) {
823                         $conv = str_replace("https://", "http://", $conv);
824                         $conv_as = fetch_url($conv."?page=".$pageno);
825                 } else
826                         $conv_as = $conv_arr["body"];
827
828                 $conv_as = str_replace(',"statusnet:notice_info":', ',"statusnet_notice_info":', $conv_as);
829                 $conv_as = json_decode($conv_as);
830
831                 $no_of_items = sizeof($items);
832
833                 if (@is_array($conv_as->items))
834                         foreach ($conv_as->items AS $single_item)
835                                 $items[$single_item->id] = $single_item;
836
837                 if ($no_of_items == sizeof($items))
838                         break;
839
840                 $pageno++;
841
842         } while (true);
843
844         logger('fetching conversation done. Found '.count($items).' items');
845
846         if (!sizeof($items)) {
847                 if (count($item) > 0) {
848                         //$arr["app"] .= " (OStatus-NoConvFetched)";
849                         $item_stored = item_store($item, true);
850
851                         if ($item_stored) {
852                                 logger("Conversation ".$conversation_url." couldn't be fetched. Item uri ".$item["uri"]." stored: ".$item_stored, LOGGER_DEBUG);
853                                 ostatus_store_conversation($item_id, $conversation_url);
854                         }
855
856                         return($item_stored);
857                 } else
858                         return(-3);
859         }
860
861         $items = array_reverse($items);
862
863         $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self`", intval($uid));
864         $importer = $r[0];
865
866         $new_parent = true;
867
868         foreach ($items as $single_conv) {
869
870                 // Update the gcontact table
871                 ostatus_conv_fetch_actor($single_conv->actor);
872
873                 // Test - remove before flight
874                 //$tempfile = tempnam(get_temppath(), "conversation");
875                 //file_put_contents($tempfile, json_encode($single_conv));
876
877                 $mention = false;
878
879                 if (isset($single_conv->object->id))
880                         $single_conv->id = $single_conv->object->id;
881
882                 $plink = ostatus_convert_href($single_conv->id);
883                 if (isset($single_conv->object->url))
884                         $plink = ostatus_convert_href($single_conv->object->url);
885
886                 if (@!$single_conv->id)
887                         continue;
888
889                 logger("Got id ".$single_conv->id, LOGGER_DEBUG);
890
891                 if ($first_id == "") {
892                         $first_id = $single_conv->id;
893
894                         // The first post of the conversation isn't our first post. There are three options:
895                         // 1. Our conversation hasn't the "real" thread starter
896                         // 2. This first post is a post inside our thread
897                         // 3. This first post is a post inside another thread
898                         if (($first_id != $parent["uri"]) AND ($parent["uri"] != "")) {
899
900                                 $new_parent = true;
901
902                                 $new_parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
903                                                         (SELECT `parent` FROM `item`
904                                                                 WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s')) LIMIT 1",
905                                         intval($uid), dbesc($first_id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
906                                 if ($new_parents) {
907                                         if ($new_parents[0]["parent"] == $parent["parent"]) {
908                                                 // Option 2: This post is already present inside our thread - but not as thread starter
909                                                 logger("Option 2: uri present in our thread: ".$first_id, LOGGER_DEBUG);
910                                                 $first_id = $parent["uri"];
911                                         } else {
912                                                 // Option 3: Not so good. We have mixed parents. We have to see how to clean this up.
913                                                 // For now just take the new parent.
914                                                 $parent = $new_parents[0];
915                                                 $first_id = $parent["uri"];
916                                                 logger("Option 3: mixed parents for uri ".$first_id, LOGGER_DEBUG);
917                                         }
918                                 } else {
919                                         // Option 1: We hadn't got the real thread starter
920                                         // We have to clean up our existing messages.
921                                         $parent["id"] = 0;
922                                         $parent["uri"] = $first_id;
923                                         logger("Option 1: we have a new parent: ".$first_id, LOGGER_DEBUG);
924                                 }
925                         } elseif ($parent["uri"] == "") {
926                                 $parent["id"] = 0;
927                                 $parent["uri"] = $first_id;
928                         }
929                 }
930
931                 $parent_uri = $parent["uri"];
932
933                 // "context" only seems to exist on older servers
934                 if (isset($single_conv->context->inReplyTo->id)) {
935                         $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
936                                                 intval($uid), dbesc($single_conv->context->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
937                         if ($parent_exists)
938                                 $parent_uri = $single_conv->context->inReplyTo->id;
939                 }
940
941                 // This is the current way
942                 if (isset($single_conv->object->inReplyTo->id)) {
943                         $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
944                                                 intval($uid), dbesc($single_conv->object->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
945                         if ($parent_exists)
946                                 $parent_uri = $single_conv->object->inReplyTo->id;
947                 }
948
949                 $message_exists = q("SELECT `id`, `parent`, `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
950                                                 intval($uid), dbesc($single_conv->id),
951                                                 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
952                 if ($message_exists) {
953                         logger("Message ".$single_conv->id." already existed on the system", LOGGER_DEBUG);
954
955                         if ($parent["id"] != 0) {
956                                 $existing_message = $message_exists[0];
957
958                                 // We improved the way we fetch OStatus messages, this shouldn't happen very often now
959                                 /// @TODO We have to change the shadow copies as well. This way here is really ugly.
960                                 if ($existing_message["parent"] != $parent["id"]) {
961                                         logger('updating id '.$existing_message["id"].' with parent '.$existing_message["parent"].' to parent '.$parent["id"].' uri '.$parent["uri"].' thread '.$parent_uri, LOGGER_DEBUG);
962
963                                         // Update the parent id of the selected item
964                                         $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `id` = %d",
965                                                 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["id"]));
966
967                                         // Update the parent uri in the thread - but only if it points to itself
968                                         $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE `id` = %d AND `uri` = `thr-parent`",
969                                                 dbesc($parent_uri), intval($existing_message["id"]));
970
971                                         // try to change all items of the same parent
972                                         $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `parent` = %d",
973                                                 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["parent"]));
974
975                                         // Update the parent uri in the thread - but only if it points to itself
976                                         $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE (`parent` = %d) AND (`uri` = `thr-parent`)",
977                                                 dbesc($parent["uri"]), intval($existing_message["parent"]));
978
979                                         // Now delete the thread
980                                         delete_thread($existing_message["parent"]);
981                                 }
982                         }
983
984                         // The item we are having on the system is the one that we wanted to store via the item array
985                         if (isset($item["uri"]) AND ($item["uri"] == $existing_message["uri"])) {
986                                 $item = array();
987                                 $item_stored = 0;
988                         }
989
990                         continue;
991                 }
992
993                 if (is_array($single_conv->to))
994                         foreach($single_conv->to AS $to)
995                                 if ($importer["nurl"] == normalise_link($to->id))
996                                         $mention = true;
997
998                 $actor = $single_conv->actor->id;
999                 if (isset($single_conv->actor->url))
1000                         $actor = $single_conv->actor->url;
1001
1002                 $details = ostatus_get_actor_details($actor, $uid, $parent["contact-id"]);
1003
1004                 // Do we only want to import threads that were started by our contacts?
1005                 if ($details["not_following"] AND $new_parent AND get_config('system','ostatus_full_threads')) {
1006                         logger("Don't import uri ".$first_id." because user ".$uid." doesn't follow the person ".$actor, LOGGER_DEBUG);
1007                         continue;
1008                 }
1009
1010                 $arr = array();
1011                 $arr["network"] = $details["network"];
1012                 $arr["uri"] = $single_conv->id;
1013                 $arr["plink"] = $plink;
1014                 $arr["uid"] = $uid;
1015                 $arr["contact-id"] = $details["contact_id"];
1016                 $arr["parent-uri"] = $parent_uri;
1017                 $arr["created"] = $single_conv->published;
1018                 $arr["edited"] = $single_conv->published;
1019                 $arr["owner-name"] = $single_conv->actor->displayName;
1020                 if ($arr["owner-name"] == '')
1021                         $arr["owner-name"] = $single_conv->actor->contact->displayName;
1022                 if ($arr["owner-name"] == '')
1023                         $arr["owner-name"] = $single_conv->actor->portablecontacts_net->displayName;
1024
1025                 $arr["owner-link"] = $actor;
1026                 $arr["owner-avatar"] = $single_conv->actor->image->url;
1027                 $arr["author-name"] = $arr["owner-name"];
1028                 $arr["author-link"] = $actor;
1029                 $arr["author-avatar"] = $single_conv->actor->image->url;
1030                 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->content));
1031
1032                 if (isset($single_conv->status_net->notice_info->source))
1033                         $arr["app"] = strip_tags($single_conv->status_net->notice_info->source);
1034                 elseif (isset($single_conv->statusnet->notice_info->source))
1035                         $arr["app"] = strip_tags($single_conv->statusnet->notice_info->source);
1036                 elseif (isset($single_conv->statusnet_notice_info->source))
1037                         $arr["app"] = strip_tags($single_conv->statusnet_notice_info->source);
1038                 elseif (isset($single_conv->provider->displayName))
1039                         $arr["app"] = $single_conv->provider->displayName;
1040                 else
1041                         $arr["app"] = "OStatus";
1042
1043                 //$arr["app"] .= " (Conversation)";
1044
1045                 $arr["object"] = json_encode($single_conv);
1046                 $arr["verb"] = $parent["verb"];
1047                 $arr["visible"] = $parent["visible"];
1048                 $arr["location"] = $single_conv->location->displayName;
1049                 $arr["coord"] = trim($single_conv->location->lat." ".$single_conv->location->lon);
1050
1051                 // Is it a reshared item?
1052                 if (isset($single_conv->verb) AND ($single_conv->verb == "share") AND isset($single_conv->object)) {
1053                         if (is_array($single_conv->object))
1054                                 $single_conv->object = $single_conv->object[0];
1055
1056                         logger("Found reshared item ".$single_conv->object->id);
1057
1058                         // $single_conv->object->context->conversation;
1059
1060                         if (isset($single_conv->object->object->id))
1061                                 $arr["uri"] = $single_conv->object->object->id;
1062                         else
1063                                 $arr["uri"] = $single_conv->object->id;
1064
1065                         if (isset($single_conv->object->object->url))
1066                                 $plink = ostatus_convert_href($single_conv->object->object->url);
1067                         else
1068                                 $plink = ostatus_convert_href($single_conv->object->url);
1069
1070                         if (isset($single_conv->object->object->content))
1071                                 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->object->content));
1072                         else
1073                                 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->content));
1074
1075                         $arr["plink"] = $plink;
1076
1077                         $arr["created"] = $single_conv->object->published;
1078                         $arr["edited"] = $single_conv->object->published;
1079
1080                         $arr["author-name"] = $single_conv->object->actor->displayName;
1081                         if ($arr["owner-name"] == '')
1082                                 $arr["author-name"] = $single_conv->object->actor->contact->displayName;
1083
1084                         $arr["author-link"] = $single_conv->object->actor->url;
1085                         $arr["author-avatar"] = $single_conv->object->actor->image->url;
1086
1087                         $arr["app"] = $single_conv->object->provider->displayName."#";
1088                         //$arr["verb"] = $single_conv->object->verb;
1089
1090                         $arr["location"] = $single_conv->object->location->displayName;
1091                         $arr["coord"] = trim($single_conv->object->location->lat." ".$single_conv->object->location->lon);
1092                 }
1093
1094                 if ($arr["location"] == "")
1095                         unset($arr["location"]);
1096
1097                 if ($arr["coord"] == "")
1098                         unset($arr["coord"]);
1099
1100                 // Copy fields from given item array
1101                 if (isset($item["uri"]) AND (($item["uri"] == $arr["uri"]) OR ($item["uri"] ==  $single_conv->id))) {
1102                         $copy_fields = array("owner-name", "owner-link", "owner-avatar", "author-name", "author-link", "author-avatar",
1103                                                 "gravity", "body", "object-type", "object", "verb", "created", "edited", "coord", "tag",
1104                                                 "title", "attach", "app", "type", "location", "contact-id", "uri");
1105                         foreach ($copy_fields AS $field)
1106                                 if (isset($item[$field]))
1107                                         $arr[$field] = $item[$field];
1108
1109                         //$arr["app"] .= " (OStatus)";
1110                 }
1111
1112                 $newitem = item_store($arr);
1113                 if (!$newitem) {
1114                         logger("Item wasn't stored ".print_r($arr, true), LOGGER_DEBUG);
1115                         continue;
1116                 }
1117
1118                 if (isset($item["uri"]) AND ($item["uri"] == $arr["uri"])) {
1119                         $item = array();
1120                         $item_stored = $newitem;
1121                 }
1122
1123                 logger('Stored new item '.$plink.' for parent '.$arr["parent-uri"].' under id '.$newitem, LOGGER_DEBUG);
1124
1125                 // Add the conversation entry (but don't fetch the whole conversation)
1126                 ostatus_store_conversation($newitem, $conversation_url);
1127
1128                 // If the newly created item is the top item then change the parent settings of the thread
1129                 // This shouldn't happen anymore. This is supposed to be absolote.
1130                 if ($arr["uri"] == $first_id) {
1131                         logger('setting new parent to id '.$newitem);
1132                         $new_parents = q("SELECT `id`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
1133                                 intval($uid), intval($newitem));
1134                         if ($new_parents)
1135                                 $parent = $new_parents[0];
1136                 }
1137         }
1138
1139         if (($item_stored < 0) AND (count($item) > 0)) {
1140                 //$arr["app"] .= " (OStatus-NoConvFound)";
1141
1142                 if (get_config('system','ostatus_full_threads')) {
1143                         $details = ostatus_get_actor_details($item["owner-link"], $uid, $item["contact-id"]);
1144                         if ($details["not_following"]) {
1145                                 logger("Don't import uri ".$item["uri"]." because user ".$uid." doesn't follow the person ".$item["owner-link"], LOGGER_DEBUG);
1146                                 return false;
1147                         }
1148                 }
1149
1150                 $item_stored = item_store($item, true);
1151                 if ($item_stored) {
1152                         logger("Uri ".$item["uri"]." wasn't found in conversation ".$conversation_url, LOGGER_DEBUG);
1153                         ostatus_store_conversation($item_stored, $conversation_url);
1154                 }
1155         }
1156
1157         return($item_stored);
1158 }
1159
1160 function ostatus_store_conversation($itemid, $conversation_url) {
1161         global $a;
1162
1163         $conversation_url = ostatus_convert_href($conversation_url);
1164
1165         $messages = q("SELECT `uid`, `parent`, `created`, `received`, `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($itemid));
1166         if (!$messages)
1167                 return;
1168         $message = $messages[0];
1169
1170         // Store conversation url if not done before
1171         $conversation = q("SELECT `url` FROM `term` WHERE `uid` = %d AND `oid` = %d AND `otype` = %d AND `type` = %d",
1172                 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION));
1173
1174         if (!$conversation) {
1175                 $r = q("INSERT INTO `term` (`uid`, `oid`, `otype`, `type`, `term`, `url`, `created`, `received`, `guid`) VALUES (%d, %d, %d, %d, '%s', '%s', '%s', '%s', '%s')",
1176                         intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION),
1177                         dbesc($message["created"]), dbesc($conversation_url), dbesc($message["created"]), dbesc($message["received"]), dbesc($message["guid"]));
1178                 logger('Storing conversation url '.$conversation_url.' for id '.$itemid);
1179         }
1180 }
1181
1182 function get_reshared_guid($item) {
1183         $body = trim($item["body"]);
1184
1185         // Skip if it isn't a pure repeated messages
1186         // Does it start with a share?
1187         if (strpos($body, "[share") > 0)
1188                 return("");
1189
1190         // Does it end with a share?
1191         if (strlen($body) > (strrpos($body, "[/share]") + 8))
1192                 return("");
1193
1194         $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
1195         // Skip if there is no shared message in there
1196         if ($body == $attributes)
1197                 return(false);
1198
1199         $guid = "";
1200         preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1201         if ($matches[1] != "")
1202                 $guid = $matches[1];
1203
1204         preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1205         if ($matches[1] != "")
1206                 $guid = $matches[1];
1207
1208         return $guid;
1209 }
1210
1211 function xml_create_element($doc, $element, $value = "", $attributes = array()) {
1212         $element = $doc->createElement($element, xmlify($value));
1213
1214         foreach ($attributes AS $key => $value) {
1215                 $attribute = $doc->createAttribute($key);
1216                 $attribute->value = xmlify($value);
1217                 $element->appendChild($attribute);
1218         }
1219         return $element;
1220 }
1221
1222 function xml_add_element($doc, $parent, $element, $value = "", $attributes = array()) {
1223         $element = xml_create_element($doc, $element, $value, $attributes);
1224         $parent->appendChild($element);
1225 }
1226
1227 function ostatus_format_picture_post($body) {
1228         $siteinfo = get_attached_data($body);
1229
1230         if (($siteinfo["type"] == "photo")) {
1231                 if (isset($siteinfo["preview"]))
1232                         $preview = $siteinfo["preview"];
1233                 else
1234                         $preview = $siteinfo["image"];
1235
1236                 // Is it a remote picture? Then make a smaller preview here
1237                 $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
1238
1239                 // Is it a local picture? Then make it smaller here
1240                 $preview = str_replace(array("-0.jpg", "-0.png"), array("-2.jpg", "-2.png"), $preview);
1241                 $preview = str_replace(array("-1.jpg", "-1.png"), array("-2.jpg", "-2.png"), $preview);
1242
1243                 if (isset($siteinfo["url"]))
1244                         $url = $siteinfo["url"];
1245                 else
1246                         $url = $siteinfo["image"];
1247
1248                 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1249         }
1250
1251         return $body;
1252 }
1253
1254 function ostatus_add_header($doc, $owner) {
1255         $a = get_app();
1256
1257         $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1258         $doc->appendChild($root);
1259
1260         $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1261         $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1262         $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1263         $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1264         $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1265         $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1266         $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1267
1268         $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
1269         xml_add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1270         xml_add_element($doc, $root, "id", $a->get_baseurl()."/profile/".$owner["nick"]);
1271         xml_add_element($doc, $root, "title", sprintf("%s timeline", $owner["name"]));
1272         xml_add_element($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
1273         xml_add_element($doc, $root, "logo", $owner["photo"]);
1274         xml_add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
1275
1276         $author = ostatus_add_author($doc, $owner);
1277         $root->appendChild($author);
1278
1279         $attributes = array("href" => $owner["url"], "rel" => "alternate", "type" => "text/html");
1280         xml_add_element($doc, $root, "link", "", $attributes);
1281
1282         /// @TODO We have to find out what this is
1283         /// $attributes = array("href" => $a->get_baseurl()."/sup",
1284         ///             "rel" => "http://api.friendfeed.com/2008/03#sup",
1285         ///             "type" => "application/json");
1286         /// xml_add_element($doc, $root, "link", "", $attributes);
1287
1288         ostatus_hublinks($doc, $root);
1289
1290         $attributes = array("href" => $a->get_baseurl()."/salmon/".$owner["nick"], "rel" => "salmon");
1291         xml_add_element($doc, $root, "link", "", $attributes);
1292
1293         $attributes = array("href" => $a->get_baseurl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies");
1294         xml_add_element($doc, $root, "link", "", $attributes);
1295
1296         $attributes = array("href" => $a->get_baseurl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention");
1297         xml_add_element($doc, $root, "link", "", $attributes);
1298
1299         $attributes = array("href" => $a->get_baseurl()."/api/statuses/user_timeline/".$owner["nick"].".atom",
1300                         "rel" => "self", "type" => "application/atom+xml");
1301         xml_add_element($doc, $root, "link", "", $attributes);
1302
1303         return $root;
1304 }
1305
1306 function ostatus_hublinks($doc, $root) {
1307         $a = get_app();
1308         $hub = get_config('system','huburl');
1309
1310         $hubxml = '';
1311         if(strlen($hub)) {
1312                 $hubs = explode(',', $hub);
1313                 if(count($hubs)) {
1314                         foreach($hubs as $h) {
1315                                 $h = trim($h);
1316                                 if(! strlen($h))
1317                                         continue;
1318                                 if ($h === '[internal]')
1319                                         $h = $a->get_baseurl() . '/pubsubhubbub';
1320                                 xml_add_element($doc, $root, "link", "", array("href" => $h, "rel" => "hub"));
1321                         }
1322                 }
1323         }
1324 }
1325
1326 function ostatus_get_attachment($doc, $root, $item) {
1327         $o = "";
1328         $siteinfo = get_attached_data($item["body"]);
1329
1330         switch($siteinfo["type"]) {
1331                 case 'link':
1332                         $attributes = array("rel" => "enclosure",
1333                                         "href" => $siteinfo["url"],
1334                                         "type" => "text/html; charset=UTF-8",
1335                                         "length" => "",
1336                                         "title" => $siteinfo["title"]);
1337                         xml_add_element($doc, $root, "link", "", $attributes);
1338                         break;
1339                 case 'photo':
1340                         $imgdata = get_photo_info($siteinfo["image"]);
1341                         $attributes = array("rel" => "enclosure",
1342                                         "href" => $siteinfo["image"],
1343                                         "type" => $imgdata["mime"],
1344                                         "length" => intval($imgdata["size"]));
1345                         xml_add_element($doc, $root, "link", "", $attributes);
1346                         break;
1347                 case 'video':
1348                         $attributes = array("rel" => "enclosure",
1349                                         "href" => $siteinfo["url"],
1350                                         "type" => "text/html; charset=UTF-8",
1351                                         "length" => "",
1352                                         "title" => $siteinfo["title"]);
1353                         xml_add_element($doc, $root, "link", "", $attributes);
1354                         break;
1355                 default:
1356                         break;
1357         }
1358
1359         if (($siteinfo["type"] != "photo") AND isset($siteinfo["image"])) {
1360                 $photodata = get_photo_info($siteinfo["image"]);
1361
1362                 $attributes = array("rel" => "preview", "href" => $siteinfo["image"], "media:width" => $photodata[0], "media:height" => $photodata[1]);
1363                 xml_add_element($doc, $root, "link", "", $attributes);
1364         }
1365
1366
1367         $arr = explode('[/attach],',$item['attach']);
1368         if(count($arr)) {
1369                 foreach($arr as $r) {
1370                         $matches = false;
1371                         $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches);
1372                         if($cnt) {
1373                                 $attributes = array("rel" => "enclosure",
1374                                                 "href" => $matches[1],
1375                                                 "type" => $matches[3]);
1376
1377                                 if(intval($matches[2]))
1378                                         $attributes["length"] = intval($matches[2]);
1379
1380                                 if(trim($matches[4]) != "")
1381                                         $attributes["title"] = trim($matches[4]);
1382
1383                                 xml_add_element($doc, $root, "link", "", $attributes);
1384                         }
1385                 }
1386         }
1387 }
1388
1389 function ostatus_add_author($doc, $owner) {
1390         $a = get_app();
1391
1392         $r = q("SELECT `homepage` FROM `profile` WHERE `uid` = %d AND `is-default` LIMIT 1", intval($owner["uid"]));
1393         if ($r)
1394                 $profile = $r[0];
1395
1396         $author = $doc->createElement("author");
1397         xml_add_element($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1398         xml_add_element($doc, $author, "uri", $owner["url"]);
1399         xml_add_element($doc, $author, "name", $owner["name"]);
1400
1401         $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $owner["url"]);
1402         xml_add_element($doc, $author, "link", "", $attributes);
1403
1404         $attributes = array(
1405                         "rel" => "avatar",
1406                         "type" => "image/jpeg", // To-Do?
1407                         "media:width" => 175,
1408                         "media:height" => 175,
1409                         "href" => $owner["photo"]);
1410         xml_add_element($doc, $author, "link", "", $attributes);
1411
1412         if (isset($owner["thumb"])) {
1413                 $attributes = array(
1414                                 "rel" => "avatar",
1415                                 "type" => "image/jpeg", // To-Do?
1416                                 "media:width" => 80,
1417                                 "media:height" => 80,
1418                                 "href" => $owner["thumb"]);
1419                 xml_add_element($doc, $author, "link", "", $attributes);
1420         }
1421
1422         xml_add_element($doc, $author, "poco:preferredUsername", $owner["nick"]);
1423         xml_add_element($doc, $author, "poco:displayName", $owner["name"]);
1424         xml_add_element($doc, $author, "poco:note", $owner["about"]);
1425
1426         if (trim($owner["location"]) != "") {
1427                 $element = $doc->createElement("poco:address");
1428                 xml_add_element($doc, $element, "poco:formatted", $owner["location"]);
1429                 $author->appendChild($element);
1430         }
1431
1432         if (trim($profile["homepage"]) != "") {
1433                 $urls = $doc->createElement("poco:urls");
1434                 xml_add_element($doc, $urls, "poco:type", "homepage");
1435                 xml_add_element($doc, $urls, "poco:value", $profile["homepage"]);
1436                 xml_add_element($doc, $urls, "poco:primary", "true");
1437                 $author->appendChild($urls);
1438         }
1439
1440         if (count($profile)) {
1441                 xml_add_element($doc, $author, "followers", "", array("url" => $a->get_baseurl()."/viewcontacts/".$owner["nick"]));
1442                 xml_add_element($doc, $author, "statusnet:profile_info", "", array("local_id" => $owner["uid"]));
1443         }
1444
1445         return $author;
1446 }
1447
1448 /** 
1449  * @TODO Picture attachments should look like this:
1450  *      <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1451  *      class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1452  * 
1453 */
1454
1455 function ostatus_entry($doc, $item, $owner, $toplevel = false, $repeat = false) {
1456         $a = get_app();
1457
1458         if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1459                 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1460         }
1461
1462         $is_repeat = false;
1463
1464 /*      if (!$repeat) {
1465                 $repeated_guid = get_reshared_guid($item);
1466
1467                 if ($repeated_guid != "") {
1468                         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1469                                 intval($owner["uid"]), dbesc($repeated_guid));
1470                         if ($r) {
1471                                 $repeated_item = $r[0];
1472                                 $is_repeat = true;
1473                         }
1474                 }
1475         }
1476 */
1477         if (!$toplevel AND !$repeat) {
1478                 $entry = $doc->createElement("entry");
1479                 $title = sprintf("New note by %s", $owner["nick"]);
1480         } elseif (!$toplevel AND $repeat) {
1481                 $entry = $doc->createElement("activity:object");
1482                 $title = sprintf("New note by %s", $owner["nick"]);
1483         } else {
1484                 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
1485
1486                 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1487                 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1488                 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1489                 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1490                 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
1491                 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1492                 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1493
1494                 $author = ostatus_add_author($doc, $owner);
1495                 $entry->appendChild($author);
1496
1497                 $title = sprintf("New comment by %s", $owner["nick"]);
1498         }
1499
1500         // To use the object-type "bookmark" we have to implement these elements:
1501         //
1502         // <activity:object-type>http://activitystrea.ms/schema/1.0/bookmark</activity:object-type>
1503         // <title>Historic Rocket Landing</title>
1504         // <summary>Nur ein Testbeitrag.</summary>
1505         // <link rel="related" href="https://www.youtube.com/watch?v=9pillaOxGCo"/>
1506         // <link rel="preview" href="https://pirati.cc/file/thumb-4526-450x338-b48c8055f0c2fed0c3f67adc234c4b99484a90c42ed3cac73dc1081a4d0a7bc1.jpg.jpg" media:width="450" media:height="338"/>
1507         //
1508         // But: it seems as if it doesn't federate well between the GS servers
1509         // So we just set it to "note" to be sure that it reaches their target systems
1510
1511         if (!$repeat)
1512                 xml_add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1513         else
1514                 xml_add_element($doc, $entry, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA.'activity');
1515
1516         xml_add_element($doc, $entry, "id", $item["uri"]);
1517         xml_add_element($doc, $entry, "title", $title);
1518
1519         if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
1520                 $body = fix_private_photos($item['body'],$owner['uid'],$item, 0);
1521         else
1522                 $body = $item['body'];
1523
1524         $body = ostatus_format_picture_post($body);
1525
1526         if ($item['title'] != "")
1527                 $body = "[b]".$item['title']."[/b]\n\n".$body;
1528
1529         //$body = bb_remove_share_information($body);
1530         $body = bbcode($body, false, false, 7);
1531
1532         xml_add_element($doc, $entry, "content", $body, array("type" => "html"));
1533
1534         xml_add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
1535                                                         "href" => $a->get_baseurl()."/display/".$item["guid"]));
1536
1537         xml_add_element($doc, $entry, "status_net", "", array("notice_id" => $item["id"]));
1538
1539         if (!$is_repeat)
1540                 xml_add_element($doc, $entry, "activity:verb", construct_verb($item));
1541         else
1542                 xml_add_element($doc, $entry, "activity:verb", ACTIVITY_SHARE);
1543
1544         xml_add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
1545         xml_add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
1546
1547         if ($is_repeat) {
1548                 $repeated_owner = array();
1549                 $repeated_owner["name"] = $repeated_item["author-name"];
1550                 $repeated_owner["url"] = $repeated_item["author-link"];
1551                 $repeated_owner["photo"] = $repeated_item["author-avatar"];
1552                 $repeated_owner["nick"] = $repeated_owner["name"];
1553                 $repeated_owner["location"] = "";
1554                 $repeated_owner["about"] = "";
1555                 $repeated_owner["uid"] = 0;
1556
1557                 // Fetch the missing data from the global contacts
1558                 $r =q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'", normalise_link($repeated_item["author-link"]));
1559                 if ($r) {
1560                         if ($r[0]["nick"] != "")
1561                                 $repeated_owner["nick"] = $r[0]["nick"];
1562
1563                         $repeated_owner["location"] = $r[0]["location"];
1564                         $repeated_owner["about"] = $r[0]["about"];
1565                 }
1566
1567                 $entry_repeat = ostatus_entry($doc, $repeated_item, $repeated_owner, false, true);
1568                 $entry->appendChild($entry_repeat);
1569         } elseif ($repeat) {
1570                 $author = ostatus_add_author($doc, $owner);
1571                 $entry->appendChild($author);
1572         }
1573
1574         $mentioned = array();
1575
1576         if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
1577                 $parent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `id` = %d", intval($item["parent"]));
1578                 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1579
1580                 $attributes = array(
1581                                 "ref" => $parent_item,
1582                                 "type" => "text/html",
1583                                 "href" => $a->get_baseurl()."/display/".$parent[0]["guid"]);
1584                 xml_add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
1585
1586                 $attributes = array(
1587                                 "rel" => "related",
1588                                 "href" => $a->get_baseurl()."/display/".$parent[0]["guid"]);
1589                 xml_add_element($doc, $entry, "link", "", $attributes);
1590
1591                 $mentioned[$parent[0]["author-link"]] = $parent[0]["author-link"];
1592                 $mentioned[$parent[0]["owner-link"]] = $parent[0]["owner-link"];
1593
1594                 $thrparent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
1595                                 intval($owner["uid"]),
1596                                 dbesc($parent_item));
1597                 if ($thrparent) {
1598                         $mentioned[$thrparent[0]["author-link"]] = $thrparent[0]["author-link"];
1599                         $mentioned[$thrparent[0]["owner-link"]] = $thrparent[0]["owner-link"];
1600                 }
1601         }
1602
1603         xml_add_element($doc, $entry, "link", "", array("rel" => "ostatus:conversation",
1604                                                         "href" => $a->get_baseurl()."/display/".$owner["nick"]."/".$item["parent"]));
1605         xml_add_element($doc, $entry, "ostatus:conversation", $a->get_baseurl()."/display/".$owner["nick"]."/".$item["parent"]);
1606
1607         $tags = item_getfeedtags($item);
1608
1609         if(count($tags))
1610                 foreach($tags as $t)
1611                         if ($t[0] == "@")
1612                                 $mentioned[$t[1]] = $t[1];
1613
1614         // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
1615         $newmentions = array();
1616         foreach ($mentioned AS $mention) {
1617                 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
1618                 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
1619         }
1620         $mentioned = $newmentions;
1621
1622         foreach ($mentioned AS $mention) {
1623                 $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1624                         intval($owner["uid"]),
1625                         dbesc(normalise_link($mention)));
1626                 if ($r[0]["forum"] OR $r[0]["prv"])
1627                         xml_add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1628                                                                                 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1629                                                                                 "href" => $mention));
1630                 else
1631                         xml_add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1632                                                                                 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1633                                                                                 "href" => $mention));
1634         }
1635
1636         if (!$item["private"])
1637                 xml_add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1638                                                                 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
1639                                                                 "href" => "http://activityschema.org/collection/public"));
1640
1641         if(count($tags))
1642                 foreach($tags as $t)
1643                         if ($t[0] != "@")
1644                                 xml_add_element($doc, $entry, "category", "", array("term" => $t[2]));
1645
1646         ostatus_get_attachment($doc, $entry, $item);
1647
1648         /// @TODO
1649         /// The API call has yet to be implemented
1650         //$attributes = array("href" => $a->get_baseurl()."/api/statuses/show/".$item["id"].".atom",
1651         //              "rel" => "self", "type" => "application/atom+xml");
1652         //xml_add_element($doc, $entry, "link", "", $attributes);
1653
1654         //$attributes = array("href" => $a->get_baseurl()."/api/statuses/show/".$item["id"].".atom",
1655         //              "rel" => "edit", "type" => "application/atom+xml");
1656         //xml_add_element($doc, $entry, "link", "", $attributes);
1657
1658         $app = $item["app"];
1659         if ($app == "")
1660                 $app = "web";
1661
1662
1663         $attributes = array("local_id" => $item["id"], "source" => $app);
1664         if ($is_repeat)
1665                 $attributes["repeat_of"] = $repeated_item["id"];
1666
1667         xml_add_element($doc, $entry, "statusnet:notice_info", "", $attributes);
1668
1669         return $entry;
1670 }
1671
1672 function ostatus_feed(&$a, $owner_nick, $last_update) {
1673
1674         $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
1675                         FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
1676                         WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
1677                         dbesc($owner_nick));
1678         if (!$r)
1679                 return;
1680
1681         $owner = $r[0];
1682
1683         if(!strlen($last_update))
1684                 $last_update = 'now -30 days';
1685
1686         $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
1687
1688         $items = q("SELECT STRAIGHT_JOIN `item`.*, `item`.`id` AS `item_id` FROM `item`
1689                         INNER JOIN `thread` ON `thread`.`iid` = `item`.`parent`
1690                         LEFT JOIN `item` AS `thritem` ON `thritem`.`uri`=`item`.`thr-parent` AND `thritem`.`uid`=`item`.`uid`
1691                         WHERE `item`.`uid` = %d AND `item`.`received` > '%s' AND NOT `item`.`private` AND NOT `item`.`deleted`
1692                                 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid`  = '' AND `item`.`deny_gid`  = ''
1693                                 AND ((`item`.`wall` AND (`item`.`parent` = `item`.`id`))
1694                                         OR (`item`.`network` = '%s' AND ((`thread`.`network` IN ('%s', '%s')) OR (`thritem`.`network` IN ('%s', '%s')))) AND `thread`.`mention`)
1695                                 AND ((`item`.`owner-link` IN ('%s', '%s') AND (`item`.`parent` = `item`.`id`))
1696                                         OR (`item`.`author-link` IN ('%s', '%s')))
1697                         ORDER BY `item`.`received` DESC
1698                         LIMIT 0, 300",
1699                         intval($owner["uid"]), dbesc($check_date), dbesc(NETWORK_DFRN),
1700                         //dbesc(NETWORK_OSTATUS), dbesc(NETWORK_OSTATUS),
1701                         //dbesc(NETWORK_OSTATUS), dbesc(NETWORK_OSTATUS),
1702                         dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN),
1703                         dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN),
1704                         dbesc($owner["nurl"]), dbesc(str_replace("http://", "https://", $owner["nurl"])),
1705                         dbesc($owner["nurl"]), dbesc(str_replace("http://", "https://", $owner["nurl"]))
1706                 );
1707
1708         $doc = new DOMDocument('1.0', 'utf-8');
1709         $doc->formatOutput = true;
1710
1711         $root = ostatus_add_header($doc, $owner);
1712
1713         foreach ($items AS $item) {
1714                 $entry = ostatus_entry($doc, $item, $owner);
1715                 $root->appendChild($entry);
1716         }
1717
1718         return(trim($doc->saveXML()));
1719 }
1720
1721 function ostatus_salmon($item,$owner) {
1722
1723         $doc = new DOMDocument('1.0', 'utf-8');
1724         $doc->formatOutput = true;
1725
1726         $entry = ostatus_entry($doc, $item, $owner, true);
1727
1728         $doc->appendChild($entry);
1729
1730         return(trim($doc->saveXML()));
1731 }
1732 ?>