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