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