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