3 * @file src/Protocol/OStatus.php
5 namespace Friendica\Protocol;
9 use Friendica\Content\Text\BBCode;
10 use Friendica\Content\Text\HTML;
11 use Friendica\Core\Cache\Duration;
12 use Friendica\Core\Config;
13 use Friendica\Core\Logger;
14 use Friendica\Core\Protocol;
15 use Friendica\Database\DBA;
17 use Friendica\Model\APContact;
18 use Friendica\Model\Contact;
19 use Friendica\Model\Conversation;
20 use Friendica\Model\GContact;
21 use Friendica\Model\Item;
22 use Friendica\Model\User;
23 use Friendica\Network\Probe;
24 use Friendica\Util\DateTimeFormat;
25 use Friendica\Util\Images;
26 use Friendica\Util\Network;
27 use Friendica\Util\Proxy as ProxyUtils;
28 use Friendica\Util\Strings;
29 use Friendica\Util\XML;
31 require_once 'mod/share.php';
32 require_once 'include/api.php';
35 * This class contain functions for the OStatus protocol
39 private static $itemlist;
40 private static $conv_list = [];
45 * @param DOMXPath $xpath The xpath object
46 * @param object $context The xml context of the author details
47 * @param array $importer user record of the importing user
48 * @param array $contact Called by reference, will contain the fetched contact
49 * @param bool $onlyfetch Only fetch the header without updating the contact entries
51 * @return array Array of author related entries for the item
52 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
53 * @throws \ImagickException
55 private static function fetchAuthor(DOMXPath $xpath, $context, array $importer, array &$contact = null, $onlyfetch)
58 $author["author-link"] = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
59 $author["author-name"] = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $context);
60 $addr = XML::getFirstNodeValue($xpath, 'atom:author/atom:email/text()', $context);
62 $aliaslink = $author["author-link"];
64 $alternate_item = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0);
65 if (is_object($alternate_item)) {
66 foreach ($alternate_item->attributes as $attributes) {
67 if (($attributes->name == "href") && ($attributes->textContent != "")) {
68 $author["author-link"] = $attributes->textContent;
72 $author["author-id"] = Contact::getIdForURL($author["author-link"]);
74 $author['contact-id'] = ($contact['id'] ?? 0) ?: $author['author-id'];
79 This here would be better, but we would get problems with contacts from the statusnet addon
80 This is kept here as a reminder for the future
82 $cid = Contact::getIdForURL($author["author-link"], $importer["uid"]);
84 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
87 if ($aliaslink != '') {
88 $condition = ["`uid` = ? AND `alias` = ? AND `network` != ? AND `rel` IN (?, ?)",
89 $importer["uid"], $aliaslink, Protocol::STATUSNET,
90 Contact::SHARING, Contact::FRIEND];
91 $contact = DBA::selectFirst('contact', [], $condition);
94 if (!DBA::isResult($contact) && $author["author-link"] != '') {
95 if ($aliaslink == "") {
96 $aliaslink = $author["author-link"];
99 $condition = ["`uid` = ? AND `nurl` IN (?, ?) AND `network` != ? AND `rel` IN (?, ?)",
100 $importer["uid"], Strings::normaliseLink($author["author-link"]), Strings::normaliseLink($aliaslink),
101 Protocol::STATUSNET, Contact::SHARING, Contact::FRIEND];
102 $contact = DBA::selectFirst('contact', [], $condition);
105 if (!DBA::isResult($contact) && ($addr != '')) {
106 $condition = ["`uid` = ? AND `addr` = ? AND `network` != ? AND `rel` IN (?, ?)",
107 $importer["uid"], $addr, Protocol::STATUSNET,
108 Contact::SHARING, Contact::FRIEND];
109 $contact = DBA::selectFirst('contact', [], $condition);
112 if (DBA::isResult($contact)) {
113 if ($contact['blocked']) {
115 } elseif (!empty(APContact::getByURL($contact['url'], false))) {
116 ActivityPub\Receiver::switchContact($contact['id'], $importer['uid'], $contact['url']);
118 $author["contact-id"] = $contact["id"];
122 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
123 foreach ($avatars as $avatar) {
126 foreach ($avatar->attributes as $attributes) {
127 if ($attributes->name == "href") {
128 $href = $attributes->textContent;
130 if ($attributes->name == "width") {
131 $width = $attributes->textContent;
135 $avatarlist[$width] = $href;
138 if (count($avatarlist) > 0) {
140 $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
143 $displayname = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
144 if ($displayname != "") {
145 $author["author-name"] = $displayname;
148 $author["owner-id"] = $author["author-id"];
150 // Only update the contacts if it is an OStatus contact
151 if (DBA::isResult($contact) && ($contact['id'] > 0) && !$onlyfetch && ($contact["network"] == Protocol::OSTATUS)) {
153 // Update contact data
155 unset($current['name-date']);
157 // This query doesn't seem to work
158 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
160 // $contact["notify"] = $value;
162 // This query doesn't seem to work as well - I hate these queries
163 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
165 // $contact["poll"] = $value;
167 $contact['url'] = $author["author-link"];
168 $contact['nurl'] = Strings::normaliseLink($contact['url']);
170 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
172 $contact["alias"] = $value;
175 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
177 $contact["name"] = $value;
180 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()', $context);
182 $contact["nick"] = $value;
185 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()', $context);
187 $contact["about"] = HTML::toBBCode($value);
190 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()', $context);
192 $contact["location"] = $value;
195 $contact['name-date'] = DateTimeFormat::utcNow();
197 DBA::update('contact', $contact, ['id' => $contact["id"]], $current);
199 if (!empty($author["author-avatar"]) && ($author["author-avatar"] != $current['avatar'])) {
200 Logger::log("Update profile picture for contact ".$contact["id"], Logger::DEBUG);
201 Contact::updateAvatar($author["author-avatar"], $importer["uid"], $contact["id"]);
204 // Ensure that we are having this contact (with uid=0)
205 $cid = Contact::getIdForURL($aliaslink, 0, true);
208 $fields = ['url', 'nurl', 'name', 'nick', 'alias', 'about', 'location'];
209 $old_contact = DBA::selectFirst('contact', $fields, ['id' => $cid]);
211 // Update it with the current values
212 $fields = ['url' => $author["author-link"], 'name' => $contact["name"],
213 'nurl' => Strings::normaliseLink($author["author-link"]),
214 'nick' => $contact["nick"], 'alias' => $contact["alias"],
215 'about' => $contact["about"], 'location' => $contact["location"],
216 'success_update' => DateTimeFormat::utcNow(), 'last-update' => DateTimeFormat::utcNow()];
218 DBA::update('contact', $fields, ['id' => $cid], $old_contact);
221 if (!empty($author["author-avatar"])) {
222 Contact::updateAvatar($author["author-avatar"], 0, $cid);
226 $contact["generation"] = 2;
227 $contact["hide"] = false; // OStatus contacts are never hidden
228 if (!empty($author["author-avatar"])) {
229 $contact["photo"] = $author["author-avatar"];
231 $gcid = GContact::update($contact);
233 GContact::link($gcid, $contact["uid"], $contact["id"]);
234 } elseif ($contact["network"] != Protocol::DFRN) {
242 * Fetches author data from a given XML string
244 * @param string $xml The XML
245 * @param array $importer user record of the importing user
247 * @return array Array of author related entries for the item
248 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
249 * @throws \ImagickException
251 public static function salmonAuthor($xml, array $importer)
257 $doc = new DOMDocument();
258 @$doc->loadXML($xml);
260 $xpath = new DOMXPath($doc);
261 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
262 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
263 $xpath->registerNamespace('georss', ActivityNamespace::GEORSS);
264 $xpath->registerNamespace('activity', ActivityNamespace::ACTIVITY);
265 $xpath->registerNamespace('media', ActivityNamespace::MEDIA);
266 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
267 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
268 $xpath->registerNamespace('statusnet', ActivityNamespace::STATUSNET);
270 $contact = ["id" => 0];
272 // Fetch the first author
273 $authordata = $xpath->query('//author')->item(0);
274 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, true);
279 * Read attributes from element
281 * @param object $element Element object
283 * @return array attributes
285 private static function readAttributes($element)
289 foreach ($element->attributes as $attributes) {
290 $attribute[$attributes->name] = $attributes->textContent;
297 * Imports an XML string containing OStatus elements
299 * @param string $xml The XML
300 * @param array $importer user record of the importing user
301 * @param array $contact contact
302 * @param string $hub Called by reference, returns the fetched hub data
304 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
305 * @throws \ImagickException
307 public static function import($xml, array $importer, array &$contact, &$hub)
309 self::process($xml, $importer, $contact, $hub);
313 * Internal feed processing
315 * @param string $xml The XML
316 * @param array $importer user record of the importing user
317 * @param array $contact contact
318 * @param string $hub Called by reference, returns the fetched hub data
319 * @param boolean $stored Is the post fresh imported or from the database?
320 * @param boolean $initialize Is it the leading post so that data has to be initialized?
322 * @return boolean Could the XML be processed?
323 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
324 * @throws \ImagickException
326 private static function process($xml, array $importer, array &$contact = null, &$hub, $stored = false, $initialize = true)
329 self::$itemlist = [];
330 self::$conv_list = [];
333 Logger::log('Import OStatus message for user ' . $importer['uid'], Logger::DEBUG);
338 $doc = new DOMDocument();
339 @$doc->loadXML($xml);
341 $xpath = new DOMXPath($doc);
342 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
343 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
344 $xpath->registerNamespace('georss', ActivityNamespace::GEORSS);
345 $xpath->registerNamespace('activity', ActivityNamespace::ACTIVITY);
346 $xpath->registerNamespace('media', ActivityNamespace::MEDIA);
347 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
348 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
349 $xpath->registerNamespace('statusnet', ActivityNamespace::STATUSNET);
352 $hub_items = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0);
353 if (is_object($hub_items)) {
354 $hub_attributes = $hub_items->attributes;
355 if (is_object($hub_attributes)) {
356 foreach ($hub_attributes as $hub_attribute) {
357 if ($hub_attribute->name == "href") {
358 $hub = $hub_attribute->textContent;
359 Logger::log("Found hub ".$hub, Logger::DEBUG);
366 $header["uid"] = $importer["uid"];
367 $header["network"] = Protocol::OSTATUS;
369 $header["origin"] = 0;
370 $header["gravity"] = GRAVITY_COMMENT;
372 if (!is_object($doc->firstChild) || empty($doc->firstChild->tagName)) {
376 $first_child = $doc->firstChild->tagName;
378 if ($first_child == "feed") {
379 $entries = $xpath->query('/atom:feed/atom:entry');
381 $entries = $xpath->query('/atom:entry');
384 if ($entries->length == 1) {
385 // We reformat the XML to make it better readable
386 $doc2 = new DOMDocument();
387 $doc2->loadXML($xml);
388 $doc2->preserveWhiteSpace = false;
389 $doc2->formatOutput = true;
390 $xml2 = $doc2->saveXML();
392 $header["protocol"] = Conversation::PARCEL_SALMON;
393 $header["source"] = $xml2;
394 } elseif (!$initialize) {
398 // Fetch the first author
399 $authordata = $xpath->query('//author')->item(0);
400 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, $stored);
402 // Reverse the order of the entries
405 foreach ($entries as $entry) {
406 $entrylist[] = $entry;
409 foreach (array_reverse($entrylist) as $entry) {
411 $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
413 if ($authorelement->length == 0) {
414 $authorelement = $xpath->query('atom:author', $entry);
417 if ($authorelement->length > 0) {
418 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, $stored);
421 $item = array_merge($header, $author);
423 $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
425 $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $entry);
428 if (in_array($item["verb"], ['qvitter-delete-notice', Activity::DELETE, 'delete'])) {
429 self::deleteNotice($item);
433 if (in_array($item["verb"], [Activity::O_UNFAVOURITE, Activity::UNFAVORITE])) {
434 // Ignore "Unfavorite" message
435 Logger::log("Ignore unfavorite message ".print_r($item, true), Logger::DEBUG);
439 // Deletions come with the same uri, so we check for duplicates after processing deletions
440 if (Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]])) {
441 Logger::log('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', Logger::DEBUG);
444 Logger::log('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', Logger::DEBUG);
447 if ($item["verb"] == Activity::JOIN) {
448 // ignore "Join" messages
449 Logger::log("Ignore join message ".print_r($item, true), Logger::DEBUG);
453 if ($item["verb"] == "http://mastodon.social/schema/1.0/block") {
454 // ignore mastodon "block" messages
455 Logger::log("Ignore block message ".print_r($item, true), Logger::DEBUG);
459 if ($item["verb"] == Activity::FOLLOW) {
460 Contact::addRelationship($importer, $contact, $item);
464 if ($item["verb"] == Activity::O_UNFOLLOW) {
466 Contact::removeFollower($importer, $contact, $item, $dummy);
470 if ($item["verb"] == Activity::FAVORITE) {
471 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
472 Logger::log("Favorite ".$orig_uri." ".print_r($item, true));
474 $item["verb"] = Activity::LIKE;
475 $item["parent-uri"] = $orig_uri;
476 $item["gravity"] = GRAVITY_ACTIVITY;
477 $item["object-type"] = Activity\ObjectType::NOTE;
480 // http://activitystrea.ms/schema/1.0/rsvp-yes
481 if (!in_array($item["verb"], [Activity::POST, Activity::LIKE, Activity::SHARE])) {
482 Logger::log("Unhandled verb ".$item["verb"]." ".print_r($item, true), Logger::DEBUG);
485 self::processPost($xpath, $entry, $item, $importer);
487 if ($initialize && (count(self::$itemlist) > 0)) {
488 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['parent-uri']) {
489 // We will import it everytime, when it is started by our contacts
490 $valid = Contact::isSharingByURL(self::$itemlist[0]['author-link'], self::$itemlist[0]['uid']);
493 // If not, then it depends on this setting
494 $valid = ((self::$itemlist[0]['uid'] == 0) || !DI::pConfig()->get(self::$itemlist[0]['uid'], 'system', 'accept_only_sharer', false));
496 Logger::log("Item with uri ".self::$itemlist[0]['uri']." will be imported due to the system settings.", Logger::DEBUG);
499 Logger::log("Item with uri ".self::$itemlist[0]['uri']." belongs to a contact (".self::$itemlist[0]['contact-id']."). It will be imported.", Logger::DEBUG);
502 // Never post a thread when the only interaction by our contact was a like
504 $verbs = [Activity::POST, Activity::SHARE];
505 foreach (self::$itemlist as $item) {
506 if (in_array($item['verb'], $verbs) && Contact::isSharingByURL($item['author-link'], $item['uid'])) {
511 Logger::log("Item with uri ".self::$itemlist[0]['uri']." will be imported since the thread contains posts or shares.", Logger::DEBUG);
515 // But we will only import complete threads
516 $valid = Item::exists(['uid' => $importer["uid"], 'uri' => self::$itemlist[0]['parent-uri']]);
518 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);
523 $default_contact = 0;
524 for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
525 if (empty(self::$itemlist[$key]['contact-id'])) {
526 self::$itemlist[$key]['contact-id'] = $default_contact;
528 $default_contact = $item['contact-id'];
531 foreach (self::$itemlist as $item) {
532 $found = Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]]);
534 Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", Logger::DEBUG);
535 } elseif ($item['contact-id'] < 0) {
536 Logger::log("Item with uri ".$item["uri"]." is from a blocked contact.", Logger::DEBUG);
538 // We are having duplicated entries. Hopefully this solves it.
539 if (DI::lock()->acquire('ostatus_process_item_insert')) {
540 $ret = Item::insert($item);
541 DI::lock()->release('ostatus_process_item_insert');
542 Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret);
544 $ret = Item::insert($item);
545 Logger::log("We couldn't lock - but tried to store the item anyway. Return value is ".$ret);
550 self::$itemlist = [];
552 Logger::log('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.', Logger::DEBUG);
558 * Removes notice item from database
560 * @param array $item item
564 private static function deleteNotice(array $item)
566 $condition = ['uid' => $item['uid'], 'author-id' => $item['author-id'], 'uri' => $item['uri']];
567 if (!Item::exists($condition)) {
568 Logger::log('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it.");
572 Item::delete($condition);
574 Logger::log('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
578 * Processes the XML for a post
580 * @param DOMXPath $xpath The xpath object
581 * @param object $entry The xml entry that is processed
582 * @param array $item The item array
583 * @param array $importer user record of the importing user
585 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
586 * @throws \ImagickException
588 private static function processPost(DOMXPath $xpath, $entry, array &$item, array $importer)
590 $item["body"] = HTML::toBBCode(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
591 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $entry);
592 if (($item["object-type"] == Activity\ObjectType::BOOKMARK) || ($item["object-type"] == Activity\ObjectType::EVENT)) {
593 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
594 $item["body"] = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
595 } elseif ($item["object-type"] == Activity\ObjectType::QUESTION) {
596 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
599 $item["created"] = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
600 $item["edited"] = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
601 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
603 $conv = $xpath->query('ostatus:conversation', $entry);
604 if (is_object($conv->item(0))) {
605 foreach ($conv->item(0)->attributes as $attributes) {
606 if ($attributes->name == "ref") {
607 $item['conversation-uri'] = $attributes->textContent;
609 if ($attributes->name == "href") {
610 $item['conversation-href'] = $attributes->textContent;
617 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
618 if (is_object($inreplyto->item(0))) {
619 foreach ($inreplyto->item(0)->attributes as $attributes) {
620 if ($attributes->name == "ref") {
621 $item["parent-uri"] = $attributes->textContent;
623 if ($attributes->name == "href") {
624 $related = $attributes->textContent;
629 $georsspoint = $xpath->query('georss:point', $entry);
630 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
631 $item["coord"] = $georsspoint->item(0)->nodeValue;
634 $categories = $xpath->query('atom:category', $entry);
636 foreach ($categories as $category) {
637 foreach ($category->attributes as $attributes) {
638 if ($attributes->name == 'term') {
639 $term = $attributes->textContent;
640 if (!empty($item['tag'])) {
646 $item['tag'] .= '#[url=' . DI::baseUrl() . '/search?tag=' . $term . ']' . $term . '[/url]';
655 $links = $xpath->query('atom:link', $entry);
657 $link_data = self::processLinks($links, $item);
658 $self = $link_data['self'];
659 $add_body = $link_data['add_body'];
664 $notice_info = $xpath->query('statusnet:notice_info', $entry);
665 if ($notice_info && ($notice_info->length > 0)) {
666 foreach ($notice_info->item(0)->attributes as $attributes) {
667 if ($attributes->name == "source") {
668 $item["app"] = strip_tags($attributes->textContent);
670 if ($attributes->name == "repeat_of") {
671 $repeat_of = $attributes->textContent;
675 // Is it a repeated post?
676 if (($repeat_of != "") || ($item["verb"] == Activity::SHARE)) {
677 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
678 if (!empty($link_data['add_body'])) {
679 $add_body .= $link_data['add_body'];
683 $item["body"] .= $add_body;
685 // Only add additional data when there is no picture in the post
686 if (!strstr($item["body"], '[/img]')) {
687 $item["body"] = add_page_info_to_body($item["body"]);
690 // Mastodon Content Warning
691 if (($item["verb"] == Activity::POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
692 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
693 if (!empty($clear_text)) {
694 $item['content-warning'] = HTML::toBBCode($clear_text);
698 if (($self != '') && empty($item['protocol'])) {
699 self::fetchSelf($self, $item);
702 if (!empty($item["conversation-href"])) {
703 self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
706 if (isset($item["parent-uri"])) {
707 if (!Item::exists(['uid' => $importer["uid"], 'uri' => $item['parent-uri']])) {
708 if ($related != '') {
709 self::fetchRelated($related, $item["parent-uri"], $importer);
712 Logger::log('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', Logger::DEBUG);
715 $item["parent-uri"] = $item["uri"];
716 $item["gravity"] = GRAVITY_PARENT;
719 if (($item['author-link'] != '') && !empty($item['protocol'])) {
720 $item = Conversation::insert($item);
723 self::$itemlist[] = $item;
727 * Fetch the conversation for posts
729 * @param string $conversation The link to the conversation
730 * @param string $conversation_uri The conversation in "uri" format
732 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
734 private static function fetchConversation($conversation, $conversation_uri)
736 // Ensure that we only store a conversation once in a process
737 if (isset(self::$conv_list[$conversation])) {
741 self::$conv_list[$conversation] = true;
743 $curlResult = Network::curl($conversation, false, ['accept_content' => 'application/atom+xml, text/html']);
745 if (!$curlResult->isSuccess()) {
751 if (stristr($curlResult->getHeader(), 'Content-Type: application/atom+xml')) {
752 $xml = $curlResult->getBody();
756 $doc = new DOMDocument();
757 if (!@$doc->loadHTML($curlResult->getBody())) {
760 $xpath = new DOMXPath($doc);
762 $links = $xpath->query('//link');
765 foreach ($links as $link) {
766 $attribute = self::readAttributes($link);
767 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
768 $file = $attribute['href'];
772 $conversation_atom = Network::curl($attribute['href']);
774 if ($conversation_atom->isSuccess()) {
775 $xml = $conversation_atom->getBody();
785 self::storeConversation($xml, $conversation, $conversation_uri);
789 * Store a feed in several conversation entries
791 * @param string $xml The feed
792 * @param string $conversation conversation
793 * @param string $conversation_uri conversation uri
797 private static function storeConversation($xml, $conversation = '', $conversation_uri = '')
799 $doc = new DOMDocument();
800 @$doc->loadXML($xml);
802 $xpath = new DOMXPath($doc);
803 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
804 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
805 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
807 $entries = $xpath->query('/atom:feed/atom:entry');
809 // Now store the entries
810 foreach ($entries as $entry) {
811 $doc2 = new DOMDocument();
812 $doc2->preserveWhiteSpace = false;
813 $doc2->formatOutput = true;
817 $conv_data['protocol'] = Conversation::PARCEL_SPLIT_CONVERSATION;
818 $conv_data['network'] = Protocol::OSTATUS;
819 $conv_data['uri'] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
821 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
822 if (is_object($inreplyto->item(0))) {
823 foreach ($inreplyto->item(0)->attributes as $attributes) {
824 if ($attributes->name == "ref") {
825 $conv_data['reply-to-uri'] = $attributes->textContent;
830 $conv_data['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
832 $conv = $xpath->query('ostatus:conversation', $entry);
833 if (is_object($conv->item(0))) {
834 foreach ($conv->item(0)->attributes as $attributes) {
835 if ($attributes->name == "ref") {
836 $conv_data['conversation-uri'] = $attributes->textContent;
838 if ($attributes->name == "href") {
839 $conv_data['conversation-href'] = $attributes->textContent;
844 if ($conversation != '') {
845 $conv_data['conversation-uri'] = $conversation;
848 if ($conversation_uri != '') {
849 $conv_data['conversation-uri'] = $conversation_uri;
852 $entry = $doc2->importNode($entry, true);
854 $doc2->appendChild($entry);
856 $conv_data['source'] = $doc2->saveXML();
858 $condition = ['item-uri' => $conv_data['uri'],'protocol' => Conversation::PARCEL_FEED];
859 if (DBA::exists('conversation', $condition)) {
860 Logger::log('Delete deprecated entry for URI '.$conv_data['uri'], Logger::DEBUG);
861 DBA::delete('conversation', ['item-uri' => $conv_data['uri']]);
864 Logger::log('Store conversation data for uri '.$conv_data['uri'], Logger::DEBUG);
865 Conversation::insert($conv_data);
870 * Fetch the own post so that it can be stored later
872 * We want to store the original data for later processing.
873 * This function is meant for cases where we process a feed with multiple entries.
874 * In that case we need to fetch the single posts here.
876 * @param string $self The link to the self item
877 * @param array $item The item array
879 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
881 private static function fetchSelf($self, array &$item)
883 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $self, Conversation::PARCEL_DFRN, Conversation::PARCEL_SALMON];
884 if (DBA::exists('conversation', $condition)) {
885 Logger::log('Conversation '.$item['uri'].' is already stored.', Logger::DEBUG);
889 $curlResult = Network::curl($self);
891 if (!$curlResult->isSuccess()) {
895 // We reformat the XML to make it better readable
896 $doc = new DOMDocument();
897 $doc->loadXML($curlResult->getBody());
898 $doc->preserveWhiteSpace = false;
899 $doc->formatOutput = true;
900 $xml = $doc->saveXML();
902 $item["protocol"] = Conversation::PARCEL_SALMON;
903 $item["source"] = $xml;
905 Logger::log('Conversation '.$item['uri'].' is now fetched.', Logger::DEBUG);
909 * Fetch related posts and processes them
911 * @param string $related The link to the related item
912 * @param string $related_uri The related item in "uri" format
913 * @param array $importer user record of the importing user
915 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
916 * @throws \ImagickException
918 private static function fetchRelated($related, $related_uri, $importer)
920 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, Conversation::PARCEL_DFRN, Conversation::PARCEL_SALMON];
921 $conversation = DBA::selectFirst('conversation', ['source', 'protocol'], $condition);
922 if (DBA::isResult($conversation)) {
924 $xml = $conversation['source'];
925 if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
926 Logger::log('Got valid cached XML for URI '.$related_uri, Logger::DEBUG);
929 if ($conversation['protocol'] == Conversation::PARCEL_SALMON) {
930 Logger::log('Delete invalid cached XML for URI '.$related_uri, Logger::DEBUG);
931 DBA::delete('conversation', ['item-uri' => $related_uri]);
936 $curlResult = Network::curl($related, false, ['accept_content' => 'application/atom+xml, text/html']);
938 if (!$curlResult->isSuccess()) {
944 if (stristr($curlResult->getHeader(), 'Content-Type: application/atom+xml')) {
945 Logger::log('Directly fetched XML for URI ' . $related_uri, Logger::DEBUG);
946 $xml = $curlResult->getBody();
950 $doc = new DOMDocument();
951 if (!@$doc->loadHTML($curlResult->getBody())) {
954 $xpath = new DOMXPath($doc);
958 $links = $xpath->query('//link');
960 foreach ($links as $link) {
961 $attribute = self::readAttributes($link);
962 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
963 $atom_file = $attribute['href'];
966 if ($atom_file != '') {
967 $curlResult = Network::curl($atom_file);
969 if ($curlResult->isSuccess()) {
970 Logger::log('Fetched XML for URI ' . $related_uri, Logger::DEBUG);
971 $xml = $curlResult->getBody();
977 // Workaround for older GNU Social servers
978 if (($xml == '') && strstr($related, '/notice/')) {
979 $curlResult = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related).'.atom');
981 if ($curlResult->isSuccess()) {
982 Logger::log('GNU Social workaround to fetch XML for URI ' . $related_uri, Logger::DEBUG);
983 $xml = $curlResult->getBody();
987 // Even more worse workaround for GNU Social ;-)
989 $related_guess = OStatus::convertHref($related_uri);
990 $curlResult = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related_guess).'.atom');
992 if ($curlResult->isSuccess()) {
993 Logger::log('GNU Social workaround 2 to fetch XML for URI ' . $related_uri, Logger::DEBUG);
994 $xml = $curlResult->getBody();
998 // Finally we take the data that we fetched from "ostatus:conversation"
1000 $condition = ['item-uri' => $related_uri, 'protocol' => Conversation::PARCEL_SPLIT_CONVERSATION];
1001 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1002 if (DBA::isResult($conversation)) {
1004 Logger::log('Got cached XML from conversation for URI '.$related_uri, Logger::DEBUG);
1005 $xml = $conversation['source'];
1010 self::process($xml, $importer, $contact, $hub, $stored, false);
1012 Logger::log("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, Logger::DEBUG);
1018 * Processes the XML for a repeated post
1020 * @param DOMXPath $xpath The xpath object
1021 * @param object $entry The xml entry that is processed
1022 * @param array $item The item array
1023 * @param array $importer user record of the importing user
1025 * @return array with data from links
1026 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1027 * @throws \ImagickException
1029 private static function processRepeatedItem(DOMXPath $xpath, $entry, array &$item, array $importer)
1031 $activityobject = $xpath->query('activity:object', $entry)->item(0);
1033 if (!is_object($activityobject)) {
1039 $orig_uri = XML::getFirstNodeValue($xpath, 'atom:id/text()', $activityobject);
1041 $links = $xpath->query("atom:link", $activityobject);
1043 $link_data = self::processLinks($links, $item);
1046 $orig_body = XML::getFirstNodeValue($xpath, 'atom:content/text()', $activityobject);
1047 $orig_created = XML::getFirstNodeValue($xpath, 'atom:published/text()', $activityobject);
1048 $orig_edited = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $activityobject);
1050 $orig_author = self::fetchAuthor($xpath, $activityobject, $importer, $dummy, false);
1052 $item["author-name"] = $orig_author["author-name"];
1053 $item["author-link"] = $orig_author["author-link"];
1054 $item["author-id"] = $orig_author["author-id"];
1056 $item["body"] = HTML::toBBCode($orig_body);
1057 $item["created"] = $orig_created;
1058 $item["edited"] = $orig_edited;
1060 $item["uri"] = $orig_uri;
1062 $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $activityobject);
1064 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $activityobject);
1066 // Mastodon Content Warning
1067 if (($item["verb"] == Activity::POST) && $xpath->evaluate('boolean(atom:summary)', $activityobject)) {
1068 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $activityobject);
1069 if (!empty($clear_text)) {
1070 $item['content-warning'] = HTML::toBBCode($clear_text);
1074 $inreplyto = $xpath->query('thr:in-reply-to', $activityobject);
1075 if (is_object($inreplyto->item(0))) {
1076 foreach ($inreplyto->item(0)->attributes as $attributes) {
1077 if ($attributes->name == "ref") {
1078 $item["parent-uri"] = $attributes->textContent;
1087 * Processes links in the XML
1089 * @param object $links The xml data that contain links
1090 * @param array $item The item array
1092 * @return array with data from the links
1094 private static function processLinks($links, array &$item)
1096 $link_data = ['add_body' => '', 'self' => ''];
1098 foreach ($links as $link) {
1099 $attribute = self::readAttributes($link);
1101 if (!empty($attribute['rel']) && !empty($attribute['href'])) {
1102 switch ($attribute['rel']) {
1104 $item["plink"] = $attribute['href'];
1105 if (($item["object-type"] == Activity\ObjectType::QUESTION)
1106 || ($item["object-type"] == Activity\ObjectType::EVENT)
1108 $item["body"] .= add_page_info($attribute['href']);
1111 case "ostatus:conversation":
1112 $link_data['conversation'] = $attribute['href'];
1113 $item['conversation-href'] = $link_data['conversation'];
1114 if (!isset($item['conversation-uri'])) {
1115 $item['conversation-uri'] = $item['conversation-href'];
1119 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
1120 if ($filetype == 'image') {
1121 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1123 if (!empty($item["attach"])) {
1124 $item["attach"] .= ',';
1126 $item["attach"] = '';
1128 if (!isset($attribute['length'])) {
1129 $attribute['length'] = "0";
1131 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.($attribute['title'] ?? '') .'"[/attach]';
1135 if ($item["object-type"] != Activity\ObjectType::BOOKMARK) {
1136 if (!isset($item["parent-uri"])) {
1137 $item["parent-uri"] = $attribute['href'];
1139 $link_data['related'] = $attribute['href'];
1141 $item["body"] .= add_page_info($attribute['href']);
1145 if (empty($item["plink"])) {
1146 $item["plink"] = $attribute['href'];
1148 $link_data['self'] = $attribute['href'];
1157 * Create an url out of an uri
1159 * @param string $href URI in the format "parameter1:parameter1:..."
1161 * @return string URL in the format http(s)://....
1163 public static function convertHref($href)
1165 $elements = explode(":", $href);
1167 if ((count($elements) <= 2) || ($elements[0] != "tag")) {
1171 $server = explode(",", $elements[1]);
1172 $conversation = explode("=", $elements[2]);
1174 if ((count($elements) == 4) && ($elements[2] == "post")) {
1175 return "http://".$server[0]."/notice/".$elements[3];
1178 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1181 if ($elements[3] == "objectType=thread") {
1182 return "http://".$server[0]."/conversation/".$conversation[1];
1184 return "http://".$server[0]."/notice/".$conversation[1];
1189 * Checks if the current post is a reshare
1191 * @param array $item The item array of thw post
1193 * @return string The guid if the post is a reshare
1195 private static function getResharedGuid(array $item)
1197 $reshared = Item::getShareArray($item);
1198 if (empty($reshared['guid']) || !empty($reshared['comment'])) {
1202 return $reshared['guid'];
1206 * Cleans the body of a post if it contains picture links
1208 * @param string $body The body
1210 * @return string The cleaned body
1211 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1213 private static function formatPicturePost($body)
1215 $siteinfo = BBCode::getAttachedData($body);
1217 if (($siteinfo["type"] == "photo") && (!empty($siteinfo["preview"]) || !empty($siteinfo["image"]))) {
1218 if (isset($siteinfo["preview"])) {
1219 $preview = $siteinfo["preview"];
1221 $preview = $siteinfo["image"];
1224 // Is it a remote picture? Then make a smaller preview here
1225 $preview = ProxyUtils::proxifyUrl($preview, false, ProxyUtils::SIZE_SMALL);
1227 // Is it a local picture? Then make it smaller here
1228 $preview = str_replace(["-0.jpg", "-0.png"], ["-2.jpg", "-2.png"], $preview);
1229 $preview = str_replace(["-1.jpg", "-1.png"], ["-2.jpg", "-2.png"], $preview);
1231 if (isset($siteinfo["url"])) {
1232 $url = $siteinfo["url"];
1234 $url = $siteinfo["image"];
1237 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1244 * Adds the header elements to the XML document
1246 * @param DOMDocument $doc XML document
1247 * @param array $owner Contact data of the poster
1248 * @param string $filter The related feed filter (activity, posts or comments)
1249 * @param bool $feed_mode Behave like a regular feed for users if true
1251 * @return object header root element
1252 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1254 private static function addHeader(DOMDocument $doc, array $owner, $filter, $feed_mode = false)
1256 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
1257 $doc->appendChild($root);
1259 $root->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
1260 $root->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
1261 $root->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
1262 $root->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
1263 $root->setAttribute("xmlns:poco", ActivityNamespace::POCO);
1264 $root->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
1265 $root->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
1266 $root->setAttribute("xmlns:mastodon", ActivityNamespace::MASTODON);
1269 $selfUri = '/feed/' . $owner["nick"] . '/';
1272 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
1273 $selfUri .= $filter;
1276 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
1279 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
1280 $selfUri .= $filter;
1285 $selfUri = "/dfrn_poll/" . $owner["nick"];
1288 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
1289 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1290 XML::addElement($doc, $root, "id", DI::baseUrl() . "/profile/" . $owner["nick"]);
1291 XML::addElement($doc, $root, "title", $title);
1292 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], DI::config()->get('config', 'sitename')));
1293 XML::addElement($doc, $root, "logo", $owner["photo"]);
1294 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1296 $author = self::addAuthor($doc, $owner);
1297 $root->appendChild($author);
1299 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1300 XML::addElement($doc, $root, "link", "", $attributes);
1302 /// @TODO We have to find out what this is
1303 /// $attributes = array("href" => DI::baseUrl()."/sup",
1304 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1305 /// "type" => "application/json");
1306 /// XML::addElement($doc, $root, "link", "", $attributes);
1308 self::hublinks($doc, $root, $owner["nick"]);
1310 $attributes = ["href" => DI::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "salmon"];
1311 XML::addElement($doc, $root, "link", "", $attributes);
1313 $attributes = ["href" => DI::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies"];
1314 XML::addElement($doc, $root, "link", "", $attributes);
1316 $attributes = ["href" => DI::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention"];
1317 XML::addElement($doc, $root, "link", "", $attributes);
1319 $attributes = ["href" => DI::baseUrl() . $selfUri, "rel" => "self", "type" => "application/atom+xml"];
1320 XML::addElement($doc, $root, "link", "", $attributes);
1322 if ($owner['account-type'] == Contact::TYPE_COMMUNITY) {
1323 $condition = ['uid' => $owner['uid'], 'self' => false, 'pending' => false,
1324 'archive' => false, 'hidden' => false, 'blocked' => false];
1325 $members = DBA::count('contact', $condition);
1326 XML::addElement($doc, $root, "statusnet:group_info", "", ["member_count" => $members]);
1333 * Add the link to the push hubs to the XML document
1335 * @param DOMDocument $doc XML document
1336 * @param object $root XML root element where the hub links are added
1337 * @param object $nick nick
1339 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1341 public static function hublinks(DOMDocument $doc, $root, $nick)
1343 $h = DI::baseUrl() . '/pubsubhubbub/'.$nick;
1344 XML::addElement($doc, $root, "link", "", ["href" => $h, "rel" => "hub"]);
1348 * Adds attachment data to the XML document
1350 * @param DOMDocument $doc XML document
1351 * @param object $root XML root element where the hub links are added
1352 * @param array $item Data of the item that is to be posted
1354 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1356 private static function getAttachment(DOMDocument $doc, $root, $item)
1358 $siteinfo = BBCode::getAttachedData($item["body"]);
1360 switch ($siteinfo["type"]) {
1362 if (!empty($siteinfo["image"])) {
1363 $imgdata = Images::getInfoFromURLCached($siteinfo["image"]);
1365 $attributes = ["rel" => "enclosure",
1366 "href" => $siteinfo["image"],
1367 "type" => $imgdata["mime"],
1368 "length" => intval($imgdata["size"])];
1369 XML::addElement($doc, $root, "link", "", $attributes);
1374 $attributes = ["rel" => "enclosure",
1375 "href" => $siteinfo["url"],
1376 "type" => "text/html; charset=UTF-8",
1378 "title" => ($siteinfo["title"] ?? '') ?: $siteinfo["url"],
1380 XML::addElement($doc, $root, "link", "", $attributes);
1386 if (!DI::config()->get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1387 $imgdata = Images::getInfoFromURLCached($siteinfo["image"]);
1389 $attributes = ["rel" => "enclosure",
1390 "href" => $siteinfo["image"],
1391 "type" => $imgdata["mime"],
1392 "length" => intval($imgdata["size"])];
1394 XML::addElement($doc, $root, "link", "", $attributes);
1398 $arr = explode('[/attach],', $item['attach']);
1400 foreach ($arr as $r) {
1402 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1404 $attributes = ["rel" => "enclosure",
1405 "href" => $matches[1],
1406 "type" => $matches[3]];
1408 if (intval($matches[2])) {
1409 $attributes["length"] = intval($matches[2]);
1411 if (trim($matches[4]) != "") {
1412 $attributes["title"] = trim($matches[4]);
1414 XML::addElement($doc, $root, "link", "", $attributes);
1421 * Adds the author element to the XML document
1423 * @param DOMDocument $doc XML document
1424 * @param array $owner Contact data of the poster
1425 * @param bool $show_profile Whether to show profile
1427 * @return \DOMElement author element
1428 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1430 private static function addAuthor(DOMDocument $doc, array $owner, $show_profile = true)
1432 $profile = DBA::selectFirst('profile', ['homepage', 'publish'], ['uid' => $owner['uid'], 'is-default' => true]);
1433 $author = $doc->createElement("author");
1434 XML::addElement($doc, $author, "id", $owner["url"]);
1435 if ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
1436 XML::addElement($doc, $author, "activity:object-type", Activity\ObjectType::GROUP);
1438 XML::addElement($doc, $author, "activity:object-type", Activity\ObjectType::PERSON);
1440 XML::addElement($doc, $author, "uri", $owner["url"]);
1441 XML::addElement($doc, $author, "name", $owner["nick"]);
1442 XML::addElement($doc, $author, "email", $owner["addr"]);
1443 if ($show_profile) {
1444 XML::addElement($doc, $author, "summary", BBCode::convert($owner["about"], false, 7));
1447 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $owner["url"]];
1448 XML::addElement($doc, $author, "link", "", $attributes);
1452 "type" => "image/jpeg", // To-Do?
1453 "media:width" => 300,
1454 "media:height" => 300,
1455 "href" => $owner["photo"]];
1456 XML::addElement($doc, $author, "link", "", $attributes);
1458 if (isset($owner["thumb"])) {
1461 "type" => "image/jpeg", // To-Do?
1462 "media:width" => 80,
1463 "media:height" => 80,
1464 "href" => $owner["thumb"]];
1465 XML::addElement($doc, $author, "link", "", $attributes);
1468 XML::addElement($doc, $author, "poco:preferredUsername", $owner["nick"]);
1469 XML::addElement($doc, $author, "poco:displayName", $owner["name"]);
1470 if ($show_profile) {
1471 XML::addElement($doc, $author, "poco:note", BBCode::convert($owner["about"], false, 7));
1473 if (trim($owner["location"]) != "") {
1474 $element = $doc->createElement("poco:address");
1475 XML::addElement($doc, $element, "poco:formatted", $owner["location"]);
1476 $author->appendChild($element);
1480 if (DBA::isResult($profile) && !$show_profile) {
1481 if (trim($profile["homepage"]) != "") {
1482 $urls = $doc->createElement("poco:urls");
1483 XML::addElement($doc, $urls, "poco:type", "homepage");
1484 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
1485 XML::addElement($doc, $urls, "poco:primary", "true");
1486 $author->appendChild($urls);
1489 XML::addElement($doc, $author, "followers", "", ["url" => DI::baseUrl() . "/profile/" . $owner["nick"] . "/contacts/followers"]);
1490 XML::addElement($doc, $author, "statusnet:profile_info", "", ["local_id" => $owner["uid"]]);
1492 if ($profile["publish"]) {
1493 XML::addElement($doc, $author, "mastodon:scope", "public");
1501 * @TODO Picture attachments should look like this:
1502 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1503 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1507 * Returns the given activity if present - otherwise returns the "post" activity
1509 * @param array $item Data of the item that is to be posted
1511 * @return string activity
1513 private static function constructVerb(array $item)
1515 if (!empty($item['verb'])) {
1516 return $item['verb'];
1519 return Activity::POST;
1523 * Returns the given object type if present - otherwise returns the "note" object type
1525 * @param array $item Data of the item that is to be posted
1527 * @return string Object type
1529 private static function constructObjecttype(array $item)
1531 if (!empty($item['object-type']) && in_array($item['object-type'], [Activity\ObjectType::NOTE, Activity\ObjectType::COMMENT])) {
1532 return $item['object-type'];
1535 return Activity\ObjectType::NOTE;
1539 * Adds an entry element to the XML document
1541 * @param DOMDocument $doc XML document
1542 * @param array $item Data of the item that is to be posted
1543 * @param array $owner Contact data of the poster
1544 * @param bool $toplevel optional default false
1545 * @param bool $feed_mode Behave like a regular feed for users if true
1547 * @return \DOMElement Entry element
1548 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1549 * @throws \ImagickException
1551 private static function entry(DOMDocument $doc, array $item, array $owner, $toplevel = false, $feed_mode = false)
1555 $repeated_guid = self::getResharedGuid($item);
1556 if ($repeated_guid != "") {
1557 $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel);
1564 if ($item["verb"] == Activity::LIKE) {
1565 return self::likeEntry($doc, $item, $owner, $toplevel);
1566 } elseif (in_array($item["verb"], [Activity::FOLLOW, Activity::O_UNFOLLOW])) {
1567 return self::followEntry($doc, $item, $owner, $toplevel);
1569 return self::noteEntry($doc, $item, $owner, $toplevel, $feed_mode);
1574 * Adds a source entry to the XML document
1576 * @param DOMDocument $doc XML document
1577 * @param array $contact Array of the contact that is added
1579 * @return \DOMElement Source element
1580 * @throws \Exception
1582 private static function sourceEntry(DOMDocument $doc, array $contact)
1584 $source = $doc->createElement("source");
1585 XML::addElement($doc, $source, "id", $contact["poll"]);
1586 XML::addElement($doc, $source, "title", $contact["name"]);
1587 XML::addElement($doc, $source, "link", "", ["rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]]);
1588 XML::addElement($doc, $source, "link", "", ["rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]]);
1589 XML::addElement($doc, $source, "icon", $contact["photo"]);
1590 XML::addElement($doc, $source, "updated", DateTimeFormat::utc($contact["success_update"]."+00:00", DateTimeFormat::ATOM));
1596 * Fetches contact data from the contact or the gcontact table
1598 * @param string $url URL of the contact
1599 * @param array $owner Contact data of the poster
1601 * @return array Contact array
1602 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1603 * @throws \ImagickException
1605 private static function contactEntry($url, array $owner)
1608 "SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1609 DBA::escape(Strings::normaliseLink($url)),
1610 intval($owner["uid"])
1612 if (DBA::isResult($r)) {
1614 $contact["uid"] = -1;
1617 if (!DBA::isResult($r)) {
1618 $gcontact = DBA::selectFirst('gcontact', [], ['nurl' => Strings::normaliseLink($url)]);
1619 if (DBA::isResult($r)) {
1620 $contact = $gcontact;
1621 $contact["uid"] = -1;
1622 $contact["success_update"] = $contact["updated"];
1626 if (!DBA::isResult($r)) {
1630 if (!isset($contact["poll"])) {
1631 $data = Probe::uri($url);
1632 $contact["poll"] = $data["poll"];
1634 if (!$contact["alias"]) {
1635 $contact["alias"] = $data["alias"];
1639 if (!isset($contact["alias"])) {
1640 $contact["alias"] = $contact["url"];
1643 $contact['account-type'] = $owner['account-type'];
1649 * Adds an entry element with reshared content
1651 * @param DOMDocument $doc XML document
1652 * @param array $item Data of the item that is to be posted
1653 * @param array $owner Contact data of the poster
1654 * @param string $repeated_guid guid
1655 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1657 * @return bool Entry element
1658 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1659 * @throws \ImagickException
1661 private static function reshareEntry(DOMDocument $doc, array $item, array $owner, $repeated_guid, $toplevel)
1663 if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1664 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1667 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1669 $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => false,
1670 'network' => [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS]];
1671 $repeated_item = Item::selectFirst([], $condition);
1672 if (!DBA::isResult($repeated_item)) {
1676 $contact = self::contactEntry($repeated_item['author-link'], $owner);
1678 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1680 self::entryContent($doc, $entry, $item, $owner, $title, Activity::SHARE, false);
1682 $as_object = $doc->createElement("activity:object");
1684 XML::addElement($doc, $as_object, "activity:object-type", ActivityNamespace::ACTIVITY_SCHEMA . "activity");
1686 self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false);
1688 $author = self::addAuthor($doc, $contact, false);
1689 $as_object->appendChild($author);
1691 $as_object2 = $doc->createElement("activity:object");
1693 XML::addElement($doc, $as_object2, "activity:object-type", self::constructObjecttype($repeated_item));
1695 $title = sprintf("New comment by %s", $contact["nick"]);
1697 self::entryContent($doc, $as_object2, $repeated_item, $owner, $title);
1699 $as_object->appendChild($as_object2);
1701 self::entryFooter($doc, $as_object, $item, $owner, false);
1703 $source = self::sourceEntry($doc, $contact);
1705 $as_object->appendChild($source);
1707 $entry->appendChild($as_object);
1709 self::entryFooter($doc, $entry, $item, $owner);
1715 * Adds an entry element with a "like"
1717 * @param DOMDocument $doc XML document
1718 * @param array $item Data of the item that is to be posted
1719 * @param array $owner Contact data of the poster
1720 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1722 * @return \DOMElement Entry element with "like"
1723 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1724 * @throws \ImagickException
1726 private static function likeEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1728 if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1729 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1732 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1734 $verb = ActivityNamespace::ACTIVITY_SCHEMA . "favorite";
1735 self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false);
1737 $parent = Item::selectFirst([], ['uri' => $item["thr-parent"], 'uid' => $item["uid"]]);
1738 if (DBA::isResult($parent)) {
1739 $as_object = $doc->createElement("activity:object");
1741 XML::addElement($doc, $as_object, "activity:object-type", self::constructObjecttype($parent));
1743 self::entryContent($doc, $as_object, $parent, $owner, "New entry");
1745 $entry->appendChild($as_object);
1748 self::entryFooter($doc, $entry, $item, $owner);
1754 * Adds the person object element to the XML document
1756 * @param DOMDocument $doc XML document
1757 * @param array $owner Contact data of the poster
1758 * @param array $contact Contact data of the target
1760 * @return object author element
1762 private static function addPersonObject(DOMDocument $doc, array $owner, array $contact)
1764 $object = $doc->createElement("activity:object");
1765 XML::addElement($doc, $object, "activity:object-type", Activity\ObjectType::PERSON);
1767 if ($contact['network'] == Protocol::PHANTOM) {
1768 XML::addElement($doc, $object, "id", $contact['url']);
1772 XML::addElement($doc, $object, "id", $contact["alias"]);
1773 XML::addElement($doc, $object, "title", $contact["nick"]);
1775 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $contact["url"]];
1776 XML::addElement($doc, $object, "link", "", $attributes);
1780 "type" => "image/jpeg", // To-Do?
1781 "media:width" => 300,
1782 "media:height" => 300,
1783 "href" => $contact["photo"]];
1784 XML::addElement($doc, $object, "link", "", $attributes);
1786 XML::addElement($doc, $object, "poco:preferredUsername", $contact["nick"]);
1787 XML::addElement($doc, $object, "poco:displayName", $contact["name"]);
1789 if (trim($contact["location"]) != "") {
1790 $element = $doc->createElement("poco:address");
1791 XML::addElement($doc, $element, "poco:formatted", $contact["location"]);
1792 $object->appendChild($element);
1799 * Adds a follow/unfollow entry element
1801 * @param DOMDocument $doc XML document
1802 * @param array $item Data of the follow/unfollow message
1803 * @param array $owner Contact data of the poster
1804 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1806 * @return \DOMElement Entry element
1807 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1808 * @throws \ImagickException
1810 private static function followEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1812 $item["id"] = $item["parent"] = 0;
1813 $item["created"] = $item["edited"] = date("c");
1814 $item["private"] = true;
1816 $contact = Probe::uri($item['follow']);
1818 if ($contact['alias'] == '') {
1819 $contact['alias'] = $contact["url"];
1821 $item['follow'] = $contact['alias'];
1824 $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($contact["url"])];
1825 $user_contact = DBA::selectFirst('contact', ['id'], $condition);
1827 if (DBA::isResult($user_contact)) {
1828 $connect_id = $user_contact['id'];
1833 if ($item['verb'] == Activity::FOLLOW) {
1834 $message = DI::l10n()->t('%s is now following %s.');
1835 $title = DI::l10n()->t('following');
1836 $action = "subscription";
1838 $message = DI::l10n()->t('%s stopped following %s.');
1839 $title = DI::l10n()->t('stopped following');
1840 $action = "unfollow";
1843 $item["uri"] = $item['parent-uri'] = $item['thr-parent']
1844 = 'tag:' . DI::baseUrl()->getHostname().
1845 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1846 ':person:'.$connect_id.':'.$item['created'];
1848 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1850 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1852 self::entryContent($doc, $entry, $item, $owner, $title);
1854 $object = self::addPersonObject($doc, $owner, $contact);
1855 $entry->appendChild($object);
1857 self::entryFooter($doc, $entry, $item, $owner);
1863 * Adds a regular entry element
1865 * @param DOMDocument $doc XML document
1866 * @param array $item Data of the item that is to be posted
1867 * @param array $owner Contact data of the poster
1868 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1869 * @param bool $feed_mode Behave like a regular feed for users if true
1871 * @return \DOMElement Entry element
1872 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1873 * @throws \ImagickException
1875 private static function noteEntry(DOMDocument $doc, array $item, array $owner, $toplevel, $feed_mode)
1877 if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1878 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1882 if (!empty($item['title'])) {
1883 $title = BBCode::convert($item['title'], false, 7);
1885 $title = sprintf("New note by %s", $owner["nick"]);
1888 $title = sprintf("New comment by %s", $owner["nick"]);
1891 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1893 XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::NOTE);
1895 self::entryContent($doc, $entry, $item, $owner, $title, '', true, $feed_mode);
1897 self::entryFooter($doc, $entry, $item, $owner, !$feed_mode, $feed_mode);
1903 * Adds a header element to the XML document
1905 * @param DOMDocument $doc XML document
1906 * @param array $owner Contact data of the poster
1907 * @param array $item
1908 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1910 * @return \DOMElement The entry element where the elements are added
1911 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1912 * @throws \ImagickException
1914 private static function entryHeader(DOMDocument $doc, array $owner, array $item, $toplevel)
1917 $entry = $doc->createElement("entry");
1919 if ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
1920 $contact = self::contactEntry($item['author-link'], $owner);
1921 $author = self::addAuthor($doc, $contact, false);
1922 $entry->appendChild($author);
1925 $entry = $doc->createElementNS(ActivityNamespace::ATOM1, "entry");
1927 $entry->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
1928 $entry->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
1929 $entry->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
1930 $entry->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
1931 $entry->setAttribute("xmlns:poco", ActivityNamespace::POCO);
1932 $entry->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
1933 $entry->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
1934 $entry->setAttribute("xmlns:mastodon", ActivityNamespace::MASTODON);
1936 $author = self::addAuthor($doc, $owner);
1937 $entry->appendChild($author);
1944 * Adds elements to the XML document
1946 * @param DOMDocument $doc XML document
1947 * @param \DOMElement $entry Entry element where the content is added
1948 * @param array $item Data of the item that is to be posted
1949 * @param array $owner Contact data of the poster
1950 * @param string $title Title for the post
1951 * @param string $verb The activity verb
1952 * @param bool $complete Add the "status_net" element?
1953 * @param bool $feed_mode Behave like a regular feed for users if true
1955 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1957 private static function entryContent(DOMDocument $doc, \DOMElement $entry, array $item, array $owner, $title, $verb = "", $complete = true, $feed_mode = false)
1960 $verb = self::constructVerb($item);
1963 XML::addElement($doc, $entry, "id", $item["uri"]);
1964 XML::addElement($doc, $entry, "title", html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1966 $body = self::formatPicturePost($item['body']);
1968 if (!empty($item['title']) && !$feed_mode) {
1969 $body = "[b]".$item['title']."[/b]\n\n".$body;
1972 $body = BBCode::convert($body, false, 7);
1974 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1976 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1977 "href" => DI::baseUrl()."/display/".$item["guid"]]
1980 if (!$feed_mode && $complete && ($item["id"] > 0)) {
1981 XML::addElement($doc, $entry, "status_net", "", ["notice_id" => $item["id"]]);
1985 XML::addElement($doc, $entry, "activity:verb", $verb);
1988 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
1989 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
1993 * Adds the elements at the foot of an entry to the XML document
1995 * @param DOMDocument $doc XML document
1996 * @param object $entry The entry element where the elements are added
1997 * @param array $item Data of the item that is to be posted
1998 * @param array $owner Contact data of the poster
1999 * @param bool $complete default true
2000 * @param bool $feed_mode Behave like a regular feed for users if true
2002 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2004 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner, $complete = true, $feed_mode = false)
2008 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
2009 $parent = Item::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item["parent"]]);
2010 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
2012 $thrparent = Item::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $parent_item]);
2014 if (DBA::isResult($thrparent)) {
2015 $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
2016 $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
2017 $parent_plink = $thrparent["plink"];
2019 $mentioned[$parent["author-link"]] = $parent["author-link"];
2020 $mentioned[$parent["owner-link"]] = $parent["owner-link"];
2021 $parent_plink = DI::baseUrl()."/display/".$parent["guid"];
2025 "ref" => $parent_item,
2026 "href" => $parent_plink];
2027 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
2031 "href" => $parent_plink];
2032 XML::addElement($doc, $entry, "link", "", $attributes);
2035 if (!$feed_mode && (intval($item["parent"]) > 0)) {
2036 $conversation_href = $conversation_uri = str_replace('/objects/', '/context/', $item['parent-uri']);
2038 if (isset($parent_item)) {
2039 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $parent_item]);
2040 if (DBA::isResult($conversation)) {
2041 if ($conversation['conversation-uri'] != '') {
2042 $conversation_uri = $conversation['conversation-uri'];
2044 if ($conversation['conversation-href'] != '') {
2045 $conversation_href = $conversation['conversation-href'];
2050 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:conversation", "href" => $conversation_href]);
2053 "href" => $conversation_href,
2054 "local_id" => $item["parent"],
2055 "ref" => $conversation_uri];
2057 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
2060 $tags = item::getFeedTags($item);
2063 foreach ($tags as $t) {
2065 $mentioned[$t[1]] = $t[1];
2070 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2072 foreach ($mentioned as $mention) {
2073 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2074 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2076 $mentioned = $newmentions;
2078 foreach ($mentioned as $mention) {
2079 $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($mention)];
2080 $contact = DBA::selectFirst('contact', ['forum', 'prv', 'self', 'contact-type'], $condition);
2081 if ($contact["forum"] || $contact["prv"] || ($owner['contact-type'] == Contact::TYPE_COMMUNITY) ||
2082 ($contact['self'] && ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY))) {
2083 XML::addElement($doc, $entry, "link", "",
2085 "rel" => "mentioned",
2086 "ostatus:object-type" => Activity\ObjectType::GROUP,
2090 XML::addElement($doc, $entry, "link", "",
2092 "rel" => "mentioned",
2093 "ostatus:object-type" => Activity\ObjectType::PERSON,
2099 if ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
2100 XML::addElement($doc, $entry, "link", "", [
2101 "rel" => "mentioned",
2102 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/group",
2103 "href" => $owner['url']
2107 if (!$item["private"] && !$feed_mode) {
2108 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:attention",
2109 "href" => "http://activityschema.org/collection/public"]);
2110 XML::addElement($doc, $entry, "link", "", ["rel" => "mentioned",
2111 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2112 "href" => "http://activityschema.org/collection/public"]);
2113 XML::addElement($doc, $entry, "mastodon:scope", "public");
2117 foreach ($tags as $t) {
2119 XML::addElement($doc, $entry, "category", "", ["term" => $t[2]]);
2124 self::getAttachment($doc, $entry, $item);
2126 if ($complete && ($item["id"] > 0)) {
2127 $app = $item["app"];
2132 $attributes = ["local_id" => $item["id"], "source" => $app];
2134 if (isset($parent["id"])) {
2135 $attributes["repeat_of"] = $parent["id"];
2138 if ($item["coord"] != "") {
2139 XML::addElement($doc, $entry, "georss:point", $item["coord"]);
2142 XML::addElement($doc, $entry, "statusnet:notice_info", "", $attributes);
2147 * Creates the XML feed for a given nickname
2149 * Supported filters:
2150 * - activity (default): all the public posts
2151 * - posts: all the public top-level posts
2152 * - comments: all the public replies
2154 * Updates the provided last_update parameter if the result comes from the
2155 * cache or it is empty
2157 * @param string $owner_nick Nickname of the feed owner
2158 * @param string $last_update Date of the last update
2159 * @param integer $max_items Number of maximum items to fetch
2160 * @param string $filter Feed items filter (activity, posts or comments)
2161 * @param boolean $nocache Wether to bypass caching
2162 * @param boolean $feed_mode Behave like a regular feed for users if true
2164 * @return string XML feed
2165 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2166 * @throws \ImagickException
2168 public static function feed($owner_nick, &$last_update, $max_items = 300, $filter = 'activity', $nocache = false, $feed_mode = false)
2170 $stamp = microtime(true);
2172 $owner = User::getOwnerDataByNick($owner_nick);
2177 $cachekey = "ostatus:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
2179 $previous_created = $last_update;
2181 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
2182 if ((time() - strtotime($owner['last-item'])) < 15*60) {
2183 $result = DI::cache()->get($cachekey);
2184 if (!$nocache && !is_null($result)) {
2185 Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', Logger::DEBUG);
2186 $last_update = $result['last_update'];
2187 return $result['feed'];
2191 if (!strlen($last_update)) {
2192 $last_update = 'now -30 days';
2195 $check_date = DateTimeFormat::utc($last_update);
2196 $authorid = Contact::getIdForURL($owner["url"], 0, true);
2198 $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted`
2199 AND NOT `private` AND `visible` AND `wall` AND `parent-network` IN (?, ?)",
2200 $owner["uid"], $check_date, Protocol::OSTATUS, Protocol::DFRN];
2202 if ($filter === 'comments') {
2203 $condition[0] .= " AND `object-type` = ? ";
2204 $condition[] = Activity\ObjectType::COMMENT;
2207 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
2208 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
2209 $condition[] = $owner["id"];
2210 $condition[] = $authorid;
2213 $params = ['order' => ['received' => true], 'limit' => $max_items];
2215 if ($filter === 'posts') {
2216 $ret = Item::selectThread([], $condition, $params);
2218 $ret = Item::select([], $condition, $params);
2221 $items = Item::inArray($ret);
2223 $doc = new DOMDocument('1.0', 'utf-8');
2224 $doc->formatOutput = true;
2226 $root = self::addHeader($doc, $owner, $filter, $feed_mode);
2228 foreach ($items as $item) {
2229 if (DI::config()->get('system', 'ostatus_debug')) {
2230 $item['body'] .= '🍼';
2233 $entry = self::entry($doc, $item, $owner, false, $feed_mode);
2234 $root->appendChild($entry);
2236 if ($last_update < $item['created']) {
2237 $last_update = $item['created'];
2241 $feeddata = trim($doc->saveXML());
2243 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
2244 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
2246 Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, Logger::DEBUG);
2252 * Creates the XML for a salmon message
2254 * @param array $item Data of the item that is to be posted
2255 * @param array $owner Contact data of the poster
2257 * @return string XML for the salmon
2258 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2259 * @throws \ImagickException
2261 public static function salmon(array $item, array $owner)
2263 $doc = new DOMDocument('1.0', 'utf-8');
2264 $doc->formatOutput = true;
2266 if (DI::config()->get('system', 'ostatus_debug')) {
2267 $item['body'] .= '🐟';
2270 $entry = self::entry($doc, $item, $owner, true);
2272 $doc->appendChild($entry);
2274 return trim($doc->saveXML());
2278 * Checks if the given contact url does support OStatus
2280 * @param string $url profile url
2281 * @param boolean $update Update the profile
2283 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2284 * @throws \ImagickException
2286 public static function isSupportedByContactUrl($url, $update = false)
2288 $probe = Probe::uri($url, Protocol::OSTATUS, 0, !$update);
2289 return $probe['network'] == Protocol::OSTATUS;