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