3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol;
27 use Friendica\Content\Text\BBCode;
28 use Friendica\Content\Text\HTML;
29 use Friendica\Core\Cache\Enum\Duration;
30 use Friendica\Core\Logger;
31 use Friendica\Core\Protocol;
32 use Friendica\Database\DBA;
34 use Friendica\Model\APContact;
35 use Friendica\Model\Contact;
36 use Friendica\Model\Conversation;
37 use Friendica\Model\Item;
38 use Friendica\Model\ItemURI;
39 use Friendica\Model\Post;
40 use Friendica\Model\Tag;
41 use Friendica\Model\User;
42 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
43 use Friendica\Network\Probe;
44 use Friendica\Util\DateTimeFormat;
45 use Friendica\Util\Images;
46 use Friendica\Util\Proxy;
47 use Friendica\Util\Strings;
48 use Friendica\Util\XML;
51 * This class contain functions for the OStatus protocol
55 private static $itemlist;
56 private static $conv_list = [];
61 * @param DOMXPath $xpath The xpath object
62 * @param object $context The xml context of the author details
63 * @param array $importer user record of the importing user
64 * @param array $contact Called by reference, will contain the fetched contact
65 * @param bool $onlyfetch Only fetch the header without updating the contact entries
67 * @return array Array of author related entries for the item
68 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
69 * @throws \ImagickException
71 private static function fetchAuthor(DOMXPath $xpath, $context, array $importer, array &$contact = null, bool $onlyfetch): array
74 $author['author-link'] = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
75 $author['author-name'] = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $context);
76 $addr = XML::getFirstNodeValue($xpath, 'atom:author/atom:email/text()', $context);
78 $aliaslink = $author['author-link'];
80 $alternate_item = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0);
81 if (is_object($alternate_item)) {
82 foreach ($alternate_item->attributes as $attributes) {
83 if (($attributes->name == 'href') && ($attributes->textContent != '')) {
84 $author['author-link'] = $attributes->textContent;
88 $author['author-id'] = Contact::getIdForURL($author['author-link']);
90 $author['contact-id'] = ($contact['id'] ?? 0) ?: $author['author-id'];
95 This here would be better, but we would get problems with contacts from the statusnet addon
96 This is kept here as a reminder for the future
98 $cid = Contact::getIdForURL($author['author-link'], $importer['uid']);
100 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
103 if ($aliaslink != '') {
104 $contact = DBA::selectFirst('contact', [], [
105 "`uid` = ? AND `alias` = ? AND `network` != ? AND `rel` IN (?, ?)",
107 $aliaslink, Protocol::STATUSNET,
108 Contact::SHARING, Contact::FRIEND,
112 if (!DBA::isResult($contact) && $author['author-link'] != '') {
113 if ($aliaslink == '') {
114 $aliaslink = $author['author-link'];
117 $contact = DBA::selectFirst('contact', [], [
118 "`uid` = ? AND `nurl` IN (?, ?) AND `network` != ? AND `rel` IN (?, ?)",
120 Strings::normaliseLink($author['author-link']),
121 Strings::normaliseLink($aliaslink),
128 if (!DBA::isResult($contact) && ($addr != '')) {
129 $contact = DBA::selectFirst('contact', [], [
130 "`uid` = ? AND `addr` = ? AND `network` != ? AND `rel` IN (?, ?)",
139 if (DBA::isResult($contact)) {
140 if ($contact['blocked']) {
142 } elseif (!empty(APContact::getByURL($contact['url'], false))) {
143 ActivityPub\Receiver::switchContact($contact['id'], $importer['uid'], $contact['url']);
145 $author['contact-id'] = $contact['id'];
149 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
150 foreach ($avatars as $avatar) {
153 foreach ($avatar->attributes as $attributes) {
154 if ($attributes->name == 'href') {
155 $href = $attributes->textContent;
157 if ($attributes->name == 'width') {
158 $width = $attributes->textContent;
162 $avatarlist[$width] = $href;
165 if (count($avatarlist) > 0) {
167 $author['author-avatar'] = Probe::fixAvatar(current($avatarlist), $author['author-link']);
170 $displayname = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
171 if ($displayname != '') {
172 $author['author-name'] = $displayname;
175 $author['owner-id'] = $author['author-id'];
177 // Only update the contacts if it is an OStatus contact
178 if (DBA::isResult($contact) && ($contact['id'] > 0) && !$onlyfetch && ($contact['network'] == Protocol::OSTATUS)) {
180 // Update contact data
182 unset($current['name-date']);
184 // This query doesn't seem to work
185 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
187 // $contact["notify"] = $value;
189 // This query doesn't seem to work as well - I hate these queries
190 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
192 // $contact["poll"] = $value;
194 $contact['url'] = $author['author-link'];
195 $contact['nurl'] = Strings::normaliseLink($contact['url']);
197 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
199 $contact['alias'] = $value;
202 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
204 $contact['name'] = $value;
207 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()', $context);
209 $contact['nick'] = $value;
212 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()', $context);
214 $contact['about'] = HTML::toBBCode($value);
217 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()', $context);
219 $contact['location'] = $value;
222 $contact['name-date'] = DateTimeFormat::utcNow();
224 Contact::update($contact, ['id' => $contact['id']], $current);
226 if (!empty($author['author-avatar']) && ($author['author-avatar'] != $current['avatar'])) {
227 Logger::info('Update profile picture for contact ' . $contact['id']);
228 Contact::updateAvatar($contact['id'], $author['author-avatar']);
231 // Ensure that we are having this contact (with uid=0)
232 $cid = Contact::getIdForURL($aliaslink);
235 $fields = ['url', 'nurl', 'name', 'nick', 'alias', 'about', 'location'];
236 $old_contact = DBA::selectFirst('contact', $fields, ['id' => $cid]);
238 // Update it with the current values
240 'url' => $author['author-link'],
241 'name' => $contact['name'],
242 'nurl' => Strings::normaliseLink($author['author-link']),
243 'nick' => $contact['nick'],
244 'alias' => $contact['alias'],
245 'about' => $contact['about'],
246 'location' => $contact['location'],
247 'success_update' => DateTimeFormat::utcNow(),
248 'last-update' => DateTimeFormat::utcNow(),
251 Contact::update($fields, ['id' => $cid], $old_contact);
254 if (!empty($author['author-avatar'])) {
255 Contact::updateAvatar($cid, $author['author-avatar']);
258 } elseif (empty($contact['network']) || ($contact['network'] != Protocol::DFRN)) {
266 * Fetches author data from a given XML string
268 * @param string $xml The XML
269 * @param array $importer user record of the importing user
271 * @return array Array of author related entries for the item
272 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
273 * @throws \ImagickException
275 public static function salmonAuthor(string $xml, array $importer): array
281 $doc = new DOMDocument();
282 @$doc->loadXML($xml);
284 $xpath = new DOMXPath($doc);
285 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
286 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
287 $xpath->registerNamespace('georss', ActivityNamespace::GEORSS);
288 $xpath->registerNamespace('activity', ActivityNamespace::ACTIVITY);
289 $xpath->registerNamespace('media', ActivityNamespace::MEDIA);
290 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
291 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
292 $xpath->registerNamespace('statusnet', ActivityNamespace::STATUSNET);
294 $contact = ['id' => 0];
296 // Fetch the first author
297 $authordata = $xpath->query('//author')->item(0);
298 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, true);
303 * Read attributes from element
305 * @param object $element Element object
306 * @return array attributes
308 private static function readAttributes($element): array
312 foreach ($element->attributes as $attributes) {
313 $attribute[$attributes->name] = $attributes->textContent;
320 * Imports an XML string containing OStatus elements
322 * @param string $xml The XML
323 * @param array $importer user record of the importing user
324 * @param array $contact contact
325 * @param string $hub Called by reference, returns the fetched hub data
327 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
328 * @throws \ImagickException
330 public static function import($xml, array $importer, array &$contact, &$hub)
332 self::process($xml, $importer, $contact, $hub, false, true, Conversation::PUSH);
336 * Internal feed processing
338 * @param string $xml The XML
339 * @param array $importer user record of the importing user
340 * @param array $contact contact
341 * @param string $hub Called by reference, returns the fetched hub data
342 * @param boolean $stored Is the post fresh imported or from the database?
343 * @param boolean $initialize Is it the leading post so that data has to be initialized?
344 * @param integer $direction Direction, default UNKNOWN(0)
345 * @return boolean Could the XML be processed?
346 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
347 * @throws \ImagickException
349 private static function process(string $xml, array $importer, array &$contact = null, string &$hub, bool $stored = false, bool $initialize = true, int $direction = Conversation::UNKNOWN)
352 self::$itemlist = [];
353 self::$conv_list = [];
356 Logger::info('Import OStatus message for user ' . $importer['uid']);
362 $doc = new DOMDocument();
363 @$doc->loadXML($xml);
365 $xpath = new DOMXPath($doc);
366 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
367 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
368 $xpath->registerNamespace('georss', ActivityNamespace::GEORSS);
369 $xpath->registerNamespace('activity', ActivityNamespace::ACTIVITY);
370 $xpath->registerNamespace('media', ActivityNamespace::MEDIA);
371 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
372 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
373 $xpath->registerNamespace('statusnet', ActivityNamespace::STATUSNET);
376 $hub_items = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0);
377 if (is_object($hub_items)) {
378 $hub_attributes = $hub_items->attributes;
379 if (is_object($hub_attributes)) {
380 foreach ($hub_attributes as $hub_attribute) {
381 if ($hub_attribute->name == 'href') {
382 $hub = $hub_attribute->textContent;
383 Logger::info('Found hub ', ['hub' => $hub]);
390 $header['uid'] = $importer['uid'];
391 $header['network'] = Protocol::OSTATUS;
393 $header['origin'] = 0;
394 $header['gravity'] = GRAVITY_COMMENT;
396 if (!is_object($doc->firstChild) || empty($doc->firstChild->tagName)) {
400 $first_child = $doc->firstChild->tagName;
402 if ($first_child == 'feed') {
403 $entries = $xpath->query('/atom:feed/atom:entry');
405 $entries = $xpath->query('/atom:entry');
408 if ($entries->length == 1) {
409 // We reformat the XML to make it better readable
410 $doc2 = new DOMDocument();
411 $doc2->loadXML($xml);
412 $doc2->preserveWhiteSpace = false;
413 $doc2->formatOutput = true;
414 $xml2 = $doc2->saveXML();
416 $header['protocol'] = Conversation::PARCEL_SALMON;
417 $header['source'] = $xml2;
418 $header['direction'] = $direction;
419 } elseif (!$initialize) {
423 // Fetch the first author
424 $authordata = $xpath->query('//author')->item(0);
425 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, $stored);
427 // Reverse the order of the entries
430 foreach ($entries as $entry) {
431 $entrylist[] = $entry;
434 foreach (array_reverse($entrylist) as $entry) {
436 $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
438 if ($authorelement->length == 0) {
439 $authorelement = $xpath->query('atom:author', $entry);
442 if ($authorelement->length > 0) {
443 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, $stored);
446 $item = array_merge($header, $author);
448 $item['uri'] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
449 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri']]);
451 $item['verb'] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $entry);
454 if (in_array($item['verb'], ['qvitter-delete-notice', Activity::DELETE, 'delete'])) {
455 self::deleteNotice($item);
459 if (in_array($item['verb'], [Activity::O_UNFAVOURITE, Activity::UNFAVORITE])) {
460 // Ignore "Unfavorite" message
461 Logger::info('Ignore unfavorite message ', ['item' => $item]);
465 // Deletions come with the same uri, so we check for duplicates after processing deletions
466 if (Post::exists(['uid' => $importer['uid'], 'uri' => $item['uri']])) {
467 Logger::info('Post with URI ' . $item['uri'] . ' already existed for user ' . $importer['uid'] . '.');
470 Logger::info('Processing post with URI ' . $item['uri'] . ' for user ' . $importer['uid'] . '.');
473 if ($item['verb'] == Activity::JOIN) {
474 // ignore "Join" messages
475 Logger::info('Ignore join message ', ['item' => $item]);
479 if ($item['verb'] == 'http://mastodon.social/schema/1.0/block') {
480 // ignore mastodon "block" messages
481 Logger::info('Ignore block message ', ['item' => $item]);
485 if ($item['verb'] == Activity::FOLLOW) {
486 Contact::addRelationship($importer, $contact, $item);
490 if ($item['verb'] == Activity::O_UNFOLLOW) {
492 Contact::removeFollower($contact);
496 if ($item['verb'] == Activity::FAVORITE) {
497 $orig_uri = $xpath->query('activity:object/atom:id', $entry)->item(0)->nodeValue;
498 Logger::notice('Favorite', ['uri' => $orig_uri, 'item' => $item]);
500 $item['verb'] = Activity::LIKE;
501 $item['thr-parent'] = $orig_uri;
502 $item['gravity'] = GRAVITY_ACTIVITY;
503 $item['object-type'] = Activity\ObjectType::NOTE;
506 // http://activitystrea.ms/schema/1.0/rsvp-yes
507 if (!in_array($item['verb'], [Activity::POST, Activity::LIKE, Activity::SHARE])) {
508 Logger::info('Unhandled verb', ['verb' => $item['verb'], 'item' => $item]);
511 self::processPost($xpath, $entry, $item, $importer);
513 if ($initialize && (count(self::$itemlist) > 0)) {
514 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['thr-parent']) {
515 $uid = self::$itemlist[0]['uid'];
516 // We will import it everytime, when it is started by our contacts
517 $valid = Contact::isSharingByURL(self::$itemlist[0]['author-link'], $uid);
520 // If not, then it depends on this setting
521 $valid = !$uid || DI::pConfig()->get($uid, 'system', 'accept_only_sharer') != Item::COMPLETION_NONE;
524 Logger::info('Item with URI ' . self::$itemlist[0]['uri'] . ' will be imported due to the system settings.');
527 Logger::info('Item with URI ' . self::$itemlist[0]['uri'] . ' belongs to a contact (' . self::$itemlist[0]['contact-id'] . '). It will be imported.');
530 if ($valid && DI::pConfig()->get($uid, 'system', 'accept_only_sharer') != Item::COMPLETION_LIKE) {
531 // Never post a thread when the only interaction by our contact was a like
533 $verbs = [Activity::POST, Activity::SHARE];
534 foreach (self::$itemlist as $item) {
535 if (in_array($item['verb'], $verbs) && Contact::isSharingByURL($item['author-link'], $item['uid'])) {
540 Logger::info('Item with URI ' . self::$itemlist[0]['uri'] . ' will be imported since the thread contains posts or shares.');
548 $default_contact = 0;
549 for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
550 if (empty(self::$itemlist[$key]['contact-id'])) {
551 self::$itemlist[$key]['contact-id'] = $default_contact;
553 $default_contact = $item['contact-id'];
556 foreach (self::$itemlist as $item) {
557 $found = Post::exists(['uid' => $importer['uid'], 'uri' => $item['uri']]);
559 Logger::notice('Item with URI ' . $item['uri'] . ' for user ' . $importer['uid'] . ' already exists.');
560 } elseif ($item['contact-id'] < 0) {
561 Logger::notice('Item with URI ' . $item['uri'] . ' is from a blocked contact.');
563 $ret = Item::insert($item);
564 Logger::info('Item with URI ' . $item['uri'] . ' for user ' . $importer['uid'] . ' stored. Return value: ' . $ret);
568 self::$itemlist = [];
570 Logger::info('Processing done for post with URI ' . $item['uri'] . ' for user '.$importer['uid'] . '.');
576 * Removes notice item from database
578 * @param array $item item
582 private static function deleteNotice(array $item)
584 $condition = ['uid' => $item['uid'], 'author-id' => $item['author-id'], 'uri' => $item['uri']];
585 if (!Post::exists($condition)) {
586 Logger::notice('Item from ' . $item['author-link'] . ' with uri ' . $item['uri'] . ' for user ' . $item['uid'] . " wasn't found. We don't delete it.");
590 Item::markForDeletion($condition);
592 Logger::notice('Deleted item with URI ' . $item['uri'] . ' for user ' . $item['uid']);
596 * Processes the XML for a post
598 * @param DOMXPath $xpath The xpath object
599 * @param object $entry The xml entry that is processed
600 * @param array $item The item array
601 * @param array $importer user record of the importing user
603 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
604 * @throws \ImagickException
606 private static function processPost(DOMXPath $xpath, $entry, array &$item, array $importer)
608 $item['body'] = HTML::toBBCode(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
609 $item['object-type'] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $entry);
610 if (($item['object-type'] == Activity\ObjectType::BOOKMARK) || ($item['object-type'] == Activity\ObjectType::EVENT)) {
611 $item['title'] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
612 $item['body'] = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
613 } elseif ($item['object-type'] == Activity\ObjectType::QUESTION) {
614 $item['title'] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
617 $item['created'] = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
618 $item['edited'] = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
619 $item['conversation'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
621 $conv = $xpath->query('ostatus:conversation', $entry);
622 if (is_object($conv->item(0))) {
623 foreach ($conv->item(0)->attributes as $attributes) {
624 if ($attributes->name == 'ref') {
625 $item['conversation'] = $attributes->textContent;
627 if ($attributes->name == 'href') {
628 $item['conversation'] = $attributes->textContent;
635 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
636 if (is_object($inreplyto->item(0))) {
637 foreach ($inreplyto->item(0)->attributes as $attributes) {
638 if ($attributes->name == 'ref') {
639 $item['thr-parent'] = $attributes->textContent;
641 if ($attributes->name == 'href') {
642 $related = $attributes->textContent;
647 $georsspoint = $xpath->query('georss:point', $entry);
648 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
649 $item['coord'] = $georsspoint->item(0)->nodeValue;
652 $categories = $xpath->query('atom:category', $entry);
654 foreach ($categories as $category) {
655 foreach ($category->attributes as $attributes) {
656 if ($attributes->name == 'term') {
658 Tag::store($item['uri-id'], Tag::HASHTAG, $attributes->textContent);
667 $links = $xpath->query('atom:link', $entry);
669 $link_data = self::processLinks($links, $item);
670 $self = $link_data['self'];
671 $add_body = $link_data['add_body'];
676 $notice_info = $xpath->query('statusnet:notice_info', $entry);
677 if ($notice_info && ($notice_info->length > 0)) {
678 foreach ($notice_info->item(0)->attributes as $attributes) {
679 if ($attributes->name == 'source') {
680 $item['app'] = strip_tags($attributes->textContent);
682 if ($attributes->name == 'repeat_of') {
683 $repeat_of = $attributes->textContent;
687 // Is it a repeated post?
688 if (($repeat_of != '') || ($item['verb'] == Activity::SHARE)) {
689 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
690 if (!empty($link_data['add_body'])) {
691 $add_body .= $link_data['add_body'];
695 $item['body'] .= $add_body;
697 Tag::storeFromBody($item['uri-id'], $item['body']);
699 // Mastodon Content Warning
700 if (($item['verb'] == Activity::POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
701 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
702 if (!empty($clear_text)) {
703 $item['content-warning'] = HTML::toBBCode($clear_text);
707 if (isset($item['thr-parent'])) {
708 if (!Post::exists(['uid' => $importer['uid'], 'uri' => $item['thr-parent']])) {
709 if ($related != '') {
710 self::fetchRelated($related, $item['thr-parent'], $importer);
713 Logger::info('Reply with URI ' . $item['uri'] . ' already existed for user ' . $importer['uid'] . '.');
716 $item['thr-parent'] = $item['uri'];
717 $item['gravity'] = GRAVITY_PARENT;
720 self::$itemlist[] = $item;
724 * Fetch related posts and processes them
726 * @param string $related The link to the related item
727 * @param string $related_uri The related item in "uri" format
728 * @param array $importer user record of the importing user
730 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
731 * @throws \ImagickException
733 private static function fetchRelated(string $related, string $related_uri, array $importer)
736 $curlResult = DI::httpClient()->get($related, HttpClientAccept::ATOM_XML);
738 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
744 if ($curlResult->inHeader('Content-Type') &&
745 in_array('application/atom+xml', $curlResult->getHeader('Content-Type'))) {
746 Logger::info('Directly fetched XML for URI ' . $related_uri);
747 $xml = $curlResult->getBody();
751 $doc = new DOMDocument();
752 if (!@$doc->loadHTML($curlResult->getBody())) {
755 $xpath = new DOMXPath($doc);
759 $links = $xpath->query('//link');
761 foreach ($links as $link) {
762 $attribute = self::readAttributes($link);
763 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
764 $atom_file = $attribute['href'];
767 if ($atom_file != '') {
768 $curlResult = DI::httpClient()->get($atom_file, HttpClientAccept::ATOM_XML);
770 if ($curlResult->isSuccess()) {
771 Logger::info('Fetched XML for URI ' . $related_uri);
772 $xml = $curlResult->getBody();
778 // Workaround for older GNU Social servers
779 if (($xml == '') && strstr($related, '/notice/')) {
780 $curlResult = DI::httpClient()->get(str_replace('/notice/', '/api/statuses/show/', $related) . '.atom', HttpClientAccept::ATOM_XML);
782 if ($curlResult->isSuccess()) {
783 Logger::info('GNU Social workaround to fetch XML for URI ' . $related_uri);
784 $xml = $curlResult->getBody();
788 // Even more worse workaround for GNU Social ;-)
790 $related_guess = self::convertHref($related_uri);
791 $curlResult = DI::httpClient()->get(str_replace('/notice/', '/api/statuses/show/', $related_guess) . '.atom', HttpClientAccept::ATOM_XML);
793 if ($curlResult->isSuccess()) {
794 Logger::info('GNU Social workaround 2 to fetch XML for URI ' . $related_uri);
795 $xml = $curlResult->getBody();
801 self::process($xml, $importer, $contact, $hub, $stored, false, Conversation::PULL);
803 Logger::info('XML could not be fetched for URI: ' . $related_uri . ' - href: ' . $related);
809 * Processes the XML for a repeated post
811 * @param DOMXPath $xpath The xpath object
812 * @param object $entry The xml entry that is processed
813 * @param array $item The item array
814 * @param array $importer user record of the importing user
816 * @return array with data from links
817 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
818 * @throws \ImagickException
820 private static function processRepeatedItem(DOMXPath $xpath, $entry, array &$item, array $importer): array
822 $activityobject = $xpath->query('activity:object', $entry)->item(0);
824 if (!is_object($activityobject)) {
830 $orig_uri = XML::getFirstNodeValue($xpath, 'atom:id/text()', $activityobject);
832 $links = $xpath->query('atom:link', $activityobject);
834 $link_data = self::processLinks($links, $item);
837 $orig_body = XML::getFirstNodeValue($xpath, 'atom:content/text()', $activityobject);
838 $orig_created = XML::getFirstNodeValue($xpath, 'atom:published/text()', $activityobject);
839 $orig_edited = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $activityobject);
841 $orig_author = self::fetchAuthor($xpath, $activityobject, $importer, $dummy, false);
843 $item['author-name'] = $orig_author['author-name'];
844 $item['author-link'] = $orig_author['author-link'];
845 $item['author-id'] = $orig_author['author-id'];
847 $item['body'] = HTML::toBBCode($orig_body);
848 $item['created'] = $orig_created;
849 $item['edited'] = $orig_edited;
851 $item['uri'] = $orig_uri;
853 $item['verb'] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $activityobject);
855 $item['object-type'] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $activityobject);
857 // Mastodon Content Warning
858 if (($item['verb'] == Activity::POST) && $xpath->evaluate('boolean(atom:summary)', $activityobject)) {
859 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $activityobject);
860 if (!empty($clear_text)) {
861 $item['content-warning'] = HTML::toBBCode($clear_text);
865 $inreplyto = $xpath->query('thr:in-reply-to', $activityobject);
866 if (is_object($inreplyto->item(0))) {
867 foreach ($inreplyto->item(0)->attributes as $attributes) {
868 if ($attributes->name == 'ref') {
869 $item['thr-parent'] = $attributes->textContent;
878 * Processes links in the XML
880 * @param object $links The xml data that contain links
881 * @param array $item The item array
882 * @return array with data from the links
884 private static function processLinks($links, array &$item): array
886 $link_data = ['add_body' => '', 'self' => ''];
888 foreach ($links as $link) {
889 $attribute = self::readAttributes($link);
891 if (!empty($attribute['rel']) && !empty($attribute['href'])) {
892 switch ($attribute['rel']) {
894 $item['plink'] = $attribute['href'];
895 if (($item['object-type'] == Activity\ObjectType::QUESTION)
896 || ($item['object-type'] == Activity\ObjectType::EVENT)
898 Post\Media::insert(['uri-id' => $item['uri-id'], 'type' => Post\Media::UNKNOWN,
899 'url' => $attribute['href'], 'mimetype' => $attribute['type'] ?? null,
900 'size' => $attribute['length'] ?? null, 'description' => $attribute['title'] ?? null]);
904 case 'ostatus:conversation':
905 $link_data['conversation'] = $attribute['href'];
906 $item['conversation'] = $link_data['conversation'];
910 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
911 if ($filetype == 'image') {
912 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
914 Post\Media::insert(['uri-id' => $item['uri-id'], 'type' => Post\Media::DOCUMENT,
915 'url' => $attribute['href'], 'mimetype' => $attribute['type'],
916 'size' => $attribute['length'] ?? null, 'description' => $attribute['title'] ?? null]);
921 if ($item['object-type'] != Activity\ObjectType::BOOKMARK) {
922 if (!isset($item['thr-parent'])) {
923 $item['thr-parent'] = $attribute['href'];
925 $link_data['related'] = $attribute['href'];
927 Post\Media::insert(['uri-id' => $item['uri-id'], 'type' => Post\Media::UNKNOWN,
928 'url' => $attribute['href'], 'mimetype' => $attribute['type'] ?? null,
929 'size' => $attribute['length'] ?? null, 'description' => $attribute['title'] ?? null]);
934 if (empty($item['plink'])) {
935 $item['plink'] = $attribute['href'];
937 $link_data['self'] = $attribute['href'];
941 Logger::warning('Unsupported rel=' . $attribute['rel'] . ', href=' . $attribute['href'] . ', object-type=' . $item['object-type']);
949 * Create an url out of an uri
951 * @param string $href URI in the format "parameter1:parameter1:..."
952 * @return string URL in the format http(s)://....
954 private static function convertHref(string $href): string
956 $elements = explode(':', $href);
958 if ((count($elements) <= 2) || ($elements[0] != 'tag')) {
962 $server = explode(',', $elements[1]);
963 $conversation = explode('=', $elements[2]);
965 if ((count($elements) == 4) && ($elements[2] == 'post')) {
966 return 'http://' . $server[0] . '/notice/' . $elements[3];
969 if ((count($conversation) != 2) || ($conversation[1] == '')) {
973 if ($elements[3] == 'objectType=thread') {
974 return 'http://' . $server[0] . '/conversation/' . $conversation[1];
976 return 'http://' . $server[0] . '/notice/' . $conversation[1];
981 * Cleans the body of a post if it contains picture links
983 * @param string $body The body
984 * @param integer $uriId
985 * @return string The cleaned body
986 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
988 public static function formatPicturePost(string $body, int $uriid): string
990 $siteinfo = BBCode::getAttachedData($body);
992 if (($siteinfo['type'] == 'photo') && (!empty($siteinfo['preview']) || !empty($siteinfo['image']))) {
993 if (isset($siteinfo['preview'])) {
994 $preview = $siteinfo['preview'];
996 $preview = $siteinfo['image'];
999 // Is it a remote picture? Then make a smaller preview here
1000 $preview = Post\Link::getByLink($uriid, $preview, Proxy::SIZE_SMALL);
1002 // Is it a local picture? Then make it smaller here
1003 $preview = str_replace(['-0.jpg', '-0.png'], ['-2.jpg', '-2.png'], $preview);
1004 $preview = str_replace(['-1.jpg', '-1.png'], ['-2.jpg', '-2.png'], $preview);
1006 if (isset($siteinfo['url'])) {
1007 $url = $siteinfo['url'];
1009 $url = $siteinfo['image'];
1012 $body = trim($siteinfo['text']) . ' [url]' . $url . "[/url]\n[img]" . $preview . '[/img]';
1019 * Adds the header elements to the XML document
1021 * @param DOMDocument $doc XML document
1022 * @param array $owner Contact data of the poster
1023 * @param string $filter The related feed filter (activity, posts or comments)
1025 * @return DOMElement Header root element
1026 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1028 private static function addHeader(DOMDocument $doc, array $owner, string $filter): DOMElement
1030 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
1031 $doc->appendChild($root);
1033 $root->setAttribute('xmlns:thr', ActivityNamespace::THREAD);
1034 $root->setAttribute('xmlns:georss', ActivityNamespace::GEORSS);
1035 $root->setAttribute('xmlns:activity', ActivityNamespace::ACTIVITY);
1036 $root->setAttribute('xmlns:media', ActivityNamespace::MEDIA);
1037 $root->setAttribute('xmlns:poco', ActivityNamespace::POCO);
1038 $root->setAttribute('xmlns:ostatus', ActivityNamespace::OSTATUS);
1039 $root->setAttribute('xmlns:statusnet', ActivityNamespace::STATUSNET);
1040 $root->setAttribute('xmlns:mastodon', ActivityNamespace::MASTODON);
1043 $selfUri = '/feed/' . $owner['nick'] . '/';
1046 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
1047 $selfUri .= $filter;
1051 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
1055 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
1056 $selfUri .= $filter;
1060 $selfUri = '/dfrn_poll/' . $owner['nick'];
1063 'uri' => 'https://friendi.ca',
1064 'version' => FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
1066 XML::addElement($doc, $root, 'generator', FRIENDICA_PLATFORM, $attributes);
1067 XML::addElement($doc, $root, 'id', DI::baseUrl() . '/profile/' . $owner['nick']);
1068 XML::addElement($doc, $root, 'title', $title);
1069 XML::addElement($doc, $root, 'subtitle', sprintf("Updates from %s on %s", $owner['name'], DI::config()->get('config', 'sitename')));
1070 XML::addElement($doc, $root, 'logo', User::getAvatarUrl($owner, Proxy::SIZE_SMALL));
1071 XML::addElement($doc, $root, 'updated', DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1073 $author = self::addAuthor($doc, $owner, true);
1074 $root->appendChild($author);
1077 'href' => $owner['url'],
1078 'rel' => 'alternate',
1079 'type' => 'text/html',
1081 XML::addElement($doc, $root, 'link', '', $attributes);
1083 /// @TODO We have to find out what this is
1084 /// $attributes = array("href" => DI::baseUrl()."/sup",
1085 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1086 /// "type" => "application/json");
1087 /// XML::addElement($doc, $root, "link", "", $attributes);
1089 self::addHubLink($doc, $root, $owner['nick']);
1091 $attributes = ['href' => DI::baseUrl() . '/salmon/' . $owner['nick'], 'rel' => 'salmon'];
1092 XML::addElement($doc, $root, 'link', '', $attributes);
1094 $attributes = ['href' => DI::baseUrl() . '/salmon/' . $owner['nick'], 'rel' => 'http://salmon-protocol.org/ns/salmon-replies'];
1095 XML::addElement($doc, $root, 'link', '', $attributes);
1097 $attributes = ['href' => DI::baseUrl() . '/salmon/' . $owner['nick'], 'rel' => 'http://salmon-protocol.org/ns/salmon-mention'];
1098 XML::addElement($doc, $root, 'link', '', $attributes);
1100 $attributes = ['href' => DI::baseUrl() . $selfUri, 'rel' => 'self', 'type' => 'application/atom+xml'];
1101 XML::addElement($doc, $root, 'link', '', $attributes);
1103 if ($owner['contact-type'] == Contact::TYPE_COMMUNITY) {
1104 $members = DBA::count('contact', [
1105 'uid' => $owner['uid'],
1112 XML::addElement($doc, $root, 'statusnet:group_info', '', ['member_count' => $members]);
1119 * Add the link to the push hubs to the XML document
1121 * @param DOMDocument $doc XML document
1122 * @param DOMElement $root XML root element where the hub links are added
1123 * @param string $nick Nickname
1125 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1127 public static function addHubLink(DOMDocument $doc, DOMElement $root, string $nick)
1129 $h = DI::baseUrl() . '/pubsubhubbub/' . $nick;
1130 XML::addElement($doc, $root, 'link', '', ['href' => $h, 'rel' => 'hub']);
1134 * Adds attachment data to the XML document
1136 * @param DOMDocument $doc XML document
1137 * @param DOMElement $root XML root element where the hub links are added
1138 * @param array $item Data of the item that is to be posted
1140 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1142 public static function getAttachment(DOMDocument $doc, DOMElement $root, array $item)
1144 $siteinfo = BBCode::getAttachedData($item['body']);
1146 switch ($siteinfo['type']) {
1148 if (!empty($siteinfo['image'])) {
1149 $imgdata = Images::getInfoFromURLCached($siteinfo['image']);
1152 'rel' => 'enclosure',
1153 'href' => $siteinfo['image'],
1154 'type' => $imgdata['mime'],
1155 'length' => intval($imgdata['size']),
1157 XML::addElement($doc, $root, 'link', '', $attributes);
1164 'rel' => 'enclosure',
1165 'href' => $siteinfo['url'],
1166 'type' => 'text/html; charset=UTF-8',
1168 'title' => ($siteinfo['title'] ?? '') ?: $siteinfo['url'],
1170 XML::addElement($doc, $root, 'link', '', $attributes);
1174 if (!DI::config()->get('system', 'ostatus_not_attach_preview') && ($siteinfo['type'] != 'photo') && isset($siteinfo['image'])) {
1175 $imgdata = Images::getInfoFromURLCached($siteinfo['image']);
1178 'rel' => 'enclosure',
1179 'href' => $siteinfo['image'],
1180 'type' => $imgdata['mime'],
1181 'length' => intval($imgdata['size']),
1184 XML::addElement($doc, $root, 'link', '', $attributes);
1188 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]) as $attachment) {
1189 $attributes = ['rel' => 'enclosure',
1190 'href' => $attachment['url'],
1191 'type' => $attachment['mimetype']];
1193 if (!empty($attachment['size'])) {
1194 $attributes['length'] = intval($attachment['size']);
1196 if (!empty($attachment['description'])) {
1197 $attributes['title'] = $attachment['description'];
1200 XML::addElement($doc, $root, 'link', '', $attributes);
1205 * Adds the author element to the XML document
1207 * @param DOMDocument $doc XML document
1208 * @param array $owner Contact data of the poster
1209 * @param bool $show_profile Whether to show profile
1210 * @return DOMElement Author element
1211 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1213 private static function addAuthor(DOMDocument $doc, array $owner, bool $show_profile = true): DOMElement
1215 $profile = DBA::selectFirst('profile', ['homepage', 'publish'], ['uid' => $owner['uid']]);
1216 $author = $doc->createElement('author');
1217 XML::addElement($doc, $author, 'id', $owner['url']);
1218 if ($owner['contact-type'] == Contact::TYPE_COMMUNITY) {
1219 XML::addElement($doc, $author, 'activity:object-type', Activity\ObjectType::GROUP);
1221 XML::addElement($doc, $author, 'activity:object-type', Activity\ObjectType::PERSON);
1224 XML::addElement($doc, $author, 'uri', $owner['url']);
1225 XML::addElement($doc, $author, 'name', $owner['nick']);
1226 XML::addElement($doc, $author, 'email', $owner['addr']);
1227 if ($show_profile) {
1228 XML::addElement($doc, $author, 'summary', BBCode::convertForUriId($owner['uri-id'], $owner['about'], BBCode::OSTATUS));
1232 'rel' => 'alternate',
1233 'type' => 'text/html',
1234 'href' => $owner['url'],
1236 XML::addElement($doc, $author, 'link', '', $attributes);
1240 'type' => 'image/jpeg', // To-Do?
1241 'media:width' => Proxy::PIXEL_SMALL,
1242 'media:height' => Proxy::PIXEL_SMALL,
1243 'href' => User::getAvatarUrl($owner, Proxy::SIZE_SMALL),
1245 XML::addElement($doc, $author, 'link', '', $attributes);
1247 if (isset($owner['thumb'])) {
1250 'type' => 'image/jpeg', // To-Do?
1251 'media:width' => Proxy::PIXEL_THUMB,
1252 'media:height' => Proxy::PIXEL_THUMB,
1253 'href' => User::getAvatarUrl($owner, Proxy::SIZE_THUMB),
1255 XML::addElement($doc, $author, 'link', '', $attributes);
1258 XML::addElement($doc, $author, 'poco:preferredUsername', $owner['nick']);
1259 XML::addElement($doc, $author, 'poco:displayName', $owner['name']);
1260 if ($show_profile) {
1261 XML::addElement($doc, $author, 'poco:note', BBCode::convertForUriId($owner['uri-id'], $owner['about'], BBCode::OSTATUS));
1263 if (trim($owner['location']) != '') {
1264 $element = $doc->createElement('poco:address');
1265 XML::addElement($doc, $element, 'poco:formatted', $owner['location']);
1266 $author->appendChild($element);
1270 if (DBA::isResult($profile) && !$show_profile) {
1271 if (trim($profile['homepage']) != '') {
1272 $urls = $doc->createElement('poco:urls');
1273 XML::addElement($doc, $urls, 'poco:type', 'homepage');
1274 XML::addElement($doc, $urls, 'poco:value', $profile['homepage']);
1275 XML::addElement($doc, $urls, 'poco:primary', 'true');
1276 $author->appendChild($urls);
1279 XML::addElement($doc, $author, 'followers', '', ['url' => DI::baseUrl() . '/profile/' . $owner['nick'] . '/contacts/followers']);
1280 XML::addElement($doc, $author, 'statusnet:profile_info', '', ['local_id' => $owner['uid']]);
1282 if ($profile['publish']) {
1283 XML::addElement($doc, $author, 'mastodon:scope', 'public');
1291 * @TODO Picture attachments should look like this:
1292 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1293 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1297 * Returns the given activity if present - otherwise returns the "post" activity
1299 * @param array $item Data of the item that is to be posted
1300 * @return string activity
1302 public static function constructVerb(array $item): string
1304 if (!empty($item['verb'])) {
1305 return $item['verb'];
1308 return Activity::POST;
1312 * Returns the given object type if present - otherwise returns the "note" object type
1314 * @param array $item Data of the item that is to be posted
1315 * @return string Object type
1317 private static function constructObjecttype(array $item): string
1319 if (!empty($item['object-type']) && in_array($item['object-type'], [Activity\ObjectType::NOTE, Activity\ObjectType::COMMENT])) {
1320 return $item['object-type'];
1323 return Activity\ObjectType::NOTE;
1327 * Adds an entry element to the XML document
1329 * @param DOMDocument $doc XML document
1330 * @param array $item Data of the item that is to be posted
1331 * @param array $owner Contact data of the poster
1332 * @param bool $toplevel optional default false
1334 * @return DOMElement Entry element
1335 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1336 * @throws \ImagickException
1338 private static function entry(DOMDocument $doc, array $item, array $owner, bool $toplevel = false): DOMElement
1340 if ($item['verb'] == Activity::LIKE) {
1341 return self::likeEntry($doc, $item, $owner, $toplevel);
1342 } elseif (in_array($item['verb'], [Activity::FOLLOW, Activity::O_UNFOLLOW])) {
1343 return self::followEntry($doc, $item, $owner, $toplevel);
1345 return self::noteEntry($doc, $item, $owner, $toplevel);
1350 * Adds an entry element with a "like"
1352 * @param DOMDocument $doc XML document
1353 * @param array $item Data of the item that is to be posted
1354 * @param array $owner Contact data of the poster
1355 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1356 * @return DOMElement Entry element with "like"
1357 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1358 * @throws \ImagickException
1360 private static function likeEntry(DOMDocument $doc, array $item, array $owner, bool $toplevel): DOMElement
1362 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item['author-link']) != Strings::normaliseLink($owner['url']))) {
1363 Logger::info('OStatus entry is from author ' . $owner['url'] . ' - not from ' . $item['author-link'] . '. Quitting.');
1366 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1368 $verb = ActivityNamespace::ACTIVITY_SCHEMA . 'favorite';
1369 self::entryContent($doc, $entry, $item, $owner, 'Favorite', $verb, false);
1371 $parent = Post::selectFirst([], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
1372 if (DBA::isResult($parent)) {
1373 $as_object = $doc->createElement('activity:object');
1375 XML::addElement($doc, $as_object, 'activity:object-type', self::constructObjecttype($parent));
1377 self::entryContent($doc, $as_object, $parent, $owner, 'New entry');
1379 $entry->appendChild($as_object);
1382 self::entryFooter($doc, $entry, $item, $owner);
1388 * Adds the person object element to the XML document
1390 * @param DOMDocument $doc XML document
1391 * @param array $owner Contact data of the poster
1392 * @param array $contact Contact data of the target
1393 * @return DOMElement author element
1395 private static function addPersonObject(DOMDocument $doc, array $owner, array $contact): DOMElement
1397 $object = $doc->createElement('activity:object');
1398 XML::addElement($doc, $object, 'activity:object-type', Activity\ObjectType::PERSON);
1400 if ($contact['network'] == Protocol::PHANTOM) {
1401 XML::addElement($doc, $object, 'id', $contact['url']);
1405 XML::addElement($doc, $object, 'id', $contact['alias']);
1406 XML::addElement($doc, $object, 'title', $contact['nick']);
1408 XML::addElement($doc, $object, 'link', '', [
1409 'rel' => 'alternate',
1410 'type' => 'text/html',
1411 'href' => $contact['url'],
1416 'type' => 'image/jpeg', // To-Do?
1417 'media:width' => 300,
1418 'media:height' => 300,
1419 'href' => $contact['photo'],
1421 XML::addElement($doc, $object, 'link', '', $attributes);
1423 XML::addElement($doc, $object, 'poco:preferredUsername', $contact['nick']);
1424 XML::addElement($doc, $object, 'poco:displayName', $contact['name']);
1426 if (trim($contact['location']) != '') {
1427 $element = $doc->createElement('poco:address');
1428 XML::addElement($doc, $element, 'poco:formatted', $contact['location']);
1429 $object->appendChild($element);
1436 * Adds a follow/unfollow entry element
1438 * @param DOMDocument $doc XML document
1439 * @param array $item Data of the follow/unfollow message
1440 * @param array $owner Contact data of the poster
1441 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1442 * @return DOMElement Entry element
1443 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1444 * @throws \ImagickException
1446 private static function followEntry(DOMDocument $doc, array $item, array $owner, bool $toplevel): DOMElement
1448 $item['id'] = $item['parent'] = 0;
1449 $item['created'] = $item['edited'] = date('c');
1450 $item['private'] = Item::PRIVATE;
1452 $contact = Contact::getByURL($item['follow']);
1453 $item['follow'] = $contact['url'];
1455 if ($contact['alias']) {
1456 $item['follow'] = $contact['alias'];
1458 $contact['alias'] = $contact['url'];
1461 $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($contact['url'])];
1462 $user_contact = DBA::selectFirst('contact', ['id'], $condition);
1464 if (DBA::isResult($user_contact)) {
1465 $connect_id = $user_contact['id'];
1470 if ($item['verb'] == Activity::FOLLOW) {
1471 $message = DI::l10n()->t('%s is now following %s.');
1472 $title = DI::l10n()->t('following');
1473 $action = 'subscription';
1475 $message = DI::l10n()->t('%s stopped following %s.');
1476 $title = DI::l10n()->t('stopped following');
1477 $action = 'unfollow';
1480 $item['uri'] = $item['parent-uri'] = $item['thr-parent']
1481 = 'tag:' . DI::baseUrl()->getHostname().
1482 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1483 ':person:'.$connect_id.':'.$item['created'];
1485 $item['body'] = sprintf($message, $owner['nick'], $contact['nick']);
1487 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1489 self::entryContent($doc, $entry, $item, $owner, $title);
1491 $object = self::addPersonObject($doc, $owner, $contact);
1492 $entry->appendChild($object);
1494 self::entryFooter($doc, $entry, $item, $owner);
1500 * Adds a regular entry element
1502 * @param DOMDocument $doc XML document
1503 * @param array $item Data of the item that is to be posted
1504 * @param array $owner Contact data of the poster
1505 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1506 * @return DOMElement Entry element
1507 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1508 * @throws \ImagickException
1510 private static function noteEntry(DOMDocument $doc, array $item, array $owner, bool $toplevel): DOMElement
1512 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item['author-link']) != Strings::normaliseLink($owner['url']))) {
1513 Logger::info('OStatus entry is from author ' . $owner['url'] . ' - not from ' . $item['author-link'] . '. Quitting.');
1517 if (!empty($item['title'])) {
1518 $title = BBCode::convertForUriId($item['uri-id'], $item['title'], BBCode::OSTATUS);
1520 $title = sprintf('New note by %s', $owner['nick']);
1523 $title = sprintf('New comment by %s', $owner['nick']);
1526 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1528 XML::addElement($doc, $entry, 'activity:object-type', Activity\ObjectType::NOTE);
1530 self::entryContent($doc, $entry, $item, $owner, $title, '', true);
1532 self::entryFooter($doc, $entry, $item, $owner, true);
1538 * Adds a header element to the XML document
1540 * @param DOMDocument $doc XML document
1541 * @param array $owner Contact data of the poster
1542 * @param array $item
1543 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1544 * @return DOMElement The entry element where the elements are added
1545 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1546 * @throws \ImagickException
1548 public static function entryHeader(DOMDocument $doc, array $owner, array $item, bool $toplevel): DOMElement
1551 $entry = $doc->createElement('entry');
1553 if ($owner['contact-type'] == Contact::TYPE_COMMUNITY) {
1554 $contact = Contact::getByURL($item['author-link']) ?: $owner;
1555 $contact['nickname'] = $contact['nickname'] ?? $contact['nick'];
1556 $author = self::addAuthor($doc, $contact, false);
1557 $entry->appendChild($author);
1560 $entry = $doc->createElementNS(ActivityNamespace::ATOM1, 'entry');
1562 $entry->setAttribute('xmlns:thr', ActivityNamespace::THREAD);
1563 $entry->setAttribute('xmlns:georss', ActivityNamespace::GEORSS);
1564 $entry->setAttribute('xmlns:activity', ActivityNamespace::ACTIVITY);
1565 $entry->setAttribute('xmlns:media', ActivityNamespace::MEDIA);
1566 $entry->setAttribute('xmlns:poco', ActivityNamespace::POCO);
1567 $entry->setAttribute('xmlns:ostatus', ActivityNamespace::OSTATUS);
1568 $entry->setAttribute('xmlns:statusnet', ActivityNamespace::STATUSNET);
1569 $entry->setAttribute('xmlns:mastodon', ActivityNamespace::MASTODON);
1571 $author = self::addAuthor($doc, $owner);
1572 $entry->appendChild($author);
1579 * Adds elements to the XML document
1581 * @param DOMDocument $doc XML document
1582 * @param DOMElement $entry Entry element where the content is added
1583 * @param array $item Data of the item that is to be posted
1584 * @param array $owner Contact data of the poster
1585 * @param string $title Title for the post
1586 * @param string $verb The activity verb
1587 * @param bool $complete Add the "status_net" element?
1589 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1591 private static function entryContent(DOMDocument $doc, DOMElement $entry, array $item, array $owner, string $title, string $verb = '', bool $complete = true)
1594 $verb = self::constructVerb($item);
1597 XML::addElement($doc, $entry, 'id', $item['uri']);
1598 XML::addElement($doc, $entry, 'title', html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1600 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
1601 $body = self::formatPicturePost($body, $item['uri-id']);
1603 if (!empty($item['title'])) {
1604 $body = '[b]' . $item['title'] . "[/b]\n\n" . $body;
1607 $body = BBCode::convertForUriId($item['uri-id'], $body, BBCode::OSTATUS);
1609 XML::addElement($doc, $entry, 'content', $body, ['type' => 'html']);
1611 XML::addElement($doc, $entry, 'link', '', [
1612 'rel' => 'alternate',
1613 'type' => 'text/html',
1614 'href' => DI::baseUrl() . '/display/' . $item['guid'],
1617 if ($complete && ($item['id'] > 0)) {
1618 XML::addElement($doc, $entry, 'status_net', '', ['notice_id' => $item['id']]);
1621 XML::addElement($doc, $entry, 'activity:verb', $verb);
1623 XML::addElement($doc, $entry, 'published', DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
1624 XML::addElement($doc, $entry, 'updated', DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM));
1628 * Adds the elements at the foot of an entry to the XML document
1630 * @param DOMDocument $doc XML document
1631 * @param object $entry The entry element where the elements are added
1632 * @param array $item Data of the item that is to be posted
1633 * @param array $owner Contact data of the poster
1634 * @param bool $complete default true
1636 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1638 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner, bool $complete = true)
1642 if ($item['gravity'] != GRAVITY_PARENT) {
1643 $parent = Post::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
1645 $thrparent = Post::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner['uid'], 'uri' => $item['thr-parent']]);
1647 if (DBA::isResult($thrparent)) {
1648 $mentioned[$thrparent['author-link']] = $thrparent['author-link'];
1649 $mentioned[$thrparent['owner-link']] = $thrparent['owner-link'];
1650 $parent_plink = $thrparent['plink'];
1651 } elseif (DBA::isResult($parent)) {
1652 $mentioned[$parent['author-link']] = $parent['author-link'];
1653 $mentioned[$parent['owner-link']] = $parent['owner-link'];
1654 $parent_plink = DI::baseUrl() . '/display/' . $parent['guid'];
1656 DI::logger()->notice('Missing parent and thr-parent for child item', ['item' => $item]);
1659 if (isset($parent_plink)) {
1661 'ref' => $item['thr-parent'],
1662 'href' => $parent_plink];
1663 XML::addElement($doc, $entry, 'thr:in-reply-to', '', $attributes);
1667 'href' => $parent_plink];
1668 XML::addElement($doc, $entry, 'link', '', $attributes);
1672 if (intval($item['parent']) > 0) {
1673 $conversation_href = $conversation_uri = $item['conversation'];
1675 XML::addElement($doc, $entry, 'link', '', ['rel' => 'ostatus:conversation', 'href' => $conversation_href]);
1678 'href' => $conversation_href,
1679 'local_id' => $item['parent'],
1680 'ref' => $conversation_uri,
1683 XML::addElement($doc, $entry, 'ostatus:conversation', $conversation_uri, $attributes);
1686 // uri-id isn't present for follow entry pseudo-items
1687 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
1688 foreach ($tags as $tag) {
1689 $mentioned[$tag['url']] = $tag['url'];
1692 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
1694 foreach ($mentioned as $mention) {
1695 $newmentions[str_replace('http://', 'https://', $mention)] = str_replace('http://', 'https://', $mention);
1696 $newmentions[str_replace('https://', 'http://', $mention)] = str_replace('https://', 'http://', $mention);
1698 $mentioned = $newmentions;
1700 foreach ($mentioned as $mention) {
1701 $contact = Contact::getByURL($mention, false, ['contact-type']);
1702 if (!empty($contact) && ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
1703 XML::addElement($doc, $entry, 'link', '', [
1704 'rel' => 'mentioned',
1705 'ostatus:object-type' => Activity\ObjectType::GROUP,
1709 XML::addElement($doc, $entry, 'link', '', [
1710 'rel' => 'mentioned',
1711 'ostatus:object-type' => Activity\ObjectType::PERSON,
1717 if ($owner['contact-type'] == Contact::TYPE_COMMUNITY) {
1718 XML::addElement($doc, $entry, 'link', '', [
1719 'rel' => 'mentioned',
1720 'ostatus:object-type' => 'http://activitystrea.ms/schema/1.0/group',
1721 'href' => $owner['url']
1725 if ($item['private'] != Item::PRIVATE) {
1726 XML::addElement($doc, $entry, 'link', '', ['rel' => 'ostatus:attention',
1727 'href' => 'http://activityschema.org/collection/public']);
1728 XML::addElement($doc, $entry, 'link', '', ['rel' => 'mentioned',
1729 'ostatus:object-type' => 'http://activitystrea.ms/schema/1.0/collection',
1730 'href' => 'http://activityschema.org/collection/public']);
1731 XML::addElement($doc, $entry, 'mastodon:scope', 'public');
1734 foreach ($tags as $tag) {
1735 if ($tag['type'] == Tag::HASHTAG) {
1736 XML::addElement($doc, $entry, 'category', '', ['term' => $tag['name']]);
1740 self::getAttachment($doc, $entry, $item);
1742 if ($complete && ($item['id'] > 0)) {
1743 $app = $item['app'];
1748 $attributes = ['local_id' => $item['id'], 'source' => $app];
1750 if (isset($parent['id'])) {
1751 $attributes['repeat_of'] = $parent['id'];
1754 if ($item['coord'] != '') {
1755 XML::addElement($doc, $entry, 'georss:point', $item['coord']);
1758 XML::addElement($doc, $entry, 'statusnet:notice_info', '', $attributes);
1763 * Creates the XML feed for a given nickname
1765 * Supported filters:
1766 * - activity (default): all the public posts
1767 * - posts: all the public top-level posts
1768 * - comments: all the public replies
1770 * Updates the provided last_update parameter if the result comes from the
1771 * cache or it is empty
1773 * @param string $owner_nick Nickname of the feed owner
1774 * @param string $last_update Date of the last update (in "Y-m-d H:i:s" format)
1775 * @param integer $max_items Number of maximum items to fetch
1776 * @param string $filter Feed items filter (activity, posts or comments)
1777 * @param boolean $nocache Wether to bypass caching
1778 * @return string XML feed or empty string on error
1779 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1780 * @throws \ImagickException
1782 public static function feed(string $owner_nick, string &$last_update, int $max_items = 300, string $filter = 'activity', bool $nocache = false): string
1784 $stamp = microtime(true);
1786 $owner = User::getOwnerDataByNick($owner_nick);
1791 $cachekey = 'ostatus:feed:' . $owner_nick . ':' . $filter . ':' . $last_update;
1793 $previous_created = $last_update;
1795 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
1796 if ((time() - strtotime($owner['last-item'])) < 15*60) {
1797 $result = DI::cache()->get($cachekey);
1798 if (!$nocache && !is_null($result)) {
1799 Logger::info('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)');
1800 $last_update = $result['last_update'];
1801 return $result['feed'];
1805 if (!strlen($last_update)) {
1806 $last_update = 'now -30 days';
1809 $check_date = DateTimeFormat::utc($last_update);
1810 $authorid = Contact::getIdForURL($owner['url']);
1813 "`uid` = ? AND `received` > ? AND NOT `deleted` AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?)",
1821 if ($filter === 'comments') {
1822 $condition[0] .= " AND `object-type` = ? ";
1823 $condition[] = Activity\ObjectType::COMMENT;
1826 if ($owner['contact-type'] != Contact::TYPE_COMMUNITY) {
1827 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
1828 $condition[] = $owner['id'];
1829 $condition[] = $authorid;
1832 $params = ['order' => ['received' => true], 'limit' => $max_items];
1834 if ($filter === 'posts') {
1835 $ret = Post::selectThread([], $condition, $params);
1837 $ret = Post::select([], $condition, $params);
1840 $items = Post::toArray($ret);
1842 $doc = new DOMDocument('1.0', 'utf-8');
1843 $doc->formatOutput = true;
1845 $root = self::addHeader($doc, $owner, $filter);
1847 foreach ($items as $item) {
1848 if (DI::config()->get('system', 'ostatus_debug')) {
1849 $item['body'] .= '🍼';
1852 if (in_array($item['verb'], [Activity::FOLLOW, Activity::O_UNFOLLOW, Activity::LIKE])) {
1856 $entry = self::entry($doc, $item, $owner, false);
1857 $root->appendChild($entry);
1859 if ($last_update < $item['created']) {
1860 $last_update = $item['created'];
1864 $feeddata = trim($doc->saveXML());
1866 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
1867 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
1869 Logger::info('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created);
1875 * Creates the XML for a salmon message
1877 * @param array $item Data of the item that is to be posted
1878 * @param array $owner Contact data of the poster
1880 * @return string XML for the salmon
1881 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1882 * @throws \ImagickException
1884 public static function salmon(array $item, array $owner): string
1886 $doc = new DOMDocument('1.0', 'utf-8');
1887 $doc->formatOutput = true;
1889 if (DI::config()->get('system', 'ostatus_debug')) {
1890 $item['body'] .= '🐟';
1893 $entry = self::entry($doc, $item, $owner, true);
1895 $doc->appendChild($entry);
1897 return trim($doc->saveXML());
1901 * Checks if the given contact url does support OStatus
1903 * @param string $url profile url
1905 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1906 * @throws \ImagickException
1908 public static function isSupportedByContactUrl(string $url): bool
1910 $probe = Probe::uri($url, Protocol::OSTATUS);
1911 return $probe['network'] == Protocol::OSTATUS;