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\ItemURI;
39 use Friendica\Model\Term;
40 use Friendica\Model\User;
41 use Friendica\Network\Probe;
42 use Friendica\Util\DateTimeFormat;
43 use Friendica\Util\Images;
44 use Friendica\Util\Network;
45 use Friendica\Util\Proxy as ProxyUtils;
46 use Friendica\Util\Strings;
47 use Friendica\Util\XML;
49 require_once 'mod/share.php';
50 require_once 'include/api.php';
53 * This class contain functions for the OStatus protocol
57 private static $itemlist;
58 private static $conv_list = [];
63 * @param DOMXPath $xpath The xpath object
64 * @param object $context The xml context of the author details
65 * @param array $importer user record of the importing user
66 * @param array $contact Called by reference, will contain the fetched contact
67 * @param bool $onlyfetch Only fetch the header without updating the contact entries
69 * @return array Array of author related entries for the item
70 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
71 * @throws \ImagickException
73 private static function fetchAuthor(DOMXPath $xpath, $context, array $importer, array &$contact = null, $onlyfetch)
76 $author["author-link"] = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
77 $author["author-name"] = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $context);
78 $addr = XML::getFirstNodeValue($xpath, 'atom:author/atom:email/text()', $context);
80 $aliaslink = $author["author-link"];
82 $alternate_item = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0);
83 if (is_object($alternate_item)) {
84 foreach ($alternate_item->attributes as $attributes) {
85 if (($attributes->name == "href") && ($attributes->textContent != "")) {
86 $author["author-link"] = $attributes->textContent;
90 $author["author-id"] = Contact::getIdForURL($author["author-link"]);
92 $author['contact-id'] = ($contact['id'] ?? 0) ?: $author['author-id'];
97 This here would be better, but we would get problems with contacts from the statusnet addon
98 This is kept here as a reminder for the future
100 $cid = Contact::getIdForURL($author["author-link"], $importer["uid"]);
102 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
105 if ($aliaslink != '') {
106 $condition = ["`uid` = ? AND `alias` = ? AND `network` != ? AND `rel` IN (?, ?)",
107 $importer["uid"], $aliaslink, Protocol::STATUSNET,
108 Contact::SHARING, Contact::FRIEND];
109 $contact = DBA::selectFirst('contact', [], $condition);
112 if (!DBA::isResult($contact) && $author["author-link"] != '') {
113 if ($aliaslink == "") {
114 $aliaslink = $author["author-link"];
117 $condition = ["`uid` = ? AND `nurl` IN (?, ?) AND `network` != ? AND `rel` IN (?, ?)",
118 $importer["uid"], Strings::normaliseLink($author["author-link"]), Strings::normaliseLink($aliaslink),
119 Protocol::STATUSNET, Contact::SHARING, Contact::FRIEND];
120 $contact = DBA::selectFirst('contact', [], $condition);
123 if (!DBA::isResult($contact) && ($addr != '')) {
124 $condition = ["`uid` = ? AND `addr` = ? AND `network` != ? AND `rel` IN (?, ?)",
125 $importer["uid"], $addr, Protocol::STATUSNET,
126 Contact::SHARING, Contact::FRIEND];
127 $contact = DBA::selectFirst('contact', [], $condition);
130 if (DBA::isResult($contact)) {
131 if ($contact['blocked']) {
133 } elseif (!empty(APContact::getByURL($contact['url'], false))) {
134 ActivityPub\Receiver::switchContact($contact['id'], $importer['uid'], $contact['url']);
136 $author["contact-id"] = $contact["id"];
140 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
141 foreach ($avatars as $avatar) {
144 foreach ($avatar->attributes as $attributes) {
145 if ($attributes->name == "href") {
146 $href = $attributes->textContent;
148 if ($attributes->name == "width") {
149 $width = $attributes->textContent;
153 $avatarlist[$width] = $href;
156 if (count($avatarlist) > 0) {
158 $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
161 $displayname = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
162 if ($displayname != "") {
163 $author["author-name"] = $displayname;
166 $author["owner-id"] = $author["author-id"];
168 // Only update the contacts if it is an OStatus contact
169 if (DBA::isResult($contact) && ($contact['id'] > 0) && !$onlyfetch && ($contact["network"] == Protocol::OSTATUS)) {
171 // Update contact data
173 unset($current['name-date']);
175 // This query doesn't seem to work
176 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
178 // $contact["notify"] = $value;
180 // This query doesn't seem to work as well - I hate these queries
181 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
183 // $contact["poll"] = $value;
185 $contact['url'] = $author["author-link"];
186 $contact['nurl'] = Strings::normaliseLink($contact['url']);
188 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
190 $contact["alias"] = $value;
193 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
195 $contact["name"] = $value;
198 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()', $context);
200 $contact["nick"] = $value;
203 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()', $context);
205 $contact["about"] = HTML::toBBCode($value);
208 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()', $context);
210 $contact["location"] = $value;
213 $contact['name-date'] = DateTimeFormat::utcNow();
215 DBA::update('contact', $contact, ['id' => $contact["id"]], $current);
217 if (!empty($author["author-avatar"]) && ($author["author-avatar"] != $current['avatar'])) {
218 Logger::log("Update profile picture for contact ".$contact["id"], Logger::DEBUG);
219 Contact::updateAvatar($author["author-avatar"], $importer["uid"], $contact["id"]);
222 // Ensure that we are having this contact (with uid=0)
223 $cid = Contact::getIdForURL($aliaslink, 0, true);
226 $fields = ['url', 'nurl', 'name', 'nick', 'alias', 'about', 'location'];
227 $old_contact = DBA::selectFirst('contact', $fields, ['id' => $cid]);
229 // Update it with the current values
230 $fields = ['url' => $author["author-link"], 'name' => $contact["name"],
231 'nurl' => Strings::normaliseLink($author["author-link"]),
232 'nick' => $contact["nick"], 'alias' => $contact["alias"],
233 'about' => $contact["about"], 'location' => $contact["location"],
234 'success_update' => DateTimeFormat::utcNow(), 'last-update' => DateTimeFormat::utcNow()];
236 DBA::update('contact', $fields, ['id' => $cid], $old_contact);
239 if (!empty($author["author-avatar"])) {
240 Contact::updateAvatar($author["author-avatar"], 0, $cid);
244 $contact["generation"] = 2;
245 $contact["hide"] = false; // OStatus contacts are never hidden
246 if (!empty($author["author-avatar"])) {
247 $contact["photo"] = $author["author-avatar"];
249 $gcid = GContact::update($contact);
251 GContact::link($gcid, $contact["uid"], $contact["id"]);
252 } elseif (empty($contact["network"]) || ($contact["network"] != Protocol::DFRN)) {
260 * Fetches author data from a given XML string
262 * @param string $xml The XML
263 * @param array $importer user record of the importing user
265 * @return array Array of author related entries for the item
266 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
267 * @throws \ImagickException
269 public static function salmonAuthor($xml, array $importer)
275 $doc = new DOMDocument();
276 @$doc->loadXML($xml);
278 $xpath = new DOMXPath($doc);
279 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
280 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
281 $xpath->registerNamespace('georss', ActivityNamespace::GEORSS);
282 $xpath->registerNamespace('activity', ActivityNamespace::ACTIVITY);
283 $xpath->registerNamespace('media', ActivityNamespace::MEDIA);
284 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
285 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
286 $xpath->registerNamespace('statusnet', ActivityNamespace::STATUSNET);
288 $contact = ["id" => 0];
290 // Fetch the first author
291 $authordata = $xpath->query('//author')->item(0);
292 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, true);
297 * Read attributes from element
299 * @param object $element Element object
301 * @return array attributes
303 private static function readAttributes($element)
307 foreach ($element->attributes as $attributes) {
308 $attribute[$attributes->name] = $attributes->textContent;
315 * Imports an XML string containing OStatus elements
317 * @param string $xml The XML
318 * @param array $importer user record of the importing user
319 * @param array $contact contact
320 * @param string $hub Called by reference, returns the fetched hub data
322 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
323 * @throws \ImagickException
325 public static function import($xml, array $importer, array &$contact, &$hub)
327 self::process($xml, $importer, $contact, $hub);
331 * Internal feed processing
333 * @param string $xml The XML
334 * @param array $importer user record of the importing user
335 * @param array $contact contact
336 * @param string $hub Called by reference, returns the fetched hub data
337 * @param boolean $stored Is the post fresh imported or from the database?
338 * @param boolean $initialize Is it the leading post so that data has to be initialized?
340 * @return boolean Could the XML be processed?
341 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
342 * @throws \ImagickException
344 private static function process($xml, array $importer, array &$contact = null, &$hub, $stored = false, $initialize = true)
347 self::$itemlist = [];
348 self::$conv_list = [];
351 Logger::log('Import OStatus message for user ' . $importer['uid'], Logger::DEBUG);
356 $doc = new DOMDocument();
357 @$doc->loadXML($xml);
359 $xpath = new DOMXPath($doc);
360 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
361 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
362 $xpath->registerNamespace('georss', ActivityNamespace::GEORSS);
363 $xpath->registerNamespace('activity', ActivityNamespace::ACTIVITY);
364 $xpath->registerNamespace('media', ActivityNamespace::MEDIA);
365 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
366 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
367 $xpath->registerNamespace('statusnet', ActivityNamespace::STATUSNET);
370 $hub_items = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0);
371 if (is_object($hub_items)) {
372 $hub_attributes = $hub_items->attributes;
373 if (is_object($hub_attributes)) {
374 foreach ($hub_attributes as $hub_attribute) {
375 if ($hub_attribute->name == "href") {
376 $hub = $hub_attribute->textContent;
377 Logger::log("Found hub ".$hub, Logger::DEBUG);
384 $header["uid"] = $importer["uid"];
385 $header["network"] = Protocol::OSTATUS;
387 $header["origin"] = 0;
388 $header["gravity"] = GRAVITY_COMMENT;
390 if (!is_object($doc->firstChild) || empty($doc->firstChild->tagName)) {
394 $first_child = $doc->firstChild->tagName;
396 if ($first_child == "feed") {
397 $entries = $xpath->query('/atom:feed/atom:entry');
399 $entries = $xpath->query('/atom:entry');
402 if ($entries->length == 1) {
403 // We reformat the XML to make it better readable
404 $doc2 = new DOMDocument();
405 $doc2->loadXML($xml);
406 $doc2->preserveWhiteSpace = false;
407 $doc2->formatOutput = true;
408 $xml2 = $doc2->saveXML();
410 $header["protocol"] = Conversation::PARCEL_SALMON;
411 $header["source"] = $xml2;
412 } elseif (!$initialize) {
416 // Fetch the first author
417 $authordata = $xpath->query('//author')->item(0);
418 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, $stored);
420 // Reverse the order of the entries
423 foreach ($entries as $entry) {
424 $entrylist[] = $entry;
427 foreach (array_reverse($entrylist) as $entry) {
429 $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
431 if ($authorelement->length == 0) {
432 $authorelement = $xpath->query('atom:author', $entry);
435 if ($authorelement->length > 0) {
436 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, $stored);
439 $item = array_merge($header, $author);
441 $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
442 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri']]);
444 $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $entry);
447 if (in_array($item["verb"], ['qvitter-delete-notice', Activity::DELETE, 'delete'])) {
448 self::deleteNotice($item);
452 if (in_array($item["verb"], [Activity::O_UNFAVOURITE, Activity::UNFAVORITE])) {
453 // Ignore "Unfavorite" message
454 Logger::log("Ignore unfavorite message ".print_r($item, true), Logger::DEBUG);
458 // Deletions come with the same uri, so we check for duplicates after processing deletions
459 if (Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]])) {
460 Logger::log('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', Logger::DEBUG);
463 Logger::log('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', Logger::DEBUG);
466 if ($item["verb"] == Activity::JOIN) {
467 // ignore "Join" messages
468 Logger::log("Ignore join message ".print_r($item, true), Logger::DEBUG);
472 if ($item["verb"] == "http://mastodon.social/schema/1.0/block") {
473 // ignore mastodon "block" messages
474 Logger::log("Ignore block message ".print_r($item, true), Logger::DEBUG);
478 if ($item["verb"] == Activity::FOLLOW) {
479 Contact::addRelationship($importer, $contact, $item);
483 if ($item["verb"] == Activity::O_UNFOLLOW) {
485 Contact::removeFollower($importer, $contact, $item, $dummy);
489 if ($item["verb"] == Activity::FAVORITE) {
490 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
491 Logger::log("Favorite ".$orig_uri." ".print_r($item, true));
493 $item["verb"] = Activity::LIKE;
494 $item["parent-uri"] = $orig_uri;
495 $item["gravity"] = GRAVITY_ACTIVITY;
496 $item["object-type"] = Activity\ObjectType::NOTE;
499 // http://activitystrea.ms/schema/1.0/rsvp-yes
500 if (!in_array($item["verb"], [Activity::POST, Activity::LIKE, Activity::SHARE])) {
501 Logger::log("Unhandled verb ".$item["verb"]." ".print_r($item, true), Logger::DEBUG);
504 self::processPost($xpath, $entry, $item, $importer);
506 if ($initialize && (count(self::$itemlist) > 0)) {
507 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['parent-uri']) {
508 // We will import it everytime, when it is started by our contacts
509 $valid = Contact::isSharingByURL(self::$itemlist[0]['author-link'], self::$itemlist[0]['uid']);
512 // If not, then it depends on this setting
513 $valid = ((self::$itemlist[0]['uid'] == 0) || !DI::pConfig()->get(self::$itemlist[0]['uid'], 'system', 'accept_only_sharer', false));
515 Logger::log("Item with uri ".self::$itemlist[0]['uri']." will be imported due to the system settings.", Logger::DEBUG);
518 Logger::log("Item with uri ".self::$itemlist[0]['uri']." belongs to a contact (".self::$itemlist[0]['contact-id']."). It will be imported.", Logger::DEBUG);
521 // Never post a thread when the only interaction by our contact was a like
523 $verbs = [Activity::POST, Activity::SHARE];
524 foreach (self::$itemlist as $item) {
525 if (in_array($item['verb'], $verbs) && Contact::isSharingByURL($item['author-link'], $item['uid'])) {
530 Logger::log("Item with uri ".self::$itemlist[0]['uri']." will be imported since the thread contains posts or shares.", Logger::DEBUG);
534 // But we will only import complete threads
535 $valid = Item::exists(['uid' => $importer["uid"], 'uri' => self::$itemlist[0]['parent-uri']]);
537 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);
542 $default_contact = 0;
543 for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
544 if (empty(self::$itemlist[$key]['contact-id'])) {
545 self::$itemlist[$key]['contact-id'] = $default_contact;
547 $default_contact = $item['contact-id'];
550 foreach (self::$itemlist as $item) {
551 $found = Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]]);
553 Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", Logger::DEBUG);
554 } elseif ($item['contact-id'] < 0) {
555 Logger::log("Item with uri ".$item["uri"]." is from a blocked contact.", Logger::DEBUG);
557 // We are having duplicated entries. Hopefully this solves it.
558 if (DI::lock()->acquire('ostatus_process_item_insert')) {
559 $ret = Item::insert($item);
560 DI::lock()->release('ostatus_process_item_insert');
561 Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret);
563 $ret = Item::insert($item);
564 Logger::log("We couldn't lock - but tried to store the item anyway. Return value is ".$ret);
569 self::$itemlist = [];
571 Logger::log('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.', Logger::DEBUG);
577 * Removes notice item from database
579 * @param array $item item
583 private static function deleteNotice(array $item)
585 $condition = ['uid' => $item['uid'], 'author-id' => $item['author-id'], 'uri' => $item['uri']];
586 if (!Item::exists($condition)) {
587 Logger::log('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it.");
591 Item::markForDeletion($condition);
593 Logger::log('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
597 * Processes the XML for a post
599 * @param DOMXPath $xpath The xpath object
600 * @param object $entry The xml entry that is processed
601 * @param array $item The item array
602 * @param array $importer user record of the importing user
604 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
605 * @throws \ImagickException
607 private static function processPost(DOMXPath $xpath, $entry, array &$item, array $importer)
609 $item["body"] = HTML::toBBCode(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
610 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $entry);
611 if (($item["object-type"] == Activity\ObjectType::BOOKMARK) || ($item["object-type"] == Activity\ObjectType::EVENT)) {
612 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
613 $item["body"] = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
614 } elseif ($item["object-type"] == Activity\ObjectType::QUESTION) {
615 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
618 $item["created"] = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
619 $item["edited"] = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
620 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
622 $conv = $xpath->query('ostatus:conversation', $entry);
623 if (is_object($conv->item(0))) {
624 foreach ($conv->item(0)->attributes as $attributes) {
625 if ($attributes->name == "ref") {
626 $item['conversation-uri'] = $attributes->textContent;
628 if ($attributes->name == "href") {
629 $item['conversation-href'] = $attributes->textContent;
636 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
637 if (is_object($inreplyto->item(0))) {
638 foreach ($inreplyto->item(0)->attributes as $attributes) {
639 if ($attributes->name == "ref") {
640 $item["parent-uri"] = $attributes->textContent;
642 if ($attributes->name == "href") {
643 $related = $attributes->textContent;
648 $georsspoint = $xpath->query('georss:point', $entry);
649 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
650 $item["coord"] = $georsspoint->item(0)->nodeValue;
653 $categories = $xpath->query('atom:category', $entry);
655 foreach ($categories as $category) {
656 foreach ($category->attributes as $attributes) {
657 if ($attributes->name == 'term') {
658 $term = $attributes->textContent;
659 if (!empty($item['tag'])) {
665 $item['tag'] .= '#[url=' . DI::baseUrl() . '/search?tag=' . $term . ']' . $term . '[/url]';
668 $fields = ['uri-id' => $item['uri-id'], 'name' => substr($term, 0, 64), 'type' => Term::HASHTAG];
669 DBA::insert('tag', $fields, true);
671 Logger::info('Stored tag', ['uri-id' => $item['uri-id'], 'tag' => $term, 'fields' => $fields]);
680 $links = $xpath->query('atom:link', $entry);
682 $link_data = self::processLinks($links, $item);
683 $self = $link_data['self'];
684 $add_body = $link_data['add_body'];
689 $notice_info = $xpath->query('statusnet:notice_info', $entry);
690 if ($notice_info && ($notice_info->length > 0)) {
691 foreach ($notice_info->item(0)->attributes as $attributes) {
692 if ($attributes->name == "source") {
693 $item["app"] = strip_tags($attributes->textContent);
695 if ($attributes->name == "repeat_of") {
696 $repeat_of = $attributes->textContent;
700 // Is it a repeated post?
701 if (($repeat_of != "") || ($item["verb"] == Activity::SHARE)) {
702 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
703 if (!empty($link_data['add_body'])) {
704 $add_body .= $link_data['add_body'];
708 $item["body"] .= $add_body;
710 // Only add additional data when there is no picture in the post
711 if (!strstr($item["body"], '[/img]')) {
712 $item["body"] = add_page_info_to_body($item["body"]);
715 // Mastodon Content Warning
716 if (($item["verb"] == Activity::POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
717 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
718 if (!empty($clear_text)) {
719 $item['content-warning'] = HTML::toBBCode($clear_text);
723 if (($self != '') && empty($item['protocol'])) {
724 self::fetchSelf($self, $item);
727 if (!empty($item["conversation-href"])) {
728 self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
731 if (isset($item["parent-uri"])) {
732 if (!Item::exists(['uid' => $importer["uid"], 'uri' => $item['parent-uri']])) {
733 if ($related != '') {
734 self::fetchRelated($related, $item["parent-uri"], $importer);
737 Logger::log('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', Logger::DEBUG);
740 $item["parent-uri"] = $item["uri"];
741 $item["gravity"] = GRAVITY_PARENT;
744 if (($item['author-link'] != '') && !empty($item['protocol'])) {
745 $item = Conversation::insert($item);
748 self::$itemlist[] = $item;
752 * Fetch the conversation for posts
754 * @param string $conversation The link to the conversation
755 * @param string $conversation_uri The conversation in "uri" format
757 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
759 private static function fetchConversation($conversation, $conversation_uri)
761 // Ensure that we only store a conversation once in a process
762 if (isset(self::$conv_list[$conversation])) {
766 self::$conv_list[$conversation] = true;
768 $curlResult = Network::curl($conversation, false, ['accept_content' => 'application/atom+xml, text/html']);
770 if (!$curlResult->isSuccess()) {
776 if (stristr($curlResult->getHeader(), 'Content-Type: application/atom+xml')) {
777 $xml = $curlResult->getBody();
781 $doc = new DOMDocument();
782 if (!@$doc->loadHTML($curlResult->getBody())) {
785 $xpath = new DOMXPath($doc);
787 $links = $xpath->query('//link');
790 foreach ($links as $link) {
791 $attribute = self::readAttributes($link);
792 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
793 $file = $attribute['href'];
797 $conversation_atom = Network::curl($attribute['href']);
799 if ($conversation_atom->isSuccess()) {
800 $xml = $conversation_atom->getBody();
810 self::storeConversation($xml, $conversation, $conversation_uri);
814 * Store a feed in several conversation entries
816 * @param string $xml The feed
817 * @param string $conversation conversation
818 * @param string $conversation_uri conversation uri
822 private static function storeConversation($xml, $conversation = '', $conversation_uri = '')
824 $doc = new DOMDocument();
825 @$doc->loadXML($xml);
827 $xpath = new DOMXPath($doc);
828 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
829 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
830 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
832 $entries = $xpath->query('/atom:feed/atom:entry');
834 // Now store the entries
835 foreach ($entries as $entry) {
836 $doc2 = new DOMDocument();
837 $doc2->preserveWhiteSpace = false;
838 $doc2->formatOutput = true;
842 $conv_data['protocol'] = Conversation::PARCEL_SPLIT_CONVERSATION;
843 $conv_data['network'] = Protocol::OSTATUS;
844 $conv_data['uri'] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
846 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
847 if (is_object($inreplyto->item(0))) {
848 foreach ($inreplyto->item(0)->attributes as $attributes) {
849 if ($attributes->name == "ref") {
850 $conv_data['reply-to-uri'] = $attributes->textContent;
855 $conv_data['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
857 $conv = $xpath->query('ostatus:conversation', $entry);
858 if (is_object($conv->item(0))) {
859 foreach ($conv->item(0)->attributes as $attributes) {
860 if ($attributes->name == "ref") {
861 $conv_data['conversation-uri'] = $attributes->textContent;
863 if ($attributes->name == "href") {
864 $conv_data['conversation-href'] = $attributes->textContent;
869 if ($conversation != '') {
870 $conv_data['conversation-uri'] = $conversation;
873 if ($conversation_uri != '') {
874 $conv_data['conversation-uri'] = $conversation_uri;
877 $entry = $doc2->importNode($entry, true);
879 $doc2->appendChild($entry);
881 $conv_data['source'] = $doc2->saveXML();
883 $condition = ['item-uri' => $conv_data['uri'],'protocol' => Conversation::PARCEL_FEED];
884 if (DBA::exists('conversation', $condition)) {
885 Logger::log('Delete deprecated entry for URI '.$conv_data['uri'], Logger::DEBUG);
886 DBA::delete('conversation', ['item-uri' => $conv_data['uri']]);
889 Logger::log('Store conversation data for uri '.$conv_data['uri'], Logger::DEBUG);
890 Conversation::insert($conv_data);
895 * Fetch the own post so that it can be stored later
897 * We want to store the original data for later processing.
898 * This function is meant for cases where we process a feed with multiple entries.
899 * In that case we need to fetch the single posts here.
901 * @param string $self The link to the self item
902 * @param array $item The item array
904 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
906 private static function fetchSelf($self, array &$item)
908 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $self, Conversation::PARCEL_DFRN, Conversation::PARCEL_SALMON];
909 if (DBA::exists('conversation', $condition)) {
910 Logger::log('Conversation '.$item['uri'].' is already stored.', Logger::DEBUG);
914 $curlResult = Network::curl($self);
916 if (!$curlResult->isSuccess()) {
920 // We reformat the XML to make it better readable
921 $doc = new DOMDocument();
922 $doc->loadXML($curlResult->getBody());
923 $doc->preserveWhiteSpace = false;
924 $doc->formatOutput = true;
925 $xml = $doc->saveXML();
927 $item["protocol"] = Conversation::PARCEL_SALMON;
928 $item["source"] = $xml;
930 Logger::log('Conversation '.$item['uri'].' is now fetched.', Logger::DEBUG);
934 * Fetch related posts and processes them
936 * @param string $related The link to the related item
937 * @param string $related_uri The related item in "uri" format
938 * @param array $importer user record of the importing user
940 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
941 * @throws \ImagickException
943 private static function fetchRelated($related, $related_uri, $importer)
945 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, Conversation::PARCEL_DFRN, Conversation::PARCEL_SALMON];
946 $conversation = DBA::selectFirst('conversation', ['source', 'protocol'], $condition);
947 if (DBA::isResult($conversation)) {
949 $xml = $conversation['source'];
950 if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
951 Logger::log('Got valid cached XML for URI '.$related_uri, Logger::DEBUG);
954 if ($conversation['protocol'] == Conversation::PARCEL_SALMON) {
955 Logger::log('Delete invalid cached XML for URI '.$related_uri, Logger::DEBUG);
956 DBA::delete('conversation', ['item-uri' => $related_uri]);
961 $curlResult = Network::curl($related, false, ['accept_content' => 'application/atom+xml, text/html']);
963 if (!$curlResult->isSuccess()) {
969 if (stristr($curlResult->getHeader(), 'Content-Type: application/atom+xml')) {
970 Logger::log('Directly fetched XML for URI ' . $related_uri, Logger::DEBUG);
971 $xml = $curlResult->getBody();
975 $doc = new DOMDocument();
976 if (!@$doc->loadHTML($curlResult->getBody())) {
979 $xpath = new DOMXPath($doc);
983 $links = $xpath->query('//link');
985 foreach ($links as $link) {
986 $attribute = self::readAttributes($link);
987 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
988 $atom_file = $attribute['href'];
991 if ($atom_file != '') {
992 $curlResult = Network::curl($atom_file);
994 if ($curlResult->isSuccess()) {
995 Logger::log('Fetched XML for URI ' . $related_uri, Logger::DEBUG);
996 $xml = $curlResult->getBody();
1002 // Workaround for older GNU Social servers
1003 if (($xml == '') && strstr($related, '/notice/')) {
1004 $curlResult = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related).'.atom');
1006 if ($curlResult->isSuccess()) {
1007 Logger::log('GNU Social workaround to fetch XML for URI ' . $related_uri, Logger::DEBUG);
1008 $xml = $curlResult->getBody();
1012 // Even more worse workaround for GNU Social ;-)
1014 $related_guess = OStatus::convertHref($related_uri);
1015 $curlResult = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related_guess).'.atom');
1017 if ($curlResult->isSuccess()) {
1018 Logger::log('GNU Social workaround 2 to fetch XML for URI ' . $related_uri, Logger::DEBUG);
1019 $xml = $curlResult->getBody();
1023 // Finally we take the data that we fetched from "ostatus:conversation"
1025 $condition = ['item-uri' => $related_uri, 'protocol' => Conversation::PARCEL_SPLIT_CONVERSATION];
1026 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1027 if (DBA::isResult($conversation)) {
1029 Logger::log('Got cached XML from conversation for URI '.$related_uri, Logger::DEBUG);
1030 $xml = $conversation['source'];
1035 self::process($xml, $importer, $contact, $hub, $stored, false);
1037 Logger::log("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, Logger::DEBUG);
1043 * Processes the XML for a repeated post
1045 * @param DOMXPath $xpath The xpath object
1046 * @param object $entry The xml entry that is processed
1047 * @param array $item The item array
1048 * @param array $importer user record of the importing user
1050 * @return array with data from links
1051 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1052 * @throws \ImagickException
1054 private static function processRepeatedItem(DOMXPath $xpath, $entry, array &$item, array $importer)
1056 $activityobject = $xpath->query('activity:object', $entry)->item(0);
1058 if (!is_object($activityobject)) {
1064 $orig_uri = XML::getFirstNodeValue($xpath, 'atom:id/text()', $activityobject);
1066 $links = $xpath->query("atom:link", $activityobject);
1068 $link_data = self::processLinks($links, $item);
1071 $orig_body = XML::getFirstNodeValue($xpath, 'atom:content/text()', $activityobject);
1072 $orig_created = XML::getFirstNodeValue($xpath, 'atom:published/text()', $activityobject);
1073 $orig_edited = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $activityobject);
1075 $orig_author = self::fetchAuthor($xpath, $activityobject, $importer, $dummy, false);
1077 $item["author-name"] = $orig_author["author-name"];
1078 $item["author-link"] = $orig_author["author-link"];
1079 $item["author-id"] = $orig_author["author-id"];
1081 $item["body"] = HTML::toBBCode($orig_body);
1082 $item["created"] = $orig_created;
1083 $item["edited"] = $orig_edited;
1085 $item["uri"] = $orig_uri;
1087 $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $activityobject);
1089 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $activityobject);
1091 // Mastodon Content Warning
1092 if (($item["verb"] == Activity::POST) && $xpath->evaluate('boolean(atom:summary)', $activityobject)) {
1093 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $activityobject);
1094 if (!empty($clear_text)) {
1095 $item['content-warning'] = HTML::toBBCode($clear_text);
1099 $inreplyto = $xpath->query('thr:in-reply-to', $activityobject);
1100 if (is_object($inreplyto->item(0))) {
1101 foreach ($inreplyto->item(0)->attributes as $attributes) {
1102 if ($attributes->name == "ref") {
1103 $item["parent-uri"] = $attributes->textContent;
1112 * Processes links in the XML
1114 * @param object $links The xml data that contain links
1115 * @param array $item The item array
1117 * @return array with data from the links
1119 private static function processLinks($links, array &$item)
1121 $link_data = ['add_body' => '', 'self' => ''];
1123 foreach ($links as $link) {
1124 $attribute = self::readAttributes($link);
1126 if (!empty($attribute['rel']) && !empty($attribute['href'])) {
1127 switch ($attribute['rel']) {
1129 $item["plink"] = $attribute['href'];
1130 if (($item["object-type"] == Activity\ObjectType::QUESTION)
1131 || ($item["object-type"] == Activity\ObjectType::EVENT)
1133 $item["body"] .= add_page_info($attribute['href']);
1136 case "ostatus:conversation":
1137 $link_data['conversation'] = $attribute['href'];
1138 $item['conversation-href'] = $link_data['conversation'];
1139 if (!isset($item['conversation-uri'])) {
1140 $item['conversation-uri'] = $item['conversation-href'];
1144 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
1145 if ($filetype == 'image') {
1146 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1148 if (!empty($item["attach"])) {
1149 $item["attach"] .= ',';
1151 $item["attach"] = '';
1153 if (!isset($attribute['length'])) {
1154 $attribute['length'] = "0";
1156 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.($attribute['title'] ?? '') .'"[/attach]';
1160 if ($item["object-type"] != Activity\ObjectType::BOOKMARK) {
1161 if (!isset($item["parent-uri"])) {
1162 $item["parent-uri"] = $attribute['href'];
1164 $link_data['related'] = $attribute['href'];
1166 $item["body"] .= add_page_info($attribute['href']);
1170 if (empty($item["plink"])) {
1171 $item["plink"] = $attribute['href'];
1173 $link_data['self'] = $attribute['href'];
1182 * Create an url out of an uri
1184 * @param string $href URI in the format "parameter1:parameter1:..."
1186 * @return string URL in the format http(s)://....
1188 public static function convertHref($href)
1190 $elements = explode(":", $href);
1192 if ((count($elements) <= 2) || ($elements[0] != "tag")) {
1196 $server = explode(",", $elements[1]);
1197 $conversation = explode("=", $elements[2]);
1199 if ((count($elements) == 4) && ($elements[2] == "post")) {
1200 return "http://".$server[0]."/notice/".$elements[3];
1203 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1206 if ($elements[3] == "objectType=thread") {
1207 return "http://".$server[0]."/conversation/".$conversation[1];
1209 return "http://".$server[0]."/notice/".$conversation[1];
1214 * Checks if the current post is a reshare
1216 * @param array $item The item array of thw post
1218 * @return string The guid if the post is a reshare
1220 private static function getResharedGuid(array $item)
1222 $reshared = Item::getShareArray($item);
1223 if (empty($reshared['guid']) || !empty($reshared['comment'])) {
1227 return $reshared['guid'];
1231 * Cleans the body of a post if it contains picture links
1233 * @param string $body The body
1235 * @return string The cleaned body
1236 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1238 private static function formatPicturePost($body)
1240 $siteinfo = BBCode::getAttachedData($body);
1242 if (($siteinfo["type"] == "photo") && (!empty($siteinfo["preview"]) || !empty($siteinfo["image"]))) {
1243 if (isset($siteinfo["preview"])) {
1244 $preview = $siteinfo["preview"];
1246 $preview = $siteinfo["image"];
1249 // Is it a remote picture? Then make a smaller preview here
1250 $preview = ProxyUtils::proxifyUrl($preview, false, ProxyUtils::SIZE_SMALL);
1252 // Is it a local picture? Then make it smaller here
1253 $preview = str_replace(["-0.jpg", "-0.png"], ["-2.jpg", "-2.png"], $preview);
1254 $preview = str_replace(["-1.jpg", "-1.png"], ["-2.jpg", "-2.png"], $preview);
1256 if (isset($siteinfo["url"])) {
1257 $url = $siteinfo["url"];
1259 $url = $siteinfo["image"];
1262 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1269 * Adds the header elements to the XML document
1271 * @param DOMDocument $doc XML document
1272 * @param array $owner Contact data of the poster
1273 * @param string $filter The related feed filter (activity, posts or comments)
1274 * @param bool $feed_mode Behave like a regular feed for users if true
1276 * @return object header root element
1277 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1279 private static function addHeader(DOMDocument $doc, array $owner, $filter, $feed_mode = false)
1281 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
1282 $doc->appendChild($root);
1284 $root->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
1285 $root->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
1286 $root->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
1287 $root->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
1288 $root->setAttribute("xmlns:poco", ActivityNamespace::POCO);
1289 $root->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
1290 $root->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
1291 $root->setAttribute("xmlns:mastodon", ActivityNamespace::MASTODON);
1294 $selfUri = '/feed/' . $owner["nick"] . '/';
1297 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
1298 $selfUri .= $filter;
1301 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
1304 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
1305 $selfUri .= $filter;
1310 $selfUri = "/dfrn_poll/" . $owner["nick"];
1313 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
1314 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1315 XML::addElement($doc, $root, "id", DI::baseUrl() . "/profile/" . $owner["nick"]);
1316 XML::addElement($doc, $root, "title", $title);
1317 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], DI::config()->get('config', 'sitename')));
1318 XML::addElement($doc, $root, "logo", $owner["photo"]);
1319 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1321 $author = self::addAuthor($doc, $owner);
1322 $root->appendChild($author);
1324 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1325 XML::addElement($doc, $root, "link", "", $attributes);
1327 /// @TODO We have to find out what this is
1328 /// $attributes = array("href" => DI::baseUrl()."/sup",
1329 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1330 /// "type" => "application/json");
1331 /// XML::addElement($doc, $root, "link", "", $attributes);
1333 self::hublinks($doc, $root, $owner["nick"]);
1335 $attributes = ["href" => DI::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "salmon"];
1336 XML::addElement($doc, $root, "link", "", $attributes);
1338 $attributes = ["href" => DI::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies"];
1339 XML::addElement($doc, $root, "link", "", $attributes);
1341 $attributes = ["href" => DI::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention"];
1342 XML::addElement($doc, $root, "link", "", $attributes);
1344 $attributes = ["href" => DI::baseUrl() . $selfUri, "rel" => "self", "type" => "application/atom+xml"];
1345 XML::addElement($doc, $root, "link", "", $attributes);
1347 if ($owner['account-type'] == Contact::TYPE_COMMUNITY) {
1348 $condition = ['uid' => $owner['uid'], 'self' => false, 'pending' => false,
1349 'archive' => false, 'hidden' => false, 'blocked' => false];
1350 $members = DBA::count('contact', $condition);
1351 XML::addElement($doc, $root, "statusnet:group_info", "", ["member_count" => $members]);
1358 * Add the link to the push hubs to the XML document
1360 * @param DOMDocument $doc XML document
1361 * @param object $root XML root element where the hub links are added
1362 * @param object $nick nick
1364 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1366 public static function hublinks(DOMDocument $doc, $root, $nick)
1368 $h = DI::baseUrl() . '/pubsubhubbub/'.$nick;
1369 XML::addElement($doc, $root, "link", "", ["href" => $h, "rel" => "hub"]);
1373 * Adds attachment data to the XML document
1375 * @param DOMDocument $doc XML document
1376 * @param object $root XML root element where the hub links are added
1377 * @param array $item Data of the item that is to be posted
1379 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1381 private static function getAttachment(DOMDocument $doc, $root, $item)
1383 $siteinfo = BBCode::getAttachedData($item["body"]);
1385 switch ($siteinfo["type"]) {
1387 if (!empty($siteinfo["image"])) {
1388 $imgdata = Images::getInfoFromURLCached($siteinfo["image"]);
1390 $attributes = ["rel" => "enclosure",
1391 "href" => $siteinfo["image"],
1392 "type" => $imgdata["mime"],
1393 "length" => intval($imgdata["size"])];
1394 XML::addElement($doc, $root, "link", "", $attributes);
1399 $attributes = ["rel" => "enclosure",
1400 "href" => $siteinfo["url"],
1401 "type" => "text/html; charset=UTF-8",
1403 "title" => ($siteinfo["title"] ?? '') ?: $siteinfo["url"],
1405 XML::addElement($doc, $root, "link", "", $attributes);
1411 if (!DI::config()->get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1412 $imgdata = Images::getInfoFromURLCached($siteinfo["image"]);
1414 $attributes = ["rel" => "enclosure",
1415 "href" => $siteinfo["image"],
1416 "type" => $imgdata["mime"],
1417 "length" => intval($imgdata["size"])];
1419 XML::addElement($doc, $root, "link", "", $attributes);
1423 $arr = explode('[/attach],', $item['attach']);
1425 foreach ($arr as $r) {
1427 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1429 $attributes = ["rel" => "enclosure",
1430 "href" => $matches[1],
1431 "type" => $matches[3]];
1433 if (intval($matches[2])) {
1434 $attributes["length"] = intval($matches[2]);
1436 if (trim($matches[4]) != "") {
1437 $attributes["title"] = trim($matches[4]);
1439 XML::addElement($doc, $root, "link", "", $attributes);
1446 * Adds the author element to the XML document
1448 * @param DOMDocument $doc XML document
1449 * @param array $owner Contact data of the poster
1450 * @param bool $show_profile Whether to show profile
1452 * @return \DOMElement author element
1453 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1455 private static function addAuthor(DOMDocument $doc, array $owner, $show_profile = true)
1457 $profile = DBA::selectFirst('profile', ['homepage', 'publish'], ['uid' => $owner['uid']]);
1458 $author = $doc->createElement("author");
1459 XML::addElement($doc, $author, "id", $owner["url"]);
1460 if ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
1461 XML::addElement($doc, $author, "activity:object-type", Activity\ObjectType::GROUP);
1463 XML::addElement($doc, $author, "activity:object-type", Activity\ObjectType::PERSON);
1465 XML::addElement($doc, $author, "uri", $owner["url"]);
1466 XML::addElement($doc, $author, "name", $owner["nick"]);
1467 XML::addElement($doc, $author, "email", $owner["addr"]);
1468 if ($show_profile) {
1469 XML::addElement($doc, $author, "summary", BBCode::convert($owner["about"], false, 7));
1472 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $owner["url"]];
1473 XML::addElement($doc, $author, "link", "", $attributes);
1477 "type" => "image/jpeg", // To-Do?
1478 "media:width" => 300,
1479 "media:height" => 300,
1480 "href" => $owner["photo"]];
1481 XML::addElement($doc, $author, "link", "", $attributes);
1483 if (isset($owner["thumb"])) {
1486 "type" => "image/jpeg", // To-Do?
1487 "media:width" => 80,
1488 "media:height" => 80,
1489 "href" => $owner["thumb"]];
1490 XML::addElement($doc, $author, "link", "", $attributes);
1493 XML::addElement($doc, $author, "poco:preferredUsername", $owner["nick"]);
1494 XML::addElement($doc, $author, "poco:displayName", $owner["name"]);
1495 if ($show_profile) {
1496 XML::addElement($doc, $author, "poco:note", BBCode::convert($owner["about"], false, 7));
1498 if (trim($owner["location"]) != "") {
1499 $element = $doc->createElement("poco:address");
1500 XML::addElement($doc, $element, "poco:formatted", $owner["location"]);
1501 $author->appendChild($element);
1505 if (DBA::isResult($profile) && !$show_profile) {
1506 if (trim($profile["homepage"]) != "") {
1507 $urls = $doc->createElement("poco:urls");
1508 XML::addElement($doc, $urls, "poco:type", "homepage");
1509 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
1510 XML::addElement($doc, $urls, "poco:primary", "true");
1511 $author->appendChild($urls);
1514 XML::addElement($doc, $author, "followers", "", ["url" => DI::baseUrl() . "/profile/" . $owner["nick"] . "/contacts/followers"]);
1515 XML::addElement($doc, $author, "statusnet:profile_info", "", ["local_id" => $owner["uid"]]);
1517 if ($profile["publish"]) {
1518 XML::addElement($doc, $author, "mastodon:scope", "public");
1526 * @TODO Picture attachments should look like this:
1527 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1528 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1532 * Returns the given activity if present - otherwise returns the "post" activity
1534 * @param array $item Data of the item that is to be posted
1536 * @return string activity
1538 private static function constructVerb(array $item)
1540 if (!empty($item['verb'])) {
1541 return $item['verb'];
1544 return Activity::POST;
1548 * Returns the given object type if present - otherwise returns the "note" object type
1550 * @param array $item Data of the item that is to be posted
1552 * @return string Object type
1554 private static function constructObjecttype(array $item)
1556 if (!empty($item['object-type']) && in_array($item['object-type'], [Activity\ObjectType::NOTE, Activity\ObjectType::COMMENT])) {
1557 return $item['object-type'];
1560 return Activity\ObjectType::NOTE;
1564 * Adds an entry element to the XML document
1566 * @param DOMDocument $doc XML document
1567 * @param array $item Data of the item that is to be posted
1568 * @param array $owner Contact data of the poster
1569 * @param bool $toplevel optional default false
1570 * @param bool $feed_mode Behave like a regular feed for users if true
1572 * @return \DOMElement Entry element
1573 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1574 * @throws \ImagickException
1576 private static function entry(DOMDocument $doc, array $item, array $owner, $toplevel = false, $feed_mode = false)
1580 $repeated_guid = self::getResharedGuid($item);
1581 if ($repeated_guid != "") {
1582 $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel);
1589 if ($item["verb"] == Activity::LIKE) {
1590 return self::likeEntry($doc, $item, $owner, $toplevel);
1591 } elseif (in_array($item["verb"], [Activity::FOLLOW, Activity::O_UNFOLLOW])) {
1592 return self::followEntry($doc, $item, $owner, $toplevel);
1594 return self::noteEntry($doc, $item, $owner, $toplevel, $feed_mode);
1599 * Adds a source entry to the XML document
1601 * @param DOMDocument $doc XML document
1602 * @param array $contact Array of the contact that is added
1604 * @return \DOMElement Source element
1605 * @throws \Exception
1607 private static function sourceEntry(DOMDocument $doc, array $contact)
1609 $source = $doc->createElement("source");
1610 XML::addElement($doc, $source, "id", $contact["poll"]);
1611 XML::addElement($doc, $source, "title", $contact["name"]);
1612 XML::addElement($doc, $source, "link", "", ["rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]]);
1613 XML::addElement($doc, $source, "link", "", ["rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]]);
1614 XML::addElement($doc, $source, "icon", $contact["photo"]);
1615 XML::addElement($doc, $source, "updated", DateTimeFormat::utc($contact["success_update"]."+00:00", DateTimeFormat::ATOM));
1621 * Fetches contact data from the contact or the gcontact table
1623 * @param string $url URL of the contact
1624 * @param array $owner Contact data of the poster
1626 * @return array Contact array
1627 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1628 * @throws \ImagickException
1630 private static function contactEntry($url, array $owner)
1633 "SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1634 DBA::escape(Strings::normaliseLink($url)),
1635 intval($owner["uid"])
1637 if (DBA::isResult($r)) {
1639 $contact["uid"] = -1;
1642 if (!DBA::isResult($r)) {
1643 $gcontact = DBA::selectFirst('gcontact', [], ['nurl' => Strings::normaliseLink($url)]);
1644 if (DBA::isResult($r)) {
1645 $contact = $gcontact;
1646 $contact["uid"] = -1;
1647 $contact["success_update"] = $contact["updated"];
1651 if (!DBA::isResult($r)) {
1655 if (!isset($contact["poll"])) {
1656 $data = Probe::uri($url);
1657 $contact["poll"] = $data["poll"];
1659 if (!$contact["alias"]) {
1660 $contact["alias"] = $data["alias"];
1664 if (!isset($contact["alias"])) {
1665 $contact["alias"] = $contact["url"];
1668 $contact['account-type'] = $owner['account-type'];
1674 * Adds an entry element with reshared content
1676 * @param DOMDocument $doc XML document
1677 * @param array $item Data of the item that is to be posted
1678 * @param array $owner Contact data of the poster
1679 * @param string $repeated_guid guid
1680 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1682 * @return bool Entry element
1683 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1684 * @throws \ImagickException
1686 private static function reshareEntry(DOMDocument $doc, array $item, array $owner, $repeated_guid, $toplevel)
1688 if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1689 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1692 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1694 $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => [Item::PUBLIC, Item::UNLISTED],
1695 'network' => [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS]];
1696 $repeated_item = Item::selectFirst([], $condition);
1697 if (!DBA::isResult($repeated_item)) {
1701 $contact = self::contactEntry($repeated_item['author-link'], $owner);
1703 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1705 self::entryContent($doc, $entry, $item, $owner, $title, Activity::SHARE, false);
1707 $as_object = $doc->createElement("activity:object");
1709 XML::addElement($doc, $as_object, "activity:object-type", ActivityNamespace::ACTIVITY_SCHEMA . "activity");
1711 self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false);
1713 $author = self::addAuthor($doc, $contact, false);
1714 $as_object->appendChild($author);
1716 $as_object2 = $doc->createElement("activity:object");
1718 XML::addElement($doc, $as_object2, "activity:object-type", self::constructObjecttype($repeated_item));
1720 $title = sprintf("New comment by %s", $contact["nick"]);
1722 self::entryContent($doc, $as_object2, $repeated_item, $owner, $title);
1724 $as_object->appendChild($as_object2);
1726 self::entryFooter($doc, $as_object, $item, $owner, false);
1728 $source = self::sourceEntry($doc, $contact);
1730 $as_object->appendChild($source);
1732 $entry->appendChild($as_object);
1734 self::entryFooter($doc, $entry, $item, $owner);
1740 * Adds an entry element with a "like"
1742 * @param DOMDocument $doc XML document
1743 * @param array $item Data of the item that is to be posted
1744 * @param array $owner Contact data of the poster
1745 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1747 * @return \DOMElement Entry element with "like"
1748 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1749 * @throws \ImagickException
1751 private static function likeEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1753 if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1754 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1757 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1759 $verb = ActivityNamespace::ACTIVITY_SCHEMA . "favorite";
1760 self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false);
1762 $parent = Item::selectFirst([], ['uri' => $item["thr-parent"], 'uid' => $item["uid"]]);
1763 if (DBA::isResult($parent)) {
1764 $as_object = $doc->createElement("activity:object");
1766 XML::addElement($doc, $as_object, "activity:object-type", self::constructObjecttype($parent));
1768 self::entryContent($doc, $as_object, $parent, $owner, "New entry");
1770 $entry->appendChild($as_object);
1773 self::entryFooter($doc, $entry, $item, $owner);
1779 * Adds the person object element to the XML document
1781 * @param DOMDocument $doc XML document
1782 * @param array $owner Contact data of the poster
1783 * @param array $contact Contact data of the target
1785 * @return object author element
1787 private static function addPersonObject(DOMDocument $doc, array $owner, array $contact)
1789 $object = $doc->createElement("activity:object");
1790 XML::addElement($doc, $object, "activity:object-type", Activity\ObjectType::PERSON);
1792 if ($contact['network'] == Protocol::PHANTOM) {
1793 XML::addElement($doc, $object, "id", $contact['url']);
1797 XML::addElement($doc, $object, "id", $contact["alias"]);
1798 XML::addElement($doc, $object, "title", $contact["nick"]);
1800 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $contact["url"]];
1801 XML::addElement($doc, $object, "link", "", $attributes);
1805 "type" => "image/jpeg", // To-Do?
1806 "media:width" => 300,
1807 "media:height" => 300,
1808 "href" => $contact["photo"]];
1809 XML::addElement($doc, $object, "link", "", $attributes);
1811 XML::addElement($doc, $object, "poco:preferredUsername", $contact["nick"]);
1812 XML::addElement($doc, $object, "poco:displayName", $contact["name"]);
1814 if (trim($contact["location"]) != "") {
1815 $element = $doc->createElement("poco:address");
1816 XML::addElement($doc, $element, "poco:formatted", $contact["location"]);
1817 $object->appendChild($element);
1824 * Adds a follow/unfollow entry element
1826 * @param DOMDocument $doc XML document
1827 * @param array $item Data of the follow/unfollow message
1828 * @param array $owner Contact data of the poster
1829 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1831 * @return \DOMElement Entry element
1832 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1833 * @throws \ImagickException
1835 private static function followEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1837 $item["id"] = $item["parent"] = 0;
1838 $item["created"] = $item["edited"] = date("c");
1839 $item["private"] = Item::PRIVATE;
1841 $contact = Probe::uri($item['follow']);
1843 if ($contact['alias'] == '') {
1844 $contact['alias'] = $contact["url"];
1846 $item['follow'] = $contact['alias'];
1849 $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($contact["url"])];
1850 $user_contact = DBA::selectFirst('contact', ['id'], $condition);
1852 if (DBA::isResult($user_contact)) {
1853 $connect_id = $user_contact['id'];
1858 if ($item['verb'] == Activity::FOLLOW) {
1859 $message = DI::l10n()->t('%s is now following %s.');
1860 $title = DI::l10n()->t('following');
1861 $action = "subscription";
1863 $message = DI::l10n()->t('%s stopped following %s.');
1864 $title = DI::l10n()->t('stopped following');
1865 $action = "unfollow";
1868 $item["uri"] = $item['parent-uri'] = $item['thr-parent']
1869 = 'tag:' . DI::baseUrl()->getHostname().
1870 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1871 ':person:'.$connect_id.':'.$item['created'];
1873 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1875 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1877 self::entryContent($doc, $entry, $item, $owner, $title);
1879 $object = self::addPersonObject($doc, $owner, $contact);
1880 $entry->appendChild($object);
1882 self::entryFooter($doc, $entry, $item, $owner);
1888 * Adds a regular entry element
1890 * @param DOMDocument $doc XML document
1891 * @param array $item Data of the item that is to be posted
1892 * @param array $owner Contact data of the poster
1893 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1894 * @param bool $feed_mode Behave like a regular feed for users if true
1896 * @return \DOMElement Entry element
1897 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1898 * @throws \ImagickException
1900 private static function noteEntry(DOMDocument $doc, array $item, array $owner, $toplevel, $feed_mode)
1902 if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1903 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1907 if (!empty($item['title'])) {
1908 $title = BBCode::convert($item['title'], false, 7);
1910 $title = sprintf("New note by %s", $owner["nick"]);
1913 $title = sprintf("New comment by %s", $owner["nick"]);
1916 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1918 XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::NOTE);
1920 self::entryContent($doc, $entry, $item, $owner, $title, '', true, $feed_mode);
1922 self::entryFooter($doc, $entry, $item, $owner, !$feed_mode, $feed_mode);
1928 * Adds a header element to the XML document
1930 * @param DOMDocument $doc XML document
1931 * @param array $owner Contact data of the poster
1932 * @param array $item
1933 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1935 * @return \DOMElement The entry element where the elements are added
1936 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1937 * @throws \ImagickException
1939 private static function entryHeader(DOMDocument $doc, array $owner, array $item, $toplevel)
1942 $entry = $doc->createElement("entry");
1944 if ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
1945 $contact = self::contactEntry($item['author-link'], $owner);
1946 $author = self::addAuthor($doc, $contact, false);
1947 $entry->appendChild($author);
1950 $entry = $doc->createElementNS(ActivityNamespace::ATOM1, "entry");
1952 $entry->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
1953 $entry->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
1954 $entry->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
1955 $entry->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
1956 $entry->setAttribute("xmlns:poco", ActivityNamespace::POCO);
1957 $entry->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
1958 $entry->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
1959 $entry->setAttribute("xmlns:mastodon", ActivityNamespace::MASTODON);
1961 $author = self::addAuthor($doc, $owner);
1962 $entry->appendChild($author);
1969 * Adds elements to the XML document
1971 * @param DOMDocument $doc XML document
1972 * @param \DOMElement $entry Entry element where the content is added
1973 * @param array $item Data of the item that is to be posted
1974 * @param array $owner Contact data of the poster
1975 * @param string $title Title for the post
1976 * @param string $verb The activity verb
1977 * @param bool $complete Add the "status_net" element?
1978 * @param bool $feed_mode Behave like a regular feed for users if true
1980 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1982 private static function entryContent(DOMDocument $doc, \DOMElement $entry, array $item, array $owner, $title, $verb = "", $complete = true, $feed_mode = false)
1985 $verb = self::constructVerb($item);
1988 XML::addElement($doc, $entry, "id", $item["uri"]);
1989 XML::addElement($doc, $entry, "title", html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1991 $body = self::formatPicturePost($item['body']);
1993 if (!empty($item['title']) && !$feed_mode) {
1994 $body = "[b]".$item['title']."[/b]\n\n".$body;
1997 $body = BBCode::convert($body, false, 7);
1999 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
2001 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
2002 "href" => DI::baseUrl()."/display/".$item["guid"]]
2005 if (!$feed_mode && $complete && ($item["id"] > 0)) {
2006 XML::addElement($doc, $entry, "status_net", "", ["notice_id" => $item["id"]]);
2010 XML::addElement($doc, $entry, "activity:verb", $verb);
2013 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
2014 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
2018 * Adds the elements at the foot of an entry to the XML document
2020 * @param DOMDocument $doc XML document
2021 * @param object $entry The entry element where the elements are added
2022 * @param array $item Data of the item that is to be posted
2023 * @param array $owner Contact data of the poster
2024 * @param bool $complete default true
2025 * @param bool $feed_mode Behave like a regular feed for users if true
2027 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2029 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner, $complete = true, $feed_mode = false)
2033 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
2034 $parent = Item::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item["parent"]]);
2035 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
2037 $thrparent = Item::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $parent_item]);
2039 if (DBA::isResult($thrparent)) {
2040 $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
2041 $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
2042 $parent_plink = $thrparent["plink"];
2044 $mentioned[$parent["author-link"]] = $parent["author-link"];
2045 $mentioned[$parent["owner-link"]] = $parent["owner-link"];
2046 $parent_plink = DI::baseUrl()."/display/".$parent["guid"];
2050 "ref" => $parent_item,
2051 "href" => $parent_plink];
2052 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
2056 "href" => $parent_plink];
2057 XML::addElement($doc, $entry, "link", "", $attributes);
2060 if (!$feed_mode && (intval($item["parent"]) > 0)) {
2061 $conversation_href = $conversation_uri = str_replace('/objects/', '/context/', $item['parent-uri']);
2063 if (isset($parent_item)) {
2064 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $parent_item]);
2065 if (DBA::isResult($conversation)) {
2066 if ($conversation['conversation-uri'] != '') {
2067 $conversation_uri = $conversation['conversation-uri'];
2069 if ($conversation['conversation-href'] != '') {
2070 $conversation_href = $conversation['conversation-href'];
2075 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:conversation", "href" => $conversation_href]);
2078 "href" => $conversation_href,
2079 "local_id" => $item["parent"],
2080 "ref" => $conversation_uri];
2082 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
2085 $tags = item::getFeedTags($item);
2088 foreach ($tags as $t) {
2090 $mentioned[$t[1]] = $t[1];
2095 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2097 foreach ($mentioned as $mention) {
2098 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2099 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2101 $mentioned = $newmentions;
2103 foreach ($mentioned as $mention) {
2104 $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($mention)];
2105 $contact = DBA::selectFirst('contact', ['forum', 'prv', 'self', 'contact-type'], $condition);
2106 if ($contact["forum"] || $contact["prv"] || ($owner['contact-type'] == Contact::TYPE_COMMUNITY) ||
2107 ($contact['self'] && ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY))) {
2108 XML::addElement($doc, $entry, "link", "",
2110 "rel" => "mentioned",
2111 "ostatus:object-type" => Activity\ObjectType::GROUP,
2115 XML::addElement($doc, $entry, "link", "",
2117 "rel" => "mentioned",
2118 "ostatus:object-type" => Activity\ObjectType::PERSON,
2124 if ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
2125 XML::addElement($doc, $entry, "link", "", [
2126 "rel" => "mentioned",
2127 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/group",
2128 "href" => $owner['url']
2132 if (($item['private'] != Item::PRIVATE) && !$feed_mode) {
2133 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:attention",
2134 "href" => "http://activityschema.org/collection/public"]);
2135 XML::addElement($doc, $entry, "link", "", ["rel" => "mentioned",
2136 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2137 "href" => "http://activityschema.org/collection/public"]);
2138 XML::addElement($doc, $entry, "mastodon:scope", "public");
2142 foreach ($tags as $t) {
2144 XML::addElement($doc, $entry, "category", "", ["term" => $t[2]]);
2149 self::getAttachment($doc, $entry, $item);
2151 if ($complete && ($item["id"] > 0)) {
2152 $app = $item["app"];
2157 $attributes = ["local_id" => $item["id"], "source" => $app];
2159 if (isset($parent["id"])) {
2160 $attributes["repeat_of"] = $parent["id"];
2163 if ($item["coord"] != "") {
2164 XML::addElement($doc, $entry, "georss:point", $item["coord"]);
2167 XML::addElement($doc, $entry, "statusnet:notice_info", "", $attributes);
2172 * Creates the XML feed for a given nickname
2174 * Supported filters:
2175 * - activity (default): all the public posts
2176 * - posts: all the public top-level posts
2177 * - comments: all the public replies
2179 * Updates the provided last_update parameter if the result comes from the
2180 * cache or it is empty
2182 * @param string $owner_nick Nickname of the feed owner
2183 * @param string $last_update Date of the last update
2184 * @param integer $max_items Number of maximum items to fetch
2185 * @param string $filter Feed items filter (activity, posts or comments)
2186 * @param boolean $nocache Wether to bypass caching
2187 * @param boolean $feed_mode Behave like a regular feed for users if true
2189 * @return string XML feed
2190 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2191 * @throws \ImagickException
2193 public static function feed($owner_nick, &$last_update, $max_items = 300, $filter = 'activity', $nocache = false, $feed_mode = false)
2195 $stamp = microtime(true);
2197 $owner = User::getOwnerDataByNick($owner_nick);
2202 $cachekey = "ostatus:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
2204 $previous_created = $last_update;
2206 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
2207 if ((time() - strtotime($owner['last-item'])) < 15*60) {
2208 $result = DI::cache()->get($cachekey);
2209 if (!$nocache && !is_null($result)) {
2210 Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', Logger::DEBUG);
2211 $last_update = $result['last_update'];
2212 return $result['feed'];
2216 if (!strlen($last_update)) {
2217 $last_update = 'now -30 days';
2220 $check_date = DateTimeFormat::utc($last_update);
2221 $authorid = Contact::getIdForURL($owner["url"], 0, true);
2223 $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted`
2224 AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?)",
2225 $owner["uid"], $check_date, Item::PRIVATE, Protocol::OSTATUS, Protocol::DFRN];
2227 if ($filter === 'comments') {
2228 $condition[0] .= " AND `object-type` = ? ";
2229 $condition[] = Activity\ObjectType::COMMENT;
2232 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
2233 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
2234 $condition[] = $owner["id"];
2235 $condition[] = $authorid;
2238 $params = ['order' => ['received' => true], 'limit' => $max_items];
2240 if ($filter === 'posts') {
2241 $ret = Item::selectThread([], $condition, $params);
2243 $ret = Item::select([], $condition, $params);
2246 $items = Item::inArray($ret);
2248 $doc = new DOMDocument('1.0', 'utf-8');
2249 $doc->formatOutput = true;
2251 $root = self::addHeader($doc, $owner, $filter, $feed_mode);
2253 foreach ($items as $item) {
2254 if (DI::config()->get('system', 'ostatus_debug')) {
2255 $item['body'] .= '🍼';
2258 $entry = self::entry($doc, $item, $owner, false, $feed_mode);
2259 $root->appendChild($entry);
2261 if ($last_update < $item['created']) {
2262 $last_update = $item['created'];
2266 $feeddata = trim($doc->saveXML());
2268 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
2269 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
2271 Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, Logger::DEBUG);
2277 * Creates the XML for a salmon message
2279 * @param array $item Data of the item that is to be posted
2280 * @param array $owner Contact data of the poster
2282 * @return string XML for the salmon
2283 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2284 * @throws \ImagickException
2286 public static function salmon(array $item, array $owner)
2288 $doc = new DOMDocument('1.0', 'utf-8');
2289 $doc->formatOutput = true;
2291 if (DI::config()->get('system', 'ostatus_debug')) {
2292 $item['body'] .= '🐟';
2295 $entry = self::entry($doc, $item, $owner, true);
2297 $doc->appendChild($entry);
2299 return trim($doc->saveXML());
2303 * Checks if the given contact url does support OStatus
2305 * @param string $url profile url
2306 * @param boolean $update Update the profile
2308 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2309 * @throws \ImagickException
2311 public static function isSupportedByContactUrl($url, $update = false)
2313 $probe = Probe::uri($url, Protocol::OSTATUS, 0, !$update);
2314 return $probe['network'] == Protocol::OSTATUS;