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