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\PageInfo;
27 use Friendica\Content\Text\BBCode;
28 use Friendica\Content\Text\HTML;
29 use Friendica\Core\Cache\Duration;
30 use Friendica\Core\Logger;
31 use Friendica\Core\Protocol;
32 use Friendica\Database\DBA;
34 use Friendica\Model\APContact;
35 use Friendica\Model\Contact;
36 use Friendica\Model\Conversation;
37 use Friendica\Model\GContact;
38 use Friendica\Model\Item;
39 use Friendica\Model\ItemURI;
40 use Friendica\Model\Tag;
41 use Friendica\Model\User;
42 use Friendica\Network\Probe;
43 use Friendica\Util\DateTimeFormat;
44 use Friendica\Util\Images;
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, false);
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') {
659 Tag::store($item['uri-id'], Tag::HASHTAG, $attributes->textContent);
668 $links = $xpath->query('atom:link', $entry);
670 $link_data = self::processLinks($links, $item);
671 $self = $link_data['self'];
672 $add_body = $link_data['add_body'];
677 $notice_info = $xpath->query('statusnet:notice_info', $entry);
678 if ($notice_info && ($notice_info->length > 0)) {
679 foreach ($notice_info->item(0)->attributes as $attributes) {
680 if ($attributes->name == "source") {
681 $item["app"] = strip_tags($attributes->textContent);
683 if ($attributes->name == "repeat_of") {
684 $repeat_of = $attributes->textContent;
688 // Is it a repeated post?
689 if (($repeat_of != "") || ($item["verb"] == Activity::SHARE)) {
690 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
691 if (!empty($link_data['add_body'])) {
692 $add_body .= $link_data['add_body'];
696 $item["body"] .= $add_body;
698 // Only add additional data when there is no picture in the post
699 if (!strstr($item["body"], '[/img]')) {
700 $item["body"] = PageInfo::searchAndAppendToBody($item["body"]);
703 Tag::storeFromBody($item['uri-id'], $item['body']);
705 // Mastodon Content Warning
706 if (($item["verb"] == Activity::POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
707 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
708 if (!empty($clear_text)) {
709 $item['content-warning'] = HTML::toBBCode($clear_text);
713 if (($self != '') && empty($item['protocol'])) {
714 self::fetchSelf($self, $item);
717 if (!empty($item["conversation-href"])) {
718 self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
721 if (isset($item["parent-uri"])) {
722 if (!Item::exists(['uid' => $importer["uid"], 'uri' => $item['parent-uri']])) {
723 if ($related != '') {
724 self::fetchRelated($related, $item["parent-uri"], $importer);
727 Logger::log('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', Logger::DEBUG);
730 $item["parent-uri"] = $item["uri"];
731 $item["gravity"] = GRAVITY_PARENT;
734 if (($item['author-link'] != '') && !empty($item['protocol'])) {
735 $item = Conversation::insert($item);
738 self::$itemlist[] = $item;
742 * Fetch the conversation for posts
744 * @param string $conversation The link to the conversation
745 * @param string $conversation_uri The conversation in "uri" format
747 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
749 private static function fetchConversation($conversation, $conversation_uri)
751 // Ensure that we only store a conversation once in a process
752 if (isset(self::$conv_list[$conversation])) {
756 self::$conv_list[$conversation] = true;
758 $curlResult = DI::httpRequest()->get($conversation, false, ['accept_content' => 'application/atom+xml, text/html']);
760 if (!$curlResult->isSuccess()) {
766 if (stristr($curlResult->getHeader(), 'Content-Type: application/atom+xml')) {
767 $xml = $curlResult->getBody();
771 $doc = new DOMDocument();
772 if (!@$doc->loadHTML($curlResult->getBody())) {
775 $xpath = new DOMXPath($doc);
777 $links = $xpath->query('//link');
780 foreach ($links as $link) {
781 $attribute = self::readAttributes($link);
782 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
783 $file = $attribute['href'];
787 $conversation_atom = DI::httpRequest()->get($attribute['href']);
789 if ($conversation_atom->isSuccess()) {
790 $xml = $conversation_atom->getBody();
800 self::storeConversation($xml, $conversation, $conversation_uri);
804 * Store a feed in several conversation entries
806 * @param string $xml The feed
807 * @param string $conversation conversation
808 * @param string $conversation_uri conversation uri
812 private static function storeConversation($xml, $conversation = '', $conversation_uri = '')
814 $doc = new DOMDocument();
815 @$doc->loadXML($xml);
817 $xpath = new DOMXPath($doc);
818 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
819 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
820 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
822 $entries = $xpath->query('/atom:feed/atom:entry');
824 // Now store the entries
825 foreach ($entries as $entry) {
826 $doc2 = new DOMDocument();
827 $doc2->preserveWhiteSpace = false;
828 $doc2->formatOutput = true;
832 $conv_data['protocol'] = Conversation::PARCEL_SPLIT_CONVERSATION;
833 $conv_data['network'] = Protocol::OSTATUS;
834 $conv_data['uri'] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
836 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
837 if (is_object($inreplyto->item(0))) {
838 foreach ($inreplyto->item(0)->attributes as $attributes) {
839 if ($attributes->name == "ref") {
840 $conv_data['reply-to-uri'] = $attributes->textContent;
845 $conv_data['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
847 $conv = $xpath->query('ostatus:conversation', $entry);
848 if (is_object($conv->item(0))) {
849 foreach ($conv->item(0)->attributes as $attributes) {
850 if ($attributes->name == "ref") {
851 $conv_data['conversation-uri'] = $attributes->textContent;
853 if ($attributes->name == "href") {
854 $conv_data['conversation-href'] = $attributes->textContent;
859 if ($conversation != '') {
860 $conv_data['conversation-uri'] = $conversation;
863 if ($conversation_uri != '') {
864 $conv_data['conversation-uri'] = $conversation_uri;
867 $entry = $doc2->importNode($entry, true);
869 $doc2->appendChild($entry);
871 $conv_data['source'] = $doc2->saveXML();
873 $condition = ['item-uri' => $conv_data['uri'],'protocol' => Conversation::PARCEL_FEED];
874 if (DBA::exists('conversation', $condition)) {
875 Logger::log('Delete deprecated entry for URI '.$conv_data['uri'], Logger::DEBUG);
876 DBA::delete('conversation', ['item-uri' => $conv_data['uri']]);
879 Logger::log('Store conversation data for uri '.$conv_data['uri'], Logger::DEBUG);
880 Conversation::insert($conv_data);
885 * Fetch the own post so that it can be stored later
887 * We want to store the original data for later processing.
888 * This function is meant for cases where we process a feed with multiple entries.
889 * In that case we need to fetch the single posts here.
891 * @param string $self The link to the self item
892 * @param array $item The item array
894 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
896 private static function fetchSelf($self, array &$item)
898 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $self, Conversation::PARCEL_DFRN, Conversation::PARCEL_SALMON];
899 if (DBA::exists('conversation', $condition)) {
900 Logger::log('Conversation '.$item['uri'].' is already stored.', Logger::DEBUG);
904 $curlResult = DI::httpRequest()->get($self);
906 if (!$curlResult->isSuccess()) {
910 // We reformat the XML to make it better readable
911 $doc = new DOMDocument();
912 $doc->loadXML($curlResult->getBody());
913 $doc->preserveWhiteSpace = false;
914 $doc->formatOutput = true;
915 $xml = $doc->saveXML();
917 $item["protocol"] = Conversation::PARCEL_SALMON;
918 $item["source"] = $xml;
920 Logger::log('Conversation '.$item['uri'].' is now fetched.', Logger::DEBUG);
924 * Fetch related posts and processes them
926 * @param string $related The link to the related item
927 * @param string $related_uri The related item in "uri" format
928 * @param array $importer user record of the importing user
930 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
931 * @throws \ImagickException
933 private static function fetchRelated($related, $related_uri, $importer)
935 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, Conversation::PARCEL_DFRN, Conversation::PARCEL_SALMON];
936 $conversation = DBA::selectFirst('conversation', ['source', 'protocol'], $condition);
937 if (DBA::isResult($conversation)) {
939 $xml = $conversation['source'];
940 if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
941 Logger::log('Got valid cached XML for URI '.$related_uri, Logger::DEBUG);
944 if ($conversation['protocol'] == Conversation::PARCEL_SALMON) {
945 Logger::log('Delete invalid cached XML for URI '.$related_uri, Logger::DEBUG);
946 DBA::delete('conversation', ['item-uri' => $related_uri]);
951 $curlResult = DI::httpRequest()->get($related, false, ['accept_content' => 'application/atom+xml, text/html']);
953 if (!$curlResult->isSuccess()) {
959 if (stristr($curlResult->getHeader(), 'Content-Type: application/atom+xml')) {
960 Logger::log('Directly fetched XML for URI ' . $related_uri, Logger::DEBUG);
961 $xml = $curlResult->getBody();
965 $doc = new DOMDocument();
966 if (!@$doc->loadHTML($curlResult->getBody())) {
969 $xpath = new DOMXPath($doc);
973 $links = $xpath->query('//link');
975 foreach ($links as $link) {
976 $attribute = self::readAttributes($link);
977 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
978 $atom_file = $attribute['href'];
981 if ($atom_file != '') {
982 $curlResult = DI::httpRequest()->get($atom_file);
984 if ($curlResult->isSuccess()) {
985 Logger::log('Fetched XML for URI ' . $related_uri, Logger::DEBUG);
986 $xml = $curlResult->getBody();
992 // Workaround for older GNU Social servers
993 if (($xml == '') && strstr($related, '/notice/')) {
994 $curlResult = DI::httpRequest()->get(str_replace('/notice/', '/api/statuses/show/', $related) . '.atom');
996 if ($curlResult->isSuccess()) {
997 Logger::log('GNU Social workaround to fetch XML for URI ' . $related_uri, Logger::DEBUG);
998 $xml = $curlResult->getBody();
1002 // Even more worse workaround for GNU Social ;-)
1004 $related_guess = self::convertHref($related_uri);
1005 $curlResult = DI::httpRequest()->get(str_replace('/notice/', '/api/statuses/show/', $related_guess) . '.atom');
1007 if ($curlResult->isSuccess()) {
1008 Logger::log('GNU Social workaround 2 to fetch XML for URI ' . $related_uri, Logger::DEBUG);
1009 $xml = $curlResult->getBody();
1013 // Finally we take the data that we fetched from "ostatus:conversation"
1015 $condition = ['item-uri' => $related_uri, 'protocol' => Conversation::PARCEL_SPLIT_CONVERSATION];
1016 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1017 if (DBA::isResult($conversation)) {
1019 Logger::log('Got cached XML from conversation for URI '.$related_uri, Logger::DEBUG);
1020 $xml = $conversation['source'];
1025 self::process($xml, $importer, $contact, $hub, $stored, false);
1027 Logger::log("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, Logger::DEBUG);
1033 * Processes the XML for a repeated post
1035 * @param DOMXPath $xpath The xpath object
1036 * @param object $entry The xml entry that is processed
1037 * @param array $item The item array
1038 * @param array $importer user record of the importing user
1040 * @return array with data from links
1041 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1042 * @throws \ImagickException
1044 private static function processRepeatedItem(DOMXPath $xpath, $entry, array &$item, array $importer)
1046 $activityobject = $xpath->query('activity:object', $entry)->item(0);
1048 if (!is_object($activityobject)) {
1054 $orig_uri = XML::getFirstNodeValue($xpath, 'atom:id/text()', $activityobject);
1056 $links = $xpath->query("atom:link", $activityobject);
1058 $link_data = self::processLinks($links, $item);
1061 $orig_body = XML::getFirstNodeValue($xpath, 'atom:content/text()', $activityobject);
1062 $orig_created = XML::getFirstNodeValue($xpath, 'atom:published/text()', $activityobject);
1063 $orig_edited = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $activityobject);
1065 $orig_author = self::fetchAuthor($xpath, $activityobject, $importer, $dummy, false);
1067 $item["author-name"] = $orig_author["author-name"];
1068 $item["author-link"] = $orig_author["author-link"];
1069 $item["author-id"] = $orig_author["author-id"];
1071 $item["body"] = HTML::toBBCode($orig_body);
1072 $item["created"] = $orig_created;
1073 $item["edited"] = $orig_edited;
1075 $item["uri"] = $orig_uri;
1077 $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $activityobject);
1079 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $activityobject);
1081 // Mastodon Content Warning
1082 if (($item["verb"] == Activity::POST) && $xpath->evaluate('boolean(atom:summary)', $activityobject)) {
1083 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $activityobject);
1084 if (!empty($clear_text)) {
1085 $item['content-warning'] = HTML::toBBCode($clear_text);
1089 $inreplyto = $xpath->query('thr:in-reply-to', $activityobject);
1090 if (is_object($inreplyto->item(0))) {
1091 foreach ($inreplyto->item(0)->attributes as $attributes) {
1092 if ($attributes->name == "ref") {
1093 $item["parent-uri"] = $attributes->textContent;
1102 * Processes links in the XML
1104 * @param object $links The xml data that contain links
1105 * @param array $item The item array
1107 * @return array with data from the links
1109 private static function processLinks($links, array &$item)
1111 $link_data = ['add_body' => '', 'self' => ''];
1113 foreach ($links as $link) {
1114 $attribute = self::readAttributes($link);
1116 if (!empty($attribute['rel']) && !empty($attribute['href'])) {
1117 switch ($attribute['rel']) {
1119 $item["plink"] = $attribute['href'];
1120 if (($item["object-type"] == Activity\ObjectType::QUESTION)
1121 || ($item["object-type"] == Activity\ObjectType::EVENT)
1123 $item["body"] .= "\n" . PageInfo::getFooterFromUrl($attribute['href']);
1126 case "ostatus:conversation":
1127 $link_data['conversation'] = $attribute['href'];
1128 $item['conversation-href'] = $link_data['conversation'];
1129 if (!isset($item['conversation-uri'])) {
1130 $item['conversation-uri'] = $item['conversation-href'];
1134 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
1135 if ($filetype == 'image') {
1136 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1138 if (!empty($item["attach"])) {
1139 $item["attach"] .= ',';
1141 $item["attach"] = '';
1143 if (!isset($attribute['length'])) {
1144 $attribute['length'] = "0";
1146 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.($attribute['title'] ?? '') .'"[/attach]';
1150 if ($item["object-type"] != Activity\ObjectType::BOOKMARK) {
1151 if (!isset($item["parent-uri"])) {
1152 $item["parent-uri"] = $attribute['href'];
1154 $link_data['related'] = $attribute['href'];
1156 $item["body"] .= "\n" . PageInfo::getFooterFromUrl($attribute['href']);
1160 if (empty($item["plink"])) {
1161 $item["plink"] = $attribute['href'];
1163 $link_data['self'] = $attribute['href'];
1172 * Create an url out of an uri
1174 * @param string $href URI in the format "parameter1:parameter1:..."
1176 * @return string URL in the format http(s)://....
1178 private static function convertHref($href)
1180 $elements = explode(":", $href);
1182 if ((count($elements) <= 2) || ($elements[0] != "tag")) {
1186 $server = explode(",", $elements[1]);
1187 $conversation = explode("=", $elements[2]);
1189 if ((count($elements) == 4) && ($elements[2] == "post")) {
1190 return "http://".$server[0]."/notice/".$elements[3];
1193 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1196 if ($elements[3] == "objectType=thread") {
1197 return "http://".$server[0]."/conversation/".$conversation[1];
1199 return "http://".$server[0]."/notice/".$conversation[1];
1204 * Checks if the current post is a reshare
1206 * @param array $item The item array of thw post
1208 * @return string The guid if the post is a reshare
1210 public static function getResharedGuid(array $item)
1212 $reshared = Item::getShareArray($item);
1213 if (empty($reshared['guid']) || !empty($reshared['comment'])) {
1217 return $reshared['guid'];
1221 * Cleans the body of a post if it contains picture links
1223 * @param string $body The body
1225 * @return string The cleaned body
1226 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1228 public static function formatPicturePost($body)
1230 $siteinfo = BBCode::getAttachedData($body);
1232 if (($siteinfo["type"] == "photo") && (!empty($siteinfo["preview"]) || !empty($siteinfo["image"]))) {
1233 if (isset($siteinfo["preview"])) {
1234 $preview = $siteinfo["preview"];
1236 $preview = $siteinfo["image"];
1239 // Is it a remote picture? Then make a smaller preview here
1240 $preview = ProxyUtils::proxifyUrl($preview, false, ProxyUtils::SIZE_SMALL);
1242 // Is it a local picture? Then make it smaller here
1243 $preview = str_replace(["-0.jpg", "-0.png"], ["-2.jpg", "-2.png"], $preview);
1244 $preview = str_replace(["-1.jpg", "-1.png"], ["-2.jpg", "-2.png"], $preview);
1246 if (isset($siteinfo["url"])) {
1247 $url = $siteinfo["url"];
1249 $url = $siteinfo["image"];
1252 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1259 * Adds the header elements to the XML document
1261 * @param DOMDocument $doc XML document
1262 * @param array $owner Contact data of the poster
1263 * @param string $filter The related feed filter (activity, posts or comments)
1265 * @return object header root element
1266 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1268 private static function addHeader(DOMDocument $doc, array $owner, $filter)
1270 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
1271 $doc->appendChild($root);
1273 $root->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
1274 $root->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
1275 $root->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
1276 $root->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
1277 $root->setAttribute("xmlns:poco", ActivityNamespace::POCO);
1278 $root->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
1279 $root->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
1280 $root->setAttribute("xmlns:mastodon", ActivityNamespace::MASTODON);
1283 $selfUri = '/feed/' . $owner["nick"] . '/';
1286 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
1287 $selfUri .= $filter;
1290 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
1293 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
1294 $selfUri .= $filter;
1298 $selfUri = "/dfrn_poll/" . $owner["nick"];
1300 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
1301 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1302 XML::addElement($doc, $root, "id", DI::baseUrl() . "/profile/" . $owner["nick"]);
1303 XML::addElement($doc, $root, "title", $title);
1304 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], DI::config()->get('config', 'sitename')));
1305 XML::addElement($doc, $root, "logo", $owner["photo"]);
1306 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1308 $author = self::addAuthor($doc, $owner, true);
1309 $root->appendChild($author);
1311 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1312 XML::addElement($doc, $root, "link", "", $attributes);
1314 /// @TODO We have to find out what this is
1315 /// $attributes = array("href" => DI::baseUrl()."/sup",
1316 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1317 /// "type" => "application/json");
1318 /// XML::addElement($doc, $root, "link", "", $attributes);
1320 self::hublinks($doc, $root, $owner["nick"]);
1322 $attributes = ["href" => DI::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "salmon"];
1323 XML::addElement($doc, $root, "link", "", $attributes);
1325 $attributes = ["href" => DI::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies"];
1326 XML::addElement($doc, $root, "link", "", $attributes);
1328 $attributes = ["href" => DI::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention"];
1329 XML::addElement($doc, $root, "link", "", $attributes);
1331 $attributes = ["href" => DI::baseUrl() . $selfUri, "rel" => "self", "type" => "application/atom+xml"];
1332 XML::addElement($doc, $root, "link", "", $attributes);
1334 if ($owner['contact-type'] == Contact::TYPE_COMMUNITY) {
1335 $condition = ['uid' => $owner['uid'], 'self' => false, 'pending' => false,
1336 'archive' => false, 'hidden' => false, 'blocked' => false];
1337 $members = DBA::count('contact', $condition);
1338 XML::addElement($doc, $root, "statusnet:group_info", "", ["member_count" => $members]);
1345 * Add the link to the push hubs to the XML document
1347 * @param DOMDocument $doc XML document
1348 * @param object $root XML root element where the hub links are added
1349 * @param object $nick nick
1351 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1353 public static function hublinks(DOMDocument $doc, $root, $nick)
1355 $h = DI::baseUrl() . '/pubsubhubbub/'.$nick;
1356 XML::addElement($doc, $root, "link", "", ["href" => $h, "rel" => "hub"]);
1360 * Adds attachment data to the XML document
1362 * @param DOMDocument $doc XML document
1363 * @param object $root XML root element where the hub links are added
1364 * @param array $item Data of the item that is to be posted
1366 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1368 public static function getAttachment(DOMDocument $doc, $root, $item)
1370 $siteinfo = BBCode::getAttachedData($item["body"]);
1372 switch ($siteinfo["type"]) {
1374 if (!empty($siteinfo["image"])) {
1375 $imgdata = Images::getInfoFromURLCached($siteinfo["image"]);
1377 $attributes = ["rel" => "enclosure",
1378 "href" => $siteinfo["image"],
1379 "type" => $imgdata["mime"],
1380 "length" => intval($imgdata["size"])];
1381 XML::addElement($doc, $root, "link", "", $attributes);
1386 $attributes = ["rel" => "enclosure",
1387 "href" => $siteinfo["url"],
1388 "type" => "text/html; charset=UTF-8",
1390 "title" => ($siteinfo["title"] ?? '') ?: $siteinfo["url"],
1392 XML::addElement($doc, $root, "link", "", $attributes);
1398 if (!DI::config()->get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1399 $imgdata = Images::getInfoFromURLCached($siteinfo["image"]);
1401 $attributes = ["rel" => "enclosure",
1402 "href" => $siteinfo["image"],
1403 "type" => $imgdata["mime"],
1404 "length" => intval($imgdata["size"])];
1406 XML::addElement($doc, $root, "link", "", $attributes);
1410 $arr = explode('[/attach],', $item['attach']);
1412 foreach ($arr as $r) {
1414 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1416 $attributes = ["rel" => "enclosure",
1417 "href" => $matches[1],
1418 "type" => $matches[3]];
1420 if (intval($matches[2])) {
1421 $attributes["length"] = intval($matches[2]);
1423 if (trim($matches[4]) != "") {
1424 $attributes["title"] = trim($matches[4]);
1426 XML::addElement($doc, $root, "link", "", $attributes);
1433 * Adds the author element to the XML document
1435 * @param DOMDocument $doc XML document
1436 * @param array $owner Contact data of the poster
1437 * @param bool $show_profile Whether to show profile
1439 * @return \DOMElement author element
1440 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1442 private static function addAuthor(DOMDocument $doc, array $owner, $show_profile = true)
1444 $profile = DBA::selectFirst('profile', ['homepage', 'publish'], ['uid' => $owner['uid']]);
1445 $author = $doc->createElement("author");
1446 XML::addElement($doc, $author, "id", $owner["url"]);
1447 if ($owner['contact-type'] == Contact::TYPE_COMMUNITY) {
1448 XML::addElement($doc, $author, "activity:object-type", Activity\ObjectType::GROUP);
1450 XML::addElement($doc, $author, "activity:object-type", Activity\ObjectType::PERSON);
1453 XML::addElement($doc, $author, "uri", $owner["url"]);
1454 XML::addElement($doc, $author, "name", $owner["nick"]);
1455 XML::addElement($doc, $author, "email", $owner["addr"]);
1456 if ($show_profile) {
1457 XML::addElement($doc, $author, "summary", BBCode::convert($owner["about"], false, BBCode::OSTATUS));
1460 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $owner["url"]];
1461 XML::addElement($doc, $author, "link", "", $attributes);
1465 "type" => "image/jpeg", // To-Do?
1466 "media:width" => 300,
1467 "media:height" => 300,
1468 "href" => $owner["photo"]];
1469 XML::addElement($doc, $author, "link", "", $attributes);
1471 if (isset($owner["thumb"])) {
1474 "type" => "image/jpeg", // To-Do?
1475 "media:width" => 80,
1476 "media:height" => 80,
1477 "href" => $owner["thumb"]];
1478 XML::addElement($doc, $author, "link", "", $attributes);
1481 XML::addElement($doc, $author, "poco:preferredUsername", $owner["nick"]);
1482 XML::addElement($doc, $author, "poco:displayName", $owner["name"]);
1483 if ($show_profile) {
1484 XML::addElement($doc, $author, "poco:note", BBCode::convert($owner["about"], false, BBCode::OSTATUS));
1486 if (trim($owner["location"]) != "") {
1487 $element = $doc->createElement("poco:address");
1488 XML::addElement($doc, $element, "poco:formatted", $owner["location"]);
1489 $author->appendChild($element);
1493 if (DBA::isResult($profile) && !$show_profile) {
1494 if (trim($profile["homepage"]) != "") {
1495 $urls = $doc->createElement("poco:urls");
1496 XML::addElement($doc, $urls, "poco:type", "homepage");
1497 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
1498 XML::addElement($doc, $urls, "poco:primary", "true");
1499 $author->appendChild($urls);
1502 XML::addElement($doc, $author, "followers", "", ["url" => DI::baseUrl() . "/profile/" . $owner["nick"] . "/contacts/followers"]);
1503 XML::addElement($doc, $author, "statusnet:profile_info", "", ["local_id" => $owner["uid"]]);
1505 if ($profile["publish"]) {
1506 XML::addElement($doc, $author, "mastodon:scope", "public");
1514 * @TODO Picture attachments should look like this:
1515 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1516 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1520 * Returns the given activity if present - otherwise returns the "post" activity
1522 * @param array $item Data of the item that is to be posted
1524 * @return string activity
1526 public static function constructVerb(array $item)
1528 if (!empty($item['verb'])) {
1529 return $item['verb'];
1532 return Activity::POST;
1536 * Returns the given object type if present - otherwise returns the "note" object type
1538 * @param array $item Data of the item that is to be posted
1540 * @return string Object type
1542 private static function constructObjecttype(array $item)
1544 if (!empty($item['object-type']) && in_array($item['object-type'], [Activity\ObjectType::NOTE, Activity\ObjectType::COMMENT])) {
1545 return $item['object-type'];
1548 return Activity\ObjectType::NOTE;
1552 * Adds an entry element to the XML document
1554 * @param DOMDocument $doc XML document
1555 * @param array $item Data of the item that is to be posted
1556 * @param array $owner Contact data of the poster
1557 * @param bool $toplevel optional default false
1559 * @return \DOMElement Entry element
1560 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1561 * @throws \ImagickException
1563 private static function entry(DOMDocument $doc, array $item, array $owner, $toplevel = false)
1567 $repeated_guid = self::getResharedGuid($item);
1568 if ($repeated_guid != "") {
1569 $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel);
1576 if ($item["verb"] == Activity::LIKE) {
1577 return self::likeEntry($doc, $item, $owner, $toplevel);
1578 } elseif (in_array($item["verb"], [Activity::FOLLOW, Activity::O_UNFOLLOW])) {
1579 return self::followEntry($doc, $item, $owner, $toplevel);
1581 return self::noteEntry($doc, $item, $owner, $toplevel);
1586 * Adds a source entry to the XML document
1588 * @param DOMDocument $doc XML document
1589 * @param array $contact Array of the contact that is added
1591 * @return \DOMElement Source element
1592 * @throws \Exception
1594 private static function sourceEntry(DOMDocument $doc, array $contact)
1596 $source = $doc->createElement("source");
1597 XML::addElement($doc, $source, "id", $contact["poll"]);
1598 XML::addElement($doc, $source, "title", $contact["name"]);
1599 XML::addElement($doc, $source, "link", "", ["rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]]);
1600 XML::addElement($doc, $source, "link", "", ["rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]]);
1601 XML::addElement($doc, $source, "icon", $contact["photo"]);
1602 XML::addElement($doc, $source, "updated", DateTimeFormat::utc($contact["success_update"]."+00:00", DateTimeFormat::ATOM));
1608 * Adds an entry element with reshared content
1610 * @param DOMDocument $doc XML document
1611 * @param array $item Data of the item that is to be posted
1612 * @param array $owner Contact data of the poster
1613 * @param string $repeated_guid guid
1614 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1616 * @return bool Entry element
1617 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1618 * @throws \ImagickException
1620 private static function reshareEntry(DOMDocument $doc, array $item, array $owner, $repeated_guid, $toplevel)
1622 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1623 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1626 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1628 $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => [Item::PUBLIC, Item::UNLISTED],
1629 'network' => [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS]];
1630 $repeated_item = Item::selectFirst([], $condition);
1631 if (!DBA::isResult($repeated_item)) {
1635 $contact = Contact::getByURL($repeated_item['author-link']) ?: $owner;
1637 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1639 self::entryContent($doc, $entry, $item, $owner, $title, Activity::SHARE, false);
1641 $as_object = $doc->createElement("activity:object");
1643 XML::addElement($doc, $as_object, "activity:object-type", ActivityNamespace::ACTIVITY_SCHEMA . "activity");
1645 self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false);
1647 $author = self::addAuthor($doc, $contact, false);
1648 $as_object->appendChild($author);
1650 $as_object2 = $doc->createElement("activity:object");
1652 XML::addElement($doc, $as_object2, "activity:object-type", self::constructObjecttype($repeated_item));
1654 $title = sprintf("New comment by %s", $contact["nick"]);
1656 self::entryContent($doc, $as_object2, $repeated_item, $owner, $title);
1658 $as_object->appendChild($as_object2);
1660 self::entryFooter($doc, $as_object, $item, $owner, false);
1662 $source = self::sourceEntry($doc, $contact);
1664 $as_object->appendChild($source);
1666 $entry->appendChild($as_object);
1668 self::entryFooter($doc, $entry, $item, $owner, true);
1674 * Adds an entry element with a "like"
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 bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1681 * @return \DOMElement Entry element with "like"
1682 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1683 * @throws \ImagickException
1685 private static function likeEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1687 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1688 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1691 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1693 $verb = ActivityNamespace::ACTIVITY_SCHEMA . "favorite";
1694 self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false);
1696 $parent = Item::selectFirst([], ['uri' => $item["thr-parent"], 'uid' => $item["uid"]]);
1697 if (DBA::isResult($parent)) {
1698 $as_object = $doc->createElement("activity:object");
1700 XML::addElement($doc, $as_object, "activity:object-type", self::constructObjecttype($parent));
1702 self::entryContent($doc, $as_object, $parent, $owner, "New entry");
1704 $entry->appendChild($as_object);
1707 self::entryFooter($doc, $entry, $item, $owner);
1713 * Adds the person object element to the XML document
1715 * @param DOMDocument $doc XML document
1716 * @param array $owner Contact data of the poster
1717 * @param array $contact Contact data of the target
1719 * @return object author element
1721 private static function addPersonObject(DOMDocument $doc, array $owner, array $contact)
1723 $object = $doc->createElement("activity:object");
1724 XML::addElement($doc, $object, "activity:object-type", Activity\ObjectType::PERSON);
1726 if ($contact['network'] == Protocol::PHANTOM) {
1727 XML::addElement($doc, $object, "id", $contact['url']);
1731 XML::addElement($doc, $object, "id", $contact["alias"]);
1732 XML::addElement($doc, $object, "title", $contact["nick"]);
1734 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $contact["url"]];
1735 XML::addElement($doc, $object, "link", "", $attributes);
1739 "type" => "image/jpeg", // To-Do?
1740 "media:width" => 300,
1741 "media:height" => 300,
1742 "href" => $contact["photo"]];
1743 XML::addElement($doc, $object, "link", "", $attributes);
1745 XML::addElement($doc, $object, "poco:preferredUsername", $contact["nick"]);
1746 XML::addElement($doc, $object, "poco:displayName", $contact["name"]);
1748 if (trim($contact["location"]) != "") {
1749 $element = $doc->createElement("poco:address");
1750 XML::addElement($doc, $element, "poco:formatted", $contact["location"]);
1751 $object->appendChild($element);
1758 * Adds a follow/unfollow entry element
1760 * @param DOMDocument $doc XML document
1761 * @param array $item Data of the follow/unfollow message
1762 * @param array $owner Contact data of the poster
1763 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1765 * @return \DOMElement Entry element
1766 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1767 * @throws \ImagickException
1769 private static function followEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1771 $item["id"] = $item['parent'] = 0;
1772 $item["created"] = $item["edited"] = date("c");
1773 $item["private"] = Item::PRIVATE;
1775 $contact = Contact::getByURL($item['follow']);
1776 $item['follow'] = $contact['url'];
1778 if ($contact['alias']) {
1779 $item['follow'] = $contact['alias'];
1781 $contact['alias'] = $contact['url'];
1784 $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($contact["url"])];
1785 $user_contact = DBA::selectFirst('contact', ['id'], $condition);
1787 if (DBA::isResult($user_contact)) {
1788 $connect_id = $user_contact['id'];
1793 if ($item['verb'] == Activity::FOLLOW) {
1794 $message = DI::l10n()->t('%s is now following %s.');
1795 $title = DI::l10n()->t('following');
1796 $action = "subscription";
1798 $message = DI::l10n()->t('%s stopped following %s.');
1799 $title = DI::l10n()->t('stopped following');
1800 $action = "unfollow";
1803 $item["uri"] = $item['parent-uri'] = $item['thr-parent']
1804 = 'tag:' . DI::baseUrl()->getHostname().
1805 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1806 ':person:'.$connect_id.':'.$item['created'];
1808 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1810 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1812 self::entryContent($doc, $entry, $item, $owner, $title);
1814 $object = self::addPersonObject($doc, $owner, $contact);
1815 $entry->appendChild($object);
1817 self::entryFooter($doc, $entry, $item, $owner);
1823 * Adds a regular entry element
1825 * @param DOMDocument $doc XML document
1826 * @param array $item Data of the item that is to be posted
1827 * @param array $owner Contact data of the poster
1828 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1830 * @return \DOMElement Entry element
1831 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1832 * @throws \ImagickException
1834 private static function noteEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1836 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1837 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1841 if (!empty($item['title'])) {
1842 $title = BBCode::convert($item['title'], false, BBCode::OSTATUS);
1844 $title = sprintf("New note by %s", $owner["nick"]);
1847 $title = sprintf("New comment by %s", $owner["nick"]);
1850 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1852 XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::NOTE);
1854 self::entryContent($doc, $entry, $item, $owner, $title, '', true);
1856 self::entryFooter($doc, $entry, $item, $owner, true);
1862 * Adds a header element to the XML document
1864 * @param DOMDocument $doc XML document
1865 * @param array $owner Contact data of the poster
1866 * @param array $item
1867 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1869 * @return \DOMElement The entry element where the elements are added
1870 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1871 * @throws \ImagickException
1873 public static function entryHeader(DOMDocument $doc, array $owner, array $item, $toplevel)
1876 $entry = $doc->createElement("entry");
1878 if ($owner['contact-type'] == Contact::TYPE_COMMUNITY) {
1879 $contact = Contact::getByURL($item['author-link']) ?: $owner;
1880 $author = self::addAuthor($doc, $contact, false);
1881 $entry->appendChild($author);
1884 $entry = $doc->createElementNS(ActivityNamespace::ATOM1, "entry");
1886 $entry->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
1887 $entry->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
1888 $entry->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
1889 $entry->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
1890 $entry->setAttribute("xmlns:poco", ActivityNamespace::POCO);
1891 $entry->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
1892 $entry->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
1893 $entry->setAttribute("xmlns:mastodon", ActivityNamespace::MASTODON);
1895 $author = self::addAuthor($doc, $owner);
1896 $entry->appendChild($author);
1903 * Adds elements to the XML document
1905 * @param DOMDocument $doc XML document
1906 * @param \DOMElement $entry Entry element where the content is added
1907 * @param array $item Data of the item that is to be posted
1908 * @param array $owner Contact data of the poster
1909 * @param string $title Title for the post
1910 * @param string $verb The activity verb
1911 * @param bool $complete Add the "status_net" element?
1913 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1915 private static function entryContent(DOMDocument $doc, \DOMElement $entry, array $item, array $owner, $title, $verb = "", $complete = true)
1918 $verb = self::constructVerb($item);
1921 XML::addElement($doc, $entry, "id", $item["uri"]);
1922 XML::addElement($doc, $entry, "title", html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1924 $body = self::formatPicturePost($item['body']);
1926 if (!empty($item['title'])) {
1927 $body = "[b]".$item['title']."[/b]\n\n".$body;
1930 $body = BBCode::convert($body, false, BBCode::OSTATUS);
1932 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1934 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1935 "href" => DI::baseUrl()."/display/".$item["guid"]]
1938 if ($complete && ($item["id"] > 0)) {
1939 XML::addElement($doc, $entry, "status_net", "", ["notice_id" => $item["id"]]);
1942 XML::addElement($doc, $entry, "activity:verb", $verb);
1944 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
1945 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
1949 * Adds the elements at the foot of an entry to the XML document
1951 * @param DOMDocument $doc XML document
1952 * @param object $entry The entry element where the elements are added
1953 * @param array $item Data of the item that is to be posted
1954 * @param array $owner Contact data of the poster
1955 * @param bool $complete default true
1957 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1959 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner, $complete = true)
1963 if ($item['gravity'] != GRAVITY_PARENT) {
1964 $parent = Item::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
1965 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1967 $thrparent = Item::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $parent_item]);
1969 if (DBA::isResult($thrparent)) {
1970 $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
1971 $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
1972 $parent_plink = $thrparent["plink"];
1974 $mentioned[$parent["author-link"]] = $parent["author-link"];
1975 $mentioned[$parent["owner-link"]] = $parent["owner-link"];
1976 $parent_plink = DI::baseUrl()."/display/".$parent["guid"];
1980 "ref" => $parent_item,
1981 "href" => $parent_plink];
1982 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
1986 "href" => $parent_plink];
1987 XML::addElement($doc, $entry, "link", "", $attributes);
1990 if (intval($item['parent']) > 0) {
1991 $conversation_href = $conversation_uri = str_replace('/objects/', '/context/', $item['parent-uri']);
1993 if (isset($parent_item)) {
1994 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $parent_item]);
1995 if (DBA::isResult($conversation)) {
1996 if ($conversation['conversation-uri'] != '') {
1997 $conversation_uri = $conversation['conversation-uri'];
1999 if ($conversation['conversation-href'] != '') {
2000 $conversation_href = $conversation['conversation-href'];
2005 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:conversation", "href" => $conversation_href]);
2008 "href" => $conversation_href,
2009 "local_id" => $item['parent'],
2010 "ref" => $conversation_uri];
2012 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
2015 // uri-id isn't present for follow entry pseudo-items
2016 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
2017 foreach ($tags as $tag) {
2018 $mentioned[$tag['url']] = $tag['url'];
2021 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2023 foreach ($mentioned as $mention) {
2024 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2025 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2027 $mentioned = $newmentions;
2029 foreach ($mentioned as $mention) {
2030 $contact = Contact::getByURL($mention, ['contact-type']);
2031 if (!empty($contact) && ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
2032 XML::addElement($doc, $entry, "link", "",
2034 "rel" => "mentioned",
2035 "ostatus:object-type" => Activity\ObjectType::GROUP,
2039 XML::addElement($doc, $entry, "link", "",
2041 "rel" => "mentioned",
2042 "ostatus:object-type" => Activity\ObjectType::PERSON,
2048 if ($owner['contact-type'] == Contact::TYPE_COMMUNITY) {
2049 XML::addElement($doc, $entry, "link", "", [
2050 "rel" => "mentioned",
2051 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/group",
2052 "href" => $owner['url']
2056 if ($item['private'] != Item::PRIVATE) {
2057 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:attention",
2058 "href" => "http://activityschema.org/collection/public"]);
2059 XML::addElement($doc, $entry, "link", "", ["rel" => "mentioned",
2060 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2061 "href" => "http://activityschema.org/collection/public"]);
2062 XML::addElement($doc, $entry, "mastodon:scope", "public");
2065 foreach ($tags as $tag) {
2066 if ($tag['type'] == Tag::HASHTAG) {
2067 XML::addElement($doc, $entry, "category", "", ["term" => $tag['name']]);
2071 self::getAttachment($doc, $entry, $item);
2073 if ($complete && ($item["id"] > 0)) {
2074 $app = $item["app"];
2079 $attributes = ["local_id" => $item["id"], "source" => $app];
2081 if (isset($parent["id"])) {
2082 $attributes["repeat_of"] = $parent["id"];
2085 if ($item["coord"] != "") {
2086 XML::addElement($doc, $entry, "georss:point", $item["coord"]);
2089 XML::addElement($doc, $entry, "statusnet:notice_info", "", $attributes);
2094 * Creates the XML feed for a given nickname
2096 * Supported filters:
2097 * - activity (default): all the public posts
2098 * - posts: all the public top-level posts
2099 * - comments: all the public replies
2101 * Updates the provided last_update parameter if the result comes from the
2102 * cache or it is empty
2104 * @param string $owner_nick Nickname of the feed owner
2105 * @param string $last_update Date of the last update
2106 * @param integer $max_items Number of maximum items to fetch
2107 * @param string $filter Feed items filter (activity, posts or comments)
2108 * @param boolean $nocache Wether to bypass caching
2110 * @return string XML feed
2111 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2112 * @throws \ImagickException
2114 public static function feed($owner_nick, &$last_update, $max_items = 300, $filter = 'activity', $nocache = false)
2116 $stamp = microtime(true);
2118 $owner = User::getOwnerDataByNick($owner_nick);
2123 $cachekey = "ostatus:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
2125 $previous_created = $last_update;
2127 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
2128 if ((time() - strtotime($owner['last-item'])) < 15*60) {
2129 $result = DI::cache()->get($cachekey);
2130 if (!$nocache && !is_null($result)) {
2131 Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', Logger::DEBUG);
2132 $last_update = $result['last_update'];
2133 return $result['feed'];
2137 if (!strlen($last_update)) {
2138 $last_update = 'now -30 days';
2141 $check_date = DateTimeFormat::utc($last_update);
2142 $authorid = Contact::getIdForURL($owner["url"], 0, false);
2144 $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted`
2145 AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?)",
2146 $owner["uid"], $check_date, Item::PRIVATE, Protocol::OSTATUS, Protocol::DFRN];
2148 if ($filter === 'comments') {
2149 $condition[0] .= " AND `object-type` = ? ";
2150 $condition[] = Activity\ObjectType::COMMENT;
2153 if ($owner['contact-type'] != Contact::TYPE_COMMUNITY) {
2154 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
2155 $condition[] = $owner["id"];
2156 $condition[] = $authorid;
2159 $params = ['order' => ['received' => true], 'limit' => $max_items];
2161 if ($filter === 'posts') {
2162 $ret = Item::selectThread([], $condition, $params);
2164 $ret = Item::select([], $condition, $params);
2167 $items = Item::inArray($ret);
2169 $doc = new DOMDocument('1.0', 'utf-8');
2170 $doc->formatOutput = true;
2172 $root = self::addHeader($doc, $owner, $filter);
2174 foreach ($items as $item) {
2175 if (DI::config()->get('system', 'ostatus_debug')) {
2176 $item['body'] .= '🍼';
2179 if (in_array($item["verb"], [Activity::FOLLOW, Activity::O_UNFOLLOW, Activity::LIKE])) {
2183 $entry = self::entry($doc, $item, $owner, false);
2184 $root->appendChild($entry);
2186 if ($last_update < $item['created']) {
2187 $last_update = $item['created'];
2191 $feeddata = trim($doc->saveXML());
2193 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
2194 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
2196 Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, Logger::DEBUG);
2202 * Creates the XML for a salmon message
2204 * @param array $item Data of the item that is to be posted
2205 * @param array $owner Contact data of the poster
2207 * @return string XML for the salmon
2208 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2209 * @throws \ImagickException
2211 public static function salmon(array $item, array $owner)
2213 $doc = new DOMDocument('1.0', 'utf-8');
2214 $doc->formatOutput = true;
2216 if (DI::config()->get('system', 'ostatus_debug')) {
2217 $item['body'] .= '🐟';
2220 $entry = self::entry($doc, $item, $owner, true);
2222 $doc->appendChild($entry);
2224 return trim($doc->saveXML());
2228 * Checks if the given contact url does support OStatus
2230 * @param string $url profile url
2231 * @param boolean $update Update the profile
2233 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2234 * @throws \ImagickException
2236 public static function isSupportedByContactUrl($url, $update = false)
2238 $probe = Probe::uri($url, Protocol::OSTATUS, 0, !$update);
2239 return $probe['network'] == Protocol::OSTATUS;