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