]> git.mxchange.org Git - friendica.git/blob - src/Protocol/OStatus.php
Several more warnings ... (#5340)
[friendica.git] / src / Protocol / OStatus.php
1 <?php
2 /**
3  * @file src/Protocol/OStatus.php
4  */
5 namespace Friendica\Protocol;
6
7 use dba;
8 use DOMDocument;
9 use DOMXPath;
10 use Friendica\Content\Text\BBCode;
11 use Friendica\Content\Text\HTML;
12 use Friendica\Core\Cache;
13 use Friendica\Core\Config;
14 use Friendica\Core\L10n;
15 use Friendica\Core\Lock;
16 use Friendica\Core\System;
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($xpath, $context, $importer, &$contact, $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                 }
223
224                 return $author;
225         }
226
227         /**
228          * @brief Fetches author data from a given XML string
229          *
230          * @param string $xml      The XML
231          * @param array  $importer user record of the importing user
232          *
233          * @return array Array of author related entries for the item
234          */
235         public static function salmonAuthor($xml, $importer)
236         {
237                 if ($xml == "") {
238                         return;
239                 }
240
241                 $doc = new DOMDocument();
242                 @$doc->loadXML($xml);
243
244                 $xpath = new DOMXPath($doc);
245                 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
246                 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
247                 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
248                 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
249                 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
250                 $xpath->registerNamespace('poco', NAMESPACE_POCO);
251                 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
252                 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
253
254                 $contact = ["id" => 0];
255
256                 // Fetch the first author
257                 $authordata = $xpath->query('//author')->item(0);
258                 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, true);
259                 return $author;
260         }
261
262         /**
263          * @brief Read attributes from element
264          *
265          * @param object $element Element object
266          *
267          * @return array attributes
268          */
269         private static function readAttributes($element)
270         {
271                 $attribute = [];
272
273                 foreach ($element->attributes as $attributes) {
274                         $attribute[$attributes->name] = $attributes->textContent;
275                 }
276
277                 return $attribute;
278         }
279
280         /**
281          * @brief Imports an XML string containing OStatus elements
282          *
283          * @param string $xml      The XML
284          * @param array  $importer user record of the importing user
285          * @param array  $contact  contact
286          * @param string $hub      Called by reference, returns the fetched hub data
287          * @return void
288          */
289         public static function import($xml, $importer, &$contact, &$hub)
290         {
291                 self::process($xml, $importer, $contact, $hub);
292         }
293
294         /**
295          * @brief Internal feed processing
296          *
297          * @param string  $xml        The XML
298          * @param array   $importer   user record of the importing user
299          * @param array   $contact    contact
300          * @param string  $hub        Called by reference, returns the fetched hub data
301          * @param boolean $stored     Is the post fresh imported or from the database?
302          * @param boolean $initialize Is it the leading post so that data has to be initialized?
303          *
304          * @return boolean Could the XML be processed?
305          */
306         private static function process($xml, $importer, &$contact, &$hub, $stored = false, $initialize = true)
307         {
308                 if ($initialize) {
309                         self::$itemlist = [];
310                         self::$conv_list = [];
311                 }
312
313                 logger("Import OStatus message", LOGGER_DEBUG);
314
315                 if ($xml == "") {
316                         return false;
317                 }
318                 $doc = new DOMDocument();
319                 @$doc->loadXML($xml);
320
321                 $xpath = new DOMXPath($doc);
322                 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
323                 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
324                 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
325                 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
326                 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
327                 $xpath->registerNamespace('poco', NAMESPACE_POCO);
328                 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
329                 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
330
331                 $hub = "";
332                 $hub_items = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0);
333                 if (is_object($hub_items)) {
334                         $hub_attributes = $hub_items->attributes;
335                         if (is_object($hub_attributes)) {
336                                 foreach ($hub_attributes as $hub_attribute) {
337                                         if ($hub_attribute->name == "href") {
338                                                 $hub = $hub_attribute->textContent;
339                                                 logger("Found hub ".$hub, LOGGER_DEBUG);
340                                         }
341                                 }
342                         }
343                 }
344
345                 $header = [];
346                 $header["uid"] = $importer["uid"];
347                 $header["network"] = NETWORK_OSTATUS;
348                 $header["type"] = "remote-comment";
349                 $header["wall"] = 0;
350                 $header["origin"] = 0;
351                 $header["gravity"] = GRAVITY_COMMENT;
352
353                 $first_child = $doc->firstChild->tagName;
354
355                 if ($first_child == "feed") {
356                         $entries = $xpath->query('/atom:feed/atom:entry');
357                 } else {
358                         $entries = $xpath->query('/atom:entry');
359                 }
360
361                 if ($entries->length == 1) {
362                         // We reformat the XML to make it better readable
363                         $doc2 = new DOMDocument();
364                         $doc2->loadXML($xml);
365                         $doc2->preserveWhiteSpace = false;
366                         $doc2->formatOutput = true;
367                         $xml2 = $doc2->saveXML();
368
369                         $header["protocol"] = PROTOCOL_OSTATUS_SALMON;
370                         $header["source"] = $xml2;
371                 } elseif (!$initialize) {
372                         return false;
373                 }
374
375                 // Fetch the first author
376                 $authordata = $xpath->query('//author')->item(0);
377                 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, $stored);
378
379                 $entry = $xpath->query('/atom:entry');
380
381                 // Reverse the order of the entries
382                 $entrylist = [];
383
384                 foreach ($entries as $entry) {
385                         $entrylist[] = $entry;
386                 }
387
388                 foreach (array_reverse($entrylist) as $entry) {
389                         // fetch the author
390                         $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
391
392                         if ($authorelement->length == 0) {
393                                 $authorelement = $xpath->query('atom:author', $entry);
394                         }
395
396                         if ($authorelement->length > 0) {
397                                 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, $stored);
398                         }
399
400                         $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()', $entry);
401                         if ($value != "") {
402                                 $nickname = $value;
403                         } else {
404                                 $nickname = $author["author-name"];
405                         }
406
407                         $item = array_merge($header, $author);
408
409                         $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
410
411                         $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $entry);
412
413                         // Delete a message
414                         if (in_array($item["verb"], ['qvitter-delete-notice', ACTIVITY_DELETE, 'delete'])) {
415                                 self::deleteNotice($item);
416                                 continue;
417                         }
418
419                         if (in_array($item["verb"], [NAMESPACE_OSTATUS."/unfavorite", ACTIVITY_UNFAVORITE])) {
420                                 // Ignore "Unfavorite" message
421                                 logger("Ignore unfavorite message ".print_r($item, true), LOGGER_DEBUG);
422                                 continue;
423                         }
424
425                         // Deletions come with the same uri, so we check for duplicates after processing deletions
426                         if (Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]])) {
427                                 logger('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
428                                 continue;
429                         } else {
430                                 logger('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
431                         }
432
433                         if ($item["verb"] == ACTIVITY_JOIN) {
434                                 // ignore "Join" messages
435                                 logger("Ignore join message ".print_r($item, true), LOGGER_DEBUG);
436                                 continue;
437                         }
438
439                         if ($item["verb"] == "http://mastodon.social/schema/1.0/block") {
440                                 // ignore mastodon "block" messages
441                                 logger("Ignore block message ".print_r($item, true), LOGGER_DEBUG);
442                                 continue;
443                         }
444
445                         if ($item["verb"] == ACTIVITY_FOLLOW) {
446                                 Contact::addRelationship($importer, $contact, $item, $nickname);
447                                 continue;
448                         }
449
450                         if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
451                                 $dummy = null;
452                                 Contact::removeFollower($importer, $contact, $item, $dummy);
453                                 continue;
454                         }
455
456                         if ($item["verb"] == ACTIVITY_FAVORITE) {
457                                 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
458                                 logger("Favorite ".$orig_uri." ".print_r($item, true));
459
460                                 $item["type"] = "activity";
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          * @param object $item item
546          * @return void
547          */
548         private static function deleteNotice($item)
549         {
550                 $condition = ['uid' => $item['uid'], 'author-id' => $item['author-id'], 'uri' => $item['uri']];
551                 if (!Item::exists($condition)) {
552                         logger('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it.");
553                         return;
554                 }
555
556                 Item::delete($condition);
557
558                 logger('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
559         }
560
561         /**
562          * @brief Processes the XML for a post
563          *
564          * @param object $xpath    The xpath object
565          * @param object $entry    The xml entry that is processed
566          * @param array  $item     The item array
567          * @param array  $importer user record of the importing user
568          * @return void
569          */
570         private static function processPost($xpath, $entry, &$item, $importer)
571         {
572                 $item["body"] = HTML::toBBCode(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
573                 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $entry);
574                 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) || ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
575                         $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
576                         $item["body"] = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
577                 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
578                         $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
579                 }
580
581                 $item["created"] = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
582                 $item["edited"] = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
583                 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
584
585                 $conv = $xpath->query('ostatus:conversation', $entry);
586                 if (is_object($conv->item(0))) {
587                         foreach ($conv->item(0)->attributes as $attributes) {
588                                 if ($attributes->name == "ref") {
589                                         $item['conversation-uri'] = $attributes->textContent;
590                                 }
591                                 if ($attributes->name == "href") {
592                                         $item['conversation-href'] = $attributes->textContent;
593                                 }
594                         }
595                 }
596
597                 $related = "";
598
599                 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
600                 if (is_object($inreplyto->item(0))) {
601                         foreach ($inreplyto->item(0)->attributes as $attributes) {
602                                 if ($attributes->name == "ref") {
603                                         $item["parent-uri"] = $attributes->textContent;
604                                 }
605                                 if ($attributes->name == "href") {
606                                         $related = $attributes->textContent;
607                                 }
608                         }
609                 }
610
611                 $georsspoint = $xpath->query('georss:point', $entry);
612                 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
613                         $item["coord"] = $georsspoint->item(0)->nodeValue;
614                 }
615
616                 $categories = $xpath->query('atom:category', $entry);
617                 if ($categories) {
618                         foreach ($categories as $category) {
619                                 foreach ($category->attributes as $attributes) {
620                                         if ($attributes->name == "term") {
621                                                 $term = $attributes->textContent;
622                                                 if (!empty($item["tag"])) {
623                                                         $item["tag"] .= ',';
624                                                 } else {
625                                                         $item["tag"] = '';
626                                                 }
627
628                                                 $item["tag"] .= "#[url=".System::baseUrl()."/search?tag=".$term."]".$term."[/url]";
629                                         }
630                                 }
631                         }
632                 }
633
634                 $self = '';
635                 $add_body = '';
636
637                 $links = $xpath->query('atom:link', $entry);
638                 if ($links) {
639                         $link_data = self::processLinks($links, $item);
640                         $self = $link_data['self'];
641                         $add_body = $link_data['add_body'];
642                 }
643
644                 $repeat_of = "";
645
646                 $notice_info = $xpath->query('statusnet:notice_info', $entry);
647                 if ($notice_info && ($notice_info->length > 0)) {
648                         foreach ($notice_info->item(0)->attributes as $attributes) {
649                                 if ($attributes->name == "source") {
650                                         $item["app"] = strip_tags($attributes->textContent);
651                                 }
652                                 if ($attributes->name == "repeat_of") {
653                                         $repeat_of = $attributes->textContent;
654                                 }
655                         }
656                 }
657                 // Is it a repeated post?
658                 if (($repeat_of != "") || ($item["verb"] == ACTIVITY_SHARE)) {
659                         $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
660                         if (!empty($link_data['add_body'])) {
661                                 $add_body .= $link_data['add_body'];
662                         }
663                 }
664
665                 $item["body"] .= $add_body;
666
667                 // Only add additional data when there is no picture in the post
668                 if (!strstr($item["body"], '[/img]')) {
669                         $item["body"] = add_page_info_to_body($item["body"]);
670                 }
671
672                 // Mastodon Content Warning
673                 if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
674                         $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
675                         if (!empty($clear_text)) {
676                                 $item['content-warning'] = HTML::toBBCode($clear_text);
677                         }
678                 }
679
680                 if (($self != '') && empty($item['protocol'])) {
681                         self::fetchSelf($self, $item);
682                 }
683
684                 if (!empty($item["conversation-href"])) {
685                         self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
686                 }
687
688                 if (isset($item["parent-uri"])) {
689                         if (!Item::exists(['uid' => $importer["uid"], 'uri' => $item['parent-uri']])) {
690                                 if ($related != '') {
691                                         self::fetchRelated($related, $item["parent-uri"], $importer);
692                                 }
693                         } else {
694                                 logger('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
695                         }
696                 } else {
697                         $item["parent-uri"] = $item["uri"];
698                         $item["gravity"] = GRAVITY_PARENT;
699                         $item["type"] = "remote";
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, &$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($xpath, $entry, &$item, $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, &$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($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($doc, $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"], $a->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($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($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          *
1403          * @return object author element
1404          */
1405         private static function addAuthor($doc, $owner, $show_profile = true)
1406         {
1407                 $profile = dba::selectFirst('profile', ['homepage', 'publish'], ['uid' => $owner['uid'], 'is-default' => true]);
1408                 $author = $doc->createElement("author");
1409                 XML::addElement($doc, $author, "id", $owner["url"]);
1410                 if ($owner['account-type'] == ACCOUNT_TYPE_COMMUNITY) {
1411                         XML::addElement($doc, $author, "activity:object-type", ACTIVITY_OBJ_GROUP);
1412                 } else {
1413                         XML::addElement($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1414                 }
1415                 XML::addElement($doc, $author, "uri", $owner["url"]);
1416                 XML::addElement($doc, $author, "name", $owner["nick"]);
1417                 XML::addElement($doc, $author, "email", $owner["addr"]);
1418                 if ($show_profile) {
1419                         XML::addElement($doc, $author, "summary", BBCode::convert($owner["about"], false, 7));
1420                 }
1421
1422                 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $owner["url"]];
1423                 XML::addElement($doc, $author, "link", "", $attributes);
1424
1425                 $attributes = [
1426                                 "rel" => "avatar",
1427                                 "type" => "image/jpeg", // To-Do?
1428                                 "media:width" => 175,
1429                                 "media:height" => 175,
1430                                 "href" => $owner["photo"]];
1431                 XML::addElement($doc, $author, "link", "", $attributes);
1432
1433                 if (isset($owner["thumb"])) {
1434                         $attributes = [
1435                                         "rel" => "avatar",
1436                                         "type" => "image/jpeg", // To-Do?
1437                                         "media:width" => 80,
1438                                         "media:height" => 80,
1439                                         "href" => $owner["thumb"]];
1440                         XML::addElement($doc, $author, "link", "", $attributes);
1441                 }
1442
1443                 XML::addElement($doc, $author, "poco:preferredUsername", $owner["nick"]);
1444                 XML::addElement($doc, $author, "poco:displayName", $owner["name"]);
1445                 if ($show_profile) {
1446                         XML::addElement($doc, $author, "poco:note", BBCode::convert($owner["about"], false, 7));
1447
1448                         if (trim($owner["location"]) != "") {
1449                                 $element = $doc->createElement("poco:address");
1450                                 XML::addElement($doc, $element, "poco:formatted", $owner["location"]);
1451                                 $author->appendChild($element);
1452                         }
1453                 }
1454
1455                 if (DBM::is_result($profile) && !$show_profile) {
1456                         if (trim($profile["homepage"]) != "") {
1457                                 $urls = $doc->createElement("poco:urls");
1458                                 XML::addElement($doc, $urls, "poco:type", "homepage");
1459                                 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
1460                                 XML::addElement($doc, $urls, "poco:primary", "true");
1461                                 $author->appendChild($urls);
1462                         }
1463
1464                         XML::addElement($doc, $author, "followers", "", ["url" => System::baseUrl()."/viewcontacts/".$owner["nick"]]);
1465                         XML::addElement($doc, $author, "statusnet:profile_info", "", ["local_id" => $owner["uid"]]);
1466
1467                         if ($profile["publish"]) {
1468                                 XML::addElement($doc, $author, "mastodon:scope", "public");
1469                         }
1470                 }
1471
1472                 return $author;
1473         }
1474
1475         /**
1476          * @TODO Picture attachments should look like this:
1477          *      <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1478          *      class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1479          */
1480
1481         /**
1482          * @brief Returns the given activity if present - otherwise returns the "post" activity
1483          *
1484          * @param array $item Data of the item that is to be posted
1485          *
1486          * @return string activity
1487          */
1488         private static function constructVerb($item)
1489         {
1490                 if ($item['verb']) {
1491                         return $item['verb'];
1492                 }
1493
1494                 return ACTIVITY_POST;
1495         }
1496
1497         /**
1498          * @brief Returns the given object type if present - otherwise returns the "note" object type
1499          *
1500          * @param array $item Data of the item that is to be posted
1501          *
1502          * @return string Object type
1503          */
1504         private static function constructObjecttype($item)
1505         {
1506                 if (in_array($item['object-type'], [ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT]))
1507                         return $item['object-type'];
1508                 return ACTIVITY_OBJ_NOTE;
1509         }
1510
1511         /**
1512          * @brief Adds an entry element to the XML document
1513          *
1514          * @param object $doc      XML document
1515          * @param array  $item     Data of the item that is to be posted
1516          * @param array  $owner    Contact data of the poster
1517          * @param bool   $toplevel optional default false
1518          *
1519          * @return object Entry element
1520          */
1521         private static function entry($doc, $item, $owner, $toplevel = false)
1522         {
1523                 $xml = null;
1524
1525                 $repeated_guid = self::getResharedGuid($item);
1526                 if ($repeated_guid != "") {
1527                         $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel);
1528                 }
1529
1530                 if ($xml) {
1531                         return $xml;
1532                 }
1533
1534                 if ($item["verb"] == ACTIVITY_LIKE) {
1535                         return self::likeEntry($doc, $item, $owner, $toplevel);
1536                 } elseif (in_array($item["verb"], [ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"])) {
1537                         return self::followEntry($doc, $item, $owner, $toplevel);
1538                 } else {
1539                         return self::noteEntry($doc, $item, $owner, $toplevel);
1540                 }
1541         }
1542
1543         /**
1544          * @brief Adds a source entry to the XML document
1545          *
1546          * @param object $doc     XML document
1547          * @param array  $contact Array of the contact that is added
1548          *
1549          * @return object Source element
1550          */
1551         private static function sourceEntry($doc, $contact)
1552         {
1553                 $source = $doc->createElement("source");
1554                 XML::addElement($doc, $source, "id", $contact["poll"]);
1555                 XML::addElement($doc, $source, "title", $contact["name"]);
1556                 XML::addElement($doc, $source, "link", "", ["rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]]);
1557                 XML::addElement($doc, $source, "link", "", ["rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]]);
1558                 XML::addElement($doc, $source, "icon", $contact["photo"]);
1559                 XML::addElement($doc, $source, "updated", DateTimeFormat::utc($contact["success_update"]."+00:00", DateTimeFormat::ATOM));
1560
1561                 return $source;
1562         }
1563
1564         /**
1565          * @brief Fetches contact data from the contact or the gcontact table
1566          *
1567          * @param string $url   URL of the contact
1568          * @param array  $owner Contact data of the poster
1569          *
1570          * @return array Contact array
1571          */
1572         private static function contactEntry($url, $owner)
1573         {
1574                 $r = q(
1575                         "SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1576                         dbesc(normalise_link($url)),
1577                         intval($owner["uid"])
1578                 );
1579                 if (DBM::is_result($r)) {
1580                         $contact = $r[0];
1581                         $contact["uid"] = -1;
1582                 }
1583
1584                 if (!DBM::is_result($r)) {
1585                         $r = q(
1586                                 "SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1587                                 dbesc(normalise_link($url))
1588                         );
1589                         if (DBM::is_result($r)) {
1590                                 $contact = $r[0];
1591                                 $contact["uid"] = -1;
1592                                 $contact["success_update"] = $contact["updated"];
1593                         }
1594                 }
1595
1596                 if (!DBM::is_result($r)) {
1597                         $contact = owner;
1598                 }
1599
1600                 if (!isset($contact["poll"])) {
1601                         $data = Probe::uri($url);
1602                         $contact["poll"] = $data["poll"];
1603
1604                         if (!$contact["alias"]) {
1605                                 $contact["alias"] = $data["alias"];
1606                         }
1607                 }
1608
1609                 if (!isset($contact["alias"])) {
1610                         $contact["alias"] = $contact["url"];
1611                 }
1612
1613                 return $contact;
1614         }
1615
1616         /**
1617          * @brief Adds an entry element with reshared content
1618          *
1619          * @param object $doc           XML document
1620          * @param array  $item          Data of the item that is to be posted
1621          * @param array  $owner         Contact data of the poster
1622          * @param string $repeated_guid guid
1623          * @param bool   $toplevel      Is it for en entry element (false) or a feed entry (true)?
1624          *
1625          * @return object Entry element
1626          */
1627         private static function reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel)
1628         {
1629                 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1630                         logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1631                 }
1632
1633                 $title = self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1634
1635                 $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => false,
1636                         'network' => [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS]];
1637                 $repeated_item = Item::selectFirst([], $condition);
1638                 if (!DBM::is_result($repeated_item)) {
1639                         return false;
1640                 }
1641
1642                 $contact = self::contactEntry($repeated_item['author-link'], $owner);
1643                 $contact['account-type'] = $contact['contact-type'];
1644
1645                 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1646
1647                 self::entryContent($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1648
1649                 $as_object = $doc->createElement("activity:object");
1650
1651                 XML::addElement($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1652
1653                 self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false);
1654
1655                 $author = self::addAuthor($doc, $contact, false);
1656                 $as_object->appendChild($author);
1657
1658                 $as_object2 = $doc->createElement("activity:object");
1659
1660                 XML::addElement($doc, $as_object2, "activity:object-type", self::constructObjecttype($repeated_item));
1661
1662                 $title = sprintf("New comment by %s", $contact["nick"]);
1663
1664                 self::entryContent($doc, $as_object2, $repeated_item, $owner, $title);
1665
1666                 $as_object->appendChild($as_object2);
1667
1668                 self::entryFooter($doc, $as_object, $item, $owner, false);
1669
1670                 $source = self::sourceEntry($doc, $contact);
1671
1672                 $as_object->appendChild($source);
1673
1674                 $entry->appendChild($as_object);
1675
1676                 self::entryFooter($doc, $entry, $item, $owner);
1677
1678                 return $entry;
1679         }
1680
1681         /**
1682          * @brief Adds an entry element with a "like"
1683          *
1684          * @param object $doc      XML document
1685          * @param array  $item     Data of the item that is to be posted
1686          * @param array  $owner    Contact data of the poster
1687          * @param bool   $toplevel Is it for en entry element (false) or a feed entry (true)?
1688          *
1689          * @return object Entry element with "like"
1690          */
1691         private static function likeEntry($doc, $item, $owner, $toplevel)
1692         {
1693                 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1694                         logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1695                 }
1696
1697                 $title = self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1698
1699                 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1700                 self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false);
1701
1702                 $as_object = $doc->createElement("activity:object");
1703
1704                 $parent = Item::selectFirst([], ['uri' => $item["thr-parent"], 'uid' => $item["uid"]]);
1705
1706                 XML::addElement($doc, $as_object, "activity:object-type", self::constructObjecttype($parent));
1707
1708                 self::entryContent($doc, $as_object, $parent, $owner, "New entry");
1709
1710                 $entry->appendChild($as_object);
1711
1712                 self::entryFooter($doc, $entry, $item, $owner);
1713
1714                 return $entry;
1715         }
1716
1717         /**
1718          * @brief Adds the person object element to the XML document
1719          *
1720          * @param object $doc     XML document
1721          * @param array  $owner   Contact data of the poster
1722          * @param array  $contact Contact data of the target
1723          *
1724          * @return object author element
1725          */
1726         private static function addPersonObject($doc, $owner, $contact)
1727         {
1728                 $object = $doc->createElement("activity:object");
1729                 XML::addElement($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1730
1731                 if ($contact['network'] == NETWORK_PHANTOM) {
1732                         XML::addElement($doc, $object, "id", $contact['url']);
1733                         return $object;
1734                 }
1735
1736                 XML::addElement($doc, $object, "id", $contact["alias"]);
1737                 XML::addElement($doc, $object, "title", $contact["nick"]);
1738
1739                 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $contact["url"]];
1740                 XML::addElement($doc, $object, "link", "", $attributes);
1741
1742                 $attributes = [
1743                                 "rel" => "avatar",
1744                                 "type" => "image/jpeg", // To-Do?
1745                                 "media:width" => 175,
1746                                 "media:height" => 175,
1747                                 "href" => $contact["photo"]];
1748                 XML::addElement($doc, $object, "link", "", $attributes);
1749
1750                 XML::addElement($doc, $object, "poco:preferredUsername", $contact["nick"]);
1751                 XML::addElement($doc, $object, "poco:displayName", $contact["name"]);
1752
1753                 if (trim($contact["location"]) != "") {
1754                         $element = $doc->createElement("poco:address");
1755                         XML::addElement($doc, $element, "poco:formatted", $contact["location"]);
1756                         $object->appendChild($element);
1757                 }
1758
1759                 return $object;
1760         }
1761
1762         /**
1763          * @brief Adds a follow/unfollow entry element
1764          *
1765          * @param object $doc      XML document
1766          * @param array  $item     Data of the follow/unfollow message
1767          * @param array  $owner    Contact data of the poster
1768          * @param bool   $toplevel Is it for en entry element (false) or a feed entry (true)?
1769          *
1770          * @return object Entry element
1771          */
1772         private static function followEntry($doc, $item, $owner, $toplevel)
1773         {
1774                 $item["id"] = $item["parent"] = 0;
1775                 $item["created"] = $item["edited"] = date("c");
1776                 $item["private"] = true;
1777
1778                 $contact = Probe::uri($item['follow']);
1779
1780                 if ($contact['alias'] == '') {
1781                         $contact['alias'] = $contact["url"];
1782                 } else {
1783                         $item['follow'] = $contact['alias'];
1784                 }
1785
1786                 $r = q(
1787                         "SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1788                         intval($owner['uid']),
1789                         dbesc(normalise_link($contact["url"]))
1790                 );
1791
1792                 if (DBM::is_result($r)) {
1793                         $connect_id = $r[0]['id'];
1794                 } else {
1795                         $connect_id = 0;
1796                 }
1797
1798                 if ($item['verb'] == ACTIVITY_FOLLOW) {
1799                         $message = L10n::t('%s is now following %s.');
1800                         $title = L10n::t('following');
1801                         $action = "subscription";
1802                 } else {
1803                         $message = L10n::t('%s stopped following %s.');
1804                         $title = L10n::t('stopped following');
1805                         $action = "unfollow";
1806                 }
1807
1808                 $item["uri"] = $item['parent-uri'] = $item['thr-parent']
1809                                 = 'tag:'.get_app()->get_hostname().
1810                                 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1811                                 ':person:'.$connect_id.':'.$item['created'];
1812
1813                 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1814
1815                 self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1816
1817                 self::entryContent($doc, $entry, $item, $owner, $title);
1818
1819                 $object = self::addPersonObject($doc, $owner, $contact);
1820                 $entry->appendChild($object);
1821
1822                 self::entryFooter($doc, $entry, $item, $owner);
1823
1824                 return $entry;
1825         }
1826
1827         /**
1828          * @brief Adds a regular entry element
1829          *
1830          * @param object $doc      XML document
1831          * @param array  $item     Data of the item that is to be posted
1832          * @param array  $owner    Contact data of the poster
1833          * @param bool   $toplevel Is it for en entry element (false) or a feed entry (true)?
1834          *
1835          * @return object Entry element
1836          */
1837         private static function noteEntry($doc, $item, $owner, $toplevel)
1838         {
1839                 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1840                         logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1841                 }
1842
1843                 $title = self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1844
1845                 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1846
1847                 self::entryContent($doc, $entry, $item, $owner, $title);
1848
1849                 self::entryFooter($doc, $entry, $item, $owner);
1850
1851                 return $entry;
1852         }
1853
1854         /**
1855          * @brief Adds a header element to the XML document
1856          *
1857          * @param object $doc      XML document
1858          * @param object $entry    The entry element where the elements are added
1859          * @param array  $owner    Contact data of the poster
1860          * @param bool   $toplevel Is it for en entry element (false) or a feed entry (true)?
1861          *
1862          * @return string The title for the element
1863          */
1864         private static function entryHeader($doc, &$entry, $owner, $item, $toplevel)
1865         {
1866                 /// @todo Check if this title stuff is really needed (I guess not)
1867                 if (!$toplevel) {
1868                         $entry = $doc->createElement("entry");
1869                         $title = sprintf("New note by %s", $owner["nick"]);
1870
1871                         if ($owner['account-type'] == ACCOUNT_TYPE_COMMUNITY) {
1872                                 $contact = self::contactEntry($item['author-link'], $owner);
1873                                 $author = self::addAuthor($doc, $contact, false);
1874                                 $entry->appendChild($author);
1875                         }
1876                 } else {
1877                         $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
1878
1879                         $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1880                         $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1881                         $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1882                         $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1883                         $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
1884                         $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1885                         $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1886                         $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1887
1888                         $author = self::addAuthor($doc, $owner);
1889                         $entry->appendChild($author);
1890
1891                         $title = sprintf("New comment by %s", $owner["nick"]);
1892                 }
1893                 return $title;
1894         }
1895
1896         /**
1897          * @brief Adds elements to the XML document
1898          *
1899          * @param object $doc      XML document
1900          * @param object $entry    Entry element where the content is added
1901          * @param array  $item     Data of the item that is to be posted
1902          * @param array  $owner    Contact data of the poster
1903          * @param string $title    Title for the post
1904          * @param string $verb     The activity verb
1905          * @param bool   $complete Add the "status_net" element?
1906          * @return void
1907          */
1908         private static function entryContent($doc, $entry, $item, $owner, $title, $verb = "", $complete = true)
1909         {
1910                 if ($verb == "") {
1911                         $verb = self::constructVerb($item);
1912                 }
1913
1914                 XML::addElement($doc, $entry, "id", $item["uri"]);
1915                 XML::addElement($doc, $entry, "title", $title);
1916
1917                 $body = self::formatPicturePost($item['body']);
1918
1919                 if ($item['title'] != "") {
1920                         $body = "[b]".$item['title']."[/b]\n\n".$body;
1921                 }
1922
1923                 $body = BBCode::convert($body, false, 7);
1924
1925                 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1926
1927                 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1928                                                                 "href" => System::baseUrl()."/display/".$item["guid"]]
1929                 );
1930
1931                 if ($complete && ($item["id"] > 0)) {
1932                         XML::addElement($doc, $entry, "status_net", "", ["notice_id" => $item["id"]]);
1933                 }
1934
1935                 XML::addElement($doc, $entry, "activity:verb", $verb);
1936
1937                 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
1938                 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
1939         }
1940
1941         /**
1942          * @brief Adds the elements at the foot of an entry to the XML document
1943          *
1944          * @param object $doc      XML document
1945          * @param object $entry    The entry element where the elements are added
1946          * @param array  $item     Data of the item that is to be posted
1947          * @param array  $owner    Contact data of the poster
1948          * @param bool   $complete default true
1949          * @return void
1950          */
1951         private static function entryFooter($doc, $entry, array $item, array $owner, $complete = true)
1952         {
1953                 $mentioned = [];
1954
1955                 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
1956                         $parent = Item::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item["parent"]]);
1957                         $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1958
1959                         $thrparent = Item::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $parent_item]);
1960
1961                         if (DBM::is_result($thrparent)) {
1962                                 $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
1963                                 $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
1964                                 $parent_plink = $thrparent["plink"];
1965                         } else {
1966                                 $mentioned[$parent["author-link"]] = $parent["author-link"];
1967                                 $mentioned[$parent["owner-link"]] = $parent["owner-link"];
1968                                 $parent_plink = System::baseUrl()."/display/".$parent["guid"];
1969                         }
1970
1971                         $attributes = [
1972                                         "ref" => $parent_item,
1973                                         "href" => $parent_plink];
1974                         XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
1975
1976                         $attributes = [
1977                                         "rel" => "related",
1978                                         "href" => $parent_plink];
1979                         XML::addElement($doc, $entry, "link", "", $attributes);
1980                 }
1981
1982                 if (intval($item["parent"]) > 0) {
1983                         $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
1984                         $conversation_uri = $conversation_href;
1985
1986                         if (isset($parent_item)) {
1987                                 $conversation = dba::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $parent_item]);
1988                                 if (DBM::is_result($conversation)) {
1989                                         if ($conversation['conversation-uri'] != '') {
1990                                                 $conversation_uri = $conversation['conversation-uri'];
1991                                         }
1992                                         if ($conversation['conversation-href'] != '') {
1993                                                 $conversation_href = $conversation['conversation-href'];
1994                                         }
1995                                 }
1996                         }
1997
1998                         XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:conversation", "href" => $conversation_href]);
1999
2000                         $attributes = [
2001                                         "href" => $conversation_href,
2002                                         "local_id" => $item["parent"],
2003                                         "ref" => $conversation_uri];
2004
2005                         XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
2006                 }
2007
2008                 $tags = item::getFeedTags($item);
2009
2010                 if (count($tags)) {
2011                         foreach ($tags as $t) {
2012                                 if ($t[0] == "@") {
2013                                         $mentioned[$t[1]] = $t[1];
2014                                 }
2015                         }
2016                 }
2017
2018                 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2019                 $newmentions = [];
2020                 foreach ($mentioned as $mention) {
2021                         $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2022                         $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2023                 }
2024                 $mentioned = $newmentions;
2025
2026                 foreach ($mentioned as $mention) {
2027                         $condition = ['uid' => $owner['uid'], 'nurl' => normalise_link($mention)];
2028                         $contact = dba::selectFirst('contact', ['forum', 'prv', 'self', 'contact-type'], $condition);
2029                         if ($contact["forum"] || $contact["prv"] || ($owner['contact-type'] == ACCOUNT_TYPE_COMMUNITY) ||
2030                                 ($contact['self'] && ($owner['account-type'] == ACCOUNT_TYPE_COMMUNITY))) {
2031                                 XML::addElement($doc, $entry, "link", "",
2032                                         [
2033                                                 "rel" => "mentioned",
2034                                                 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
2035                                                 "href" => $mention]
2036                                 );
2037                         } else {
2038                                 XML::addElement($doc, $entry, "link", "",
2039                                         [
2040                                                 "rel" => "mentioned",
2041                                                 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
2042                                                 "href" => $mention]
2043                                 );
2044                         }
2045                 }
2046
2047                 if ($owner['account-type'] == ACCOUNT_TYPE_COMMUNITY) {
2048                         XML::addElement($doc, $entry, "link", "", [
2049                                 "rel" => "mentioned",
2050                                 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/group",
2051                                 "href" => $owner['url']
2052                         ]);
2053                 }
2054
2055                 if (!$item["private"]) {
2056                         XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:attention",
2057                                                                         "href" => "http://activityschema.org/collection/public"]);
2058                         XML::addElement($doc, $entry, "link", "", ["rel" => "mentioned",
2059                                                                         "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2060                                                                         "href" => "http://activityschema.org/collection/public"]);
2061                         XML::addElement($doc, $entry, "mastodon:scope", "public");
2062                 }
2063
2064                 if (count($tags)) {
2065                         foreach ($tags as $t) {
2066                                 if ($t[0] != "@") {
2067                                         XML::addElement($doc, $entry, "category", "", ["term" => $t[2]]);
2068                                 }
2069                         }
2070                 }
2071
2072                 self::getAttachment($doc, $entry, $item);
2073
2074                 if ($complete && ($item["id"] > 0)) {
2075                         $app = $item["app"];
2076                         if ($app == "") {
2077                                 $app = "web";
2078                         }
2079
2080                         $attributes = ["local_id" => $item["id"], "source" => $app];
2081
2082                         if (isset($parent["id"])) {
2083                                 $attributes["repeat_of"] = $parent["id"];
2084                         }
2085
2086                         if ($item["coord"] != "") {
2087                                 XML::addElement($doc, $entry, "georss:point", $item["coord"]);
2088                         }
2089
2090                         XML::addElement($doc, $entry, "statusnet:notice_info", "", $attributes);
2091                 }
2092         }
2093
2094         /**
2095          * Creates the XML feed for a given nickname
2096          *
2097          * Supported filters:
2098          * - activity (default): all the public posts
2099          * - posts: all the public top-level posts
2100          * - comments: all the public replies
2101          *
2102          * Updates the provided last_update parameter if the result comes from the
2103          * cache or it is empty
2104          *
2105          * @brief Creates the XML feed for a given nickname
2106          *
2107          * @param string  $owner_nick  Nickname of the feed owner
2108          * @param string  $last_update Date of the last update
2109          * @param integer $max_items   Number of maximum items to fetch
2110          * @param string  $filter      Feed items filter (activity, posts or comments)
2111          * @param boolean $nocache     Wether to bypass caching
2112          *
2113          * @return string XML feed
2114          */
2115         public static function feed($owner_nick, &$last_update, $max_items = 300, $filter = 'activity', $nocache = false)
2116         {
2117                 $stamp = microtime(true);
2118
2119                 $owner = User::getOwnerDataByNick($owner_nick);
2120                 if (!$owner) {
2121                         return;
2122                 }
2123
2124                 $cachekey = "ostatus:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
2125
2126                 $previous_created = $last_update;
2127
2128                 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
2129                 if ((time() - strtotime($owner['last-item'])) < 15*60) {
2130                         $result = Cache::get($cachekey);
2131                         if (!$nocache && !is_null($result)) {
2132                                 logger('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', LOGGER_DEBUG);
2133                                 $last_update = $result['last_update'];
2134                                 return $result['feed'];
2135                         }
2136                 }
2137
2138                 if (!strlen($last_update)) {
2139                         $last_update = 'now -30 days';
2140                 }
2141
2142                 $check_date = DateTimeFormat::utc($last_update);
2143                 $authorid = Contact::getIdForURL($owner["url"], 0, true);
2144
2145                 $condition = ["`uid` = ? AND `created` > ? AND NOT `deleted`
2146                         AND NOT `private` AND `visible` AND `wall` AND `parent-network` IN (?, ?)",
2147                         $owner["uid"], $check_date, NETWORK_OSTATUS, NETWORK_DFRN];
2148
2149                 if ($filter === 'comments') {
2150                         $condition[0] .= " AND `object-type` = ? ";
2151                         $condition[] = ACTIVITY_OBJ_COMMENT;
2152                 }
2153
2154                 if ($owner['account-type'] != ACCOUNT_TYPE_COMMUNITY) {
2155                         $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
2156                         $condition[] = $owner["id"];
2157                         $condition[] = $authorid;
2158                 }
2159
2160                 $params = ['order' => ['created' => true], 'limit' => $max_items];
2161
2162                 if ($filter === 'posts') {
2163                         $ret = Item::selectThread([], $condition, $params);
2164                 } else {
2165                         $ret = Item::select([], $condition, $params);
2166                 }
2167
2168                 $items = Item::inArray($ret);
2169
2170                 $doc = new DOMDocument('1.0', 'utf-8');
2171                 $doc->formatOutput = true;
2172
2173                 $root = self::addHeader($doc, $owner, $filter);
2174
2175                 foreach ($items as $item) {
2176                         if (Config::get('system', 'ostatus_debug')) {
2177                                 $item['body'] .= '🍼';
2178                         }
2179                         $entry = self::entry($doc, $item, $owner);
2180                         $root->appendChild($entry);
2181
2182                         if ($last_update < $item['created']) {
2183                                 $last_update = $item['created'];
2184                         }
2185                 }
2186
2187                 $feeddata = trim($doc->saveXML());
2188
2189                 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
2190                 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
2191
2192                 logger('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, LOGGER_DEBUG);
2193
2194                 return $feeddata;
2195         }
2196
2197         /**
2198          * @brief Creates the XML for a salmon message
2199          *
2200          * @param array $item  Data of the item that is to be posted
2201          * @param array $owner Contact data of the poster
2202          *
2203          * @return string XML for the salmon
2204          */
2205         public static function salmon($item, $owner)
2206         {
2207                 $doc = new DOMDocument('1.0', 'utf-8');
2208                 $doc->formatOutput = true;
2209
2210                 if (Config::get('system', 'ostatus_debug')) {
2211                         $item['body'] .= '🐟';
2212                 }
2213
2214                 $entry = self::entry($doc, $item, $owner, true);
2215
2216                 $doc->appendChild($entry);
2217
2218                 return trim($doc->saveXML());
2219         }
2220 }