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