3 * @copyright Copyright (C) 2020, Friendica
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;
26 use Friendica\Content\Text\BBCode;
27 use Friendica\Content\Text\HTML;
28 use Friendica\Core\Cache\Duration;
29 use Friendica\Core\Logger;
30 use Friendica\Core\Protocol;
31 use Friendica\Database\DBA;
33 use Friendica\Model\APContact;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Conversation;
36 use Friendica\Model\GContact;
37 use Friendica\Model\Item;
38 use Friendica\Model\User;
39 use Friendica\Network\Probe;
40 use Friendica\Util\DateTimeFormat;
41 use Friendica\Util\Images;
42 use Friendica\Util\Network;
43 use Friendica\Util\Proxy as ProxyUtils;
44 use Friendica\Util\Strings;
45 use Friendica\Util\XML;
47 require_once 'mod/share.php';
48 require_once 'include/api.php';
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, $onlyfetch)
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 $condition = ["`uid` = ? AND `alias` = ? AND `network` != ? AND `rel` IN (?, ?)",
105 $importer["uid"], $aliaslink, Protocol::STATUSNET,
106 Contact::SHARING, Contact::FRIEND];
107 $contact = DBA::selectFirst('contact', [], $condition);
110 if (!DBA::isResult($contact) && $author["author-link"] != '') {
111 if ($aliaslink == "") {
112 $aliaslink = $author["author-link"];
115 $condition = ["`uid` = ? AND `nurl` IN (?, ?) AND `network` != ? AND `rel` IN (?, ?)",
116 $importer["uid"], Strings::normaliseLink($author["author-link"]), Strings::normaliseLink($aliaslink),
117 Protocol::STATUSNET, Contact::SHARING, Contact::FRIEND];
118 $contact = DBA::selectFirst('contact', [], $condition);
121 if (!DBA::isResult($contact) && ($addr != '')) {
122 $condition = ["`uid` = ? AND `addr` = ? AND `network` != ? AND `rel` IN (?, ?)",
123 $importer["uid"], $addr, Protocol::STATUSNET,
124 Contact::SHARING, Contact::FRIEND];
125 $contact = DBA::selectFirst('contact', [], $condition);
128 if (DBA::isResult($contact)) {
129 if ($contact['blocked']) {
131 } elseif (!empty(APContact::getByURL($contact['url'], false))) {
132 ActivityPub\Receiver::switchContact($contact['id'], $importer['uid'], $contact['url']);
134 $author["contact-id"] = $contact["id"];
138 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
139 foreach ($avatars as $avatar) {
142 foreach ($avatar->attributes as $attributes) {
143 if ($attributes->name == "href") {
144 $href = $attributes->textContent;
146 if ($attributes->name == "width") {
147 $width = $attributes->textContent;
151 $avatarlist[$width] = $href;
154 if (count($avatarlist) > 0) {
156 $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
159 $displayname = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
160 if ($displayname != "") {
161 $author["author-name"] = $displayname;
164 $author["owner-id"] = $author["author-id"];
166 // Only update the contacts if it is an OStatus contact
167 if (DBA::isResult($contact) && ($contact['id'] > 0) && !$onlyfetch && ($contact["network"] == Protocol::OSTATUS)) {
169 // Update contact data
171 unset($current['name-date']);
173 // This query doesn't seem to work
174 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
176 // $contact["notify"] = $value;
178 // This query doesn't seem to work as well - I hate these queries
179 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
181 // $contact["poll"] = $value;
183 $contact['url'] = $author["author-link"];
184 $contact['nurl'] = Strings::normaliseLink($contact['url']);
186 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
188 $contact["alias"] = $value;
191 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
193 $contact["name"] = $value;
196 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()', $context);
198 $contact["nick"] = $value;
201 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()', $context);
203 $contact["about"] = HTML::toBBCode($value);
206 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()', $context);
208 $contact["location"] = $value;
211 $contact['name-date'] = DateTimeFormat::utcNow();
213 DBA::update('contact', $contact, ['id' => $contact["id"]], $current);
215 if (!empty($author["author-avatar"]) && ($author["author-avatar"] != $current['avatar'])) {
216 Logger::log("Update profile picture for contact ".$contact["id"], Logger::DEBUG);
217 Contact::updateAvatar($author["author-avatar"], $importer["uid"], $contact["id"]);
220 // Ensure that we are having this contact (with uid=0)
221 $cid = Contact::getIdForURL($aliaslink, 0, true);
224 $fields = ['url', 'nurl', 'name', 'nick', 'alias', 'about', 'location'];
225 $old_contact = DBA::selectFirst('contact', $fields, ['id' => $cid]);
227 // Update it with the current values
228 $fields = ['url' => $author["author-link"], 'name' => $contact["name"],
229 'nurl' => Strings::normaliseLink($author["author-link"]),
230 'nick' => $contact["nick"], 'alias' => $contact["alias"],
231 'about' => $contact["about"], 'location' => $contact["location"],
232 'success_update' => DateTimeFormat::utcNow(), 'last-update' => DateTimeFormat::utcNow()];
234 DBA::update('contact', $fields, ['id' => $cid], $old_contact);
237 if (!empty($author["author-avatar"])) {
238 Contact::updateAvatar($author["author-avatar"], 0, $cid);
242 $contact["generation"] = 2;
243 $contact["hide"] = false; // OStatus contacts are never hidden
244 if (!empty($author["author-avatar"])) {
245 $contact["photo"] = $author["author-avatar"];
247 $gcid = GContact::update($contact);
249 GContact::link($gcid, $contact["uid"], $contact["id"]);
250 } elseif ($contact["network"] != Protocol::DFRN) {
258 * Fetches author data from a given XML string
260 * @param string $xml The XML
261 * @param array $importer user record of the importing user
263 * @return array Array of author related entries for the item
264 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
265 * @throws \ImagickException
267 public static function salmonAuthor($xml, array $importer)
273 $doc = new DOMDocument();
274 @$doc->loadXML($xml);
276 $xpath = new DOMXPath($doc);
277 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
278 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
279 $xpath->registerNamespace('georss', ActivityNamespace::GEORSS);
280 $xpath->registerNamespace('activity', ActivityNamespace::ACTIVITY);
281 $xpath->registerNamespace('media', ActivityNamespace::MEDIA);
282 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
283 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
284 $xpath->registerNamespace('statusnet', ActivityNamespace::STATUSNET);
286 $contact = ["id" => 0];
288 // Fetch the first author
289 $authordata = $xpath->query('//author')->item(0);
290 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, true);
295 * Read attributes from element
297 * @param object $element Element object
299 * @return array attributes
301 private static function readAttributes($element)
305 foreach ($element->attributes as $attributes) {
306 $attribute[$attributes->name] = $attributes->textContent;
313 * Imports an XML string containing OStatus elements
315 * @param string $xml The XML
316 * @param array $importer user record of the importing user
317 * @param array $contact contact
318 * @param string $hub Called by reference, returns the fetched hub data
320 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
321 * @throws \ImagickException
323 public static function import($xml, array $importer, array &$contact, &$hub)
325 self::process($xml, $importer, $contact, $hub);
329 * Internal feed processing
331 * @param string $xml The XML
332 * @param array $importer user record of the importing user
333 * @param array $contact contact
334 * @param string $hub Called by reference, returns the fetched hub data
335 * @param boolean $stored Is the post fresh imported or from the database?
336 * @param boolean $initialize Is it the leading post so that data has to be initialized?
338 * @return boolean Could the XML be processed?
339 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
340 * @throws \ImagickException
342 private static function process($xml, array $importer, array &$contact = null, &$hub, $stored = false, $initialize = true)
345 self::$itemlist = [];
346 self::$conv_list = [];
349 Logger::log('Import OStatus message for user ' . $importer['uid'], Logger::DEBUG);
354 $doc = new DOMDocument();
355 @$doc->loadXML($xml);
357 $xpath = new DOMXPath($doc);
358 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
359 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
360 $xpath->registerNamespace('georss', ActivityNamespace::GEORSS);
361 $xpath->registerNamespace('activity', ActivityNamespace::ACTIVITY);
362 $xpath->registerNamespace('media', ActivityNamespace::MEDIA);
363 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
364 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
365 $xpath->registerNamespace('statusnet', ActivityNamespace::STATUSNET);
368 $hub_items = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0);
369 if (is_object($hub_items)) {
370 $hub_attributes = $hub_items->attributes;
371 if (is_object($hub_attributes)) {
372 foreach ($hub_attributes as $hub_attribute) {
373 if ($hub_attribute->name == "href") {
374 $hub = $hub_attribute->textContent;
375 Logger::log("Found hub ".$hub, Logger::DEBUG);
382 $header["uid"] = $importer["uid"];
383 $header["network"] = Protocol::OSTATUS;
385 $header["origin"] = 0;
386 $header["gravity"] = GRAVITY_COMMENT;
388 if (!is_object($doc->firstChild) || empty($doc->firstChild->tagName)) {
392 $first_child = $doc->firstChild->tagName;
394 if ($first_child == "feed") {
395 $entries = $xpath->query('/atom:feed/atom:entry');
397 $entries = $xpath->query('/atom:entry');
400 if ($entries->length == 1) {
401 // We reformat the XML to make it better readable
402 $doc2 = new DOMDocument();
403 $doc2->loadXML($xml);
404 $doc2->preserveWhiteSpace = false;
405 $doc2->formatOutput = true;
406 $xml2 = $doc2->saveXML();
408 $header["protocol"] = Conversation::PARCEL_SALMON;
409 $header["source"] = $xml2;
410 } elseif (!$initialize) {
414 // Fetch the first author
415 $authordata = $xpath->query('//author')->item(0);
416 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, $stored);
418 // Reverse the order of the entries
421 foreach ($entries as $entry) {
422 $entrylist[] = $entry;
425 foreach (array_reverse($entrylist) as $entry) {
427 $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
429 if ($authorelement->length == 0) {
430 $authorelement = $xpath->query('atom:author', $entry);
433 if ($authorelement->length > 0) {
434 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, $stored);
437 $item = array_merge($header, $author);
439 $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
441 $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $entry);
444 if (in_array($item["verb"], ['qvitter-delete-notice', Activity::DELETE, 'delete'])) {
445 self::deleteNotice($item);
449 if (in_array($item["verb"], [Activity::O_UNFAVOURITE, Activity::UNFAVORITE])) {
450 // Ignore "Unfavorite" message
451 Logger::log("Ignore unfavorite message ".print_r($item, true), Logger::DEBUG);
455 // Deletions come with the same uri, so we check for duplicates after processing deletions
456 if (Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]])) {
457 Logger::log('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', Logger::DEBUG);
460 Logger::log('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', Logger::DEBUG);
463 if ($item["verb"] == Activity::JOIN) {
464 // ignore "Join" messages
465 Logger::log("Ignore join message ".print_r($item, true), Logger::DEBUG);
469 if ($item["verb"] == "http://mastodon.social/schema/1.0/block") {
470 // ignore mastodon "block" messages
471 Logger::log("Ignore block message ".print_r($item, true), Logger::DEBUG);
475 if ($item["verb"] == Activity::FOLLOW) {
476 Contact::addRelationship($importer, $contact, $item);
480 if ($item["verb"] == Activity::O_UNFOLLOW) {
482 Contact::removeFollower($importer, $contact, $item, $dummy);
486 if ($item["verb"] == Activity::FAVORITE) {
487 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
488 Logger::log("Favorite ".$orig_uri." ".print_r($item, true));
490 $item["verb"] = Activity::LIKE;
491 $item["parent-uri"] = $orig_uri;
492 $item["gravity"] = GRAVITY_ACTIVITY;
493 $item["object-type"] = Activity\ObjectType::NOTE;
496 // http://activitystrea.ms/schema/1.0/rsvp-yes
497 if (!in_array($item["verb"], [Activity::POST, Activity::LIKE, Activity::SHARE])) {
498 Logger::log("Unhandled verb ".$item["verb"]." ".print_r($item, true), Logger::DEBUG);
501 self::processPost($xpath, $entry, $item, $importer);
503 if ($initialize && (count(self::$itemlist) > 0)) {
504 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['parent-uri']) {
505 // We will import it everytime, when it is started by our contacts
506 $valid = Contact::isSharingByURL(self::$itemlist[0]['author-link'], self::$itemlist[0]['uid']);
509 // If not, then it depends on this setting
510 $valid = ((self::$itemlist[0]['uid'] == 0) || !DI::pConfig()->get(self::$itemlist[0]['uid'], 'system', 'accept_only_sharer', false));
512 Logger::log("Item with uri ".self::$itemlist[0]['uri']." will be imported due to the system settings.", Logger::DEBUG);
515 Logger::log("Item with uri ".self::$itemlist[0]['uri']." belongs to a contact (".self::$itemlist[0]['contact-id']."). It will be imported.", Logger::DEBUG);
518 // Never post a thread when the only interaction by our contact was a like
520 $verbs = [Activity::POST, Activity::SHARE];
521 foreach (self::$itemlist as $item) {
522 if (in_array($item['verb'], $verbs) && Contact::isSharingByURL($item['author-link'], $item['uid'])) {
527 Logger::log("Item with uri ".self::$itemlist[0]['uri']." will be imported since the thread contains posts or shares.", Logger::DEBUG);
531 // But we will only import complete threads
532 $valid = Item::exists(['uid' => $importer["uid"], 'uri' => self::$itemlist[0]['parent-uri']]);
534 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);
539 $default_contact = 0;
540 for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
541 if (empty(self::$itemlist[$key]['contact-id'])) {
542 self::$itemlist[$key]['contact-id'] = $default_contact;
544 $default_contact = $item['contact-id'];
547 foreach (self::$itemlist as $item) {
548 $found = Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]]);
550 Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", Logger::DEBUG);
551 } elseif ($item['contact-id'] < 0) {
552 Logger::log("Item with uri ".$item["uri"]." is from a blocked contact.", Logger::DEBUG);
554 // We are having duplicated entries. Hopefully this solves it.
555 if (DI::lock()->acquire('ostatus_process_item_insert')) {
556 $ret = Item::insert($item);
557 DI::lock()->release('ostatus_process_item_insert');
558 Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret);
560 $ret = Item::insert($item);
561 Logger::log("We couldn't lock - but tried to store the item anyway. Return value is ".$ret);
566 self::$itemlist = [];
568 Logger::log('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.', Logger::DEBUG);
574 * Removes notice item from database
576 * @param array $item item
580 private static function deleteNotice(array $item)
582 $condition = ['uid' => $item['uid'], 'author-id' => $item['author-id'], 'uri' => $item['uri']];
583 if (!Item::exists($condition)) {
584 Logger::log('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it.");
588 Item::markForDeletion($condition);
590 Logger::log('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
594 * Processes the XML for a post
596 * @param DOMXPath $xpath The xpath object
597 * @param object $entry The xml entry that is processed
598 * @param array $item The item array
599 * @param array $importer user record of the importing user
601 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
602 * @throws \ImagickException
604 private static function processPost(DOMXPath $xpath, $entry, array &$item, array $importer)
606 $item["body"] = HTML::toBBCode(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
607 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $entry);
608 if (($item["object-type"] == Activity\ObjectType::BOOKMARK) || ($item["object-type"] == Activity\ObjectType::EVENT)) {
609 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
610 $item["body"] = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
611 } elseif ($item["object-type"] == Activity\ObjectType::QUESTION) {
612 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
615 $item["created"] = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
616 $item["edited"] = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
617 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
619 $conv = $xpath->query('ostatus:conversation', $entry);
620 if (is_object($conv->item(0))) {
621 foreach ($conv->item(0)->attributes as $attributes) {
622 if ($attributes->name == "ref") {
623 $item['conversation-uri'] = $attributes->textContent;
625 if ($attributes->name == "href") {
626 $item['conversation-href'] = $attributes->textContent;
633 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
634 if (is_object($inreplyto->item(0))) {
635 foreach ($inreplyto->item(0)->attributes as $attributes) {
636 if ($attributes->name == "ref") {
637 $item["parent-uri"] = $attributes->textContent;
639 if ($attributes->name == "href") {
640 $related = $attributes->textContent;
645 $georsspoint = $xpath->query('georss:point', $entry);
646 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
647 $item["coord"] = $georsspoint->item(0)->nodeValue;
650 $categories = $xpath->query('atom:category', $entry);
652 foreach ($categories as $category) {
653 foreach ($category->attributes as $attributes) {
654 if ($attributes->name == 'term') {
655 $term = $attributes->textContent;
656 if (!empty($item['tag'])) {
662 $item['tag'] .= '#[url=' . DI::baseUrl() . '/search?tag=' . $term . ']' . $term . '[/url]';
671 $links = $xpath->query('atom:link', $entry);
673 $link_data = self::processLinks($links, $item);
674 $self = $link_data['self'];
675 $add_body = $link_data['add_body'];
680 $notice_info = $xpath->query('statusnet:notice_info', $entry);
681 if ($notice_info && ($notice_info->length > 0)) {
682 foreach ($notice_info->item(0)->attributes as $attributes) {
683 if ($attributes->name == "source") {
684 $item["app"] = strip_tags($attributes->textContent);
686 if ($attributes->name == "repeat_of") {
687 $repeat_of = $attributes->textContent;
691 // Is it a repeated post?
692 if (($repeat_of != "") || ($item["verb"] == Activity::SHARE)) {
693 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
694 if (!empty($link_data['add_body'])) {
695 $add_body .= $link_data['add_body'];
699 $item["body"] .= $add_body;
701 // Only add additional data when there is no picture in the post
702 if (!strstr($item["body"], '[/img]')) {
703 $item["body"] = add_page_info_to_body($item["body"]);
706 // Mastodon Content Warning
707 if (($item["verb"] == Activity::POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
708 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
709 if (!empty($clear_text)) {
710 $item['content-warning'] = HTML::toBBCode($clear_text);
714 if (($self != '') && empty($item['protocol'])) {
715 self::fetchSelf($self, $item);
718 if (!empty($item["conversation-href"])) {
719 self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
722 if (isset($item["parent-uri"])) {
723 if (!Item::exists(['uid' => $importer["uid"], 'uri' => $item['parent-uri']])) {
724 if ($related != '') {
725 self::fetchRelated($related, $item["parent-uri"], $importer);
728 Logger::log('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', Logger::DEBUG);
731 $item["parent-uri"] = $item["uri"];
732 $item["gravity"] = GRAVITY_PARENT;
735 if (($item['author-link'] != '') && !empty($item['protocol'])) {
736 $item = Conversation::insert($item);
739 self::$itemlist[] = $item;
743 * Fetch the conversation for posts
745 * @param string $conversation The link to the conversation
746 * @param string $conversation_uri The conversation in "uri" format
748 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
750 private static function fetchConversation($conversation, $conversation_uri)
752 // Ensure that we only store a conversation once in a process
753 if (isset(self::$conv_list[$conversation])) {
757 self::$conv_list[$conversation] = true;
759 $curlResult = Network::curl($conversation, false, ['accept_content' => 'application/atom+xml, text/html']);
761 if (!$curlResult->isSuccess()) {
767 if (stristr($curlResult->getHeader(), 'Content-Type: application/atom+xml')) {
768 $xml = $curlResult->getBody();
772 $doc = new DOMDocument();
773 if (!@$doc->loadHTML($curlResult->getBody())) {
776 $xpath = new DOMXPath($doc);
778 $links = $xpath->query('//link');
781 foreach ($links as $link) {
782 $attribute = self::readAttributes($link);
783 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
784 $file = $attribute['href'];
788 $conversation_atom = Network::curl($attribute['href']);
790 if ($conversation_atom->isSuccess()) {
791 $xml = $conversation_atom->getBody();
801 self::storeConversation($xml, $conversation, $conversation_uri);
805 * Store a feed in several conversation entries
807 * @param string $xml The feed
808 * @param string $conversation conversation
809 * @param string $conversation_uri conversation uri
813 private static function storeConversation($xml, $conversation = '', $conversation_uri = '')
815 $doc = new DOMDocument();
816 @$doc->loadXML($xml);
818 $xpath = new DOMXPath($doc);
819 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
820 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
821 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
823 $entries = $xpath->query('/atom:feed/atom:entry');
825 // Now store the entries
826 foreach ($entries as $entry) {
827 $doc2 = new DOMDocument();
828 $doc2->preserveWhiteSpace = false;
829 $doc2->formatOutput = true;
833 $conv_data['protocol'] = Conversation::PARCEL_SPLIT_CONVERSATION;
834 $conv_data['network'] = Protocol::OSTATUS;
835 $conv_data['uri'] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
837 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
838 if (is_object($inreplyto->item(0))) {
839 foreach ($inreplyto->item(0)->attributes as $attributes) {
840 if ($attributes->name == "ref") {
841 $conv_data['reply-to-uri'] = $attributes->textContent;
846 $conv_data['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
848 $conv = $xpath->query('ostatus:conversation', $entry);
849 if (is_object($conv->item(0))) {
850 foreach ($conv->item(0)->attributes as $attributes) {
851 if ($attributes->name == "ref") {
852 $conv_data['conversation-uri'] = $attributes->textContent;
854 if ($attributes->name == "href") {
855 $conv_data['conversation-href'] = $attributes->textContent;
860 if ($conversation != '') {
861 $conv_data['conversation-uri'] = $conversation;
864 if ($conversation_uri != '') {
865 $conv_data['conversation-uri'] = $conversation_uri;
868 $entry = $doc2->importNode($entry, true);
870 $doc2->appendChild($entry);
872 $conv_data['source'] = $doc2->saveXML();
874 $condition = ['item-uri' => $conv_data['uri'],'protocol' => Conversation::PARCEL_FEED];
875 if (DBA::exists('conversation', $condition)) {
876 Logger::log('Delete deprecated entry for URI '.$conv_data['uri'], Logger::DEBUG);
877 DBA::delete('conversation', ['item-uri' => $conv_data['uri']]);
880 Logger::log('Store conversation data for uri '.$conv_data['uri'], Logger::DEBUG);
881 Conversation::insert($conv_data);
886 * Fetch the own post so that it can be stored later
888 * We want to store the original data for later processing.
889 * This function is meant for cases where we process a feed with multiple entries.
890 * In that case we need to fetch the single posts here.
892 * @param string $self The link to the self item
893 * @param array $item The item array
895 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
897 private static function fetchSelf($self, array &$item)
899 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $self, Conversation::PARCEL_DFRN, Conversation::PARCEL_SALMON];
900 if (DBA::exists('conversation', $condition)) {
901 Logger::log('Conversation '.$item['uri'].' is already stored.', Logger::DEBUG);
905 $curlResult = Network::curl($self);
907 if (!$curlResult->isSuccess()) {
911 // We reformat the XML to make it better readable
912 $doc = new DOMDocument();
913 $doc->loadXML($curlResult->getBody());
914 $doc->preserveWhiteSpace = false;
915 $doc->formatOutput = true;
916 $xml = $doc->saveXML();
918 $item["protocol"] = Conversation::PARCEL_SALMON;
919 $item["source"] = $xml;
921 Logger::log('Conversation '.$item['uri'].' is now fetched.', Logger::DEBUG);
925 * Fetch related posts and processes them
927 * @param string $related The link to the related item
928 * @param string $related_uri The related item in "uri" format
929 * @param array $importer user record of the importing user
931 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
932 * @throws \ImagickException
934 private static function fetchRelated($related, $related_uri, $importer)
936 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, Conversation::PARCEL_DFRN, Conversation::PARCEL_SALMON];
937 $conversation = DBA::selectFirst('conversation', ['source', 'protocol'], $condition);
938 if (DBA::isResult($conversation)) {
940 $xml = $conversation['source'];
941 if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
942 Logger::log('Got valid cached XML for URI '.$related_uri, Logger::DEBUG);
945 if ($conversation['protocol'] == Conversation::PARCEL_SALMON) {
946 Logger::log('Delete invalid cached XML for URI '.$related_uri, Logger::DEBUG);
947 DBA::delete('conversation', ['item-uri' => $related_uri]);
952 $curlResult = Network::curl($related, false, ['accept_content' => 'application/atom+xml, text/html']);
954 if (!$curlResult->isSuccess()) {
960 if (stristr($curlResult->getHeader(), 'Content-Type: application/atom+xml')) {
961 Logger::log('Directly fetched XML for URI ' . $related_uri, Logger::DEBUG);
962 $xml = $curlResult->getBody();
966 $doc = new DOMDocument();
967 if (!@$doc->loadHTML($curlResult->getBody())) {
970 $xpath = new DOMXPath($doc);
974 $links = $xpath->query('//link');
976 foreach ($links as $link) {
977 $attribute = self::readAttributes($link);
978 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
979 $atom_file = $attribute['href'];
982 if ($atom_file != '') {
983 $curlResult = Network::curl($atom_file);
985 if ($curlResult->isSuccess()) {
986 Logger::log('Fetched XML for URI ' . $related_uri, Logger::DEBUG);
987 $xml = $curlResult->getBody();
993 // Workaround for older GNU Social servers
994 if (($xml == '') && strstr($related, '/notice/')) {
995 $curlResult = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related).'.atom');
997 if ($curlResult->isSuccess()) {
998 Logger::log('GNU Social workaround to fetch XML for URI ' . $related_uri, Logger::DEBUG);
999 $xml = $curlResult->getBody();
1003 // Even more worse workaround for GNU Social ;-)
1005 $related_guess = OStatus::convertHref($related_uri);
1006 $curlResult = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related_guess).'.atom');
1008 if ($curlResult->isSuccess()) {
1009 Logger::log('GNU Social workaround 2 to fetch XML for URI ' . $related_uri, Logger::DEBUG);
1010 $xml = $curlResult->getBody();
1014 // Finally we take the data that we fetched from "ostatus:conversation"
1016 $condition = ['item-uri' => $related_uri, 'protocol' => Conversation::PARCEL_SPLIT_CONVERSATION];
1017 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1018 if (DBA::isResult($conversation)) {
1020 Logger::log('Got cached XML from conversation for URI '.$related_uri, Logger::DEBUG);
1021 $xml = $conversation['source'];
1026 self::process($xml, $importer, $contact, $hub, $stored, false);
1028 Logger::log("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, Logger::DEBUG);
1034 * Processes the XML for a repeated post
1036 * @param DOMXPath $xpath The xpath object
1037 * @param object $entry The xml entry that is processed
1038 * @param array $item The item array
1039 * @param array $importer user record of the importing user
1041 * @return array with data from links
1042 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1043 * @throws \ImagickException
1045 private static function processRepeatedItem(DOMXPath $xpath, $entry, array &$item, array $importer)
1047 $activityobject = $xpath->query('activity:object', $entry)->item(0);
1049 if (!is_object($activityobject)) {
1055 $orig_uri = XML::getFirstNodeValue($xpath, 'atom:id/text()', $activityobject);
1057 $links = $xpath->query("atom:link", $activityobject);
1059 $link_data = self::processLinks($links, $item);
1062 $orig_body = XML::getFirstNodeValue($xpath, 'atom:content/text()', $activityobject);
1063 $orig_created = XML::getFirstNodeValue($xpath, 'atom:published/text()', $activityobject);
1064 $orig_edited = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $activityobject);
1066 $orig_author = self::fetchAuthor($xpath, $activityobject, $importer, $dummy, false);
1068 $item["author-name"] = $orig_author["author-name"];
1069 $item["author-link"] = $orig_author["author-link"];
1070 $item["author-id"] = $orig_author["author-id"];
1072 $item["body"] = HTML::toBBCode($orig_body);
1073 $item["created"] = $orig_created;
1074 $item["edited"] = $orig_edited;
1076 $item["uri"] = $orig_uri;
1078 $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $activityobject);
1080 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $activityobject);
1082 // Mastodon Content Warning
1083 if (($item["verb"] == Activity::POST) && $xpath->evaluate('boolean(atom:summary)', $activityobject)) {
1084 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $activityobject);
1085 if (!empty($clear_text)) {
1086 $item['content-warning'] = HTML::toBBCode($clear_text);
1090 $inreplyto = $xpath->query('thr:in-reply-to', $activityobject);
1091 if (is_object($inreplyto->item(0))) {
1092 foreach ($inreplyto->item(0)->attributes as $attributes) {
1093 if ($attributes->name == "ref") {
1094 $item["parent-uri"] = $attributes->textContent;
1103 * Processes links in the XML
1105 * @param object $links The xml data that contain links
1106 * @param array $item The item array
1108 * @return array with data from the links
1110 private static function processLinks($links, array &$item)
1112 $link_data = ['add_body' => '', 'self' => ''];
1114 foreach ($links as $link) {
1115 $attribute = self::readAttributes($link);
1117 if (!empty($attribute['rel']) && !empty($attribute['href'])) {
1118 switch ($attribute['rel']) {
1120 $item["plink"] = $attribute['href'];
1121 if (($item["object-type"] == Activity\ObjectType::QUESTION)
1122 || ($item["object-type"] == Activity\ObjectType::EVENT)
1124 $item["body"] .= add_page_info($attribute['href']);
1127 case "ostatus:conversation":
1128 $link_data['conversation'] = $attribute['href'];
1129 $item['conversation-href'] = $link_data['conversation'];
1130 if (!isset($item['conversation-uri'])) {
1131 $item['conversation-uri'] = $item['conversation-href'];
1135 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
1136 if ($filetype == 'image') {
1137 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1139 if (!empty($item["attach"])) {
1140 $item["attach"] .= ',';
1142 $item["attach"] = '';
1144 if (!isset($attribute['length'])) {
1145 $attribute['length'] = "0";
1147 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.($attribute['title'] ?? '') .'"[/attach]';
1151 if ($item["object-type"] != Activity\ObjectType::BOOKMARK) {
1152 if (!isset($item["parent-uri"])) {
1153 $item["parent-uri"] = $attribute['href'];
1155 $link_data['related'] = $attribute['href'];
1157 $item["body"] .= add_page_info($attribute['href']);
1161 if (empty($item["plink"])) {
1162 $item["plink"] = $attribute['href'];
1164 $link_data['self'] = $attribute['href'];
1173 * Create an url out of an uri
1175 * @param string $href URI in the format "parameter1:parameter1:..."
1177 * @return string URL in the format http(s)://....
1179 public static function convertHref($href)
1181 $elements = explode(":", $href);
1183 if ((count($elements) <= 2) || ($elements[0] != "tag")) {
1187 $server = explode(",", $elements[1]);
1188 $conversation = explode("=", $elements[2]);
1190 if ((count($elements) == 4) && ($elements[2] == "post")) {
1191 return "http://".$server[0]."/notice/".$elements[3];
1194 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1197 if ($elements[3] == "objectType=thread") {
1198 return "http://".$server[0]."/conversation/".$conversation[1];
1200 return "http://".$server[0]."/notice/".$conversation[1];
1205 * Checks if the current post is a reshare
1207 * @param array $item The item array of thw post
1209 * @return string The guid if the post is a reshare
1211 private static function getResharedGuid(array $item)
1213 $reshared = Item::getShareArray($item);
1214 if (empty($reshared['guid']) || !empty($reshared['comment'])) {
1218 return $reshared['guid'];
1222 * Cleans the body of a post if it contains picture links
1224 * @param string $body The body
1226 * @return string The cleaned body
1227 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1229 private static function formatPicturePost($body)
1231 $siteinfo = BBCode::getAttachedData($body);
1233 if (($siteinfo["type"] == "photo") && (!empty($siteinfo["preview"]) || !empty($siteinfo["image"]))) {
1234 if (isset($siteinfo["preview"])) {
1235 $preview = $siteinfo["preview"];
1237 $preview = $siteinfo["image"];
1240 // Is it a remote picture? Then make a smaller preview here
1241 $preview = ProxyUtils::proxifyUrl($preview, false, ProxyUtils::SIZE_SMALL);
1243 // Is it a local picture? Then make it smaller here
1244 $preview = str_replace(["-0.jpg", "-0.png"], ["-2.jpg", "-2.png"], $preview);
1245 $preview = str_replace(["-1.jpg", "-1.png"], ["-2.jpg", "-2.png"], $preview);
1247 if (isset($siteinfo["url"])) {
1248 $url = $siteinfo["url"];
1250 $url = $siteinfo["image"];
1253 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1260 * Adds the header elements to the XML document
1262 * @param DOMDocument $doc XML document
1263 * @param array $owner Contact data of the poster
1264 * @param string $filter The related feed filter (activity, posts or comments)
1265 * @param bool $feed_mode Behave like a regular feed for users if true
1267 * @return object header root element
1268 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1270 private static function addHeader(DOMDocument $doc, array $owner, $filter, $feed_mode = false)
1272 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
1273 $doc->appendChild($root);
1275 $root->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
1276 $root->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
1277 $root->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
1278 $root->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
1279 $root->setAttribute("xmlns:poco", ActivityNamespace::POCO);
1280 $root->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
1281 $root->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
1282 $root->setAttribute("xmlns:mastodon", ActivityNamespace::MASTODON);
1285 $selfUri = '/feed/' . $owner["nick"] . '/';
1288 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
1289 $selfUri .= $filter;
1292 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
1295 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
1296 $selfUri .= $filter;
1301 $selfUri = "/dfrn_poll/" . $owner["nick"];
1304 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
1305 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1306 XML::addElement($doc, $root, "id", DI::baseUrl() . "/profile/" . $owner["nick"]);
1307 XML::addElement($doc, $root, "title", $title);
1308 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], DI::config()->get('config', 'sitename')));
1309 XML::addElement($doc, $root, "logo", $owner["photo"]);
1310 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1312 $author = self::addAuthor($doc, $owner);
1313 $root->appendChild($author);
1315 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1316 XML::addElement($doc, $root, "link", "", $attributes);
1318 /// @TODO We have to find out what this is
1319 /// $attributes = array("href" => DI::baseUrl()."/sup",
1320 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1321 /// "type" => "application/json");
1322 /// XML::addElement($doc, $root, "link", "", $attributes);
1324 self::hublinks($doc, $root, $owner["nick"]);
1326 $attributes = ["href" => DI::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "salmon"];
1327 XML::addElement($doc, $root, "link", "", $attributes);
1329 $attributes = ["href" => DI::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies"];
1330 XML::addElement($doc, $root, "link", "", $attributes);
1332 $attributes = ["href" => DI::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention"];
1333 XML::addElement($doc, $root, "link", "", $attributes);
1335 $attributes = ["href" => DI::baseUrl() . $selfUri, "rel" => "self", "type" => "application/atom+xml"];
1336 XML::addElement($doc, $root, "link", "", $attributes);
1338 if ($owner['account-type'] == Contact::TYPE_COMMUNITY) {
1339 $condition = ['uid' => $owner['uid'], 'self' => false, 'pending' => false,
1340 'archive' => false, 'hidden' => false, 'blocked' => false];
1341 $members = DBA::count('contact', $condition);
1342 XML::addElement($doc, $root, "statusnet:group_info", "", ["member_count" => $members]);
1349 * Add the link to the push hubs to the XML document
1351 * @param DOMDocument $doc XML document
1352 * @param object $root XML root element where the hub links are added
1353 * @param object $nick nick
1355 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1357 public static function hublinks(DOMDocument $doc, $root, $nick)
1359 $h = DI::baseUrl() . '/pubsubhubbub/'.$nick;
1360 XML::addElement($doc, $root, "link", "", ["href" => $h, "rel" => "hub"]);
1364 * Adds attachment data to the XML document
1366 * @param DOMDocument $doc XML document
1367 * @param object $root XML root element where the hub links are added
1368 * @param array $item Data of the item that is to be posted
1370 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1372 private static function getAttachment(DOMDocument $doc, $root, $item)
1374 $siteinfo = BBCode::getAttachedData($item["body"]);
1376 switch ($siteinfo["type"]) {
1378 if (!empty($siteinfo["image"])) {
1379 $imgdata = Images::getInfoFromURLCached($siteinfo["image"]);
1381 $attributes = ["rel" => "enclosure",
1382 "href" => $siteinfo["image"],
1383 "type" => $imgdata["mime"],
1384 "length" => intval($imgdata["size"])];
1385 XML::addElement($doc, $root, "link", "", $attributes);
1390 $attributes = ["rel" => "enclosure",
1391 "href" => $siteinfo["url"],
1392 "type" => "text/html; charset=UTF-8",
1394 "title" => ($siteinfo["title"] ?? '') ?: $siteinfo["url"],
1396 XML::addElement($doc, $root, "link", "", $attributes);
1402 if (!DI::config()->get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1403 $imgdata = Images::getInfoFromURLCached($siteinfo["image"]);
1405 $attributes = ["rel" => "enclosure",
1406 "href" => $siteinfo["image"],
1407 "type" => $imgdata["mime"],
1408 "length" => intval($imgdata["size"])];
1410 XML::addElement($doc, $root, "link", "", $attributes);
1414 $arr = explode('[/attach],', $item['attach']);
1416 foreach ($arr as $r) {
1418 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1420 $attributes = ["rel" => "enclosure",
1421 "href" => $matches[1],
1422 "type" => $matches[3]];
1424 if (intval($matches[2])) {
1425 $attributes["length"] = intval($matches[2]);
1427 if (trim($matches[4]) != "") {
1428 $attributes["title"] = trim($matches[4]);
1430 XML::addElement($doc, $root, "link", "", $attributes);
1437 * Adds the author element to the XML document
1439 * @param DOMDocument $doc XML document
1440 * @param array $owner Contact data of the poster
1441 * @param bool $show_profile Whether to show profile
1443 * @return \DOMElement author element
1444 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1446 private static function addAuthor(DOMDocument $doc, array $owner, $show_profile = true)
1448 $profile = DBA::selectFirst('profile', ['homepage', 'publish'], ['uid' => $owner['uid']]);
1449 $author = $doc->createElement("author");
1450 XML::addElement($doc, $author, "id", $owner["url"]);
1451 if ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
1452 XML::addElement($doc, $author, "activity:object-type", Activity\ObjectType::GROUP);
1454 XML::addElement($doc, $author, "activity:object-type", Activity\ObjectType::PERSON);
1456 XML::addElement($doc, $author, "uri", $owner["url"]);
1457 XML::addElement($doc, $author, "name", $owner["nick"]);
1458 XML::addElement($doc, $author, "email", $owner["addr"]);
1459 if ($show_profile) {
1460 XML::addElement($doc, $author, "summary", BBCode::convert($owner["about"], false, 7));
1463 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $owner["url"]];
1464 XML::addElement($doc, $author, "link", "", $attributes);
1468 "type" => "image/jpeg", // To-Do?
1469 "media:width" => 300,
1470 "media:height" => 300,
1471 "href" => $owner["photo"]];
1472 XML::addElement($doc, $author, "link", "", $attributes);
1474 if (isset($owner["thumb"])) {
1477 "type" => "image/jpeg", // To-Do?
1478 "media:width" => 80,
1479 "media:height" => 80,
1480 "href" => $owner["thumb"]];
1481 XML::addElement($doc, $author, "link", "", $attributes);
1484 XML::addElement($doc, $author, "poco:preferredUsername", $owner["nick"]);
1485 XML::addElement($doc, $author, "poco:displayName", $owner["name"]);
1486 if ($show_profile) {
1487 XML::addElement($doc, $author, "poco:note", BBCode::convert($owner["about"], false, 7));
1489 if (trim($owner["location"]) != "") {
1490 $element = $doc->createElement("poco:address");
1491 XML::addElement($doc, $element, "poco:formatted", $owner["location"]);
1492 $author->appendChild($element);
1496 if (DBA::isResult($profile) && !$show_profile) {
1497 if (trim($profile["homepage"]) != "") {
1498 $urls = $doc->createElement("poco:urls");
1499 XML::addElement($doc, $urls, "poco:type", "homepage");
1500 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
1501 XML::addElement($doc, $urls, "poco:primary", "true");
1502 $author->appendChild($urls);
1505 XML::addElement($doc, $author, "followers", "", ["url" => DI::baseUrl() . "/profile/" . $owner["nick"] . "/contacts/followers"]);
1506 XML::addElement($doc, $author, "statusnet:profile_info", "", ["local_id" => $owner["uid"]]);
1508 if ($profile["publish"]) {
1509 XML::addElement($doc, $author, "mastodon:scope", "public");
1517 * @TODO Picture attachments should look like this:
1518 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1519 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1523 * Returns the given activity if present - otherwise returns the "post" activity
1525 * @param array $item Data of the item that is to be posted
1527 * @return string activity
1529 private static function constructVerb(array $item)
1531 if (!empty($item['verb'])) {
1532 return $item['verb'];
1535 return Activity::POST;
1539 * Returns the given object type if present - otherwise returns the "note" object type
1541 * @param array $item Data of the item that is to be posted
1543 * @return string Object type
1545 private static function constructObjecttype(array $item)
1547 if (!empty($item['object-type']) && in_array($item['object-type'], [Activity\ObjectType::NOTE, Activity\ObjectType::COMMENT])) {
1548 return $item['object-type'];
1551 return Activity\ObjectType::NOTE;
1555 * Adds an entry element to the XML document
1557 * @param DOMDocument $doc XML document
1558 * @param array $item Data of the item that is to be posted
1559 * @param array $owner Contact data of the poster
1560 * @param bool $toplevel optional default false
1561 * @param bool $feed_mode Behave like a regular feed for users if true
1563 * @return \DOMElement Entry element
1564 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1565 * @throws \ImagickException
1567 private static function entry(DOMDocument $doc, array $item, array $owner, $toplevel = false, $feed_mode = false)
1571 $repeated_guid = self::getResharedGuid($item);
1572 if ($repeated_guid != "") {
1573 $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel);
1580 if ($item["verb"] == Activity::LIKE) {
1581 return self::likeEntry($doc, $item, $owner, $toplevel);
1582 } elseif (in_array($item["verb"], [Activity::FOLLOW, Activity::O_UNFOLLOW])) {
1583 return self::followEntry($doc, $item, $owner, $toplevel);
1585 return self::noteEntry($doc, $item, $owner, $toplevel, $feed_mode);
1590 * Adds a source entry to the XML document
1592 * @param DOMDocument $doc XML document
1593 * @param array $contact Array of the contact that is added
1595 * @return \DOMElement Source element
1596 * @throws \Exception
1598 private static function sourceEntry(DOMDocument $doc, array $contact)
1600 $source = $doc->createElement("source");
1601 XML::addElement($doc, $source, "id", $contact["poll"]);
1602 XML::addElement($doc, $source, "title", $contact["name"]);
1603 XML::addElement($doc, $source, "link", "", ["rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]]);
1604 XML::addElement($doc, $source, "link", "", ["rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]]);
1605 XML::addElement($doc, $source, "icon", $contact["photo"]);
1606 XML::addElement($doc, $source, "updated", DateTimeFormat::utc($contact["success_update"]."+00:00", DateTimeFormat::ATOM));
1612 * Fetches contact data from the contact or the gcontact table
1614 * @param string $url URL of the contact
1615 * @param array $owner Contact data of the poster
1617 * @return array Contact array
1618 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1619 * @throws \ImagickException
1621 private static function contactEntry($url, array $owner)
1624 "SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1625 DBA::escape(Strings::normaliseLink($url)),
1626 intval($owner["uid"])
1628 if (DBA::isResult($r)) {
1630 $contact["uid"] = -1;
1633 if (!DBA::isResult($r)) {
1634 $gcontact = DBA::selectFirst('gcontact', [], ['nurl' => Strings::normaliseLink($url)]);
1635 if (DBA::isResult($r)) {
1636 $contact = $gcontact;
1637 $contact["uid"] = -1;
1638 $contact["success_update"] = $contact["updated"];
1642 if (!DBA::isResult($r)) {
1646 if (!isset($contact["poll"])) {
1647 $data = Probe::uri($url);
1648 $contact["poll"] = $data["poll"];
1650 if (!$contact["alias"]) {
1651 $contact["alias"] = $data["alias"];
1655 if (!isset($contact["alias"])) {
1656 $contact["alias"] = $contact["url"];
1659 $contact['account-type'] = $owner['account-type'];
1665 * Adds an entry element with reshared content
1667 * @param DOMDocument $doc XML document
1668 * @param array $item Data of the item that is to be posted
1669 * @param array $owner Contact data of the poster
1670 * @param string $repeated_guid guid
1671 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1673 * @return bool Entry element
1674 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1675 * @throws \ImagickException
1677 private static function reshareEntry(DOMDocument $doc, array $item, array $owner, $repeated_guid, $toplevel)
1679 if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1680 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1683 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1685 $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => [Item::PUBLIC, Item::UNLISTED],
1686 'network' => [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS]];
1687 $repeated_item = Item::selectFirst([], $condition);
1688 if (!DBA::isResult($repeated_item)) {
1692 $contact = self::contactEntry($repeated_item['author-link'], $owner);
1694 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1696 self::entryContent($doc, $entry, $item, $owner, $title, Activity::SHARE, false);
1698 $as_object = $doc->createElement("activity:object");
1700 XML::addElement($doc, $as_object, "activity:object-type", ActivityNamespace::ACTIVITY_SCHEMA . "activity");
1702 self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false);
1704 $author = self::addAuthor($doc, $contact, false);
1705 $as_object->appendChild($author);
1707 $as_object2 = $doc->createElement("activity:object");
1709 XML::addElement($doc, $as_object2, "activity:object-type", self::constructObjecttype($repeated_item));
1711 $title = sprintf("New comment by %s", $contact["nick"]);
1713 self::entryContent($doc, $as_object2, $repeated_item, $owner, $title);
1715 $as_object->appendChild($as_object2);
1717 self::entryFooter($doc, $as_object, $item, $owner, false);
1719 $source = self::sourceEntry($doc, $contact);
1721 $as_object->appendChild($source);
1723 $entry->appendChild($as_object);
1725 self::entryFooter($doc, $entry, $item, $owner);
1731 * Adds an entry element with a "like"
1733 * @param DOMDocument $doc XML document
1734 * @param array $item Data of the item that is to be posted
1735 * @param array $owner Contact data of the poster
1736 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1738 * @return \DOMElement Entry element with "like"
1739 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1740 * @throws \ImagickException
1742 private static function likeEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1744 if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1745 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1748 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1750 $verb = ActivityNamespace::ACTIVITY_SCHEMA . "favorite";
1751 self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false);
1753 $parent = Item::selectFirst([], ['uri' => $item["thr-parent"], 'uid' => $item["uid"]]);
1754 if (DBA::isResult($parent)) {
1755 $as_object = $doc->createElement("activity:object");
1757 XML::addElement($doc, $as_object, "activity:object-type", self::constructObjecttype($parent));
1759 self::entryContent($doc, $as_object, $parent, $owner, "New entry");
1761 $entry->appendChild($as_object);
1764 self::entryFooter($doc, $entry, $item, $owner);
1770 * Adds the person object element to the XML document
1772 * @param DOMDocument $doc XML document
1773 * @param array $owner Contact data of the poster
1774 * @param array $contact Contact data of the target
1776 * @return object author element
1778 private static function addPersonObject(DOMDocument $doc, array $owner, array $contact)
1780 $object = $doc->createElement("activity:object");
1781 XML::addElement($doc, $object, "activity:object-type", Activity\ObjectType::PERSON);
1783 if ($contact['network'] == Protocol::PHANTOM) {
1784 XML::addElement($doc, $object, "id", $contact['url']);
1788 XML::addElement($doc, $object, "id", $contact["alias"]);
1789 XML::addElement($doc, $object, "title", $contact["nick"]);
1791 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $contact["url"]];
1792 XML::addElement($doc, $object, "link", "", $attributes);
1796 "type" => "image/jpeg", // To-Do?
1797 "media:width" => 300,
1798 "media:height" => 300,
1799 "href" => $contact["photo"]];
1800 XML::addElement($doc, $object, "link", "", $attributes);
1802 XML::addElement($doc, $object, "poco:preferredUsername", $contact["nick"]);
1803 XML::addElement($doc, $object, "poco:displayName", $contact["name"]);
1805 if (trim($contact["location"]) != "") {
1806 $element = $doc->createElement("poco:address");
1807 XML::addElement($doc, $element, "poco:formatted", $contact["location"]);
1808 $object->appendChild($element);
1815 * Adds a follow/unfollow entry element
1817 * @param DOMDocument $doc XML document
1818 * @param array $item Data of the follow/unfollow message
1819 * @param array $owner Contact data of the poster
1820 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1822 * @return \DOMElement Entry element
1823 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1824 * @throws \ImagickException
1826 private static function followEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1828 $item["id"] = $item["parent"] = 0;
1829 $item["created"] = $item["edited"] = date("c");
1830 $item["private"] = Item::PRIVATE;
1832 $contact = Probe::uri($item['follow']);
1834 if ($contact['alias'] == '') {
1835 $contact['alias'] = $contact["url"];
1837 $item['follow'] = $contact['alias'];
1840 $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($contact["url"])];
1841 $user_contact = DBA::selectFirst('contact', ['id'], $condition);
1843 if (DBA::isResult($user_contact)) {
1844 $connect_id = $user_contact['id'];
1849 if ($item['verb'] == Activity::FOLLOW) {
1850 $message = DI::l10n()->t('%s is now following %s.');
1851 $title = DI::l10n()->t('following');
1852 $action = "subscription";
1854 $message = DI::l10n()->t('%s stopped following %s.');
1855 $title = DI::l10n()->t('stopped following');
1856 $action = "unfollow";
1859 $item["uri"] = $item['parent-uri'] = $item['thr-parent']
1860 = 'tag:' . DI::baseUrl()->getHostname().
1861 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1862 ':person:'.$connect_id.':'.$item['created'];
1864 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1866 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1868 self::entryContent($doc, $entry, $item, $owner, $title);
1870 $object = self::addPersonObject($doc, $owner, $contact);
1871 $entry->appendChild($object);
1873 self::entryFooter($doc, $entry, $item, $owner);
1879 * Adds a regular entry element
1881 * @param DOMDocument $doc XML document
1882 * @param array $item Data of the item that is to be posted
1883 * @param array $owner Contact data of the poster
1884 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1885 * @param bool $feed_mode Behave like a regular feed for users if true
1887 * @return \DOMElement Entry element
1888 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1889 * @throws \ImagickException
1891 private static function noteEntry(DOMDocument $doc, array $item, array $owner, $toplevel, $feed_mode)
1893 if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1894 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1898 if (!empty($item['title'])) {
1899 $title = BBCode::convert($item['title'], false, 7);
1901 $title = sprintf("New note by %s", $owner["nick"]);
1904 $title = sprintf("New comment by %s", $owner["nick"]);
1907 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1909 XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::NOTE);
1911 self::entryContent($doc, $entry, $item, $owner, $title, '', true, $feed_mode);
1913 self::entryFooter($doc, $entry, $item, $owner, !$feed_mode, $feed_mode);
1919 * Adds a header element to the XML document
1921 * @param DOMDocument $doc XML document
1922 * @param array $owner Contact data of the poster
1923 * @param array $item
1924 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1926 * @return \DOMElement The entry element where the elements are added
1927 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1928 * @throws \ImagickException
1930 private static function entryHeader(DOMDocument $doc, array $owner, array $item, $toplevel)
1933 $entry = $doc->createElement("entry");
1935 if ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
1936 $contact = self::contactEntry($item['author-link'], $owner);
1937 $author = self::addAuthor($doc, $contact, false);
1938 $entry->appendChild($author);
1941 $entry = $doc->createElementNS(ActivityNamespace::ATOM1, "entry");
1943 $entry->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
1944 $entry->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
1945 $entry->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
1946 $entry->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
1947 $entry->setAttribute("xmlns:poco", ActivityNamespace::POCO);
1948 $entry->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
1949 $entry->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
1950 $entry->setAttribute("xmlns:mastodon", ActivityNamespace::MASTODON);
1952 $author = self::addAuthor($doc, $owner);
1953 $entry->appendChild($author);
1960 * Adds elements to the XML document
1962 * @param DOMDocument $doc XML document
1963 * @param \DOMElement $entry Entry element where the content is added
1964 * @param array $item Data of the item that is to be posted
1965 * @param array $owner Contact data of the poster
1966 * @param string $title Title for the post
1967 * @param string $verb The activity verb
1968 * @param bool $complete Add the "status_net" element?
1969 * @param bool $feed_mode Behave like a regular feed for users if true
1971 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1973 private static function entryContent(DOMDocument $doc, \DOMElement $entry, array $item, array $owner, $title, $verb = "", $complete = true, $feed_mode = false)
1976 $verb = self::constructVerb($item);
1979 XML::addElement($doc, $entry, "id", $item["uri"]);
1980 XML::addElement($doc, $entry, "title", html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1982 $body = self::formatPicturePost($item['body']);
1984 if (!empty($item['title']) && !$feed_mode) {
1985 $body = "[b]".$item['title']."[/b]\n\n".$body;
1988 $body = BBCode::convert($body, false, 7);
1990 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1992 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1993 "href" => DI::baseUrl()."/display/".$item["guid"]]
1996 if (!$feed_mode && $complete && ($item["id"] > 0)) {
1997 XML::addElement($doc, $entry, "status_net", "", ["notice_id" => $item["id"]]);
2001 XML::addElement($doc, $entry, "activity:verb", $verb);
2004 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
2005 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
2009 * Adds the elements at the foot of an entry to the XML document
2011 * @param DOMDocument $doc XML document
2012 * @param object $entry The entry element where the elements are added
2013 * @param array $item Data of the item that is to be posted
2014 * @param array $owner Contact data of the poster
2015 * @param bool $complete default true
2016 * @param bool $feed_mode Behave like a regular feed for users if true
2018 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2020 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner, $complete = true, $feed_mode = false)
2024 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
2025 $parent = Item::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item["parent"]]);
2026 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
2028 $thrparent = Item::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $parent_item]);
2030 if (DBA::isResult($thrparent)) {
2031 $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
2032 $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
2033 $parent_plink = $thrparent["plink"];
2035 $mentioned[$parent["author-link"]] = $parent["author-link"];
2036 $mentioned[$parent["owner-link"]] = $parent["owner-link"];
2037 $parent_plink = DI::baseUrl()."/display/".$parent["guid"];
2041 "ref" => $parent_item,
2042 "href" => $parent_plink];
2043 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
2047 "href" => $parent_plink];
2048 XML::addElement($doc, $entry, "link", "", $attributes);
2051 if (!$feed_mode && (intval($item["parent"]) > 0)) {
2052 $conversation_href = $conversation_uri = str_replace('/objects/', '/context/', $item['parent-uri']);
2054 if (isset($parent_item)) {
2055 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $parent_item]);
2056 if (DBA::isResult($conversation)) {
2057 if ($conversation['conversation-uri'] != '') {
2058 $conversation_uri = $conversation['conversation-uri'];
2060 if ($conversation['conversation-href'] != '') {
2061 $conversation_href = $conversation['conversation-href'];
2066 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:conversation", "href" => $conversation_href]);
2069 "href" => $conversation_href,
2070 "local_id" => $item["parent"],
2071 "ref" => $conversation_uri];
2073 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
2076 $tags = item::getFeedTags($item);
2079 foreach ($tags as $t) {
2081 $mentioned[$t[1]] = $t[1];
2086 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2088 foreach ($mentioned as $mention) {
2089 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2090 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2092 $mentioned = $newmentions;
2094 foreach ($mentioned as $mention) {
2095 $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($mention)];
2096 $contact = DBA::selectFirst('contact', ['forum', 'prv', 'self', 'contact-type'], $condition);
2097 if ($contact["forum"] || $contact["prv"] || ($owner['contact-type'] == Contact::TYPE_COMMUNITY) ||
2098 ($contact['self'] && ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY))) {
2099 XML::addElement($doc, $entry, "link", "",
2101 "rel" => "mentioned",
2102 "ostatus:object-type" => Activity\ObjectType::GROUP,
2106 XML::addElement($doc, $entry, "link", "",
2108 "rel" => "mentioned",
2109 "ostatus:object-type" => Activity\ObjectType::PERSON,
2115 if ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
2116 XML::addElement($doc, $entry, "link", "", [
2117 "rel" => "mentioned",
2118 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/group",
2119 "href" => $owner['url']
2123 if (($item['private'] != Item::PRIVATE) && !$feed_mode) {
2124 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:attention",
2125 "href" => "http://activityschema.org/collection/public"]);
2126 XML::addElement($doc, $entry, "link", "", ["rel" => "mentioned",
2127 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2128 "href" => "http://activityschema.org/collection/public"]);
2129 XML::addElement($doc, $entry, "mastodon:scope", "public");
2133 foreach ($tags as $t) {
2135 XML::addElement($doc, $entry, "category", "", ["term" => $t[2]]);
2140 self::getAttachment($doc, $entry, $item);
2142 if ($complete && ($item["id"] > 0)) {
2143 $app = $item["app"];
2148 $attributes = ["local_id" => $item["id"], "source" => $app];
2150 if (isset($parent["id"])) {
2151 $attributes["repeat_of"] = $parent["id"];
2154 if ($item["coord"] != "") {
2155 XML::addElement($doc, $entry, "georss:point", $item["coord"]);
2158 XML::addElement($doc, $entry, "statusnet:notice_info", "", $attributes);
2163 * Creates the XML feed for a given nickname
2165 * Supported filters:
2166 * - activity (default): all the public posts
2167 * - posts: all the public top-level posts
2168 * - comments: all the public replies
2170 * Updates the provided last_update parameter if the result comes from the
2171 * cache or it is empty
2173 * @param string $owner_nick Nickname of the feed owner
2174 * @param string $last_update Date of the last update
2175 * @param integer $max_items Number of maximum items to fetch
2176 * @param string $filter Feed items filter (activity, posts or comments)
2177 * @param boolean $nocache Wether to bypass caching
2178 * @param boolean $feed_mode Behave like a regular feed for users if true
2180 * @return string XML feed
2181 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2182 * @throws \ImagickException
2184 public static function feed($owner_nick, &$last_update, $max_items = 300, $filter = 'activity', $nocache = false, $feed_mode = false)
2186 $stamp = microtime(true);
2188 $owner = User::getOwnerDataByNick($owner_nick);
2193 $cachekey = "ostatus:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
2195 $previous_created = $last_update;
2197 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
2198 if ((time() - strtotime($owner['last-item'])) < 15*60) {
2199 $result = DI::cache()->get($cachekey);
2200 if (!$nocache && !is_null($result)) {
2201 Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', Logger::DEBUG);
2202 $last_update = $result['last_update'];
2203 return $result['feed'];
2207 if (!strlen($last_update)) {
2208 $last_update = 'now -30 days';
2211 $check_date = DateTimeFormat::utc($last_update);
2212 $authorid = Contact::getIdForURL($owner["url"], 0, true);
2214 $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted`
2215 AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?)",
2216 $owner["uid"], $check_date, Item::PRIVATE, Protocol::OSTATUS, Protocol::DFRN];
2218 if ($filter === 'comments') {
2219 $condition[0] .= " AND `object-type` = ? ";
2220 $condition[] = Activity\ObjectType::COMMENT;
2223 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
2224 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
2225 $condition[] = $owner["id"];
2226 $condition[] = $authorid;
2229 $params = ['order' => ['received' => true], 'limit' => $max_items];
2231 if ($filter === 'posts') {
2232 $ret = Item::selectThread([], $condition, $params);
2234 $ret = Item::select([], $condition, $params);
2237 $items = Item::inArray($ret);
2239 $doc = new DOMDocument('1.0', 'utf-8');
2240 $doc->formatOutput = true;
2242 $root = self::addHeader($doc, $owner, $filter, $feed_mode);
2244 foreach ($items as $item) {
2245 if (DI::config()->get('system', 'ostatus_debug')) {
2246 $item['body'] .= '🍼';
2249 $entry = self::entry($doc, $item, $owner, false, $feed_mode);
2250 $root->appendChild($entry);
2252 if ($last_update < $item['created']) {
2253 $last_update = $item['created'];
2257 $feeddata = trim($doc->saveXML());
2259 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
2260 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
2262 Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, Logger::DEBUG);
2268 * Creates the XML for a salmon message
2270 * @param array $item Data of the item that is to be posted
2271 * @param array $owner Contact data of the poster
2273 * @return string XML for the salmon
2274 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2275 * @throws \ImagickException
2277 public static function salmon(array $item, array $owner)
2279 $doc = new DOMDocument('1.0', 'utf-8');
2280 $doc->formatOutput = true;
2282 if (DI::config()->get('system', 'ostatus_debug')) {
2283 $item['body'] .= '🐟';
2286 $entry = self::entry($doc, $item, $owner, true);
2288 $doc->appendChild($entry);
2290 return trim($doc->saveXML());
2294 * Checks if the given contact url does support OStatus
2296 * @param string $url profile url
2297 * @param boolean $update Update the profile
2299 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2300 * @throws \ImagickException
2302 public static function isSupportedByContactUrl($url, $update = false)
2304 $probe = Probe::uri($url, Protocol::OSTATUS, 0, !$update);
2305 return $probe['network'] == Protocol::OSTATUS;