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