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