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\Cache;
12 use Friendica\Core\Config;
13 use Friendica\Core\L10n;
14 use Friendica\Core\Logger;
15 use Friendica\Core\Protocol;
16 use Friendica\Database\DBA;
18 use Friendica\Model\APContact;
19 use Friendica\Model\Contact;
20 use Friendica\Model\Conversation;
21 use Friendica\Model\GContact;
22 use Friendica\Model\Item;
23 use Friendica\Model\User;
24 use Friendica\Network\Probe;
25 use Friendica\Util\DateTimeFormat;
26 use Friendica\Util\Images;
27 use Friendica\Util\Network;
28 use Friendica\Util\Proxy as ProxyUtils;
29 use Friendica\Util\Strings;
30 use Friendica\Util\XML;
32 require_once 'mod/share.php';
33 require_once 'include/api.php';
36 * @brief This class contain functions for the OStatus protocol
40 private static $itemlist;
41 private static $conv_list = [];
44 * @brief Fetches author data
46 * @param DOMXPath $xpath The xpath object
47 * @param object $context The xml context of the author details
48 * @param array $importer user record of the importing user
49 * @param array $contact Called by reference, will contain the fetched contact
50 * @param bool $onlyfetch Only fetch the header without updating the contact entries
52 * @return array Array of author related entries for the item
53 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
54 * @throws \ImagickException
56 private static function fetchAuthor(DOMXPath $xpath, $context, array $importer, array &$contact = null, $onlyfetch)
59 $author["author-link"] = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
60 $author["author-name"] = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $context);
61 $addr = XML::getFirstNodeValue($xpath, 'atom:author/atom:email/text()', $context);
63 $aliaslink = $author["author-link"];
65 $alternate_item = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0);
66 if (is_object($alternate_item)) {
67 foreach ($alternate_item->attributes as $attributes) {
68 if (($attributes->name == "href") && ($attributes->textContent != "")) {
69 $author["author-link"] = $attributes->textContent;
73 $author["author-id"] = Contact::getIdForURL($author["author-link"]);
75 $author['contact-id'] = ($contact['id'] ?? 0) ?: $author['author-id'];
80 This here would be better, but we would get problems with contacts from the statusnet addon
81 This is kept here as a reminder for the future
83 $cid = Contact::getIdForURL($author["author-link"], $importer["uid"]);
85 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
88 if ($aliaslink != '') {
89 $condition = ["`uid` = ? AND `alias` = ? AND `network` != ? AND `rel` IN (?, ?)",
90 $importer["uid"], $aliaslink, Protocol::STATUSNET,
91 Contact::SHARING, Contact::FRIEND];
92 $contact = DBA::selectFirst('contact', [], $condition);
95 if (!DBA::isResult($contact) && $author["author-link"] != '') {
96 if ($aliaslink == "") {
97 $aliaslink = $author["author-link"];
100 $condition = ["`uid` = ? AND `nurl` IN (?, ?) AND `network` != ? AND `rel` IN (?, ?)",
101 $importer["uid"], Strings::normaliseLink($author["author-link"]), Strings::normaliseLink($aliaslink),
102 Protocol::STATUSNET, Contact::SHARING, Contact::FRIEND];
103 $contact = DBA::selectFirst('contact', [], $condition);
106 if (!DBA::isResult($contact) && ($addr != '')) {
107 $condition = ["`uid` = ? AND `addr` = ? AND `network` != ? AND `rel` IN (?, ?)",
108 $importer["uid"], $addr, Protocol::STATUSNET,
109 Contact::SHARING, Contact::FRIEND];
110 $contact = DBA::selectFirst('contact', [], $condition);
113 if (DBA::isResult($contact)) {
114 if ($contact['blocked']) {
116 } elseif (!empty(APContact::getByURL($contact['url'], false))) {
117 ActivityPub\Receiver::switchContact($contact['id'], $importer['uid'], $contact['url']);
119 $author["contact-id"] = $contact["id"];
123 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
124 foreach ($avatars as $avatar) {
127 foreach ($avatar->attributes as $attributes) {
128 if ($attributes->name == "href") {
129 $href = $attributes->textContent;
131 if ($attributes->name == "width") {
132 $width = $attributes->textContent;
136 $avatarlist[$width] = $href;
139 if (count($avatarlist) > 0) {
141 $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
144 $displayname = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
145 if ($displayname != "") {
146 $author["author-name"] = $displayname;
149 $author["owner-id"] = $author["author-id"];
151 // Only update the contacts if it is an OStatus contact
152 if (DBA::isResult($contact) && ($contact['id'] > 0) && !$onlyfetch && ($contact["network"] == Protocol::OSTATUS)) {
154 // Update contact data
156 unset($current['name-date']);
158 // This query doesn't seem to work
159 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
161 // $contact["notify"] = $value;
163 // This query doesn't seem to work as well - I hate these queries
164 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
166 // $contact["poll"] = $value;
168 $contact['url'] = $author["author-link"];
169 $contact['nurl'] = Strings::normaliseLink($contact['url']);
171 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
173 $contact["alias"] = $value;
176 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
178 $contact["name"] = $value;
181 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()', $context);
183 $contact["nick"] = $value;
186 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()', $context);
188 $contact["about"] = HTML::toBBCode($value);
191 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()', $context);
193 $contact["location"] = $value;
196 $contact['name-date'] = DateTimeFormat::utcNow();
198 DBA::update('contact', $contact, ['id' => $contact["id"]], $current);
200 if (!empty($author["author-avatar"]) && ($author["author-avatar"] != $current['avatar'])) {
201 Logger::log("Update profile picture for contact ".$contact["id"], Logger::DEBUG);
202 Contact::updateAvatar($author["author-avatar"], $importer["uid"], $contact["id"]);
205 // Ensure that we are having this contact (with uid=0)
206 $cid = Contact::getIdForURL($aliaslink, 0, true);
209 $fields = ['url', 'nurl', 'name', 'nick', 'alias', 'about', 'location'];
210 $old_contact = DBA::selectFirst('contact', $fields, ['id' => $cid]);
212 // Update it with the current values
213 $fields = ['url' => $author["author-link"], 'name' => $contact["name"],
214 'nurl' => Strings::normaliseLink($author["author-link"]),
215 'nick' => $contact["nick"], 'alias' => $contact["alias"],
216 'about' => $contact["about"], 'location' => $contact["location"],
217 'success_update' => DateTimeFormat::utcNow(), 'last-update' => DateTimeFormat::utcNow()];
219 DBA::update('contact', $fields, ['id' => $cid], $old_contact);
222 if (!empty($author["author-avatar"])) {
223 Contact::updateAvatar($author["author-avatar"], 0, $cid);
227 $contact["generation"] = 2;
228 $contact["hide"] = false; // OStatus contacts are never hidden
229 if (!empty($author["author-avatar"])) {
230 $contact["photo"] = $author["author-avatar"];
232 $gcid = GContact::update($contact);
234 GContact::link($gcid, $contact["uid"], $contact["id"]);
235 } elseif ($contact["network"] != Protocol::DFRN) {
243 * @brief Fetches author data from a given XML string
245 * @param string $xml The XML
246 * @param array $importer user record of the importing user
248 * @return array Array of author related entries for the item
249 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
250 * @throws \ImagickException
252 public static function salmonAuthor($xml, array $importer)
258 $doc = new DOMDocument();
259 @$doc->loadXML($xml);
261 $xpath = new DOMXPath($doc);
262 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
263 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
264 $xpath->registerNamespace('georss', ActivityNamespace::GEORSS);
265 $xpath->registerNamespace('activity', ActivityNamespace::ACTIVITY);
266 $xpath->registerNamespace('media', ActivityNamespace::MEDIA);
267 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
268 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
269 $xpath->registerNamespace('statusnet', ActivityNamespace::STATUSNET);
271 $contact = ["id" => 0];
273 // Fetch the first author
274 $authordata = $xpath->query('//author')->item(0);
275 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, true);
280 * @brief Read attributes from element
282 * @param object $element Element object
284 * @return array attributes
286 private static function readAttributes($element)
290 foreach ($element->attributes as $attributes) {
291 $attribute[$attributes->name] = $attributes->textContent;
298 * @brief Imports an XML string containing OStatus elements
300 * @param string $xml The XML
301 * @param array $importer user record of the importing user
302 * @param array $contact contact
303 * @param string $hub Called by reference, returns the fetched hub data
305 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
306 * @throws \ImagickException
308 public static function import($xml, array $importer, array &$contact, &$hub)
310 self::process($xml, $importer, $contact, $hub);
314 * @brief Internal feed processing
316 * @param string $xml The XML
317 * @param array $importer user record of the importing user
318 * @param array $contact contact
319 * @param string $hub Called by reference, returns the fetched hub data
320 * @param boolean $stored Is the post fresh imported or from the database?
321 * @param boolean $initialize Is it the leading post so that data has to be initialized?
323 * @return boolean Could the XML be processed?
324 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
325 * @throws \ImagickException
327 private static function process($xml, array $importer, array &$contact = null, &$hub, $stored = false, $initialize = true)
330 self::$itemlist = [];
331 self::$conv_list = [];
334 Logger::log('Import OStatus message for user ' . $importer['uid'], Logger::DEBUG);
339 $doc = new DOMDocument();
340 @$doc->loadXML($xml);
342 $xpath = new DOMXPath($doc);
343 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
344 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
345 $xpath->registerNamespace('georss', ActivityNamespace::GEORSS);
346 $xpath->registerNamespace('activity', ActivityNamespace::ACTIVITY);
347 $xpath->registerNamespace('media', ActivityNamespace::MEDIA);
348 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
349 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
350 $xpath->registerNamespace('statusnet', ActivityNamespace::STATUSNET);
353 $hub_items = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0);
354 if (is_object($hub_items)) {
355 $hub_attributes = $hub_items->attributes;
356 if (is_object($hub_attributes)) {
357 foreach ($hub_attributes as $hub_attribute) {
358 if ($hub_attribute->name == "href") {
359 $hub = $hub_attribute->textContent;
360 Logger::log("Found hub ".$hub, Logger::DEBUG);
367 $header["uid"] = $importer["uid"];
368 $header["network"] = Protocol::OSTATUS;
370 $header["origin"] = 0;
371 $header["gravity"] = GRAVITY_COMMENT;
373 if (!is_object($doc->firstChild) || empty($doc->firstChild->tagName)) {
377 $first_child = $doc->firstChild->tagName;
379 if ($first_child == "feed") {
380 $entries = $xpath->query('/atom:feed/atom:entry');
382 $entries = $xpath->query('/atom:entry');
385 if ($entries->length == 1) {
386 // We reformat the XML to make it better readable
387 $doc2 = new DOMDocument();
388 $doc2->loadXML($xml);
389 $doc2->preserveWhiteSpace = false;
390 $doc2->formatOutput = true;
391 $xml2 = $doc2->saveXML();
393 $header["protocol"] = Conversation::PARCEL_SALMON;
394 $header["source"] = $xml2;
395 } elseif (!$initialize) {
399 // Fetch the first author
400 $authordata = $xpath->query('//author')->item(0);
401 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, $stored);
403 // Reverse the order of the entries
406 foreach ($entries as $entry) {
407 $entrylist[] = $entry;
410 foreach (array_reverse($entrylist) as $entry) {
412 $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
414 if ($authorelement->length == 0) {
415 $authorelement = $xpath->query('atom:author', $entry);
418 if ($authorelement->length > 0) {
419 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, $stored);
422 $item = array_merge($header, $author);
424 $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
426 $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $entry);
429 if (in_array($item["verb"], ['qvitter-delete-notice', Activity::DELETE, 'delete'])) {
430 self::deleteNotice($item);
434 if (in_array($item["verb"], [Activity::O_UNFAVOURITE, Activity::UNFAVORITE])) {
435 // Ignore "Unfavorite" message
436 Logger::log("Ignore unfavorite message ".print_r($item, true), Logger::DEBUG);
440 // Deletions come with the same uri, so we check for duplicates after processing deletions
441 if (Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]])) {
442 Logger::log('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', Logger::DEBUG);
445 Logger::log('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', Logger::DEBUG);
448 if ($item["verb"] == Activity::JOIN) {
449 // ignore "Join" messages
450 Logger::log("Ignore join message ".print_r($item, true), Logger::DEBUG);
454 if ($item["verb"] == "http://mastodon.social/schema/1.0/block") {
455 // ignore mastodon "block" messages
456 Logger::log("Ignore block message ".print_r($item, true), Logger::DEBUG);
460 if ($item["verb"] == Activity::FOLLOW) {
461 Contact::addRelationship($importer, $contact, $item);
465 if ($item["verb"] == Activity::O_UNFOLLOW) {
467 Contact::removeFollower($importer, $contact, $item, $dummy);
471 if ($item["verb"] == Activity::FAVORITE) {
472 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
473 Logger::log("Favorite ".$orig_uri." ".print_r($item, true));
475 $item["verb"] = Activity::LIKE;
476 $item["parent-uri"] = $orig_uri;
477 $item["gravity"] = GRAVITY_ACTIVITY;
478 $item["object-type"] = Activity\ObjectType::NOTE;
481 // http://activitystrea.ms/schema/1.0/rsvp-yes
482 if (!in_array($item["verb"], [Activity::POST, Activity::LIKE, Activity::SHARE])) {
483 Logger::log("Unhandled verb ".$item["verb"]." ".print_r($item, true), Logger::DEBUG);
486 self::processPost($xpath, $entry, $item, $importer);
488 if ($initialize && (count(self::$itemlist) > 0)) {
489 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['parent-uri']) {
490 // We will import it everytime, when it is started by our contacts
491 $valid = Contact::isSharingByURL(self::$itemlist[0]['author-link'], self::$itemlist[0]['uid']);
494 // If not, then it depends on this setting
495 $valid = ((self::$itemlist[0]['uid'] == 0) || !DI::pConfig()->get(self::$itemlist[0]['uid'], 'system', 'accept_only_sharer', false));
497 Logger::log("Item with uri ".self::$itemlist[0]['uri']." will be imported due to the system settings.", Logger::DEBUG);
500 Logger::log("Item with uri ".self::$itemlist[0]['uri']." belongs to a contact (".self::$itemlist[0]['contact-id']."). It will be imported.", Logger::DEBUG);
503 // Never post a thread when the only interaction by our contact was a like
505 $verbs = [Activity::POST, Activity::SHARE];
506 foreach (self::$itemlist as $item) {
507 if (in_array($item['verb'], $verbs) && Contact::isSharingByURL($item['author-link'], $item['uid'])) {
512 Logger::log("Item with uri ".self::$itemlist[0]['uri']." will be imported since the thread contains posts or shares.", Logger::DEBUG);
516 // But we will only import complete threads
517 $valid = Item::exists(['uid' => $importer["uid"], 'uri' => self::$itemlist[0]['parent-uri']]);
519 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);
524 $default_contact = 0;
525 for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
526 if (empty(self::$itemlist[$key]['contact-id'])) {
527 self::$itemlist[$key]['contact-id'] = $default_contact;
529 $default_contact = $item['contact-id'];
532 foreach (self::$itemlist as $item) {
533 $found = Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]]);
535 Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", Logger::DEBUG);
536 } elseif ($item['contact-id'] < 0) {
537 Logger::log("Item with uri ".$item["uri"]." is from a blocked contact.", Logger::DEBUG);
539 // We are having duplicated entries. Hopefully this solves it.
540 if (DI::lock()->acquire('ostatus_process_item_insert')) {
541 $ret = Item::insert($item);
542 DI::lock()->release('ostatus_process_item_insert');
543 Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret);
545 $ret = Item::insert($item);
546 Logger::log("We couldn't lock - but tried to store the item anyway. Return value is ".$ret);
551 self::$itemlist = [];
553 Logger::log('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.', Logger::DEBUG);
559 * Removes notice item from database
561 * @param array $item item
565 private static function deleteNotice(array $item)
567 $condition = ['uid' => $item['uid'], 'author-id' => $item['author-id'], 'uri' => $item['uri']];
568 if (!Item::exists($condition)) {
569 Logger::log('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it.");
573 Item::delete($condition);
575 Logger::log('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
579 * @brief Processes the XML for a post
581 * @param DOMXPath $xpath The xpath object
582 * @param object $entry The xml entry that is processed
583 * @param array $item The item array
584 * @param array $importer user record of the importing user
586 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
587 * @throws \ImagickException
589 private static function processPost(DOMXPath $xpath, $entry, array &$item, array $importer)
591 $item["body"] = HTML::toBBCode(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
592 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $entry);
593 if (($item["object-type"] == Activity\ObjectType::BOOKMARK) || ($item["object-type"] == Activity\ObjectType::EVENT)) {
594 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
595 $item["body"] = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
596 } elseif ($item["object-type"] == Activity\ObjectType::QUESTION) {
597 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
600 $item["created"] = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
601 $item["edited"] = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
602 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
604 $conv = $xpath->query('ostatus:conversation', $entry);
605 if (is_object($conv->item(0))) {
606 foreach ($conv->item(0)->attributes as $attributes) {
607 if ($attributes->name == "ref") {
608 $item['conversation-uri'] = $attributes->textContent;
610 if ($attributes->name == "href") {
611 $item['conversation-href'] = $attributes->textContent;
618 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
619 if (is_object($inreplyto->item(0))) {
620 foreach ($inreplyto->item(0)->attributes as $attributes) {
621 if ($attributes->name == "ref") {
622 $item["parent-uri"] = $attributes->textContent;
624 if ($attributes->name == "href") {
625 $related = $attributes->textContent;
630 $georsspoint = $xpath->query('georss:point', $entry);
631 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
632 $item["coord"] = $georsspoint->item(0)->nodeValue;
635 $categories = $xpath->query('atom:category', $entry);
637 foreach ($categories as $category) {
638 foreach ($category->attributes as $attributes) {
639 if ($attributes->name == 'term') {
640 $term = $attributes->textContent;
641 if (!empty($item['tag'])) {
647 $item['tag'] .= '#[url=' . DI::baseUrl() . '/search?tag=' . $term . ']' . $term . '[/url]';
656 $links = $xpath->query('atom:link', $entry);
658 $link_data = self::processLinks($links, $item);
659 $self = $link_data['self'];
660 $add_body = $link_data['add_body'];
665 $notice_info = $xpath->query('statusnet:notice_info', $entry);
666 if ($notice_info && ($notice_info->length > 0)) {
667 foreach ($notice_info->item(0)->attributes as $attributes) {
668 if ($attributes->name == "source") {
669 $item["app"] = strip_tags($attributes->textContent);
671 if ($attributes->name == "repeat_of") {
672 $repeat_of = $attributes->textContent;
676 // Is it a repeated post?
677 if (($repeat_of != "") || ($item["verb"] == Activity::SHARE)) {
678 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
679 if (!empty($link_data['add_body'])) {
680 $add_body .= $link_data['add_body'];
684 $item["body"] .= $add_body;
686 // Only add additional data when there is no picture in the post
687 if (!strstr($item["body"], '[/img]')) {
688 $item["body"] = add_page_info_to_body($item["body"]);
691 // Mastodon Content Warning
692 if (($item["verb"] == Activity::POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
693 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
694 if (!empty($clear_text)) {
695 $item['content-warning'] = HTML::toBBCode($clear_text);
699 if (($self != '') && empty($item['protocol'])) {
700 self::fetchSelf($self, $item);
703 if (!empty($item["conversation-href"])) {
704 self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
707 if (isset($item["parent-uri"])) {
708 if (!Item::exists(['uid' => $importer["uid"], 'uri' => $item['parent-uri']])) {
709 if ($related != '') {
710 self::fetchRelated($related, $item["parent-uri"], $importer);
713 Logger::log('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', Logger::DEBUG);
716 $item["parent-uri"] = $item["uri"];
717 $item["gravity"] = GRAVITY_PARENT;
720 if (($item['author-link'] != '') && !empty($item['protocol'])) {
721 $item = Conversation::insert($item);
724 self::$itemlist[] = $item;
728 * @brief Fetch the conversation for posts
730 * @param string $conversation The link to the conversation
731 * @param string $conversation_uri The conversation in "uri" format
733 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
735 private static function fetchConversation($conversation, $conversation_uri)
737 // Ensure that we only store a conversation once in a process
738 if (isset(self::$conv_list[$conversation])) {
742 self::$conv_list[$conversation] = true;
744 $curlResult = Network::curl($conversation, false, ['accept_content' => 'application/atom+xml, text/html']);
746 if (!$curlResult->isSuccess()) {
752 if (stristr($curlResult->getHeader(), 'Content-Type: application/atom+xml')) {
753 $xml = $curlResult->getBody();
757 $doc = new DOMDocument();
758 if (!@$doc->loadHTML($curlResult->getBody())) {
761 $xpath = new DOMXPath($doc);
763 $links = $xpath->query('//link');
766 foreach ($links as $link) {
767 $attribute = self::readAttributes($link);
768 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
769 $file = $attribute['href'];
773 $conversation_atom = Network::curl($attribute['href']);
775 if ($conversation_atom->isSuccess()) {
776 $xml = $conversation_atom->getBody();
786 self::storeConversation($xml, $conversation, $conversation_uri);
790 * @brief Store a feed in several conversation entries
792 * @param string $xml The feed
793 * @param string $conversation conversation
794 * @param string $conversation_uri conversation uri
798 private static function storeConversation($xml, $conversation = '', $conversation_uri = '')
800 $doc = new DOMDocument();
801 @$doc->loadXML($xml);
803 $xpath = new DOMXPath($doc);
804 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
805 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
806 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
808 $entries = $xpath->query('/atom:feed/atom:entry');
810 // Now store the entries
811 foreach ($entries as $entry) {
812 $doc2 = new DOMDocument();
813 $doc2->preserveWhiteSpace = false;
814 $doc2->formatOutput = true;
818 $conv_data['protocol'] = Conversation::PARCEL_SPLIT_CONVERSATION;
819 $conv_data['network'] = Protocol::OSTATUS;
820 $conv_data['uri'] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
822 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
823 if (is_object($inreplyto->item(0))) {
824 foreach ($inreplyto->item(0)->attributes as $attributes) {
825 if ($attributes->name == "ref") {
826 $conv_data['reply-to-uri'] = $attributes->textContent;
831 $conv_data['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
833 $conv = $xpath->query('ostatus:conversation', $entry);
834 if (is_object($conv->item(0))) {
835 foreach ($conv->item(0)->attributes as $attributes) {
836 if ($attributes->name == "ref") {
837 $conv_data['conversation-uri'] = $attributes->textContent;
839 if ($attributes->name == "href") {
840 $conv_data['conversation-href'] = $attributes->textContent;
845 if ($conversation != '') {
846 $conv_data['conversation-uri'] = $conversation;
849 if ($conversation_uri != '') {
850 $conv_data['conversation-uri'] = $conversation_uri;
853 $entry = $doc2->importNode($entry, true);
855 $doc2->appendChild($entry);
857 $conv_data['source'] = $doc2->saveXML();
859 $condition = ['item-uri' => $conv_data['uri'],'protocol' => Conversation::PARCEL_FEED];
860 if (DBA::exists('conversation', $condition)) {
861 Logger::log('Delete deprecated entry for URI '.$conv_data['uri'], Logger::DEBUG);
862 DBA::delete('conversation', ['item-uri' => $conv_data['uri']]);
865 Logger::log('Store conversation data for uri '.$conv_data['uri'], Logger::DEBUG);
866 Conversation::insert($conv_data);
871 * @brief Fetch the own post so that it can be stored later
873 * We want to store the original data for later processing.
874 * This function is meant for cases where we process a feed with multiple entries.
875 * In that case we need to fetch the single posts here.
877 * @param string $self The link to the self item
878 * @param array $item The item array
880 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
882 private static function fetchSelf($self, array &$item)
884 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $self, Conversation::PARCEL_DFRN, Conversation::PARCEL_SALMON];
885 if (DBA::exists('conversation', $condition)) {
886 Logger::log('Conversation '.$item['uri'].' is already stored.', Logger::DEBUG);
890 $curlResult = Network::curl($self);
892 if (!$curlResult->isSuccess()) {
896 // We reformat the XML to make it better readable
897 $doc = new DOMDocument();
898 $doc->loadXML($curlResult->getBody());
899 $doc->preserveWhiteSpace = false;
900 $doc->formatOutput = true;
901 $xml = $doc->saveXML();
903 $item["protocol"] = Conversation::PARCEL_SALMON;
904 $item["source"] = $xml;
906 Logger::log('Conversation '.$item['uri'].' is now fetched.', Logger::DEBUG);
910 * @brief Fetch related posts and processes them
912 * @param string $related The link to the related item
913 * @param string $related_uri The related item in "uri" format
914 * @param array $importer user record of the importing user
916 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
917 * @throws \ImagickException
919 private static function fetchRelated($related, $related_uri, $importer)
921 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, Conversation::PARCEL_DFRN, Conversation::PARCEL_SALMON];
922 $conversation = DBA::selectFirst('conversation', ['source', 'protocol'], $condition);
923 if (DBA::isResult($conversation)) {
925 $xml = $conversation['source'];
926 if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
927 Logger::log('Got valid cached XML for URI '.$related_uri, Logger::DEBUG);
930 if ($conversation['protocol'] == Conversation::PARCEL_SALMON) {
931 Logger::log('Delete invalid cached XML for URI '.$related_uri, Logger::DEBUG);
932 DBA::delete('conversation', ['item-uri' => $related_uri]);
937 $curlResult = Network::curl($related, false, ['accept_content' => 'application/atom+xml, text/html']);
939 if (!$curlResult->isSuccess()) {
945 if (stristr($curlResult->getHeader(), 'Content-Type: application/atom+xml')) {
946 Logger::log('Directly fetched XML for URI ' . $related_uri, Logger::DEBUG);
947 $xml = $curlResult->getBody();
951 $doc = new DOMDocument();
952 if (!@$doc->loadHTML($curlResult->getBody())) {
955 $xpath = new DOMXPath($doc);
959 $links = $xpath->query('//link');
961 foreach ($links as $link) {
962 $attribute = self::readAttributes($link);
963 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
964 $atom_file = $attribute['href'];
967 if ($atom_file != '') {
968 $curlResult = Network::curl($atom_file);
970 if ($curlResult->isSuccess()) {
971 Logger::log('Fetched XML for URI ' . $related_uri, Logger::DEBUG);
972 $xml = $curlResult->getBody();
978 // Workaround for older GNU Social servers
979 if (($xml == '') && strstr($related, '/notice/')) {
980 $curlResult = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related).'.atom');
982 if ($curlResult->isSuccess()) {
983 Logger::log('GNU Social workaround to fetch XML for URI ' . $related_uri, Logger::DEBUG);
984 $xml = $curlResult->getBody();
988 // Even more worse workaround for GNU Social ;-)
990 $related_guess = OStatus::convertHref($related_uri);
991 $curlResult = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related_guess).'.atom');
993 if ($curlResult->isSuccess()) {
994 Logger::log('GNU Social workaround 2 to fetch XML for URI ' . $related_uri, Logger::DEBUG);
995 $xml = $curlResult->getBody();
999 // Finally we take the data that we fetched from "ostatus:conversation"
1001 $condition = ['item-uri' => $related_uri, 'protocol' => Conversation::PARCEL_SPLIT_CONVERSATION];
1002 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1003 if (DBA::isResult($conversation)) {
1005 Logger::log('Got cached XML from conversation for URI '.$related_uri, Logger::DEBUG);
1006 $xml = $conversation['source'];
1011 self::process($xml, $importer, $contact, $hub, $stored, false);
1013 Logger::log("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, Logger::DEBUG);
1019 * @brief Processes the XML for a repeated post
1021 * @param DOMXPath $xpath The xpath object
1022 * @param object $entry The xml entry that is processed
1023 * @param array $item The item array
1024 * @param array $importer user record of the importing user
1026 * @return array with data from links
1027 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1028 * @throws \ImagickException
1030 private static function processRepeatedItem(DOMXPath $xpath, $entry, array &$item, array $importer)
1032 $activityobject = $xpath->query('activity:object', $entry)->item(0);
1034 if (!is_object($activityobject)) {
1040 $orig_uri = XML::getFirstNodeValue($xpath, 'atom:id/text()', $activityobject);
1042 $links = $xpath->query("atom:link", $activityobject);
1044 $link_data = self::processLinks($links, $item);
1047 $orig_body = XML::getFirstNodeValue($xpath, 'atom:content/text()', $activityobject);
1048 $orig_created = XML::getFirstNodeValue($xpath, 'atom:published/text()', $activityobject);
1049 $orig_edited = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $activityobject);
1051 $orig_author = self::fetchAuthor($xpath, $activityobject, $importer, $dummy, false);
1053 $item["author-name"] = $orig_author["author-name"];
1054 $item["author-link"] = $orig_author["author-link"];
1055 $item["author-id"] = $orig_author["author-id"];
1057 $item["body"] = HTML::toBBCode($orig_body);
1058 $item["created"] = $orig_created;
1059 $item["edited"] = $orig_edited;
1061 $item["uri"] = $orig_uri;
1063 $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $activityobject);
1065 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $activityobject);
1067 // Mastodon Content Warning
1068 if (($item["verb"] == Activity::POST) && $xpath->evaluate('boolean(atom:summary)', $activityobject)) {
1069 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $activityobject);
1070 if (!empty($clear_text)) {
1071 $item['content-warning'] = HTML::toBBCode($clear_text);
1075 $inreplyto = $xpath->query('thr:in-reply-to', $activityobject);
1076 if (is_object($inreplyto->item(0))) {
1077 foreach ($inreplyto->item(0)->attributes as $attributes) {
1078 if ($attributes->name == "ref") {
1079 $item["parent-uri"] = $attributes->textContent;
1088 * @brief Processes links in the XML
1090 * @param object $links The xml data that contain links
1091 * @param array $item The item array
1093 * @return array with data from the links
1095 private static function processLinks($links, array &$item)
1097 $link_data = ['add_body' => '', 'self' => ''];
1099 foreach ($links as $link) {
1100 $attribute = self::readAttributes($link);
1102 if (!empty($attribute['rel']) && !empty($attribute['href'])) {
1103 switch ($attribute['rel']) {
1105 $item["plink"] = $attribute['href'];
1106 if (($item["object-type"] == Activity\ObjectType::QUESTION)
1107 || ($item["object-type"] == Activity\ObjectType::EVENT)
1109 $item["body"] .= add_page_info($attribute['href']);
1112 case "ostatus:conversation":
1113 $link_data['conversation'] = $attribute['href'];
1114 $item['conversation-href'] = $link_data['conversation'];
1115 if (!isset($item['conversation-uri'])) {
1116 $item['conversation-uri'] = $item['conversation-href'];
1120 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
1121 if ($filetype == 'image') {
1122 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1124 if (!empty($item["attach"])) {
1125 $item["attach"] .= ',';
1127 $item["attach"] = '';
1129 if (!isset($attribute['length'])) {
1130 $attribute['length'] = "0";
1132 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.($attribute['title'] ?? '') .'"[/attach]';
1136 if ($item["object-type"] != Activity\ObjectType::BOOKMARK) {
1137 if (!isset($item["parent-uri"])) {
1138 $item["parent-uri"] = $attribute['href'];
1140 $link_data['related'] = $attribute['href'];
1142 $item["body"] .= add_page_info($attribute['href']);
1146 if (empty($item["plink"])) {
1147 $item["plink"] = $attribute['href'];
1149 $link_data['self'] = $attribute['href'];
1158 * @brief Create an url out of an uri
1160 * @param string $href URI in the format "parameter1:parameter1:..."
1162 * @return string URL in the format http(s)://....
1164 public static function convertHref($href)
1166 $elements = explode(":", $href);
1168 if ((count($elements) <= 2) || ($elements[0] != "tag")) {
1172 $server = explode(",", $elements[1]);
1173 $conversation = explode("=", $elements[2]);
1175 if ((count($elements) == 4) && ($elements[2] == "post")) {
1176 return "http://".$server[0]."/notice/".$elements[3];
1179 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1182 if ($elements[3] == "objectType=thread") {
1183 return "http://".$server[0]."/conversation/".$conversation[1];
1185 return "http://".$server[0]."/notice/".$conversation[1];
1190 * @brief Checks if the current post is a reshare
1192 * @param array $item The item array of thw post
1194 * @return string The guid if the post is a reshare
1196 private static function getResharedGuid(array $item)
1198 $reshared = Item::getShareArray($item);
1199 if (empty($reshared['guid']) || !empty($reshared['comment'])) {
1203 return $reshared['guid'];
1207 * @brief Cleans the body of a post if it contains picture links
1209 * @param string $body The body
1211 * @return string The cleaned body
1212 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1214 private static function formatPicturePost($body)
1216 $siteinfo = BBCode::getAttachedData($body);
1218 if (($siteinfo["type"] == "photo") && (!empty($siteinfo["preview"]) || !empty($siteinfo["image"]))) {
1219 if (isset($siteinfo["preview"])) {
1220 $preview = $siteinfo["preview"];
1222 $preview = $siteinfo["image"];
1225 // Is it a remote picture? Then make a smaller preview here
1226 $preview = ProxyUtils::proxifyUrl($preview, false, ProxyUtils::SIZE_SMALL);
1228 // Is it a local picture? Then make it smaller here
1229 $preview = str_replace(["-0.jpg", "-0.png"], ["-2.jpg", "-2.png"], $preview);
1230 $preview = str_replace(["-1.jpg", "-1.png"], ["-2.jpg", "-2.png"], $preview);
1232 if (isset($siteinfo["url"])) {
1233 $url = $siteinfo["url"];
1235 $url = $siteinfo["image"];
1238 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1245 * @brief Adds the header elements to the XML document
1247 * @param DOMDocument $doc XML document
1248 * @param array $owner Contact data of the poster
1249 * @param string $filter The related feed filter (activity, posts or comments)
1250 * @param bool $feed_mode Behave like a regular feed for users if true
1252 * @return object header root element
1253 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1255 private static function addHeader(DOMDocument $doc, array $owner, $filter, $feed_mode = false)
1257 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
1258 $doc->appendChild($root);
1260 $root->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
1261 $root->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
1262 $root->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
1263 $root->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
1264 $root->setAttribute("xmlns:poco", ActivityNamespace::POCO);
1265 $root->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
1266 $root->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
1267 $root->setAttribute("xmlns:mastodon", ActivityNamespace::MASTODON);
1270 $selfUri = '/feed/' . $owner["nick"] . '/';
1273 $title = L10n::t('%s\'s timeline', $owner['name']);
1274 $selfUri .= $filter;
1277 $title = L10n::t('%s\'s posts', $owner['name']);
1280 $title = L10n::t('%s\'s comments', $owner['name']);
1281 $selfUri .= $filter;
1286 $selfUri = "/dfrn_poll/" . $owner["nick"];
1289 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
1290 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1291 XML::addElement($doc, $root, "id", DI::baseUrl() . "/profile/" . $owner["nick"]);
1292 XML::addElement($doc, $root, "title", $title);
1293 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], Config::get('config', 'sitename')));
1294 XML::addElement($doc, $root, "logo", $owner["photo"]);
1295 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1297 $author = self::addAuthor($doc, $owner);
1298 $root->appendChild($author);
1300 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1301 XML::addElement($doc, $root, "link", "", $attributes);
1303 /// @TODO We have to find out what this is
1304 /// $attributes = array("href" => DI::baseUrl()."/sup",
1305 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1306 /// "type" => "application/json");
1307 /// XML::addElement($doc, $root, "link", "", $attributes);
1309 self::hublinks($doc, $root, $owner["nick"]);
1311 $attributes = ["href" => DI::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "salmon"];
1312 XML::addElement($doc, $root, "link", "", $attributes);
1314 $attributes = ["href" => DI::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies"];
1315 XML::addElement($doc, $root, "link", "", $attributes);
1317 $attributes = ["href" => DI::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention"];
1318 XML::addElement($doc, $root, "link", "", $attributes);
1320 $attributes = ["href" => DI::baseUrl() . $selfUri, "rel" => "self", "type" => "application/atom+xml"];
1321 XML::addElement($doc, $root, "link", "", $attributes);
1323 if ($owner['account-type'] == Contact::TYPE_COMMUNITY) {
1324 $condition = ['uid' => $owner['uid'], 'self' => false, 'pending' => false,
1325 'archive' => false, 'hidden' => false, 'blocked' => false];
1326 $members = DBA::count('contact', $condition);
1327 XML::addElement($doc, $root, "statusnet:group_info", "", ["member_count" => $members]);
1334 * @brief Add the link to the push hubs to the XML document
1336 * @param DOMDocument $doc XML document
1337 * @param object $root XML root element where the hub links are added
1338 * @param object $nick nick
1340 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1342 public static function hublinks(DOMDocument $doc, $root, $nick)
1344 $h = DI::baseUrl() . '/pubsubhubbub/'.$nick;
1345 XML::addElement($doc, $root, "link", "", ["href" => $h, "rel" => "hub"]);
1349 * @brief Adds attachment data to the XML document
1351 * @param DOMDocument $doc XML document
1352 * @param object $root XML root element where the hub links are added
1353 * @param array $item Data of the item that is to be posted
1355 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1357 private static function getAttachment(DOMDocument $doc, $root, $item)
1359 $siteinfo = BBCode::getAttachedData($item["body"]);
1361 switch ($siteinfo["type"]) {
1363 if (!empty($siteinfo["image"])) {
1364 $imgdata = Images::getInfoFromURLCached($siteinfo["image"]);
1366 $attributes = ["rel" => "enclosure",
1367 "href" => $siteinfo["image"],
1368 "type" => $imgdata["mime"],
1369 "length" => intval($imgdata["size"])];
1370 XML::addElement($doc, $root, "link", "", $attributes);
1375 $attributes = ["rel" => "enclosure",
1376 "href" => $siteinfo["url"],
1377 "type" => "text/html; charset=UTF-8",
1379 "title" => ($siteinfo["title"] ?? '') ?: $siteinfo["url"],
1381 XML::addElement($doc, $root, "link", "", $attributes);
1387 if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1388 $imgdata = Images::getInfoFromURLCached($siteinfo["image"]);
1390 $attributes = ["rel" => "enclosure",
1391 "href" => $siteinfo["image"],
1392 "type" => $imgdata["mime"],
1393 "length" => intval($imgdata["size"])];
1395 XML::addElement($doc, $root, "link", "", $attributes);
1399 $arr = explode('[/attach],', $item['attach']);
1401 foreach ($arr as $r) {
1403 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1405 $attributes = ["rel" => "enclosure",
1406 "href" => $matches[1],
1407 "type" => $matches[3]];
1409 if (intval($matches[2])) {
1410 $attributes["length"] = intval($matches[2]);
1412 if (trim($matches[4]) != "") {
1413 $attributes["title"] = trim($matches[4]);
1415 XML::addElement($doc, $root, "link", "", $attributes);
1422 * @brief Adds the author element to the XML document
1424 * @param DOMDocument $doc XML document
1425 * @param array $owner Contact data of the poster
1426 * @param bool $show_profile Whether to show profile
1428 * @return \DOMElement author element
1429 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1431 private static function addAuthor(DOMDocument $doc, array $owner, $show_profile = true)
1433 $profile = DBA::selectFirst('profile', ['homepage', 'publish'], ['uid' => $owner['uid'], 'is-default' => true]);
1434 $author = $doc->createElement("author");
1435 XML::addElement($doc, $author, "id", $owner["url"]);
1436 if ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
1437 XML::addElement($doc, $author, "activity:object-type", Activity\ObjectType::GROUP);
1439 XML::addElement($doc, $author, "activity:object-type", Activity\ObjectType::PERSON);
1441 XML::addElement($doc, $author, "uri", $owner["url"]);
1442 XML::addElement($doc, $author, "name", $owner["nick"]);
1443 XML::addElement($doc, $author, "email", $owner["addr"]);
1444 if ($show_profile) {
1445 XML::addElement($doc, $author, "summary", BBCode::convert($owner["about"], false, 7));
1448 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $owner["url"]];
1449 XML::addElement($doc, $author, "link", "", $attributes);
1453 "type" => "image/jpeg", // To-Do?
1454 "media:width" => 300,
1455 "media:height" => 300,
1456 "href" => $owner["photo"]];
1457 XML::addElement($doc, $author, "link", "", $attributes);
1459 if (isset($owner["thumb"])) {
1462 "type" => "image/jpeg", // To-Do?
1463 "media:width" => 80,
1464 "media:height" => 80,
1465 "href" => $owner["thumb"]];
1466 XML::addElement($doc, $author, "link", "", $attributes);
1469 XML::addElement($doc, $author, "poco:preferredUsername", $owner["nick"]);
1470 XML::addElement($doc, $author, "poco:displayName", $owner["name"]);
1471 if ($show_profile) {
1472 XML::addElement($doc, $author, "poco:note", BBCode::convert($owner["about"], false, 7));
1474 if (trim($owner["location"]) != "") {
1475 $element = $doc->createElement("poco:address");
1476 XML::addElement($doc, $element, "poco:formatted", $owner["location"]);
1477 $author->appendChild($element);
1481 if (DBA::isResult($profile) && !$show_profile) {
1482 if (trim($profile["homepage"]) != "") {
1483 $urls = $doc->createElement("poco:urls");
1484 XML::addElement($doc, $urls, "poco:type", "homepage");
1485 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
1486 XML::addElement($doc, $urls, "poco:primary", "true");
1487 $author->appendChild($urls);
1490 XML::addElement($doc, $author, "followers", "", ["url" => DI::baseUrl() . "/profile/" . $owner["nick"] . "/contacts/followers"]);
1491 XML::addElement($doc, $author, "statusnet:profile_info", "", ["local_id" => $owner["uid"]]);
1493 if ($profile["publish"]) {
1494 XML::addElement($doc, $author, "mastodon:scope", "public");
1502 * @TODO Picture attachments should look like this:
1503 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1504 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1508 * @brief Returns the given activity if present - otherwise returns the "post" activity
1510 * @param array $item Data of the item that is to be posted
1512 * @return string activity
1514 private static function constructVerb(array $item)
1516 if (!empty($item['verb'])) {
1517 return $item['verb'];
1520 return Activity::POST;
1524 * @brief Returns the given object type if present - otherwise returns the "note" object type
1526 * @param array $item Data of the item that is to be posted
1528 * @return string Object type
1530 private static function constructObjecttype(array $item)
1532 if (!empty($item['object-type']) && in_array($item['object-type'], [Activity\ObjectType::NOTE, Activity\ObjectType::COMMENT])) {
1533 return $item['object-type'];
1536 return Activity\ObjectType::NOTE;
1540 * @brief Adds an entry element to the XML document
1542 * @param DOMDocument $doc XML document
1543 * @param array $item Data of the item that is to be posted
1544 * @param array $owner Contact data of the poster
1545 * @param bool $toplevel optional default false
1546 * @param bool $feed_mode Behave like a regular feed for users if true
1548 * @return \DOMElement Entry element
1549 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1550 * @throws \ImagickException
1552 private static function entry(DOMDocument $doc, array $item, array $owner, $toplevel = false, $feed_mode = false)
1556 $repeated_guid = self::getResharedGuid($item);
1557 if ($repeated_guid != "") {
1558 $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel);
1565 if ($item["verb"] == Activity::LIKE) {
1566 return self::likeEntry($doc, $item, $owner, $toplevel);
1567 } elseif (in_array($item["verb"], [Activity::FOLLOW, Activity::O_UNFOLLOW])) {
1568 return self::followEntry($doc, $item, $owner, $toplevel);
1570 return self::noteEntry($doc, $item, $owner, $toplevel, $feed_mode);
1575 * @brief Adds a source entry to the XML document
1577 * @param DOMDocument $doc XML document
1578 * @param array $contact Array of the contact that is added
1580 * @return \DOMElement Source element
1581 * @throws \Exception
1583 private static function sourceEntry(DOMDocument $doc, array $contact)
1585 $source = $doc->createElement("source");
1586 XML::addElement($doc, $source, "id", $contact["poll"]);
1587 XML::addElement($doc, $source, "title", $contact["name"]);
1588 XML::addElement($doc, $source, "link", "", ["rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]]);
1589 XML::addElement($doc, $source, "link", "", ["rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]]);
1590 XML::addElement($doc, $source, "icon", $contact["photo"]);
1591 XML::addElement($doc, $source, "updated", DateTimeFormat::utc($contact["success_update"]."+00:00", DateTimeFormat::ATOM));
1597 * @brief Fetches contact data from the contact or the gcontact table
1599 * @param string $url URL of the contact
1600 * @param array $owner Contact data of the poster
1602 * @return array Contact array
1603 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1604 * @throws \ImagickException
1606 private static function contactEntry($url, array $owner)
1609 "SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1610 DBA::escape(Strings::normaliseLink($url)),
1611 intval($owner["uid"])
1613 if (DBA::isResult($r)) {
1615 $contact["uid"] = -1;
1618 if (!DBA::isResult($r)) {
1619 $gcontact = DBA::selectFirst('gcontact', [], ['nurl' => Strings::normaliseLink($url)]);
1620 if (DBA::isResult($r)) {
1621 $contact = $gcontact;
1622 $contact["uid"] = -1;
1623 $contact["success_update"] = $contact["updated"];
1627 if (!DBA::isResult($r)) {
1631 if (!isset($contact["poll"])) {
1632 $data = Probe::uri($url);
1633 $contact["poll"] = $data["poll"];
1635 if (!$contact["alias"]) {
1636 $contact["alias"] = $data["alias"];
1640 if (!isset($contact["alias"])) {
1641 $contact["alias"] = $contact["url"];
1644 $contact['account-type'] = $owner['account-type'];
1650 * @brief Adds an entry element with reshared content
1652 * @param DOMDocument $doc XML document
1653 * @param array $item Data of the item that is to be posted
1654 * @param array $owner Contact data of the poster
1655 * @param string $repeated_guid guid
1656 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1658 * @return bool Entry element
1659 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1660 * @throws \ImagickException
1662 private static function reshareEntry(DOMDocument $doc, array $item, array $owner, $repeated_guid, $toplevel)
1664 if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1665 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1668 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1670 $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => false,
1671 'network' => [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS]];
1672 $repeated_item = Item::selectFirst([], $condition);
1673 if (!DBA::isResult($repeated_item)) {
1677 $contact = self::contactEntry($repeated_item['author-link'], $owner);
1679 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1681 self::entryContent($doc, $entry, $item, $owner, $title, Activity::SHARE, false);
1683 $as_object = $doc->createElement("activity:object");
1685 XML::addElement($doc, $as_object, "activity:object-type", ActivityNamespace::ACTIVITY_SCHEMA . "activity");
1687 self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false);
1689 $author = self::addAuthor($doc, $contact, false);
1690 $as_object->appendChild($author);
1692 $as_object2 = $doc->createElement("activity:object");
1694 XML::addElement($doc, $as_object2, "activity:object-type", self::constructObjecttype($repeated_item));
1696 $title = sprintf("New comment by %s", $contact["nick"]);
1698 self::entryContent($doc, $as_object2, $repeated_item, $owner, $title);
1700 $as_object->appendChild($as_object2);
1702 self::entryFooter($doc, $as_object, $item, $owner, false);
1704 $source = self::sourceEntry($doc, $contact);
1706 $as_object->appendChild($source);
1708 $entry->appendChild($as_object);
1710 self::entryFooter($doc, $entry, $item, $owner);
1716 * @brief Adds an entry element with a "like"
1718 * @param DOMDocument $doc XML document
1719 * @param array $item Data of the item that is to be posted
1720 * @param array $owner Contact data of the poster
1721 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1723 * @return \DOMElement Entry element with "like"
1724 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1725 * @throws \ImagickException
1727 private static function likeEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1729 if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1730 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1733 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1735 $verb = ActivityNamespace::ACTIVITY_SCHEMA . "favorite";
1736 self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false);
1738 $parent = Item::selectFirst([], ['uri' => $item["thr-parent"], 'uid' => $item["uid"]]);
1739 if (DBA::isResult($parent)) {
1740 $as_object = $doc->createElement("activity:object");
1742 XML::addElement($doc, $as_object, "activity:object-type", self::constructObjecttype($parent));
1744 self::entryContent($doc, $as_object, $parent, $owner, "New entry");
1746 $entry->appendChild($as_object);
1749 self::entryFooter($doc, $entry, $item, $owner);
1755 * @brief Adds the person object element to the XML document
1757 * @param DOMDocument $doc XML document
1758 * @param array $owner Contact data of the poster
1759 * @param array $contact Contact data of the target
1761 * @return object author element
1763 private static function addPersonObject(DOMDocument $doc, array $owner, array $contact)
1765 $object = $doc->createElement("activity:object");
1766 XML::addElement($doc, $object, "activity:object-type", Activity\ObjectType::PERSON);
1768 if ($contact['network'] == Protocol::PHANTOM) {
1769 XML::addElement($doc, $object, "id", $contact['url']);
1773 XML::addElement($doc, $object, "id", $contact["alias"]);
1774 XML::addElement($doc, $object, "title", $contact["nick"]);
1776 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $contact["url"]];
1777 XML::addElement($doc, $object, "link", "", $attributes);
1781 "type" => "image/jpeg", // To-Do?
1782 "media:width" => 300,
1783 "media:height" => 300,
1784 "href" => $contact["photo"]];
1785 XML::addElement($doc, $object, "link", "", $attributes);
1787 XML::addElement($doc, $object, "poco:preferredUsername", $contact["nick"]);
1788 XML::addElement($doc, $object, "poco:displayName", $contact["name"]);
1790 if (trim($contact["location"]) != "") {
1791 $element = $doc->createElement("poco:address");
1792 XML::addElement($doc, $element, "poco:formatted", $contact["location"]);
1793 $object->appendChild($element);
1800 * @brief Adds a follow/unfollow entry element
1802 * @param DOMDocument $doc XML document
1803 * @param array $item Data of the follow/unfollow message
1804 * @param array $owner Contact data of the poster
1805 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1807 * @return \DOMElement Entry element
1808 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1809 * @throws \ImagickException
1811 private static function followEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1813 $item["id"] = $item["parent"] = 0;
1814 $item["created"] = $item["edited"] = date("c");
1815 $item["private"] = true;
1817 $contact = Probe::uri($item['follow']);
1819 if ($contact['alias'] == '') {
1820 $contact['alias'] = $contact["url"];
1822 $item['follow'] = $contact['alias'];
1825 $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($contact["url"])];
1826 $user_contact = DBA::selectFirst('contact', ['id'], $condition);
1828 if (DBA::isResult($user_contact)) {
1829 $connect_id = $user_contact['id'];
1834 if ($item['verb'] == Activity::FOLLOW) {
1835 $message = L10n::t('%s is now following %s.');
1836 $title = L10n::t('following');
1837 $action = "subscription";
1839 $message = L10n::t('%s stopped following %s.');
1840 $title = L10n::t('stopped following');
1841 $action = "unfollow";
1844 $item["uri"] = $item['parent-uri'] = $item['thr-parent']
1845 = 'tag:' . DI::baseUrl()->getHostname().
1846 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1847 ':person:'.$connect_id.':'.$item['created'];
1849 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1851 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1853 self::entryContent($doc, $entry, $item, $owner, $title);
1855 $object = self::addPersonObject($doc, $owner, $contact);
1856 $entry->appendChild($object);
1858 self::entryFooter($doc, $entry, $item, $owner);
1864 * @brief Adds a regular entry element
1866 * @param DOMDocument $doc XML document
1867 * @param array $item Data of the item that is to be posted
1868 * @param array $owner Contact data of the poster
1869 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1870 * @param bool $feed_mode Behave like a regular feed for users if true
1872 * @return \DOMElement Entry element
1873 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1874 * @throws \ImagickException
1876 private static function noteEntry(DOMDocument $doc, array $item, array $owner, $toplevel, $feed_mode)
1878 if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1879 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1883 if (!empty($item['title'])) {
1884 $title = BBCode::convert($item['title'], false, 7);
1886 $title = sprintf("New note by %s", $owner["nick"]);
1889 $title = sprintf("New comment by %s", $owner["nick"]);
1892 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1894 XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::NOTE);
1896 self::entryContent($doc, $entry, $item, $owner, $title, '', true, $feed_mode);
1898 self::entryFooter($doc, $entry, $item, $owner, !$feed_mode, $feed_mode);
1904 * @brief Adds a header element to the XML document
1906 * @param DOMDocument $doc XML document
1907 * @param array $owner Contact data of the poster
1908 * @param array $item
1909 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1911 * @return \DOMElement The entry element where the elements are added
1912 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1913 * @throws \ImagickException
1915 private static function entryHeader(DOMDocument $doc, array $owner, array $item, $toplevel)
1918 $entry = $doc->createElement("entry");
1920 if ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
1921 $contact = self::contactEntry($item['author-link'], $owner);
1922 $author = self::addAuthor($doc, $contact, false);
1923 $entry->appendChild($author);
1926 $entry = $doc->createElementNS(ActivityNamespace::ATOM1, "entry");
1928 $entry->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
1929 $entry->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
1930 $entry->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
1931 $entry->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
1932 $entry->setAttribute("xmlns:poco", ActivityNamespace::POCO);
1933 $entry->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
1934 $entry->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
1935 $entry->setAttribute("xmlns:mastodon", ActivityNamespace::MASTODON);
1937 $author = self::addAuthor($doc, $owner);
1938 $entry->appendChild($author);
1945 * @brief Adds elements to the XML document
1947 * @param DOMDocument $doc XML document
1948 * @param \DOMElement $entry Entry element where the content is added
1949 * @param array $item Data of the item that is to be posted
1950 * @param array $owner Contact data of the poster
1951 * @param string $title Title for the post
1952 * @param string $verb The activity verb
1953 * @param bool $complete Add the "status_net" element?
1954 * @param bool $feed_mode Behave like a regular feed for users if true
1956 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1958 private static function entryContent(DOMDocument $doc, \DOMElement $entry, array $item, array $owner, $title, $verb = "", $complete = true, $feed_mode = false)
1961 $verb = self::constructVerb($item);
1964 XML::addElement($doc, $entry, "id", $item["uri"]);
1965 XML::addElement($doc, $entry, "title", html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1967 $body = self::formatPicturePost($item['body']);
1969 if (!empty($item['title']) && !$feed_mode) {
1970 $body = "[b]".$item['title']."[/b]\n\n".$body;
1973 $body = BBCode::convert($body, false, 7);
1975 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1977 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1978 "href" => DI::baseUrl()."/display/".$item["guid"]]
1981 if (!$feed_mode && $complete && ($item["id"] > 0)) {
1982 XML::addElement($doc, $entry, "status_net", "", ["notice_id" => $item["id"]]);
1986 XML::addElement($doc, $entry, "activity:verb", $verb);
1989 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
1990 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
1994 * @brief Adds the elements at the foot of an entry to the XML document
1996 * @param DOMDocument $doc XML document
1997 * @param object $entry The entry element where the elements are added
1998 * @param array $item Data of the item that is to be posted
1999 * @param array $owner Contact data of the poster
2000 * @param bool $complete default true
2001 * @param bool $feed_mode Behave like a regular feed for users if true
2003 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2005 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner, $complete = true, $feed_mode = false)
2009 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
2010 $parent = Item::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item["parent"]]);
2011 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
2013 $thrparent = Item::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $parent_item]);
2015 if (DBA::isResult($thrparent)) {
2016 $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
2017 $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
2018 $parent_plink = $thrparent["plink"];
2020 $mentioned[$parent["author-link"]] = $parent["author-link"];
2021 $mentioned[$parent["owner-link"]] = $parent["owner-link"];
2022 $parent_plink = DI::baseUrl()."/display/".$parent["guid"];
2026 "ref" => $parent_item,
2027 "href" => $parent_plink];
2028 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
2032 "href" => $parent_plink];
2033 XML::addElement($doc, $entry, "link", "", $attributes);
2036 if (!$feed_mode && (intval($item["parent"]) > 0)) {
2037 $conversation_href = $conversation_uri = str_replace('/objects/', '/context/', $item['parent-uri']);
2039 if (isset($parent_item)) {
2040 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $parent_item]);
2041 if (DBA::isResult($conversation)) {
2042 if ($conversation['conversation-uri'] != '') {
2043 $conversation_uri = $conversation['conversation-uri'];
2045 if ($conversation['conversation-href'] != '') {
2046 $conversation_href = $conversation['conversation-href'];
2051 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:conversation", "href" => $conversation_href]);
2054 "href" => $conversation_href,
2055 "local_id" => $item["parent"],
2056 "ref" => $conversation_uri];
2058 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
2061 $tags = item::getFeedTags($item);
2064 foreach ($tags as $t) {
2066 $mentioned[$t[1]] = $t[1];
2071 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2073 foreach ($mentioned as $mention) {
2074 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2075 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2077 $mentioned = $newmentions;
2079 foreach ($mentioned as $mention) {
2080 $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($mention)];
2081 $contact = DBA::selectFirst('contact', ['forum', 'prv', 'self', 'contact-type'], $condition);
2082 if ($contact["forum"] || $contact["prv"] || ($owner['contact-type'] == Contact::TYPE_COMMUNITY) ||
2083 ($contact['self'] && ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY))) {
2084 XML::addElement($doc, $entry, "link", "",
2086 "rel" => "mentioned",
2087 "ostatus:object-type" => Activity\ObjectType::GROUP,
2091 XML::addElement($doc, $entry, "link", "",
2093 "rel" => "mentioned",
2094 "ostatus:object-type" => Activity\ObjectType::PERSON,
2100 if ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
2101 XML::addElement($doc, $entry, "link", "", [
2102 "rel" => "mentioned",
2103 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/group",
2104 "href" => $owner['url']
2108 if (!$item["private"] && !$feed_mode) {
2109 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:attention",
2110 "href" => "http://activityschema.org/collection/public"]);
2111 XML::addElement($doc, $entry, "link", "", ["rel" => "mentioned",
2112 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2113 "href" => "http://activityschema.org/collection/public"]);
2114 XML::addElement($doc, $entry, "mastodon:scope", "public");
2118 foreach ($tags as $t) {
2120 XML::addElement($doc, $entry, "category", "", ["term" => $t[2]]);
2125 self::getAttachment($doc, $entry, $item);
2127 if ($complete && ($item["id"] > 0)) {
2128 $app = $item["app"];
2133 $attributes = ["local_id" => $item["id"], "source" => $app];
2135 if (isset($parent["id"])) {
2136 $attributes["repeat_of"] = $parent["id"];
2139 if ($item["coord"] != "") {
2140 XML::addElement($doc, $entry, "georss:point", $item["coord"]);
2143 XML::addElement($doc, $entry, "statusnet:notice_info", "", $attributes);
2148 * Creates the XML feed for a given nickname
2150 * Supported filters:
2151 * - activity (default): all the public posts
2152 * - posts: all the public top-level posts
2153 * - comments: all the public replies
2155 * Updates the provided last_update parameter if the result comes from the
2156 * cache or it is empty
2158 * @brief Creates the XML feed for a given nickname
2160 * @param string $owner_nick Nickname of the feed owner
2161 * @param string $last_update Date of the last update
2162 * @param integer $max_items Number of maximum items to fetch
2163 * @param string $filter Feed items filter (activity, posts or comments)
2164 * @param boolean $nocache Wether to bypass caching
2165 * @param boolean $feed_mode Behave like a regular feed for users if true
2167 * @return string XML feed
2168 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2169 * @throws \ImagickException
2171 public static function feed($owner_nick, &$last_update, $max_items = 300, $filter = 'activity', $nocache = false, $feed_mode = false)
2173 $stamp = microtime(true);
2175 $owner = User::getOwnerDataByNick($owner_nick);
2180 $cachekey = "ostatus:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
2182 $previous_created = $last_update;
2184 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
2185 if ((time() - strtotime($owner['last-item'])) < 15*60) {
2186 $result = DI::cache()->get($cachekey);
2187 if (!$nocache && !is_null($result)) {
2188 Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', Logger::DEBUG);
2189 $last_update = $result['last_update'];
2190 return $result['feed'];
2194 if (!strlen($last_update)) {
2195 $last_update = 'now -30 days';
2198 $check_date = DateTimeFormat::utc($last_update);
2199 $authorid = Contact::getIdForURL($owner["url"], 0, true);
2201 $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted`
2202 AND NOT `private` AND `visible` AND `wall` AND `parent-network` IN (?, ?)",
2203 $owner["uid"], $check_date, Protocol::OSTATUS, Protocol::DFRN];
2205 if ($filter === 'comments') {
2206 $condition[0] .= " AND `object-type` = ? ";
2207 $condition[] = Activity\ObjectType::COMMENT;
2210 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
2211 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
2212 $condition[] = $owner["id"];
2213 $condition[] = $authorid;
2216 $params = ['order' => ['received' => true], 'limit' => $max_items];
2218 if ($filter === 'posts') {
2219 $ret = Item::selectThread([], $condition, $params);
2221 $ret = Item::select([], $condition, $params);
2224 $items = Item::inArray($ret);
2226 $doc = new DOMDocument('1.0', 'utf-8');
2227 $doc->formatOutput = true;
2229 $root = self::addHeader($doc, $owner, $filter, $feed_mode);
2231 foreach ($items as $item) {
2232 if (Config::get('system', 'ostatus_debug')) {
2233 $item['body'] .= '🍼';
2236 $entry = self::entry($doc, $item, $owner, false, $feed_mode);
2237 $root->appendChild($entry);
2239 if ($last_update < $item['created']) {
2240 $last_update = $item['created'];
2244 $feeddata = trim($doc->saveXML());
2246 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
2247 DI::cache()->set($cachekey, $msg, Cache::QUARTER_HOUR);
2249 Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, Logger::DEBUG);
2255 * @brief Creates the XML for a salmon message
2257 * @param array $item Data of the item that is to be posted
2258 * @param array $owner Contact data of the poster
2260 * @return string XML for the salmon
2261 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2262 * @throws \ImagickException
2264 public static function salmon(array $item, array $owner)
2266 $doc = new DOMDocument('1.0', 'utf-8');
2267 $doc->formatOutput = true;
2269 if (Config::get('system', 'ostatus_debug')) {
2270 $item['body'] .= '🐟';
2273 $entry = self::entry($doc, $item, $owner, true);
2275 $doc->appendChild($entry);
2277 return trim($doc->saveXML());
2281 * Checks if the given contact url does support OStatus
2283 * @param string $url profile url
2284 * @param boolean $update Update the profile
2286 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2287 * @throws \ImagickException
2289 public static function isSupportedByContactUrl($url, $update = false)
2291 $probe = Probe::uri($url, Protocol::OSTATUS, 0, !$update);
2292 return $probe['network'] == Protocol::OSTATUS;