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