]> git.mxchange.org Git - friendica.git/blob - src/Protocol/OStatus.php
OStatus: Fixed communication issues with deleted contacts
[friendica.git] / src / Protocol / OStatus.php
1 <?php
2 /**
3  * @file src/Protocol/OStatus.php
4  */
5 namespace Friendica\Protocol;
6
7 use Friendica\Content\Text\BBCode;
8 use Friendica\Core\Cache;
9 use Friendica\Core\Config;
10 use Friendica\Core\L10n;
11 use Friendica\Core\System;
12 use Friendica\Database\DBM;
13 use Friendica\Model\Contact;
14 use Friendica\Model\Conversation;
15 use Friendica\Model\GContact;
16 use Friendica\Model\Item;
17 use Friendica\Network\Probe;
18 use Friendica\Object\Image;
19 use Friendica\Util\DateTimeFormat;
20 use Friendica\Util\Lock;
21 use Friendica\Util\Network;
22 use Friendica\Util\XML;
23 use dba;
24 use DOMDocument;
25 use DOMXPath;
26
27 require_once 'include/dba.php';
28 require_once 'include/html2bbcode.php';
29 require_once 'include/items.php';
30 require_once 'mod/share.php';
31 require_once 'include/enotify.php';
32 require_once 'include/api.php';
33 require_once 'mod/proxy.php';
34
35 /**
36  * @brief This class contain functions for the OStatus protocol
37  */
38 class OStatus
39 {
40         private static $itemlist;
41         private static $conv_list = [];
42
43         /**
44          * @brief Fetches author data
45          *
46          * @param object $xpath     The xpath object
47          * @param object $context   The xml context of the author details
48          * @param array  $importer  user record of the importing user
49          * @param array  $contact   Called by reference, will contain the fetched contact
50          * @param bool   $onlyfetch Only fetch the header without updating the contact entries
51          *
52          * @return array Array of author related entries for the item
53          */
54         private static function fetchAuthor($xpath, $context, $importer, &$contact, $onlyfetch)
55         {
56                 $author = [];
57                 $author["author-link"] = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
58                 $author["author-name"] = $xpath->evaluate('atom:author/atom:name/text()', $context)->item(0)->nodeValue;
59                 $addr = $xpath->evaluate('atom:author/atom:email/text()', $context)->item(0)->nodeValue;
60
61                 $aliaslink = $author["author-link"];
62
63                 $alternate = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0)->attributes;
64                 if (is_object($alternate)) {
65                         foreach ($alternate as $attributes) {
66                                 if (($attributes->name == "href") && ($attributes->textContent != "")) {
67                                         $author["author-link"] = $attributes->textContent;
68                                 }
69                         }
70                 }
71                 $author["contact-id"] = $contact["id"];
72
73                 $contact = null;
74                 if ($aliaslink != '') {
75                         $condition = ["`uid` = ? AND `alias` = ? AND `network` != ? AND `rel` IN (?, ?)",
76                                         $importer["uid"], $aliaslink, NETWORK_STATUSNET,
77                                         CONTACT_IS_SHARING, CONTACT_IS_FRIEND];
78                         $contact = dba::selectFirst('contact', [], $condition);
79                 }
80
81                 if (!DBM::is_result($contact) && $author["author-link"] != '') {
82                         if ($aliaslink == "") {
83                                 $aliaslink = $author["author-link"];
84                         }
85
86                         $condition = ["`uid` = ? AND `nurl` IN (?, ?) AND `network` != ? AND `rel` IN (?, ?)",
87                                         $importer["uid"], normalise_link($author["author-link"]), normalise_link($aliaslink),
88                                         NETWORK_STATUSNET, CONTACT_IS_SHARING, CONTACT_IS_FRIEND];
89                         $contact = dba::selectFirst('contact', [], $condition);
90                 }
91
92                 if (!DBM::is_result($contact) && ($addr != '')) {
93                         $condition = ["`uid` = ? AND `addr` = ? AND `network` != ? AND `rel` IN (?, ?)",
94                                         $importer["uid"], $addr, NETWORK_STATUSNET,
95                                         CONTACT_IS_SHARING, CONTACT_IS_FRIEND];
96                         $contact = dba::selectFirst('contact', [], $condition);
97                 }
98
99                 if (DBM::is_result($contact)) {
100                         if ($contact['blocked']) {
101                                 $contact['id'] = -1;
102                         }
103                         $author["contact-id"] = $contact["id"];
104                 }
105
106                 $avatarlist = [];
107                 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
108                 foreach ($avatars as $avatar) {
109                         $href = "";
110                         $width = 0;
111                         foreach ($avatar->attributes as $attributes) {
112                                 if ($attributes->name == "href") {
113                                         $href = $attributes->textContent;
114                                 }
115                                 if ($attributes->name == "width") {
116                                         $width = $attributes->textContent;
117                                 }
118                         }
119                         if ($href != "") {
120                                 $avatarlist[$width] = $href;
121                         }
122                 }
123                 if (count($avatarlist) > 0) {
124                         krsort($avatarlist);
125                         $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
126                 }
127
128                 $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
129                 if ($displayname != "") {
130                         $author["author-name"] = $displayname;
131                 }
132
133                 $author["owner-name"] = $author["author-name"];
134                 $author["owner-link"] = $author["author-link"];
135                 $author["owner-avatar"] = $author["author-avatar"];
136
137                 // Only update the contacts if it is an OStatus contact
138                 if (DBM::is_result($contact) && ($contact['id'] > 0) && !$onlyfetch && ($contact["network"] == NETWORK_OSTATUS)) {
139
140                         // Update contact data
141                         $current = $contact;
142                         unset($current['name-date']);
143
144                         // This query doesn't seem to work
145                         // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
146                         // if ($value != "")
147                         //      $contact["notify"] = $value;
148
149                         // This query doesn't seem to work as well - I hate these queries
150                         // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
151                         // if ($value != "")
152                         //      $contact["poll"] = $value;
153
154                         $contact['url'] = $author["author-link"];
155                         $contact['nurl'] = normalise_link($contact['url']);
156
157                         $value = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
158                         if ($value != "") {
159                                 $contact["alias"] = $value;
160                         }
161
162                         $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
163                         if ($value != "") {
164                                 $contact["name"] = $value;
165                         }
166
167                         $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
168                         if ($value != "") {
169                                 $contact["nick"] = $value;
170                         }
171
172                         $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
173                         if ($value != "") {
174                                 $contact["about"] = html2bbcode($value);
175                         }
176
177                         $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
178                         if ($value != "") {
179                                 $contact["location"] = $value;
180                         }
181
182                         $contact['name-date'] = DateTimeFormat::utcNow();
183
184                         dba::update('contact', $contact, ['id' => $contact["id"]], $current);
185
186                         if (!empty($author["author-avatar"]) && ($author["author-avatar"] != $current['avatar'])) {
187                                 logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
188                                 Contact::updateAvatar($author["author-avatar"], $importer["uid"], $contact["id"]);
189                         }
190
191                         // Ensure that we are having this contact (with uid=0)
192                         $cid = Contact::getIdForURL($aliaslink, 0, true);
193
194                         if ($cid) {
195                                 $fields = ['url', 'nurl', 'name', 'nick', 'alias', 'about', 'location'];
196                                 $old_contact = dba::selectFirst('contact', $fields, ['id' => $cid]);
197
198                                 // Update it with the current values
199                                 $fields = ['url' => $author["author-link"], 'name' => $contact["name"],
200                                                 'nurl' => normalise_link($author["author-link"]),
201                                                 'nick' => $contact["nick"], 'alias' => $contact["alias"],
202                                                 'about' => $contact["about"], 'location' => $contact["location"],
203                                                 'success_update' => DateTimeFormat::utcNow(), 'last-update' => DateTimeFormat::utcNow()];
204
205                                 dba::update('contact', $fields, ['id' => $cid], $old_contact);
206
207                                 // Update the avatar
208                                 Contact::updateAvatar($author["author-avatar"], 0, $cid);
209                         }
210
211                         $contact["generation"] = 2;
212                         $contact["hide"] = false; // OStatus contacts are never hidden
213                         $contact["photo"] = $author["author-avatar"];
214                         $gcid = GContact::update($contact);
215
216                         GContact::link($gcid, $contact["uid"], $contact["id"]);
217                 }
218
219                 return $author;
220         }
221
222         /**
223          * @brief Fetches author data from a given XML string
224          *
225          * @param string $xml      The XML
226          * @param array  $importer user record of the importing user
227          *
228          * @return array Array of author related entries for the item
229          */
230         public static function salmonAuthor($xml, $importer)
231         {
232                 if ($xml == "") {
233                         return;
234                 }
235
236                 $doc = new DOMDocument();
237                 @$doc->loadXML($xml);
238
239                 $xpath = new DOMXPath($doc);
240                 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
241                 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
242                 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
243                 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
244                 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
245                 $xpath->registerNamespace('poco', NAMESPACE_POCO);
246                 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
247                 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
248
249                 $contact = ["id" => 0];
250
251                 // Fetch the first author
252                 $authordata = $xpath->query('//author')->item(0);
253                 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, true);
254                 return $author;
255         }
256
257         /**
258          * @brief Read attributes from element
259          *
260          * @param object $element Element object
261          *
262          * @return array attributes
263          */
264         private static function readAttributes($element)
265         {
266                 $attribute = [];
267
268                 foreach ($element->attributes as $attributes) {
269                         $attribute[$attributes->name] = $attributes->textContent;
270                 }
271
272                 return $attribute;
273         }
274
275         /**
276          * @brief Imports an XML string containing OStatus elements
277          *
278          * @param string $xml      The XML
279          * @param array  $importer user record of the importing user
280          * @param array  $contact  contact
281          * @param string $hub      Called by reference, returns the fetched hub data
282          * @return void
283          */
284         public static function import($xml, $importer, &$contact, &$hub)
285         {
286                 self::process($xml, $importer, $contact, $hub);
287         }
288
289         /**
290          * @brief Internal feed processing
291          *
292          * @param string  $xml        The XML
293          * @param array   $importer   user record of the importing user
294          * @param array   $contact    contact
295          * @param string  $hub        Called by reference, returns the fetched hub data
296          * @param boolean $stored     Is the post fresh imported or from the database?
297          * @param boolean $initialize Is it the leading post so that data has to be initialized?
298          *
299          * @return boolean Could the XML be processed?
300          */
301         private static function process($xml, $importer, &$contact, &$hub, $stored = false, $initialize = true)
302         {
303                 if ($initialize) {
304                         self::$itemlist = [];
305                         self::$conv_list = [];
306                 }
307
308                 logger("Import OStatus message", LOGGER_DEBUG);
309
310                 if ($xml == "") {
311                         return false;
312                 }
313                 $doc = new DOMDocument();
314                 @$doc->loadXML($xml);
315
316                 $xpath = new DOMXPath($doc);
317                 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
318                 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
319                 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
320                 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
321                 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
322                 $xpath->registerNamespace('poco', NAMESPACE_POCO);
323                 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
324                 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
325
326                 $hub = "";
327                 $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
328                 if (is_object($hub_attributes)) {
329                         foreach ($hub_attributes as $hub_attribute) {
330                                 if ($hub_attribute->name == "href") {
331                                         $hub = $hub_attribute->textContent;
332                                         logger("Found hub ".$hub, LOGGER_DEBUG);
333                                 }
334                         }
335                 }
336
337                 $header = [];
338                 $header["uid"] = $importer["uid"];
339                 $header["network"] = NETWORK_OSTATUS;
340                 $header["type"] = "remote";
341                 $header["wall"] = 0;
342                 $header["origin"] = 0;
343                 $header["gravity"] = GRAVITY_PARENT;
344
345                 $first_child = $doc->firstChild->tagName;
346
347                 if ($first_child == "feed") {
348                         $entries = $xpath->query('/atom:feed/atom:entry');
349                 } else {
350                         $entries = $xpath->query('/atom:entry');
351                 }
352
353                 if ($entries->length == 1) {
354                         // We reformat the XML to make it better readable
355                         $doc2 = new DOMDocument();
356                         $doc2->loadXML($xml);
357                         $doc2->preserveWhiteSpace = false;
358                         $doc2->formatOutput = true;
359                         $xml2 = $doc2->saveXML();
360
361                         $header["protocol"] = PROTOCOL_OSTATUS_SALMON;
362                         $header["source"] = $xml2;
363                 } elseif (!$initialize) {
364                         return false;
365                 }
366
367                 // Fetch the first author
368                 $authordata = $xpath->query('//author')->item(0);
369                 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, $stored);
370
371                 $entry = $xpath->query('/atom:entry');
372
373                 // Reverse the order of the entries
374                 $entrylist = [];
375
376                 foreach ($entries as $entry) {
377                         $entrylist[] = $entry;
378                 }
379
380                 foreach (array_reverse($entrylist) as $entry) {
381                         // fetch the author
382                         $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
383
384                         if ($authorelement->length == 0) {
385                                 $authorelement = $xpath->query('atom:author', $entry);
386                         }
387
388                         if ($authorelement->length > 0) {
389                                 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, $stored);
390                         }
391
392                         $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $entry)->item(0)->nodeValue;
393                         if ($value != "") {
394                                 $nickname = $value;
395                         } else {
396                                 $nickname = $author["author-name"];
397                         }
398
399                         $item = array_merge($header, $author);
400
401                         $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
402
403                         $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
404
405                         // Delete a message
406                         if (in_array($item["verb"], ['qvitter-delete-notice', ACTIVITY_DELETE, 'delete'])) {
407                                 self::deleteNotice($item);
408                                 continue;
409                         }
410
411                         if (in_array($item["verb"], [NAMESPACE_OSTATUS."/unfavorite", ACTIVITY_UNFAVORITE])) {
412                                 // Ignore "Unfavorite" message
413                                 logger("Ignore unfavorite message ".print_r($item, true), LOGGER_DEBUG);
414                                 continue;
415                         }
416
417                         // Deletions come with the same uri, so we check for duplicates after processing deletions
418                         if (dba::exists('item', ['uid' => $importer["uid"], 'uri' => $item["uri"]])) {
419                                 logger('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
420                                 continue;
421                         } else {
422                                 logger('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
423                         }
424
425                         if ($item["verb"] == ACTIVITY_JOIN) {
426                                 // ignore "Join" messages
427                                 logger("Ignore join message ".print_r($item, true), LOGGER_DEBUG);
428                                 continue;
429                         }
430
431                         if ($item["verb"] == "http://mastodon.social/schema/1.0/block") {
432                                 // ignore mastodon "block" messages
433                                 logger("Ignore block message ".print_r($item, true), LOGGER_DEBUG);
434                                 continue;
435                         }
436
437                         if ($item["verb"] == ACTIVITY_FOLLOW) {
438                                 Contact::addRelationship($importer, $contact, $item, $nickname);
439                                 continue;
440                         }
441
442                         if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
443                                 Contact::removeFollower($importer, $contact, $item, $dummy);
444                                 continue;
445                         }
446
447                         if ($item["verb"] == ACTIVITY_FAVORITE) {
448                                 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
449                                 logger("Favorite ".$orig_uri." ".print_r($item, true));
450
451                                 $item["verb"] = ACTIVITY_LIKE;
452                                 $item["parent-uri"] = $orig_uri;
453                                 $item["gravity"] = GRAVITY_LIKE;
454                         }
455
456                         // http://activitystrea.ms/schema/1.0/rsvp-yes
457                         if (!in_array($item["verb"], [ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE])) {
458                                 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true), LOGGER_DEBUG);
459                         }
460
461                         self::processPost($xpath, $entry, $item, $importer);
462
463                         if ($initialize && (count(self::$itemlist) > 0)) {
464                                 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['parent-uri']) {
465                                         // We will import it everytime, when it is started by our contacts
466                                         $valid = !empty(self::$itemlist[0]['contact-id']);
467                                         if (!$valid) {
468                                                 // If not, then it depends on this setting
469                                                 $valid = !Config::get('system', 'ostatus_full_threads');
470                                                 if ($valid) {
471                                                         logger("Item with uri ".self::$itemlist[0]['uri']." will be imported due to the system settings.", LOGGER_DEBUG);
472                                                 }
473                                         } else {
474                                                 logger("Item with uri ".self::$itemlist[0]['uri']." belongs to a contact (".self::$itemlist[0]['contact-id']."). It will be imported.", LOGGER_DEBUG);
475                                         }
476                                         if ($valid) {
477                                                 // Never post a thread when the only interaction by our contact was a like
478                                                 $valid = false;
479                                                 $verbs = [ACTIVITY_POST, ACTIVITY_SHARE];
480                                                 foreach (self::$itemlist as $item) {
481                                                         if (!empty($item['contact-id']) && in_array($item['verb'], $verbs)) {
482                                                                 $valid = true;
483                                                         }
484                                                 }
485                                                 if ($valid) {
486                                                         logger("Item with uri ".self::$itemlist[0]['uri']." will be imported since the thread contains posts or shares.", LOGGER_DEBUG);
487                                                 }
488                                         }
489                                 } else {
490                                         // But we will only import complete threads
491                                         $valid = dba::exists('item', ['uid' => $importer["uid"], 'uri' => self::$itemlist[0]['parent-uri']]);
492                                         if ($valid) {
493                                                 logger("Item with uri ".self::$itemlist[0]["uri"]." belongs to parent ".self::$itemlist[0]['parent-uri']." of user ".$importer["uid"].". It will be imported.", LOGGER_DEBUG);
494                                         }
495                                 }
496
497                                 if ($valid) {
498                                         $default_contact = 0;
499                                         $key = count(self::$itemlist);
500                                         for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
501                                                 if (empty(self::$itemlist[$key]['contact-id'])) {
502                                                         self::$itemlist[$key]['contact-id'] = $default_contact;
503                                                 } else {
504                                                         $default_contact = $item['contact-id'];
505                                                 }
506                                         }
507                                         foreach (self::$itemlist as $item) {
508                                                 $found = dba::exists('item', ['uid' => $importer["uid"], 'uri' => $item["uri"]]);
509                                                 if ($found) {
510                                                         logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", LOGGER_DEBUG);
511                                                 } elseif ($item['contact-id'] < 0) {
512                                                         logger("Item with uri ".$item["uri"]." is from a blocked contact.", LOGGER_DEBUG);
513                                                 } else {
514                                                         // We are having duplicated entries. Hopefully this solves it.
515                                                         if (Lock::set('ostatus_process_item_insert')) {
516                                                                 $ret = Item::insert($item);
517                                                                 Lock::remove('ostatus_process_item_insert');
518                                                                 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret);
519                                                         } else {
520                                                                 $ret = Item::insert($item);
521                                                                 logger("We couldn't lock - but tried to store the item anyway. Return value is ".$ret);
522                                                         }
523                                                 }
524                                         }
525                                 }
526                                 self::$itemlist = [];
527                         }
528                         logger('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
529                 }
530                 return true;
531         }
532
533         /**
534          * @param object $item item
535          * @return void
536          */
537         private static function deleteNotice($item)
538         {
539                 $condition = ['uid' => $item['uid'], 'author-link' => $item['author-link'], 'uri' => $item['uri']];
540                 $deleted = dba::selectFirst('item', ['id', 'parent-uri'], $condition);
541                 if (!DBM::is_result($deleted)) {
542                         logger('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it. ");
543                         return;
544                 }
545
546                 Item::deleteById($deleted["id"]);
547
548                 logger('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
549         }
550
551         /**
552          * @brief Processes the XML for a post
553          *
554          * @param object $xpath    The xpath object
555          * @param object $entry    The xml entry that is processed
556          * @param array  $item     The item array
557          * @param array  $importer user record of the importing user
558          * @return void
559          */
560         private static function processPost($xpath, $entry, &$item, $importer)
561         {
562                 $item["body"] = html2bbcode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue);
563                 $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
564                 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) || ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
565                         $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
566                         $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
567                 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
568                         $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
569                 }
570
571                 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
572                 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
573                 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
574                 $item['conversation-uri'] = $conversation;
575
576                 $conv = $xpath->query('ostatus:conversation', $entry);
577                 if (is_object($conv->item(0))) {
578                         foreach ($conv->item(0)->attributes as $attributes) {
579                                 if ($attributes->name == "ref") {
580                                         $item['conversation-uri'] = $attributes->textContent;
581                                 }
582                                 if ($attributes->name == "href") {
583                                         $item['conversation-href'] = $attributes->textContent;
584                                 }
585                         }
586                 }
587
588                 $related = "";
589
590                 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
591                 if (is_object($inreplyto->item(0))) {
592                         foreach ($inreplyto->item(0)->attributes as $attributes) {
593                                 if ($attributes->name == "ref") {
594                                         $item["parent-uri"] = $attributes->textContent;
595                                 }
596                                 if ($attributes->name == "href") {
597                                         $related = $attributes->textContent;
598                                 }
599                         }
600                 }
601
602                 $georsspoint = $xpath->query('georss:point', $entry);
603                 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
604                         $item["coord"] = $georsspoint->item(0)->nodeValue;
605                 }
606
607                 $categories = $xpath->query('atom:category', $entry);
608                 if ($categories) {
609                         foreach ($categories as $category) {
610                                 foreach ($category->attributes as $attributes) {
611                                         if ($attributes->name == "term") {
612                                                 $term = $attributes->textContent;
613                                                 if (strlen($item["tag"])) {
614                                                         $item["tag"] .= ',';
615                                                 }
616                                                 $item["tag"] .= "#[url=".System::baseUrl()."/search?tag=".$term."]".$term."[/url]";
617                                         }
618                                 }
619                         }
620                 }
621
622                 $self = '';
623                 $add_body = '';
624
625                 $links = $xpath->query('atom:link', $entry);
626                 if ($links) {
627                         $link_data = self::processLinks($links, $item);
628                         $self = $link_data['self'];
629                         $add_body = $link_data['add_body'];
630                 }
631
632                 $repeat_of = "";
633
634                 $notice_info = $xpath->query('statusnet:notice_info', $entry);
635                 if ($notice_info && ($notice_info->length > 0)) {
636                         foreach ($notice_info->item(0)->attributes as $attributes) {
637                                 if ($attributes->name == "source") {
638                                         $item["app"] = strip_tags($attributes->textContent);
639                                 }
640                                 if ($attributes->name == "repeat_of") {
641                                         $repeat_of = $attributes->textContent;
642                                 }
643                         }
644                 }
645                 // Is it a repeated post?
646                 if (($repeat_of != "") || ($item["verb"] == ACTIVITY_SHARE)) {
647                         $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
648                         if (!empty($link_data['add_body'])) {
649                                 $add_body .= $link_data['add_body'];
650                         }
651                 }
652
653                 $item["body"] .= $add_body;
654
655                 // Only add additional data when there is no picture in the post
656                 if (!strstr($item["body"], '[/img]')) {
657                         $item["body"] = add_page_info_to_body($item["body"]);
658                 }
659
660                 // Mastodon Content Warning
661                 if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
662                         $clear_text = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
663
664                         $item["body"] = html2bbcode($clear_text) . '[spoiler]' . $item["body"] . '[/spoiler]';
665                 }
666
667                 if (($self != '') && empty($item['protocol'])) {
668                         self::fetchSelf($self, $item);
669                 }
670
671                 if (!empty($item["conversation-href"])) {
672                         self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
673                 }
674
675                 if (isset($item["parent-uri"]) && ($related != '')) {
676                         if (!dba::exists('item', ['uid' => $importer["uid"], 'uri' => $item['parent-uri']])) {
677                                 self::fetchRelated($related, $item["parent-uri"], $importer);
678                         } else {
679                                 logger('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
680                         }
681
682                         $item["type"] = 'remote-comment';
683                         $item["gravity"] = GRAVITY_COMMENT;
684                 } else {
685                         $item["parent-uri"] = $item["uri"];
686                 }
687
688                 if (($item['author-link'] != '') && !empty($item['protocol'])) {
689                         $item = Conversation::insert($item);
690                 }
691
692                 self::$itemlist[] = $item;
693         }
694
695         /**
696          * @brief Fetch the conversation for posts
697          *
698          * @param string $conversation     The link to the conversation
699          * @param string $conversation_uri The conversation in "uri" format
700          * @return void
701          */
702         private static function fetchConversation($conversation, $conversation_uri)
703         {
704                 // Ensure that we only store a conversation once in a process
705                 if (isset(self::$conv_list[$conversation])) {
706                         return;
707                 }
708
709                 self::$conv_list[$conversation] = true;
710
711                 $conversation_data = Network::curl($conversation, false, $redirects, ['accept_content' => 'application/atom+xml, text/html']);
712
713                 if (!$conversation_data['success']) {
714                         return;
715                 }
716
717                 $xml = '';
718
719                 if (stristr($conversation_data['header'], 'Content-Type: application/atom+xml')) {
720                         $xml = $conversation_data['body'];
721                 }
722
723                 if ($xml == '') {
724                         $doc = new DOMDocument();
725                         if (!@$doc->loadHTML($conversation_data['body'])) {
726                                 return;
727                         }
728                         $xpath = new DOMXPath($doc);
729
730                         $links = $xpath->query('//link');
731                         if ($links) {
732                                 $file = '';
733                                 foreach ($links as $link) {
734                                         $attribute = self::readAttributes($link);
735                                         if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
736                                                 $file = $attribute['href'];
737                                         }
738                                 }
739                                 if ($file != '') {
740                                         $conversation_atom = Network::curl($attribute['href']);
741
742                                         if ($conversation_atom['success']) {
743                                                 $xml = $conversation_atom['body'];
744                                         }
745                                 }
746                         }
747                 }
748
749                 if ($xml == '') {
750                         return;
751                 }
752
753                 self::storeConversation($xml, $conversation, $conversation_uri);
754         }
755
756         /**
757          * @brief Store a feed in several conversation entries
758          *
759          * @param string $xml              The feed
760          * @param string $conversation     conversation
761          * @param string $conversation_uri conversation uri
762          * @return void
763          */
764         private static function storeConversation($xml, $conversation = '', $conversation_uri = '')
765         {
766                 $doc = new DOMDocument();
767                 @$doc->loadXML($xml);
768
769                 $xpath = new DOMXPath($doc);
770                 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
771                 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
772                 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
773
774                 $entries = $xpath->query('/atom:feed/atom:entry');
775
776                 // Now store the entries
777                 foreach ($entries as $entry) {
778                         $doc2 = new DOMDocument();
779                         $doc2->preserveWhiteSpace = false;
780                         $doc2->formatOutput = true;
781
782                         $conv_data = [];
783
784                         $conv_data['protocol'] = PROTOCOL_SPLITTED_CONV;
785                         $conv_data['network'] = NETWORK_OSTATUS;
786                         $conv_data['uri'] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
787
788                         $inreplyto = $xpath->query('thr:in-reply-to', $entry);
789                         if (is_object($inreplyto->item(0))) {
790                                 foreach ($inreplyto->item(0)->attributes as $attributes) {
791                                         if ($attributes->name == "ref") {
792                                                 $conv_data['reply-to-uri'] = $attributes->textContent;
793                                         }
794                                 }
795                         }
796
797                         $conv = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
798                         $conv_data['conversation-uri'] = $conv;
799
800                         $conv = $xpath->query('ostatus:conversation', $entry);
801                         if (is_object($conv->item(0))) {
802                                 foreach ($conv->item(0)->attributes as $attributes) {
803                                         if ($attributes->name == "ref") {
804                                                 $conv_data['conversation-uri'] = $attributes->textContent;
805                                         }
806                                         if ($attributes->name == "href") {
807                                                 $conv_data['conversation-href'] = $attributes->textContent;
808                                         }
809                                 }
810                         }
811
812                         if ($conversation != '') {
813                                 $conv_data['conversation-uri'] = $conversation;
814                         }
815
816                         if ($conversation_uri != '') {
817                                 $conv_data['conversation-uri'] = $conversation_uri;
818                         }
819
820                         $entry = $doc2->importNode($entry, true);
821
822                         $doc2->appendChild($entry);
823
824                         $conv_data['source'] = $doc2->saveXML();
825
826                         $condition = ['item-uri' => $conv_data['uri'],'protocol' => PROTOCOL_OSTATUS_FEED];
827                         if (dba::exists('conversation', $condition)) {
828                                 logger('Delete deprecated entry for URI '.$conv_data['uri'], LOGGER_DEBUG);
829                                 dba::delete('conversation', ['item-uri' => $conv_data['uri']]);
830                         }
831
832                         logger('Store conversation data for uri '.$conv_data['uri'], LOGGER_DEBUG);
833                         Conversation::insert($conv_data);
834                 }
835         }
836
837         /**
838          * @brief Fetch the own post so that it can be stored later
839          *
840          * We want to store the original data for later processing.
841          * This function is meant for cases where we process a feed with multiple entries.
842          * In that case we need to fetch the single posts here.
843          *
844          * @param string $self The link to the self item
845          * @param array  $item The item array
846          * @return void
847          */
848         private static function fetchSelf($self, &$item)
849         {
850                 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $self, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON];
851                 if (dba::exists('conversation', $condition)) {
852                         logger('Conversation '.$item['uri'].' is already stored.', LOGGER_DEBUG);
853                         return;
854                 }
855
856                 $self_data = Network::curl($self);
857
858                 if (!$self_data['success']) {
859                         return;
860                 }
861
862                 // We reformat the XML to make it better readable
863                 $doc = new DOMDocument();
864                 $doc->loadXML($self_data['body']);
865                 $doc->preserveWhiteSpace = false;
866                 $doc->formatOutput = true;
867                 $xml = $doc->saveXML();
868
869                 $item["protocol"] = PROTOCOL_OSTATUS_SALMON;
870                 $item["source"] = $xml;
871
872                 logger('Conversation '.$item['uri'].' is now fetched.', LOGGER_DEBUG);
873         }
874
875         /**
876          * @brief Fetch related posts and processes them
877          *
878          * @param string $related     The link to the related item
879          * @param string $related_uri The related item in "uri" format
880          * @param array  $importer    user record of the importing user
881          * @return void
882          */
883         private static function fetchRelated($related, $related_uri, $importer)
884         {
885                 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON];
886                 $conversation = dba::selectFirst('conversation', ['source', 'protocol'], $condition);
887                 if (DBM::is_result($conversation)) {
888                         $stored = true;
889                         $xml = $conversation['source'];
890                         if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
891                                 logger('Got valid cached XML for URI '.$related_uri, LOGGER_DEBUG);
892                                 return;
893                         }
894                         if ($conversation['protocol'] == PROTOCOL_OSTATUS_SALMON) {
895                                 logger('Delete invalid cached XML for URI '.$related_uri, LOGGER_DEBUG);
896                                 dba::delete('conversation', ['item-uri' => $related_uri]);
897                         }
898                 }
899
900                 $stored = false;
901                 $related_data = Network::curl($related, false, $redirects, ['accept_content' => 'application/atom+xml, text/html']);
902
903                 if (!$related_data['success']) {
904                         return;
905                 }
906
907                 $xml = '';
908
909                 if (stristr($related_data['header'], 'Content-Type: application/atom+xml')) {
910                         logger('Directly fetched XML for URI '.$related_uri, LOGGER_DEBUG);
911                         $xml = $related_data['body'];
912                 }
913
914                 if ($xml == '') {
915                         $doc = new DOMDocument();
916                         if (!@$doc->loadHTML($related_data['body'])) {
917                                 return;
918                         }
919                         $xpath = new DOMXPath($doc);
920
921                         $atom_file = '';
922
923                         $links = $xpath->query('//link');
924                         if ($links) {
925                                 foreach ($links as $link) {
926                                         $attribute = self::readAttributes($link);
927                                         if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
928                                                 $atom_file = $attribute['href'];
929                                         }
930                                 }
931                                 if ($atom_file != '') {
932                                         $related_atom = Network::curl($atom_file);
933
934                                         if ($related_atom['success']) {
935                                                 logger('Fetched XML for URI '.$related_uri, LOGGER_DEBUG);
936                                                 $xml = $related_atom['body'];
937                                         }
938                                 }
939                         }
940                 }
941
942                 // Workaround for older GNU Social servers
943                 if (($xml == '') && strstr($related, '/notice/')) {
944                         $related_atom = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related).'.atom');
945
946                         if ($related_atom['success']) {
947                                 logger('GNU Social workaround to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
948                                 $xml = $related_atom['body'];
949                         }
950                 }
951
952                 // Even more worse workaround for GNU Social ;-)
953                 if ($xml == '') {
954                         $related_guess = OStatus::convertHref($related_uri);
955                         $related_atom = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related_guess).'.atom');
956
957                         if ($related_atom['success']) {
958                                 logger('GNU Social workaround 2 to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
959                                 $xml = $related_atom['body'];
960                         }
961                 }
962
963                 // Finally we take the data that we fetched from "ostatus:conversation"
964                 if ($xml == '') {
965                         $condition = ['item-uri' => $related_uri, 'protocol' => PROTOCOL_SPLITTED_CONV];
966                         $conversation = dba::selectFirst('conversation', ['source'], $condition);
967                         if (DBM::is_result($conversation)) {
968                                 $stored = true;
969                                 logger('Got cached XML from conversation for URI '.$related_uri, LOGGER_DEBUG);
970                                 $xml = $conversation['source'];
971                         }
972                 }
973
974                 if ($xml != '') {
975                         self::process($xml, $importer, $contact, $hub, $stored, false);
976                 } else {
977                         logger("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, LOGGER_DEBUG);
978                 }
979                 return;
980         }
981
982         /**
983          * @brief Processes the XML for a repeated post
984          *
985          * @param object $xpath    The xpath object
986          * @param object $entry    The xml entry that is processed
987          * @param array  $item     The item array
988          * @param array  $importer user record of the importing user
989          *
990          * @return array with data from links
991          */
992         private static function processRepeatedItem($xpath, $entry, &$item, $importer)
993         {
994                 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
995
996                 if (!is_object($activityobjects)) {
997                         return [];
998                 }
999
1000                 $link_data = [];
1001
1002                 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
1003
1004                 $links = $xpath->query("atom:link", $activityobjects);
1005                 if ($links) {
1006                         $link_data = self::processLinks($links, $item);
1007                 }
1008
1009                 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
1010                 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
1011                 $orig_edited = $xpath->query('atom:updated/text()', $activityobjects)->item(0)->nodeValue;
1012
1013                 $orig_author = self::fetchAuthor($xpath, $activityobjects, $importer, $dummy, false);
1014
1015                 $item["author-name"] = $orig_author["author-name"];
1016                 $item["author-link"] = $orig_author["author-link"];
1017                 $item["author-avatar"] = $orig_author["author-avatar"];
1018
1019                 $item["body"] = html2bbcode($orig_body);
1020                 $item["created"] = $orig_created;
1021                 $item["edited"] = $orig_edited;
1022
1023                 $item["uri"] = $orig_uri;
1024
1025                 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
1026
1027                 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
1028
1029                 $inreplyto = $xpath->query('thr:in-reply-to', $activityobjects);
1030                 if (is_object($inreplyto->item(0))) {
1031                         foreach ($inreplyto->item(0)->attributes as $attributes) {
1032                                 if ($attributes->name == "ref") {
1033                                         $item["parent-uri"] = $attributes->textContent;
1034                                 }
1035                         }
1036                 }
1037
1038                 return $link_data;
1039         }
1040
1041         /**
1042          * @brief Processes links in the XML
1043          *
1044          * @param object $links The xml data that contain links
1045          * @param array  $item  The item array
1046          *
1047          * @return array with data from the links
1048          */
1049         private static function processLinks($links, &$item)
1050         {
1051                 $link_data = ['add_body' => '', 'self' => ''];
1052
1053                 foreach ($links as $link) {
1054                         $attribute = self::readAttributes($link);
1055
1056                         if (($attribute['rel'] != "") && ($attribute['href'] != "")) {
1057                                 switch ($attribute['rel']) {
1058                                         case "alternate":
1059                                                 $item["plink"] = $attribute['href'];
1060                                                 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION)
1061                                                         || ($item["object-type"] == ACTIVITY_OBJ_EVENT)
1062                                                 ) {
1063                                                         $item["body"] .= add_page_info($attribute['href']);
1064                                                 }
1065                                                 break;
1066                                         case "ostatus:conversation":
1067                                                 $link_data['conversation'] = $attribute['href'];
1068                                                 $item['conversation-href'] = $link_data['conversation'];
1069                                                 if (!isset($item['conversation-uri'])) {
1070                                                         $item['conversation-uri'] = $item['conversation-href'];
1071                                                 }
1072                                                 break;
1073                                         case "enclosure":
1074                                                 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
1075                                                 if ($filetype == 'image') {
1076                                                         $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1077                                                 } else {
1078                                                         if (strlen($item["attach"])) {
1079                                                                 $item["attach"] .= ',';
1080                                                         }
1081                                                         if (!isset($attribute['length'])) {
1082                                                                 $attribute['length'] = "0";
1083                                                         }
1084                                                         $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
1085                                                 }
1086                                                 break;
1087                                         case "related":
1088                                                 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
1089                                                         if (!isset($item["parent-uri"])) {
1090                                                                 $item["parent-uri"] = $attribute['href'];
1091                                                         }
1092                                                         $link_data['related'] = $attribute['href'];
1093                                                 } else {
1094                                                         $item["body"] .= add_page_info($attribute['href']);
1095                                                 }
1096                                                 break;
1097                                         case "self":
1098                                                 if ($item["plink"] == '') {
1099                                                         $item["plink"] = $attribute['href'];
1100                                                 }
1101                                                 $link_data['self'] = $attribute['href'];
1102                                                 break;
1103                                 }
1104                         }
1105                 }
1106                 return $link_data;
1107         }
1108
1109         /**
1110          * @brief Create an url out of an uri
1111          *
1112          * @param string $href URI in the format "parameter1:parameter1:..."
1113          *
1114          * @return string URL in the format http(s)://....
1115          */
1116         public static function convertHref($href)
1117         {
1118                 $elements = explode(":", $href);
1119
1120                 if ((count($elements) <= 2) || ($elements[0] != "tag")) {
1121                         return $href;
1122                 }
1123
1124                 $server = explode(",", $elements[1]);
1125                 $conversation = explode("=", $elements[2]);
1126
1127                 if ((count($elements) == 4) && ($elements[2] == "post")) {
1128                         return "http://".$server[0]."/notice/".$elements[3];
1129                 }
1130
1131                 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1132                         return $href;
1133                 }
1134                 if ($elements[3] == "objectType=thread") {
1135                         return "http://".$server[0]."/conversation/".$conversation[1];
1136                 } else {
1137                         return "http://".$server[0]."/notice/".$conversation[1];
1138                 }
1139                 return $href;
1140         }
1141
1142         /**
1143          * @brief Checks if the current post is a reshare
1144          *
1145          * @param array $item The item array of thw post
1146          *
1147          * @return string The guid if the post is a reshare
1148          */
1149         private static function getResharedGuid($item)
1150         {
1151                 $body = trim($item["body"]);
1152
1153                 // Skip if it isn't a pure repeated messages
1154                 // Does it start with a share?
1155                 if (strpos($body, "[share") > 0) {
1156                         return "";
1157                 }
1158
1159                 // Does it end with a share?
1160                 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
1161                         return "";
1162                 }
1163
1164                 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
1165                 // Skip if there is no shared message in there
1166                 if ($body == $attributes) {
1167                         return false;
1168                 }
1169
1170                 $guid = "";
1171                 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1172                 if ($matches[1] != "") {
1173                         $guid = $matches[1];
1174                 }
1175
1176                 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1177                 if ($matches[1] != "") {
1178                         $guid = $matches[1];
1179                 }
1180
1181                 return $guid;
1182         }
1183
1184         /**
1185          * @brief Cleans the body of a post if it contains picture links
1186          *
1187          * @param string $body The body
1188          *
1189          * @return string The cleaned body
1190          */
1191         private static function formatPicturePost($body)
1192         {
1193                 $siteinfo = BBCode::getAttachedData($body);
1194
1195                 if (($siteinfo["type"] == "photo")) {
1196                         if (isset($siteinfo["preview"])) {
1197                                 $preview = $siteinfo["preview"];
1198                         } else {
1199                                 $preview = $siteinfo["image"];
1200                         }
1201
1202                         // Is it a remote picture? Then make a smaller preview here
1203                         $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
1204
1205                         // Is it a local picture? Then make it smaller here
1206                         $preview = str_replace(["-0.jpg", "-0.png"], ["-2.jpg", "-2.png"], $preview);
1207                         $preview = str_replace(["-1.jpg", "-1.png"], ["-2.jpg", "-2.png"], $preview);
1208
1209                         if (isset($siteinfo["url"])) {
1210                                 $url = $siteinfo["url"];
1211                         } else {
1212                                 $url = $siteinfo["image"];
1213                         }
1214
1215                         $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1216                 }
1217
1218                 return $body;
1219         }
1220
1221         /**
1222          * @brief Adds the header elements to the XML document
1223          *
1224          * @param object $doc    XML document
1225          * @param array  $owner  Contact data of the poster
1226          * @param string $filter The related feed filter (activity, posts or comments)
1227          *
1228          * @return object header root element
1229          */
1230         private static function addHeader($doc, $owner, $filter)
1231         {
1232                 $a = get_app();
1233
1234                 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1235                 $doc->appendChild($root);
1236
1237                 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1238                 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1239                 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1240                 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1241                 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1242                 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1243                 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1244                 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1245
1246                 $title = '';
1247                 switch ($filter) {
1248                         case 'activity': $title = L10n::t('%s\'s timeline', $owner['name']); break;
1249                         case 'posts'   : $title = L10n::t('%s\'s posts'   , $owner['name']); break;
1250                         case 'comments': $title = L10n::t('%s\'s comments', $owner['name']); break;
1251                 }
1252
1253                 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
1254                 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1255                 XML::addElement($doc, $root, "id", System::baseUrl() . "/profile/" . $owner["nick"]);
1256                 XML::addElement($doc, $root, "title", $title);
1257                 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
1258                 XML::addElement($doc, $root, "logo", $owner["photo"]);
1259                 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1260
1261                 $author = self::addAuthor($doc, $owner);
1262                 $root->appendChild($author);
1263
1264                 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1265                 XML::addElement($doc, $root, "link", "", $attributes);
1266
1267                 /// @TODO We have to find out what this is
1268                 /// $attributes = array("href" => System::baseUrl()."/sup",
1269                 ///             "rel" => "http://api.friendfeed.com/2008/03#sup",
1270                 ///             "type" => "application/json");
1271                 /// XML::addElement($doc, $root, "link", "", $attributes);
1272
1273                 self::hublinks($doc, $root, $owner["nick"]);
1274
1275                 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "salmon"];
1276                 XML::addElement($doc, $root, "link", "", $attributes);
1277
1278                 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies"];
1279                 XML::addElement($doc, $root, "link", "", $attributes);
1280
1281                 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention"];
1282                 XML::addElement($doc, $root, "link", "", $attributes);
1283
1284                 $attributes = ["href" => System::baseUrl() . "/api/statuses/user_timeline/" . $owner["nick"] . ".atom",
1285                         "rel" => "self", "type" => "application/atom+xml"];
1286                 XML::addElement($doc, $root, "link", "", $attributes);
1287
1288                 return $root;
1289         }
1290
1291         /**
1292          * @brief Add the link to the push hubs to the XML document
1293          *
1294          * @param object $doc  XML document
1295          * @param object $root XML root element where the hub links are added
1296          * @param object $nick nick
1297          * @return void
1298          */
1299         public static function hublinks($doc, $root, $nick)
1300         {
1301                 $h = System::baseUrl() . '/pubsubhubbub/'.$nick;
1302                 XML::addElement($doc, $root, "link", "", ["href" => $h, "rel" => "hub"]);
1303         }
1304
1305         /**
1306          * @brief Adds attachement data to the XML document
1307          *
1308          * @param object $doc  XML document
1309          * @param object $root XML root element where the hub links are added
1310          * @param array  $item Data of the item that is to be posted
1311          * @return void
1312          */
1313         private static function getAttachment($doc, $root, $item)
1314         {
1315                 $o = "";
1316                 $siteinfo = BBCode::getAttachedData($item["body"]);
1317
1318                 switch ($siteinfo["type"]) {
1319                         case 'photo':
1320                                 $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1321                                 $attributes = ["rel" => "enclosure",
1322                                                 "href" => $siteinfo["image"],
1323                                                 "type" => $imgdata["mime"],
1324                                                 "length" => intval($imgdata["size"])];
1325                                 XML::addElement($doc, $root, "link", "", $attributes);
1326                                 break;
1327                         case 'video':
1328                                 $attributes = ["rel" => "enclosure",
1329                                                 "href" => $siteinfo["url"],
1330                                                 "type" => "text/html; charset=UTF-8",
1331                                                 "length" => "",
1332                                                 "title" => $siteinfo["title"]];
1333                                 XML::addElement($doc, $root, "link", "", $attributes);
1334                                 break;
1335                         default:
1336                                 break;
1337                 }
1338
1339                 if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1340                         $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1341                         $attributes = ["rel" => "enclosure",
1342                                         "href" => $siteinfo["image"],
1343                                         "type" => $imgdata["mime"],
1344                                         "length" => intval($imgdata["size"])];
1345
1346                         XML::addElement($doc, $root, "link", "", $attributes);
1347                 }
1348
1349                 $arr = explode('[/attach],', $item['attach']);
1350                 if (count($arr)) {
1351                         foreach ($arr as $r) {
1352                                 $matches = false;
1353                                 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1354                                 if ($cnt) {
1355                                         $attributes = ["rel" => "enclosure",
1356                                                         "href" => $matches[1],
1357                                                         "type" => $matches[3]];
1358
1359                                         if (intval($matches[2])) {
1360                                                 $attributes["length"] = intval($matches[2]);
1361                                         }
1362                                         if (trim($matches[4]) != "") {
1363                                                 $attributes["title"] = trim($matches[4]);
1364                                         }
1365                                         XML::addElement($doc, $root, "link", "", $attributes);
1366                                 }
1367                         }
1368                 }
1369         }
1370
1371         /**
1372          * @brief Adds the author element to the XML document
1373          *
1374          * @param object $doc   XML document
1375          * @param array  $owner Contact data of the poster
1376          *
1377          * @return object author element
1378          */
1379         private static function addAuthor($doc, $owner)
1380         {
1381                 $profile = dba::selectFirst('profile', ['homepage', 'publish'], ['uid' => $owner['uid'], 'is-default' => true]);
1382                 $author = $doc->createElement("author");
1383                 XML::addElement($doc, $author, "id", $owner["url"]);
1384                 XML::addElement($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1385                 XML::addElement($doc, $author, "uri", $owner["url"]);
1386                 XML::addElement($doc, $author, "name", $owner["nick"]);
1387                 XML::addElement($doc, $author, "email", $owner["addr"]);
1388                 XML::addElement($doc, $author, "summary", BBCode::convert($owner["about"], false, 7));
1389
1390                 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $owner["url"]];
1391                 XML::addElement($doc, $author, "link", "", $attributes);
1392
1393                 $attributes = [
1394                                 "rel" => "avatar",
1395                                 "type" => "image/jpeg", // To-Do?
1396                                 "media:width" => 175,
1397                                 "media:height" => 175,
1398                                 "href" => $owner["photo"]];
1399                 XML::addElement($doc, $author, "link", "", $attributes);
1400
1401                 if (isset($owner["thumb"])) {
1402                         $attributes = [
1403                                         "rel" => "avatar",
1404                                         "type" => "image/jpeg", // To-Do?
1405                                         "media:width" => 80,
1406                                         "media:height" => 80,
1407                                         "href" => $owner["thumb"]];
1408                         XML::addElement($doc, $author, "link", "", $attributes);
1409                 }
1410
1411                 XML::addElement($doc, $author, "poco:preferredUsername", $owner["nick"]);
1412                 XML::addElement($doc, $author, "poco:displayName", $owner["name"]);
1413                 XML::addElement($doc, $author, "poco:note", BBCode::convert($owner["about"], false, 7));
1414
1415                 if (trim($owner["location"]) != "") {
1416                         $element = $doc->createElement("poco:address");
1417                         XML::addElement($doc, $element, "poco:formatted", $owner["location"]);
1418                         $author->appendChild($element);
1419                 }
1420
1421                 if (DBM::is_result($profile)) {
1422                         if (trim($profile["homepage"]) != "") {
1423                                 $urls = $doc->createElement("poco:urls");
1424                                 XML::addElement($doc, $urls, "poco:type", "homepage");
1425                                 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
1426                                 XML::addElement($doc, $urls, "poco:primary", "true");
1427                                 $author->appendChild($urls);
1428                         }
1429
1430                         XML::addElement($doc, $author, "followers", "", ["url" => System::baseUrl()."/viewcontacts/".$owner["nick"]]);
1431                         XML::addElement($doc, $author, "statusnet:profile_info", "", ["local_id" => $owner["uid"]]);
1432                 }
1433
1434                 if ($profile["publish"]) {
1435                         XML::addElement($doc, $author, "mastodon:scope", "public");
1436                 }
1437                 return $author;
1438         }
1439
1440         /**
1441          * @TODO Picture attachments should look like this:
1442          *      <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1443          *      class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1444          */
1445
1446         /**
1447          * @brief Returns the given activity if present - otherwise returns the "post" activity
1448          *
1449          * @param array $item Data of the item that is to be posted
1450          *
1451          * @return string activity
1452          */
1453         private static function constructVerb($item)
1454         {
1455                 if ($item['verb']) {
1456                         return $item['verb'];
1457                 }
1458
1459                 return ACTIVITY_POST;
1460         }
1461
1462         /**
1463          * @brief Returns the given object type if present - otherwise returns the "note" object type
1464          *
1465          * @param array $item Data of the item that is to be posted
1466          *
1467          * @return string Object type
1468          */
1469         private static function constructObjecttype($item)
1470         {
1471                 if (in_array($item['object-type'], [ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT]))
1472                         return $item['object-type'];
1473                 return ACTIVITY_OBJ_NOTE;
1474         }
1475
1476         /**
1477          * @brief Adds an entry element to the XML document
1478          *
1479          * @param object $doc      XML document
1480          * @param array  $item     Data of the item that is to be posted
1481          * @param array  $owner    Contact data of the poster
1482          * @param bool   $toplevel optional default false
1483          *
1484          * @return object Entry element
1485          */
1486         private static function entry($doc, $item, $owner, $toplevel = false)
1487         {
1488                 $xml = null;
1489
1490                 $repeated_guid = self::getResharedGuid($item);
1491                 if ($repeated_guid != "") {
1492                         $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel);
1493                 }
1494
1495                 if ($xml) {
1496                         return $xml;
1497                 }
1498
1499                 if ($item["verb"] == ACTIVITY_LIKE) {
1500                         return self::likeEntry($doc, $item, $owner, $toplevel);
1501                 } elseif (in_array($item["verb"], [ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"])) {
1502                         return self::followEntry($doc, $item, $owner, $toplevel);
1503                 } else {
1504                         return self::noteEntry($doc, $item, $owner, $toplevel);
1505                 }
1506         }
1507
1508         /**
1509          * @brief Adds a source entry to the XML document
1510          *
1511          * @param object $doc     XML document
1512          * @param array  $contact Array of the contact that is added
1513          *
1514          * @return object Source element
1515          */
1516         private static function sourceEntry($doc, $contact)
1517         {
1518                 $source = $doc->createElement("source");
1519                 XML::addElement($doc, $source, "id", $contact["poll"]);
1520                 XML::addElement($doc, $source, "title", $contact["name"]);
1521                 XML::addElement($doc, $source, "link", "", ["rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]]);
1522                 XML::addElement($doc, $source, "link", "", ["rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]]);
1523                 XML::addElement($doc, $source, "icon", $contact["photo"]);
1524                 XML::addElement($doc, $source, "updated", DateTimeFormat::utc($contact["success_update"]."+00:00", DateTimeFormat::ATOM));
1525
1526                 return $source;
1527         }
1528
1529         /**
1530          * @brief Fetches contact data from the contact or the gcontact table
1531          *
1532          * @param string $url   URL of the contact
1533          * @param array  $owner Contact data of the poster
1534          *
1535          * @return array Contact array
1536          */
1537         private static function contactEntry($url, $owner)
1538         {
1539                 $r = q(
1540                         "SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1541                         dbesc(normalise_link($url)),
1542                         intval($owner["uid"])
1543                 );
1544                 if (DBM::is_result($r)) {
1545                         $contact = $r[0];
1546                         $contact["uid"] = -1;
1547                 }
1548
1549                 if (!DBM::is_result($r)) {
1550                         $r = q(
1551                                 "SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1552                                 dbesc(normalise_link($url))
1553                         );
1554                         if (DBM::is_result($r)) {
1555                                 $contact = $r[0];
1556                                 $contact["uid"] = -1;
1557                                 $contact["success_update"] = $contact["updated"];
1558                         }
1559                 }
1560
1561                 if (!DBM::is_result($r)) {
1562                         $contact = owner;
1563                 }
1564
1565                 if (!isset($contact["poll"])) {
1566                         $data = Probe::uri($url);
1567                         $contact["poll"] = $data["poll"];
1568
1569                         if (!$contact["alias"]) {
1570                                 $contact["alias"] = $data["alias"];
1571                         }
1572                 }
1573
1574                 if (!isset($contact["alias"])) {
1575                         $contact["alias"] = $contact["url"];
1576                 }
1577
1578                 return $contact;
1579         }
1580
1581         /**
1582          * @brief Adds an entry element with reshared content
1583          *
1584          * @param object $doc           XML document
1585          * @param array  $item          Data of the item that is to be posted
1586          * @param array  $owner         Contact data of the poster
1587          * @param string $repeated_guid guid
1588          * @param bool   $toplevel      Is it for en entry element (false) or a feed entry (true)?
1589          *
1590          * @return object Entry element
1591          */
1592         private static function reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel)
1593         {
1594                 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1595                         logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1596                 }
1597
1598                 $title = self::entryHeader($doc, $entry, $owner, $toplevel);
1599
1600                 $r = q(
1601                         "SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' AND NOT `private` AND `network` IN ('%s', '%s', '%s') LIMIT 1",
1602                         intval($owner["uid"]),
1603                         dbesc($repeated_guid),
1604                         dbesc(NETWORK_DFRN),
1605                         dbesc(NETWORK_DIASPORA),
1606                         dbesc(NETWORK_OSTATUS)
1607                 );
1608                 if (DBM::is_result($r)) {
1609                         $repeated_item = $r[0];
1610                 } else {
1611                         return false;
1612                 }
1613                 $contact = self::contactEntry($repeated_item['author-link'], $owner);
1614
1615                 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1616
1617                 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1618
1619                 self::entryContent($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1620
1621                 $as_object = $doc->createElement("activity:object");
1622
1623                 XML::addElement($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1624
1625                 self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false);
1626
1627                 $author = self::addAuthor($doc, $contact);
1628                 $as_object->appendChild($author);
1629
1630                 $as_object2 = $doc->createElement("activity:object");
1631
1632                 XML::addElement($doc, $as_object2, "activity:object-type", self::constructObjecttype($repeated_item));
1633
1634                 $title = sprintf("New comment by %s", $contact["nick"]);
1635
1636                 self::entryContent($doc, $as_object2, $repeated_item, $owner, $title);
1637
1638                 $as_object->appendChild($as_object2);
1639
1640                 self::entryFooter($doc, $as_object, $item, $owner, false);
1641
1642                 $source = self::sourceEntry($doc, $contact);
1643
1644                 $as_object->appendChild($source);
1645
1646                 $entry->appendChild($as_object);
1647
1648                 self::entryFooter($doc, $entry, $item, $owner);
1649
1650                 return $entry;
1651         }
1652
1653         /**
1654          * @brief Adds an entry element with a "like"
1655          *
1656          * @param object $doc      XML document
1657          * @param array  $item     Data of the item that is to be posted
1658          * @param array  $owner    Contact data of the poster
1659          * @param bool   $toplevel Is it for en entry element (false) or a feed entry (true)?
1660          *
1661          * @return object Entry element with "like"
1662          */
1663         private static function likeEntry($doc, $item, $owner, $toplevel)
1664         {
1665                 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1666                         logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1667                 }
1668
1669                 $title = self::entryHeader($doc, $entry, $owner, $toplevel);
1670
1671                 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1672                 self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false);
1673
1674                 $as_object = $doc->createElement("activity:object");
1675
1676                 $parent = q(
1677                         "SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
1678                         dbesc($item["thr-parent"]),
1679                         intval($item["uid"])
1680                 );
1681                 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1682
1683                 XML::addElement($doc, $as_object, "activity:object-type", self::constructObjecttype($parent[0]));
1684
1685                 self::entryContent($doc, $as_object, $parent[0], $owner, "New entry");
1686
1687                 $entry->appendChild($as_object);
1688
1689                 self::entryFooter($doc, $entry, $item, $owner);
1690
1691                 return $entry;
1692         }
1693
1694         /**
1695          * @brief Adds the person object element to the XML document
1696          *
1697          * @param object $doc     XML document
1698          * @param array  $owner   Contact data of the poster
1699          * @param array  $contact Contact data of the target
1700          *
1701          * @return object author element
1702          */
1703         private static function addPersonObject($doc, $owner, $contact)
1704         {
1705                 $object = $doc->createElement("activity:object");
1706                 XML::addElement($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1707
1708                 if ($contact['network'] == NETWORK_PHANTOM) {
1709                         XML::addElement($doc, $object, "id", $contact['url']);
1710                         return $object;
1711                 }
1712
1713                 XML::addElement($doc, $object, "id", $contact["alias"]);
1714                 XML::addElement($doc, $object, "title", $contact["nick"]);
1715
1716                 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $contact["url"]];
1717                 XML::addElement($doc, $object, "link", "", $attributes);
1718
1719                 $attributes = [
1720                                 "rel" => "avatar",
1721                                 "type" => "image/jpeg", // To-Do?
1722                                 "media:width" => 175,
1723                                 "media:height" => 175,
1724                                 "href" => $contact["photo"]];
1725                 XML::addElement($doc, $object, "link", "", $attributes);
1726
1727                 XML::addElement($doc, $object, "poco:preferredUsername", $contact["nick"]);
1728                 XML::addElement($doc, $object, "poco:displayName", $contact["name"]);
1729
1730                 if (trim($contact["location"]) != "") {
1731                         $element = $doc->createElement("poco:address");
1732                         XML::addElement($doc, $element, "poco:formatted", $contact["location"]);
1733                         $object->appendChild($element);
1734                 }
1735
1736                 return $object;
1737         }
1738
1739         /**
1740          * @brief Adds a follow/unfollow entry element
1741          *
1742          * @param object $doc      XML document
1743          * @param array  $item     Data of the follow/unfollow message
1744          * @param array  $owner    Contact data of the poster
1745          * @param bool   $toplevel Is it for en entry element (false) or a feed entry (true)?
1746          *
1747          * @return object Entry element
1748          */
1749         private static function followEntry($doc, $item, $owner, $toplevel)
1750         {
1751                 $item["id"] = $item["parent"] = 0;
1752                 $item["created"] = $item["edited"] = date("c");
1753                 $item["private"] = true;
1754
1755                 $contact = Probe::uri($item['follow']);
1756
1757                 if ($contact['alias'] == '') {
1758                         $contact['alias'] = $contact["url"];
1759                 } else {
1760                         $item['follow'] = $contact['alias'];
1761                 }
1762
1763                 $r = q(
1764                         "SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1765                         intval($owner['uid']),
1766                         dbesc(normalise_link($contact["url"]))
1767                 );
1768
1769                 if (DBM::is_result($r)) {
1770                         $connect_id = $r[0]['id'];
1771                 } else {
1772                         $connect_id = 0;
1773                 }
1774
1775                 if ($item['verb'] == ACTIVITY_FOLLOW) {
1776                         $message = L10n::t('%s is now following %s.');
1777                         $title = L10n::t('following');
1778                         $action = "subscription";
1779                 } else {
1780                         $message = L10n::t('%s stopped following %s.');
1781                         $title = L10n::t('stopped following');
1782                         $action = "unfollow";
1783                 }
1784
1785                 $item["uri"] = $item['parent-uri'] = $item['thr-parent']
1786                                 = 'tag:'.get_app()->get_hostname().
1787                                 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1788                                 ':person:'.$connect_id.':'.$item['created'];
1789
1790                 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1791
1792                 self::entryHeader($doc, $entry, $owner, $toplevel);
1793
1794                 self::entryContent($doc, $entry, $item, $owner, $title);
1795
1796                 $object = self::addPersonObject($doc, $owner, $contact);
1797                 $entry->appendChild($object);
1798
1799                 self::entryFooter($doc, $entry, $item, $owner);
1800
1801                 return $entry;
1802         }
1803
1804         /**
1805          * @brief Adds a regular entry element
1806          *
1807          * @param object $doc      XML document
1808          * @param array  $item     Data of the item that is to be posted
1809          * @param array  $owner    Contact data of the poster
1810          * @param bool   $toplevel Is it for en entry element (false) or a feed entry (true)?
1811          *
1812          * @return object Entry element
1813          */
1814         private static function noteEntry($doc, $item, $owner, $toplevel)
1815         {
1816                 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1817                         logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1818                 }
1819
1820                 $title = self::entryHeader($doc, $entry, $owner, $toplevel);
1821
1822                 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1823
1824                 self::entryContent($doc, $entry, $item, $owner, $title);
1825
1826                 self::entryFooter($doc, $entry, $item, $owner);
1827
1828                 return $entry;
1829         }
1830
1831         /**
1832          * @brief Adds a header element to the XML document
1833          *
1834          * @param object $doc      XML document
1835          * @param object $entry    The entry element where the elements are added
1836          * @param array  $owner    Contact data of the poster
1837          * @param bool   $toplevel Is it for en entry element (false) or a feed entry (true)?
1838          *
1839          * @return string The title for the element
1840          */
1841         private static function entryHeader($doc, &$entry, $owner, $toplevel)
1842         {
1843                 /// @todo Check if this title stuff is really needed (I guess not)
1844                 if (!$toplevel) {
1845                         $entry = $doc->createElement("entry");
1846                         $title = sprintf("New note by %s", $owner["nick"]);
1847                 } else {
1848                         $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
1849
1850                         $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1851                         $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1852                         $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1853                         $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1854                         $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
1855                         $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1856                         $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1857                         $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1858
1859                         $author = self::addAuthor($doc, $owner);
1860                         $entry->appendChild($author);
1861
1862                         $title = sprintf("New comment by %s", $owner["nick"]);
1863                 }
1864                 return $title;
1865         }
1866
1867         /**
1868          * @brief Adds elements to the XML document
1869          *
1870          * @param object $doc      XML document
1871          * @param object $entry    Entry element where the content is added
1872          * @param array  $item     Data of the item that is to be posted
1873          * @param array  $owner    Contact data of the poster
1874          * @param string $title    Title for the post
1875          * @param string $verb     The activity verb
1876          * @param bool   $complete Add the "status_net" element?
1877          * @return void
1878          */
1879         private static function entryContent($doc, $entry, $item, $owner, $title, $verb = "", $complete = true)
1880         {
1881                 if ($verb == "") {
1882                         $verb = self::constructVerb($item);
1883                 }
1884
1885                 XML::addElement($doc, $entry, "id", $item["uri"]);
1886                 XML::addElement($doc, $entry, "title", $title);
1887
1888                 $body = self::formatPicturePost($item['body']);
1889
1890                 if ($item['title'] != "") {
1891                         $body = "[b]".$item['title']."[/b]\n\n".$body;
1892                 }
1893
1894                 $body = BBCode::convert($body, false, 7);
1895
1896                 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1897
1898                 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1899                                                                 "href" => System::baseUrl()."/display/".$item["guid"]]
1900                 );
1901
1902                 if ($complete && ($item["id"] > 0)) {
1903                         XML::addElement($doc, $entry, "status_net", "", ["notice_id" => $item["id"]]);
1904                 }
1905
1906                 XML::addElement($doc, $entry, "activity:verb", $verb);
1907
1908                 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
1909                 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
1910         }
1911
1912         /**
1913          * @brief Adds the elements at the foot of an entry to the XML document
1914          *
1915          * @param object $doc      XML document
1916          * @param object $entry    The entry element where the elements are added
1917          * @param array  $item     Data of the item that is to be posted
1918          * @param array  $owner    Contact data of the poster
1919          * @param bool   $complete default true
1920          * @return void
1921          */
1922         private static function entryFooter($doc, $entry, $item, $owner, $complete = true)
1923         {
1924                 $mentioned = [];
1925
1926                 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
1927                         $parent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `id` = %d", intval($item["parent"]));
1928                         $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1929
1930                         $thrparent = q(
1931                                 "SELECT `guid`, `author-link`, `owner-link`, `plink` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
1932                                 intval($owner["uid"]),
1933                                 dbesc($parent_item)
1934                         );
1935                         if ($thrparent) {
1936                                 $mentioned[$thrparent[0]["author-link"]] = $thrparent[0]["author-link"];
1937                                 $mentioned[$thrparent[0]["owner-link"]] = $thrparent[0]["owner-link"];
1938                                 $parent_plink = $thrparent[0]["plink"];
1939                         } else {
1940                                 $mentioned[$parent[0]["author-link"]] = $parent[0]["author-link"];
1941                                 $mentioned[$parent[0]["owner-link"]] = $parent[0]["owner-link"];
1942                                 $parent_plink = System::baseUrl()."/display/".$parent[0]["guid"];
1943                         }
1944
1945                         $attributes = [
1946                                         "ref" => $parent_item,
1947                                         "href" => $parent_plink];
1948                         XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
1949
1950                         $attributes = [
1951                                         "rel" => "related",
1952                                         "href" => $parent_plink];
1953                         XML::addElement($doc, $entry, "link", "", $attributes);
1954                 }
1955
1956                 if (intval($item["parent"]) > 0) {
1957                         $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
1958                         $conversation_uri = $conversation_href;
1959
1960                         if (isset($parent_item)) {
1961                                 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $parent_item);
1962                                 if (DBM::is_result($r)) {
1963                                         if ($r['conversation-uri'] != '') {
1964                                                 $conversation_uri = $r['conversation-uri'];
1965                                         }
1966                                         if ($r['conversation-href'] != '') {
1967                                                 $conversation_href = $r['conversation-href'];
1968                                         }
1969                                 }
1970                         }
1971
1972                         XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:conversation", "href" => $conversation_href]);
1973
1974                         $attributes = [
1975                                         "href" => $conversation_href,
1976                                         "local_id" => $item["parent"],
1977                                         "ref" => $conversation_uri];
1978
1979                         XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
1980                 }
1981
1982                 $tags = item::getFeedTags($item);
1983
1984                 if (count($tags)) {
1985                         foreach ($tags as $t) {
1986                                 if ($t[0] == "@") {
1987                                         $mentioned[$t[1]] = $t[1];
1988                                 }
1989                         }
1990                 }
1991
1992                 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
1993                 $newmentions = [];
1994                 foreach ($mentioned as $mention) {
1995                         $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
1996                         $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
1997                 }
1998                 $mentioned = $newmentions;
1999
2000                 foreach ($mentioned as $mention) {
2001                         $r = q(
2002                                 "SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
2003                                 intval($owner["uid"]),
2004                                 dbesc(normalise_link($mention))
2005                         );
2006                         if ($r[0]["forum"] || $r[0]["prv"]) {
2007                                 XML::addElement($doc, $entry, "link", "",
2008                                         [
2009                                                 "rel" => "mentioned",
2010                                                 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
2011                                                 "href" => $mention]
2012                                 );
2013                         } else {
2014                                 XML::addElement($doc, $entry, "link", "",
2015                                         [
2016                                                 "rel" => "mentioned",
2017                                                 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
2018                                                 "href" => $mention]
2019                                 );
2020                         }
2021                 }
2022
2023                 if (!$item["private"]) {
2024                         XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:attention",
2025                                                                         "href" => "http://activityschema.org/collection/public"]);
2026                         XML::addElement($doc, $entry, "link", "", ["rel" => "mentioned",
2027                                                                         "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2028                                                                         "href" => "http://activityschema.org/collection/public"]);
2029                         XML::addElement($doc, $entry, "mastodon:scope", "public");
2030                 }
2031
2032                 if (count($tags)) {
2033                         foreach ($tags as $t) {
2034                                 if ($t[0] != "@") {
2035                                         XML::addElement($doc, $entry, "category", "", ["term" => $t[2]]);
2036                                 }
2037                         }
2038                 }
2039
2040                 self::getAttachment($doc, $entry, $item);
2041
2042                 if ($complete && ($item["id"] > 0)) {
2043                         $app = $item["app"];
2044                         if ($app == "") {
2045                                 $app = "web";
2046                         }
2047
2048                         $attributes = ["local_id" => $item["id"], "source" => $app];
2049
2050                         if (isset($parent["id"])) {
2051                                 $attributes["repeat_of"] = $parent["id"];
2052                         }
2053
2054                         if ($item["coord"] != "") {
2055                                 XML::addElement($doc, $entry, "georss:point", $item["coord"]);
2056                         }
2057
2058                         XML::addElement($doc, $entry, "statusnet:notice_info", "", $attributes);
2059                 }
2060         }
2061
2062         /**
2063          * Creates the XML feed for a given nickname
2064          *
2065          * Supported filters:
2066          * - activity (default): all the public posts
2067          * - posts: all the public top-level posts
2068          * - comments: all the public replies
2069          *
2070          * Updates the provided last_update parameter if the result comes from the
2071          * cache or it is empty
2072          *
2073          * @brief Creates the XML feed for a given nickname
2074          *
2075          * @param string  $owner_nick  Nickname of the feed owner
2076          * @param string  $last_update Date of the last update
2077          * @param integer $max_items   Number of maximum items to fetch
2078          * @param string  $filter      Feed items filter (activity, posts or comments)
2079          * @param boolean $nocache     Wether to bypass caching
2080          *
2081          * @return string XML feed
2082          */
2083         public static function feed($owner_nick, &$last_update, $max_items = 300, $filter = 'activity', $nocache = false)
2084         {
2085                 $stamp = microtime(true);
2086
2087                 $cachekey = "ostatus:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
2088
2089                 $previous_created = $last_update;
2090
2091                 $result = Cache::get($cachekey);
2092                 if (!$nocache && !is_null($result)) {
2093                         logger('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', LOGGER_DEBUG);
2094                         $last_update = $result['last_update'];
2095                         return $result['feed'];
2096                 }
2097
2098                 $owner = dba::fetch_first(
2099                         "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
2100                                 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
2101                                 WHERE `contact`.`self` AND `user`.`nickname` = ? LIMIT 1",
2102                         $owner_nick
2103                 );
2104                 if (!DBM::is_result($owner)) {
2105                         return;
2106                 }
2107
2108                 if (!strlen($last_update)) {
2109                         $last_update = 'now -30 days';
2110                 }
2111
2112                 $check_date = DateTimeFormat::utc($last_update);
2113                 $authorid = Contact::getIdForURL($owner["url"], 0, true);
2114
2115                 $sql_extra = '';
2116                 if ($filter === 'posts') {
2117                         $sql_extra .= ' AND `item`.`id` = `item`.`parent` ';
2118                 }
2119
2120                 if ($filter === 'comments') {
2121                         $sql_extra .= sprintf(" AND `item`.`object-type` = '%s' ", dbesc(ACTIVITY_OBJ_COMMENT));
2122                 }
2123
2124                 if ($owner['account-type'] != ACCOUNT_TYPE_COMMUNITY) {
2125                         $sql_extra .= sprintf(" AND `item`.`contact-id` = %d AND `item`.`author-id` = %d ", intval($owner["id"]), intval($authorid));
2126                 }
2127
2128                 $items = q(
2129                         "SELECT `item`.*, `item`.`id` AS `item_id` FROM `item` USE INDEX (`uid_contactid_created`)
2130                                 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2131                                 WHERE `item`.`uid` = %d
2132                                 AND `item`.`created` > '%s'
2133                                 AND NOT `item`.`deleted`
2134                                 AND NOT `item`.`private`
2135                                 AND `item`.`visible`
2136                                 AND `item`.`wall`
2137                                 AND `thread`.`network` IN ('%s', '%s')
2138                                 $sql_extra
2139                                 ORDER BY `item`.`created` DESC LIMIT %d",
2140                         intval($owner["uid"]),
2141                         dbesc($check_date),
2142                         dbesc(NETWORK_OSTATUS),
2143                         dbesc(NETWORK_DFRN),
2144                         intval($max_items)
2145                 );
2146
2147                 $doc = new DOMDocument('1.0', 'utf-8');
2148                 $doc->formatOutput = true;
2149
2150                 $root = self::addHeader($doc, $owner, $filter);
2151
2152                 foreach ($items as $item) {
2153                         if (Config::get('system', 'ostatus_debug')) {
2154                                 $item['body'] .= '🍼';
2155                         }
2156                         $entry = self::entry($doc, $item, $owner);
2157                         $root->appendChild($entry);
2158
2159                         if ($last_update < $item['created']) {
2160                                 $last_update = $item['created'];
2161                         }
2162                 }
2163
2164                 $feeddata = trim($doc->saveXML());
2165
2166                 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
2167                 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
2168
2169                 logger('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, LOGGER_DEBUG);
2170
2171                 return $feeddata;
2172         }
2173
2174         /**
2175          * @brief Creates the XML for a salmon message
2176          *
2177          * @param array $item  Data of the item that is to be posted
2178          * @param array $owner Contact data of the poster
2179          *
2180          * @return string XML for the salmon
2181          */
2182         public static function salmon($item, $owner)
2183         {
2184                 $doc = new DOMDocument('1.0', 'utf-8');
2185                 $doc->formatOutput = true;
2186
2187                 if (Config::get('system', 'ostatus_debug')) {
2188                         $item['body'] .= '🐟';
2189                 }
2190
2191                 $entry = self::entry($doc, $item, $owner, true);
2192
2193                 $doc->appendChild($entry);
2194
2195                 return trim($doc->saveXML());
2196         }
2197 }