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;
12 use Friendica\Core\Config;
13 use Friendica\Core\L10n;
14 use Friendica\Core\Lock;
15 use Friendica\Core\Logger;
16 use Friendica\Core\PConfig;
17 use Friendica\Core\Protocol;
18 use Friendica\Core\System;
19 use Friendica\Database\DBA;
21 use Friendica\Model\APContact;
22 use Friendica\Model\Contact;
23 use Friendica\Model\Conversation;
24 use Friendica\Model\GContact;
25 use Friendica\Model\Item;
26 use Friendica\Model\User;
27 use Friendica\Network\Probe;
28 use Friendica\Object\Image;
29 use Friendica\Protocol\ActivityNamespace;
30 use Friendica\Util\DateTimeFormat;
31 use Friendica\Util\Images;
32 use Friendica\Util\Network;
33 use Friendica\Util\Proxy as ProxyUtils;
34 use Friendica\Util\Strings;
35 use Friendica\Util\XML;
37 require_once 'mod/share.php';
38 require_once 'include/api.php';
41 * @brief This class contain functions for the OStatus protocol
45 private static $itemlist;
46 private static $conv_list = [];
49 * @brief Fetches author data
51 * @param DOMXPath $xpath The xpath object
52 * @param object $context The xml context of the author details
53 * @param array $importer user record of the importing user
54 * @param array $contact Called by reference, will contain the fetched contact
55 * @param bool $onlyfetch Only fetch the header without updating the contact entries
57 * @return array Array of author related entries for the item
58 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
59 * @throws \ImagickException
61 private static function fetchAuthor(DOMXPath $xpath, $context, array $importer, array &$contact = null, $onlyfetch)
64 $author["author-link"] = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
65 $author["author-name"] = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $context);
66 $addr = XML::getFirstNodeValue($xpath, 'atom:author/atom:email/text()', $context);
68 $aliaslink = $author["author-link"];
70 $alternate_item = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0);
71 if (is_object($alternate_item)) {
72 foreach ($alternate_item->attributes as $attributes) {
73 if (($attributes->name == "href") && ($attributes->textContent != "")) {
74 $author["author-link"] = $attributes->textContent;
78 $author["author-id"] = Contact::getIdForURL($author["author-link"]);
80 $author['contact-id'] = ($contact['id'] ?? 0) ?: $author['author-id'];
85 This here would be better, but we would get problems with contacts from the statusnet addon
86 This is kept here as a reminder for the future
88 $cid = Contact::getIdForURL($author["author-link"], $importer["uid"]);
90 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
93 if ($aliaslink != '') {
94 $condition = ["`uid` = ? AND `alias` = ? AND `network` != ? AND `rel` IN (?, ?)",
95 $importer["uid"], $aliaslink, Protocol::STATUSNET,
96 Contact::SHARING, Contact::FRIEND];
97 $contact = DBA::selectFirst('contact', [], $condition);
100 if (!DBA::isResult($contact) && $author["author-link"] != '') {
101 if ($aliaslink == "") {
102 $aliaslink = $author["author-link"];
105 $condition = ["`uid` = ? AND `nurl` IN (?, ?) AND `network` != ? AND `rel` IN (?, ?)",
106 $importer["uid"], Strings::normaliseLink($author["author-link"]), Strings::normaliseLink($aliaslink),
107 Protocol::STATUSNET, Contact::SHARING, Contact::FRIEND];
108 $contact = DBA::selectFirst('contact', [], $condition);
111 if (!DBA::isResult($contact) && ($addr != '')) {
112 $condition = ["`uid` = ? AND `addr` = ? AND `network` != ? AND `rel` IN (?, ?)",
113 $importer["uid"], $addr, Protocol::STATUSNET,
114 Contact::SHARING, Contact::FRIEND];
115 $contact = DBA::selectFirst('contact', [], $condition);
118 if (DBA::isResult($contact)) {
119 if ($contact['blocked']) {
121 } elseif (!empty(APContact::getByURL($contact['url'], false))) {
122 ActivityPub\Receiver::switchContact($contact['id'], $importer['uid'], $contact['url']);
124 $author["contact-id"] = $contact["id"];
128 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
129 foreach ($avatars as $avatar) {
132 foreach ($avatar->attributes as $attributes) {
133 if ($attributes->name == "href") {
134 $href = $attributes->textContent;
136 if ($attributes->name == "width") {
137 $width = $attributes->textContent;
141 $avatarlist[$width] = $href;
144 if (count($avatarlist) > 0) {
146 $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
149 $displayname = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
150 if ($displayname != "") {
151 $author["author-name"] = $displayname;
154 $author["owner-id"] = $author["author-id"];
156 // Only update the contacts if it is an OStatus contact
157 if (DBA::isResult($contact) && ($contact['id'] > 0) && !$onlyfetch && ($contact["network"] == Protocol::OSTATUS)) {
159 // Update contact data
161 unset($current['name-date']);
163 // This query doesn't seem to work
164 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
166 // $contact["notify"] = $value;
168 // This query doesn't seem to work as well - I hate these queries
169 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
171 // $contact["poll"] = $value;
173 $contact['url'] = $author["author-link"];
174 $contact['nurl'] = Strings::normaliseLink($contact['url']);
176 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
178 $contact["alias"] = $value;
181 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
183 $contact["name"] = $value;
186 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()', $context);
188 $contact["nick"] = $value;
191 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()', $context);
193 $contact["about"] = HTML::toBBCode($value);
196 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()', $context);
198 $contact["location"] = $value;
201 $contact['name-date'] = DateTimeFormat::utcNow();
203 DBA::update('contact', $contact, ['id' => $contact["id"]], $current);
205 if (!empty($author["author-avatar"]) && ($author["author-avatar"] != $current['avatar'])) {
206 Logger::log("Update profile picture for contact ".$contact["id"], Logger::DEBUG);
207 Contact::updateAvatar($author["author-avatar"], $importer["uid"], $contact["id"]);
210 // Ensure that we are having this contact (with uid=0)
211 $cid = Contact::getIdForURL($aliaslink, 0, true);
214 $fields = ['url', 'nurl', 'name', 'nick', 'alias', 'about', 'location'];
215 $old_contact = DBA::selectFirst('contact', $fields, ['id' => $cid]);
217 // Update it with the current values
218 $fields = ['url' => $author["author-link"], 'name' => $contact["name"],
219 'nurl' => Strings::normaliseLink($author["author-link"]),
220 'nick' => $contact["nick"], 'alias' => $contact["alias"],
221 'about' => $contact["about"], 'location' => $contact["location"],
222 'success_update' => DateTimeFormat::utcNow(), 'last-update' => DateTimeFormat::utcNow()];
224 DBA::update('contact', $fields, ['id' => $cid], $old_contact);
227 if (!empty($author["author-avatar"])) {
228 Contact::updateAvatar($author["author-avatar"], 0, $cid);
232 $contact["generation"] = 2;
233 $contact["hide"] = false; // OStatus contacts are never hidden
234 if (!empty($author["author-avatar"])) {
235 $contact["photo"] = $author["author-avatar"];
237 $gcid = GContact::update($contact);
239 GContact::link($gcid, $contact["uid"], $contact["id"]);
240 } elseif ($contact["network"] != Protocol::DFRN) {
248 * @brief Fetches author data from a given XML string
250 * @param string $xml The XML
251 * @param array $importer user record of the importing user
253 * @return array Array of author related entries for the item
254 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
255 * @throws \ImagickException
257 public static function salmonAuthor($xml, array $importer)
263 $doc = new DOMDocument();
264 @$doc->loadXML($xml);
266 $xpath = new DOMXPath($doc);
267 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
268 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
269 $xpath->registerNamespace('georss', ActivityNamespace::GEORSS);
270 $xpath->registerNamespace('activity', ActivityNamespace::ACTIVITY);
271 $xpath->registerNamespace('media', ActivityNamespace::MEDIA);
272 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
273 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
274 $xpath->registerNamespace('statusnet', ActivityNamespace::STATUSNET);
276 $contact = ["id" => 0];
278 // Fetch the first author
279 $authordata = $xpath->query('//author')->item(0);
280 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, true);
285 * @brief Read attributes from element
287 * @param object $element Element object
289 * @return array attributes
291 private static function readAttributes($element)
295 foreach ($element->attributes as $attributes) {
296 $attribute[$attributes->name] = $attributes->textContent;
303 * @brief Imports an XML string containing OStatus elements
305 * @param string $xml The XML
306 * @param array $importer user record of the importing user
307 * @param array $contact contact
308 * @param string $hub Called by reference, returns the fetched hub data
310 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
311 * @throws \ImagickException
313 public static function import($xml, array $importer, array &$contact, &$hub)
315 self::process($xml, $importer, $contact, $hub);
319 * @brief Internal feed processing
321 * @param string $xml The XML
322 * @param array $importer user record of the importing user
323 * @param array $contact contact
324 * @param string $hub Called by reference, returns the fetched hub data
325 * @param boolean $stored Is the post fresh imported or from the database?
326 * @param boolean $initialize Is it the leading post so that data has to be initialized?
328 * @return boolean Could the XML be processed?
329 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
330 * @throws \ImagickException
332 private static function process($xml, array $importer, array &$contact = null, &$hub, $stored = false, $initialize = true)
335 self::$itemlist = [];
336 self::$conv_list = [];
339 Logger::log('Import OStatus message for user ' . $importer['uid'], Logger::DEBUG);
344 $doc = new DOMDocument();
345 @$doc->loadXML($xml);
347 $xpath = new DOMXPath($doc);
348 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
349 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
350 $xpath->registerNamespace('georss', ActivityNamespace::GEORSS);
351 $xpath->registerNamespace('activity', ActivityNamespace::ACTIVITY);
352 $xpath->registerNamespace('media', ActivityNamespace::MEDIA);
353 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
354 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
355 $xpath->registerNamespace('statusnet', ActivityNamespace::STATUSNET);
358 $hub_items = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0);
359 if (is_object($hub_items)) {
360 $hub_attributes = $hub_items->attributes;
361 if (is_object($hub_attributes)) {
362 foreach ($hub_attributes as $hub_attribute) {
363 if ($hub_attribute->name == "href") {
364 $hub = $hub_attribute->textContent;
365 Logger::log("Found hub ".$hub, Logger::DEBUG);
372 $header["uid"] = $importer["uid"];
373 $header["network"] = Protocol::OSTATUS;
375 $header["origin"] = 0;
376 $header["gravity"] = GRAVITY_COMMENT;
378 if (!is_object($doc->firstChild) || empty($doc->firstChild->tagName)) {
382 $first_child = $doc->firstChild->tagName;
384 if ($first_child == "feed") {
385 $entries = $xpath->query('/atom:feed/atom:entry');
387 $entries = $xpath->query('/atom:entry');
390 if ($entries->length == 1) {
391 // We reformat the XML to make it better readable
392 $doc2 = new DOMDocument();
393 $doc2->loadXML($xml);
394 $doc2->preserveWhiteSpace = false;
395 $doc2->formatOutput = true;
396 $xml2 = $doc2->saveXML();
398 $header["protocol"] = Conversation::PARCEL_SALMON;
399 $header["source"] = $xml2;
400 } elseif (!$initialize) {
404 // Fetch the first author
405 $authordata = $xpath->query('//author')->item(0);
406 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, $stored);
408 // Reverse the order of the entries
411 foreach ($entries as $entry) {
412 $entrylist[] = $entry;
415 foreach (array_reverse($entrylist) as $entry) {
417 $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
419 if ($authorelement->length == 0) {
420 $authorelement = $xpath->query('atom:author', $entry);
423 if ($authorelement->length > 0) {
424 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, $stored);
427 $item = array_merge($header, $author);
429 $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
431 $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $entry);
434 if (in_array($item["verb"], ['qvitter-delete-notice', Activity::DELETE, 'delete'])) {
435 self::deleteNotice($item);
439 if (in_array($item["verb"], [Activity::O_UNFAVOURITE, Activity::UNFAVORITE])) {
440 // Ignore "Unfavorite" message
441 Logger::log("Ignore unfavorite message ".print_r($item, true), Logger::DEBUG);
445 // Deletions come with the same uri, so we check for duplicates after processing deletions
446 if (Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]])) {
447 Logger::log('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', Logger::DEBUG);
450 Logger::log('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', Logger::DEBUG);
453 if ($item["verb"] == Activity::JOIN) {
454 // ignore "Join" messages
455 Logger::log("Ignore join message ".print_r($item, true), Logger::DEBUG);
459 if ($item["verb"] == "http://mastodon.social/schema/1.0/block") {
460 // ignore mastodon "block" messages
461 Logger::log("Ignore block message ".print_r($item, true), Logger::DEBUG);
465 if ($item["verb"] == Activity::FOLLOW) {
466 Contact::addRelationship($importer, $contact, $item);
470 if ($item["verb"] == Activity::O_UNFOLLOW) {
472 Contact::removeFollower($importer, $contact, $item, $dummy);
476 if ($item["verb"] == Activity::FAVORITE) {
477 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
478 Logger::log("Favorite ".$orig_uri." ".print_r($item, true));
480 $item["verb"] = Activity::LIKE;
481 $item["parent-uri"] = $orig_uri;
482 $item["gravity"] = GRAVITY_ACTIVITY;
483 $item["object-type"] = Activity\ObjectType::NOTE;
486 // http://activitystrea.ms/schema/1.0/rsvp-yes
487 if (!in_array($item["verb"], [Activity::POST, Activity::LIKE, Activity::SHARE])) {
488 Logger::log("Unhandled verb ".$item["verb"]." ".print_r($item, true), Logger::DEBUG);
491 self::processPost($xpath, $entry, $item, $importer);
493 if ($initialize && (count(self::$itemlist) > 0)) {
494 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['parent-uri']) {
495 // We will import it everytime, when it is started by our contacts
496 $valid = Contact::isSharingByURL(self::$itemlist[0]['author-link'], self::$itemlist[0]['uid']);
499 // If not, then it depends on this setting
500 $valid = ((self::$itemlist[0]['uid'] == 0) || !PConfig::get(self::$itemlist[0]['uid'], 'system', 'accept_only_sharer', false));
502 Logger::log("Item with uri ".self::$itemlist[0]['uri']." will be imported due to the system settings.", Logger::DEBUG);
505 Logger::log("Item with uri ".self::$itemlist[0]['uri']." belongs to a contact (".self::$itemlist[0]['contact-id']."). It will be imported.", Logger::DEBUG);
508 // Never post a thread when the only interaction by our contact was a like
510 $verbs = [Activity::POST, Activity::SHARE];
511 foreach (self::$itemlist as $item) {
512 if (in_array($item['verb'], $verbs) && Contact::isSharingByURL($item['author-link'], $item['uid'])) {
517 Logger::log("Item with uri ".self::$itemlist[0]['uri']." will be imported since the thread contains posts or shares.", Logger::DEBUG);
521 // But we will only import complete threads
522 $valid = Item::exists(['uid' => $importer["uid"], 'uri' => self::$itemlist[0]['parent-uri']]);
524 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);
529 $default_contact = 0;
530 for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
531 if (empty(self::$itemlist[$key]['contact-id'])) {
532 self::$itemlist[$key]['contact-id'] = $default_contact;
534 $default_contact = $item['contact-id'];
537 foreach (self::$itemlist as $item) {
538 $found = Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]]);
540 Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", Logger::DEBUG);
541 } elseif ($item['contact-id'] < 0) {
542 Logger::log("Item with uri ".$item["uri"]." is from a blocked contact.", Logger::DEBUG);
544 // We are having duplicated entries. Hopefully this solves it.
545 if (Lock::acquire('ostatus_process_item_insert')) {
546 $ret = Item::insert($item);
547 Lock::release('ostatus_process_item_insert');
548 Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret);
550 $ret = Item::insert($item);
551 Logger::log("We couldn't lock - but tried to store the item anyway. Return value is ".$ret);
556 self::$itemlist = [];
558 Logger::log('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.', Logger::DEBUG);
564 * Removes notice item from database
566 * @param array $item item
570 private static function deleteNotice(array $item)
572 $condition = ['uid' => $item['uid'], 'author-id' => $item['author-id'], 'uri' => $item['uri']];
573 if (!Item::exists($condition)) {
574 Logger::log('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it.");
578 Item::delete($condition);
580 Logger::log('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
584 * @brief Processes the XML for a post
586 * @param DOMXPath $xpath The xpath object
587 * @param object $entry The xml entry that is processed
588 * @param array $item The item array
589 * @param array $importer user record of the importing user
591 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
592 * @throws \ImagickException
594 private static function processPost(DOMXPath $xpath, $entry, array &$item, array $importer)
596 $item["body"] = HTML::toBBCode(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
597 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $entry);
598 if (($item["object-type"] == Activity\ObjectType::BOOKMARK) || ($item["object-type"] == Activity\ObjectType::EVENT)) {
599 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
600 $item["body"] = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
601 } elseif ($item["object-type"] == Activity\ObjectType::QUESTION) {
602 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
605 $item["created"] = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
606 $item["edited"] = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
607 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
609 $conv = $xpath->query('ostatus:conversation', $entry);
610 if (is_object($conv->item(0))) {
611 foreach ($conv->item(0)->attributes as $attributes) {
612 if ($attributes->name == "ref") {
613 $item['conversation-uri'] = $attributes->textContent;
615 if ($attributes->name == "href") {
616 $item['conversation-href'] = $attributes->textContent;
623 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
624 if (is_object($inreplyto->item(0))) {
625 foreach ($inreplyto->item(0)->attributes as $attributes) {
626 if ($attributes->name == "ref") {
627 $item["parent-uri"] = $attributes->textContent;
629 if ($attributes->name == "href") {
630 $related = $attributes->textContent;
635 $georsspoint = $xpath->query('georss:point', $entry);
636 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
637 $item["coord"] = $georsspoint->item(0)->nodeValue;
640 $categories = $xpath->query('atom:category', $entry);
642 foreach ($categories as $category) {
643 foreach ($category->attributes as $attributes) {
644 if ($attributes->name == 'term') {
645 $term = $attributes->textContent;
646 if (!empty($item['tag'])) {
652 $item['tag'] .= '#[url=' . System::baseUrl() . '/search?tag=' . $term . ']' . $term . '[/url]';
661 $links = $xpath->query('atom:link', $entry);
663 $link_data = self::processLinks($links, $item);
664 $self = $link_data['self'];
665 $add_body = $link_data['add_body'];
670 $notice_info = $xpath->query('statusnet:notice_info', $entry);
671 if ($notice_info && ($notice_info->length > 0)) {
672 foreach ($notice_info->item(0)->attributes as $attributes) {
673 if ($attributes->name == "source") {
674 $item["app"] = strip_tags($attributes->textContent);
676 if ($attributes->name == "repeat_of") {
677 $repeat_of = $attributes->textContent;
681 // Is it a repeated post?
682 if (($repeat_of != "") || ($item["verb"] == Activity::SHARE)) {
683 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
684 if (!empty($link_data['add_body'])) {
685 $add_body .= $link_data['add_body'];
689 $item["body"] .= $add_body;
691 // Only add additional data when there is no picture in the post
692 if (!strstr($item["body"], '[/img]')) {
693 $item["body"] = add_page_info_to_body($item["body"]);
696 // Mastodon Content Warning
697 if (($item["verb"] == Activity::POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
698 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
699 if (!empty($clear_text)) {
700 $item['content-warning'] = HTML::toBBCode($clear_text);
704 if (($self != '') && empty($item['protocol'])) {
705 self::fetchSelf($self, $item);
708 if (!empty($item["conversation-href"])) {
709 self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
712 if (isset($item["parent-uri"])) {
713 if (!Item::exists(['uid' => $importer["uid"], 'uri' => $item['parent-uri']])) {
714 if ($related != '') {
715 self::fetchRelated($related, $item["parent-uri"], $importer);
718 Logger::log('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', Logger::DEBUG);
721 $item["parent-uri"] = $item["uri"];
722 $item["gravity"] = GRAVITY_PARENT;
725 if (($item['author-link'] != '') && !empty($item['protocol'])) {
726 $item = Conversation::insert($item);
729 self::$itemlist[] = $item;
733 * @brief Fetch the conversation for posts
735 * @param string $conversation The link to the conversation
736 * @param string $conversation_uri The conversation in "uri" format
738 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
740 private static function fetchConversation($conversation, $conversation_uri)
742 // Ensure that we only store a conversation once in a process
743 if (isset(self::$conv_list[$conversation])) {
747 self::$conv_list[$conversation] = true;
749 $curlResult = Network::curl($conversation, false, ['accept_content' => 'application/atom+xml, text/html']);
751 if (!$curlResult->isSuccess()) {
757 if (stristr($curlResult->getHeader(), 'Content-Type: application/atom+xml')) {
758 $xml = $curlResult->getBody();
762 $doc = new DOMDocument();
763 if (!@$doc->loadHTML($curlResult->getBody())) {
766 $xpath = new DOMXPath($doc);
768 $links = $xpath->query('//link');
771 foreach ($links as $link) {
772 $attribute = self::readAttributes($link);
773 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
774 $file = $attribute['href'];
778 $conversation_atom = Network::curl($attribute['href']);
780 if ($conversation_atom->isSuccess()) {
781 $xml = $conversation_atom->getBody();
791 self::storeConversation($xml, $conversation, $conversation_uri);
795 * @brief Store a feed in several conversation entries
797 * @param string $xml The feed
798 * @param string $conversation conversation
799 * @param string $conversation_uri conversation uri
803 private static function storeConversation($xml, $conversation = '', $conversation_uri = '')
805 $doc = new DOMDocument();
806 @$doc->loadXML($xml);
808 $xpath = new DOMXPath($doc);
809 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
810 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
811 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
813 $entries = $xpath->query('/atom:feed/atom:entry');
815 // Now store the entries
816 foreach ($entries as $entry) {
817 $doc2 = new DOMDocument();
818 $doc2->preserveWhiteSpace = false;
819 $doc2->formatOutput = true;
823 $conv_data['protocol'] = Conversation::PARCEL_SPLIT_CONVERSATION;
824 $conv_data['network'] = Protocol::OSTATUS;
825 $conv_data['uri'] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
827 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
828 if (is_object($inreplyto->item(0))) {
829 foreach ($inreplyto->item(0)->attributes as $attributes) {
830 if ($attributes->name == "ref") {
831 $conv_data['reply-to-uri'] = $attributes->textContent;
836 $conv_data['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
838 $conv = $xpath->query('ostatus:conversation', $entry);
839 if (is_object($conv->item(0))) {
840 foreach ($conv->item(0)->attributes as $attributes) {
841 if ($attributes->name == "ref") {
842 $conv_data['conversation-uri'] = $attributes->textContent;
844 if ($attributes->name == "href") {
845 $conv_data['conversation-href'] = $attributes->textContent;
850 if ($conversation != '') {
851 $conv_data['conversation-uri'] = $conversation;
854 if ($conversation_uri != '') {
855 $conv_data['conversation-uri'] = $conversation_uri;
858 $entry = $doc2->importNode($entry, true);
860 $doc2->appendChild($entry);
862 $conv_data['source'] = $doc2->saveXML();
864 $condition = ['item-uri' => $conv_data['uri'],'protocol' => Conversation::PARCEL_FEED];
865 if (DBA::exists('conversation', $condition)) {
866 Logger::log('Delete deprecated entry for URI '.$conv_data['uri'], Logger::DEBUG);
867 DBA::delete('conversation', ['item-uri' => $conv_data['uri']]);
870 Logger::log('Store conversation data for uri '.$conv_data['uri'], Logger::DEBUG);
871 Conversation::insert($conv_data);
876 * @brief Fetch the own post so that it can be stored later
878 * We want to store the original data for later processing.
879 * This function is meant for cases where we process a feed with multiple entries.
880 * In that case we need to fetch the single posts here.
882 * @param string $self The link to the self item
883 * @param array $item The item array
885 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
887 private static function fetchSelf($self, array &$item)
889 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $self, Conversation::PARCEL_DFRN, Conversation::PARCEL_SALMON];
890 if (DBA::exists('conversation', $condition)) {
891 Logger::log('Conversation '.$item['uri'].' is already stored.', Logger::DEBUG);
895 $curlResult = Network::curl($self);
897 if (!$curlResult->isSuccess()) {
901 // We reformat the XML to make it better readable
902 $doc = new DOMDocument();
903 $doc->loadXML($curlResult->getBody());
904 $doc->preserveWhiteSpace = false;
905 $doc->formatOutput = true;
906 $xml = $doc->saveXML();
908 $item["protocol"] = Conversation::PARCEL_SALMON;
909 $item["source"] = $xml;
911 Logger::log('Conversation '.$item['uri'].' is now fetched.', Logger::DEBUG);
915 * @brief Fetch related posts and processes them
917 * @param string $related The link to the related item
918 * @param string $related_uri The related item in "uri" format
919 * @param array $importer user record of the importing user
921 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
922 * @throws \ImagickException
924 private static function fetchRelated($related, $related_uri, $importer)
926 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, Conversation::PARCEL_DFRN, Conversation::PARCEL_SALMON];
927 $conversation = DBA::selectFirst('conversation', ['source', 'protocol'], $condition);
928 if (DBA::isResult($conversation)) {
930 $xml = $conversation['source'];
931 if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
932 Logger::log('Got valid cached XML for URI '.$related_uri, Logger::DEBUG);
935 if ($conversation['protocol'] == Conversation::PARCEL_SALMON) {
936 Logger::log('Delete invalid cached XML for URI '.$related_uri, Logger::DEBUG);
937 DBA::delete('conversation', ['item-uri' => $related_uri]);
942 $curlResult = Network::curl($related, false, ['accept_content' => 'application/atom+xml, text/html']);
944 if (!$curlResult->isSuccess()) {
950 if (stristr($curlResult->getHeader(), 'Content-Type: application/atom+xml')) {
951 Logger::log('Directly fetched XML for URI ' . $related_uri, Logger::DEBUG);
952 $xml = $curlResult->getBody();
956 $doc = new DOMDocument();
957 if (!@$doc->loadHTML($curlResult->getBody())) {
960 $xpath = new DOMXPath($doc);
964 $links = $xpath->query('//link');
966 foreach ($links as $link) {
967 $attribute = self::readAttributes($link);
968 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
969 $atom_file = $attribute['href'];
972 if ($atom_file != '') {
973 $curlResult = Network::curl($atom_file);
975 if ($curlResult->isSuccess()) {
976 Logger::log('Fetched XML for URI ' . $related_uri, Logger::DEBUG);
977 $xml = $curlResult->getBody();
983 // Workaround for older GNU Social servers
984 if (($xml == '') && strstr($related, '/notice/')) {
985 $curlResult = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related).'.atom');
987 if ($curlResult->isSuccess()) {
988 Logger::log('GNU Social workaround to fetch XML for URI ' . $related_uri, Logger::DEBUG);
989 $xml = $curlResult->getBody();
993 // Even more worse workaround for GNU Social ;-)
995 $related_guess = OStatus::convertHref($related_uri);
996 $curlResult = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related_guess).'.atom');
998 if ($curlResult->isSuccess()) {
999 Logger::log('GNU Social workaround 2 to fetch XML for URI ' . $related_uri, Logger::DEBUG);
1000 $xml = $curlResult->getBody();
1004 // Finally we take the data that we fetched from "ostatus:conversation"
1006 $condition = ['item-uri' => $related_uri, 'protocol' => Conversation::PARCEL_SPLIT_CONVERSATION];
1007 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1008 if (DBA::isResult($conversation)) {
1010 Logger::log('Got cached XML from conversation for URI '.$related_uri, Logger::DEBUG);
1011 $xml = $conversation['source'];
1016 self::process($xml, $importer, $contact, $hub, $stored, false);
1018 Logger::log("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, Logger::DEBUG);
1024 * @brief Processes the XML for a repeated post
1026 * @param DOMXPath $xpath The xpath object
1027 * @param object $entry The xml entry that is processed
1028 * @param array $item The item array
1029 * @param array $importer user record of the importing user
1031 * @return array with data from links
1032 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1033 * @throws \ImagickException
1035 private static function processRepeatedItem(DOMXPath $xpath, $entry, array &$item, array $importer)
1037 $activityobject = $xpath->query('activity:object', $entry)->item(0);
1039 if (!is_object($activityobject)) {
1045 $orig_uri = XML::getFirstNodeValue($xpath, 'atom:id/text()', $activityobject);
1047 $links = $xpath->query("atom:link", $activityobject);
1049 $link_data = self::processLinks($links, $item);
1052 $orig_body = XML::getFirstNodeValue($xpath, 'atom:content/text()', $activityobject);
1053 $orig_created = XML::getFirstNodeValue($xpath, 'atom:published/text()', $activityobject);
1054 $orig_edited = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $activityobject);
1056 $orig_author = self::fetchAuthor($xpath, $activityobject, $importer, $dummy, false);
1058 $item["author-name"] = $orig_author["author-name"];
1059 $item["author-link"] = $orig_author["author-link"];
1060 $item["author-id"] = $orig_author["author-id"];
1062 $item["body"] = HTML::toBBCode($orig_body);
1063 $item["created"] = $orig_created;
1064 $item["edited"] = $orig_edited;
1066 $item["uri"] = $orig_uri;
1068 $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $activityobject);
1070 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $activityobject);
1072 // Mastodon Content Warning
1073 if (($item["verb"] == Activity::POST) && $xpath->evaluate('boolean(atom:summary)', $activityobject)) {
1074 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $activityobject);
1075 if (!empty($clear_text)) {
1076 $item['content-warning'] = HTML::toBBCode($clear_text);
1080 $inreplyto = $xpath->query('thr:in-reply-to', $activityobject);
1081 if (is_object($inreplyto->item(0))) {
1082 foreach ($inreplyto->item(0)->attributes as $attributes) {
1083 if ($attributes->name == "ref") {
1084 $item["parent-uri"] = $attributes->textContent;
1093 * @brief Processes links in the XML
1095 * @param object $links The xml data that contain links
1096 * @param array $item The item array
1098 * @return array with data from the links
1100 private static function processLinks($links, array &$item)
1102 $link_data = ['add_body' => '', 'self' => ''];
1104 foreach ($links as $link) {
1105 $attribute = self::readAttributes($link);
1107 if (!empty($attribute['rel']) && !empty($attribute['href'])) {
1108 switch ($attribute['rel']) {
1110 $item["plink"] = $attribute['href'];
1111 if (($item["object-type"] == Activity\ObjectType::QUESTION)
1112 || ($item["object-type"] == Activity\ObjectType::EVENT)
1114 $item["body"] .= add_page_info($attribute['href']);
1117 case "ostatus:conversation":
1118 $link_data['conversation'] = $attribute['href'];
1119 $item['conversation-href'] = $link_data['conversation'];
1120 if (!isset($item['conversation-uri'])) {
1121 $item['conversation-uri'] = $item['conversation-href'];
1125 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
1126 if ($filetype == 'image') {
1127 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1129 if (!empty($item["attach"])) {
1130 $item["attach"] .= ',';
1132 $item["attach"] = '';
1134 if (!isset($attribute['length'])) {
1135 $attribute['length'] = "0";
1137 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.($attribute['title'] ?? '') .'"[/attach]';
1141 if ($item["object-type"] != Activity\ObjectType::BOOKMARK) {
1142 if (!isset($item["parent-uri"])) {
1143 $item["parent-uri"] = $attribute['href'];
1145 $link_data['related'] = $attribute['href'];
1147 $item["body"] .= add_page_info($attribute['href']);
1151 if (empty($item["plink"])) {
1152 $item["plink"] = $attribute['href'];
1154 $link_data['self'] = $attribute['href'];
1163 * @brief Create an url out of an uri
1165 * @param string $href URI in the format "parameter1:parameter1:..."
1167 * @return string URL in the format http(s)://....
1169 public static function convertHref($href)
1171 $elements = explode(":", $href);
1173 if ((count($elements) <= 2) || ($elements[0] != "tag")) {
1177 $server = explode(",", $elements[1]);
1178 $conversation = explode("=", $elements[2]);
1180 if ((count($elements) == 4) && ($elements[2] == "post")) {
1181 return "http://".$server[0]."/notice/".$elements[3];
1184 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1187 if ($elements[3] == "objectType=thread") {
1188 return "http://".$server[0]."/conversation/".$conversation[1];
1190 return "http://".$server[0]."/notice/".$conversation[1];
1195 * @brief Checks if the current post is a reshare
1197 * @param array $item The item array of thw post
1199 * @return string The guid if the post is a reshare
1201 private static function getResharedGuid(array $item)
1203 $reshared = Item::getShareArray($item);
1204 if (empty($reshared['guid']) || !empty($reshared['comment'])) {
1208 return $reshared['guid'];
1212 * @brief Cleans the body of a post if it contains picture links
1214 * @param string $body The body
1216 * @return string The cleaned body
1217 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1219 private static function formatPicturePost($body)
1221 $siteinfo = BBCode::getAttachedData($body);
1223 if (($siteinfo["type"] == "photo") && (!empty($siteinfo["preview"]) || !empty($siteinfo["image"]))) {
1224 if (isset($siteinfo["preview"])) {
1225 $preview = $siteinfo["preview"];
1227 $preview = $siteinfo["image"];
1230 // Is it a remote picture? Then make a smaller preview here
1231 $preview = ProxyUtils::proxifyUrl($preview, false, ProxyUtils::SIZE_SMALL);
1233 // Is it a local picture? Then make it smaller here
1234 $preview = str_replace(["-0.jpg", "-0.png"], ["-2.jpg", "-2.png"], $preview);
1235 $preview = str_replace(["-1.jpg", "-1.png"], ["-2.jpg", "-2.png"], $preview);
1237 if (isset($siteinfo["url"])) {
1238 $url = $siteinfo["url"];
1240 $url = $siteinfo["image"];
1243 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1250 * @brief Adds the header elements to the XML document
1252 * @param DOMDocument $doc XML document
1253 * @param array $owner Contact data of the poster
1254 * @param string $filter The related feed filter (activity, posts or comments)
1255 * @param bool $feed_mode Behave like a regular feed for users if true
1257 * @return object header root element
1258 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1260 private static function addHeader(DOMDocument $doc, array $owner, $filter, $feed_mode = false)
1262 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
1263 $doc->appendChild($root);
1265 $root->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
1266 $root->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
1267 $root->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
1268 $root->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
1269 $root->setAttribute("xmlns:poco", ActivityNamespace::POCO);
1270 $root->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
1271 $root->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
1272 $root->setAttribute("xmlns:mastodon", ActivityNamespace::MASTODON);
1275 $selfUri = '/feed/' . $owner["nick"] . '/';
1278 $title = L10n::t('%s\'s timeline', $owner['name']);
1279 $selfUri .= $filter;
1282 $title = L10n::t('%s\'s posts', $owner['name']);
1285 $title = L10n::t('%s\'s comments', $owner['name']);
1286 $selfUri .= $filter;
1291 $selfUri = "/dfrn_poll/" . $owner["nick"];
1294 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
1295 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1296 XML::addElement($doc, $root, "id", System::baseUrl() . "/profile/" . $owner["nick"]);
1297 XML::addElement($doc, $root, "title", $title);
1298 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], Config::get('config', 'sitename')));
1299 XML::addElement($doc, $root, "logo", $owner["photo"]);
1300 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1302 $author = self::addAuthor($doc, $owner);
1303 $root->appendChild($author);
1305 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1306 XML::addElement($doc, $root, "link", "", $attributes);
1308 /// @TODO We have to find out what this is
1309 /// $attributes = array("href" => System::baseUrl()."/sup",
1310 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1311 /// "type" => "application/json");
1312 /// XML::addElement($doc, $root, "link", "", $attributes);
1314 self::hublinks($doc, $root, $owner["nick"]);
1316 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "salmon"];
1317 XML::addElement($doc, $root, "link", "", $attributes);
1319 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies"];
1320 XML::addElement($doc, $root, "link", "", $attributes);
1322 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention"];
1323 XML::addElement($doc, $root, "link", "", $attributes);
1325 $attributes = ["href" => System::baseUrl() . $selfUri, "rel" => "self", "type" => "application/atom+xml"];
1326 XML::addElement($doc, $root, "link", "", $attributes);
1328 if ($owner['account-type'] == Contact::TYPE_COMMUNITY) {
1329 $condition = ['uid' => $owner['uid'], 'self' => false, 'pending' => false,
1330 'archive' => false, 'hidden' => false, 'blocked' => false];
1331 $members = DBA::count('contact', $condition);
1332 XML::addElement($doc, $root, "statusnet:group_info", "", ["member_count" => $members]);
1339 * @brief Add the link to the push hubs to the XML document
1341 * @param DOMDocument $doc XML document
1342 * @param object $root XML root element where the hub links are added
1343 * @param object $nick nick
1345 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1347 public static function hublinks(DOMDocument $doc, $root, $nick)
1349 $h = System::baseUrl() . '/pubsubhubbub/'.$nick;
1350 XML::addElement($doc, $root, "link", "", ["href" => $h, "rel" => "hub"]);
1354 * @brief Adds attachment data to the XML document
1356 * @param DOMDocument $doc XML document
1357 * @param object $root XML root element where the hub links are added
1358 * @param array $item Data of the item that is to be posted
1360 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1362 private static function getAttachment(DOMDocument $doc, $root, $item)
1364 $siteinfo = BBCode::getAttachedData($item["body"]);
1366 switch ($siteinfo["type"]) {
1368 if (!empty($siteinfo["image"])) {
1369 $imgdata = Images::getInfoFromURLCached($siteinfo["image"]);
1371 $attributes = ["rel" => "enclosure",
1372 "href" => $siteinfo["image"],
1373 "type" => $imgdata["mime"],
1374 "length" => intval($imgdata["size"])];
1375 XML::addElement($doc, $root, "link", "", $attributes);
1380 $attributes = ["rel" => "enclosure",
1381 "href" => $siteinfo["url"],
1382 "type" => "text/html; charset=UTF-8",
1384 "title" => ($siteinfo["title"] ?? '') ?: $siteinfo["url"],
1386 XML::addElement($doc, $root, "link", "", $attributes);
1392 if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1393 $imgdata = Images::getInfoFromURLCached($siteinfo["image"]);
1395 $attributes = ["rel" => "enclosure",
1396 "href" => $siteinfo["image"],
1397 "type" => $imgdata["mime"],
1398 "length" => intval($imgdata["size"])];
1400 XML::addElement($doc, $root, "link", "", $attributes);
1404 $arr = explode('[/attach],', $item['attach']);
1406 foreach ($arr as $r) {
1408 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1410 $attributes = ["rel" => "enclosure",
1411 "href" => $matches[1],
1412 "type" => $matches[3]];
1414 if (intval($matches[2])) {
1415 $attributes["length"] = intval($matches[2]);
1417 if (trim($matches[4]) != "") {
1418 $attributes["title"] = trim($matches[4]);
1420 XML::addElement($doc, $root, "link", "", $attributes);
1427 * @brief Adds the author element to the XML document
1429 * @param DOMDocument $doc XML document
1430 * @param array $owner Contact data of the poster
1431 * @param bool $show_profile Whether to show profile
1433 * @return \DOMElement author element
1434 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1436 private static function addAuthor(DOMDocument $doc, array $owner, $show_profile = true)
1438 $profile = DBA::selectFirst('profile', ['homepage', 'publish'], ['uid' => $owner['uid'], 'is-default' => true]);
1439 $author = $doc->createElement("author");
1440 XML::addElement($doc, $author, "id", $owner["url"]);
1441 if ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
1442 XML::addElement($doc, $author, "activity:object-type", Activity\ObjectType::GROUP);
1444 XML::addElement($doc, $author, "activity:object-type", Activity\ObjectType::PERSON);
1446 XML::addElement($doc, $author, "uri", $owner["url"]);
1447 XML::addElement($doc, $author, "name", $owner["nick"]);
1448 XML::addElement($doc, $author, "email", $owner["addr"]);
1449 if ($show_profile) {
1450 XML::addElement($doc, $author, "summary", BBCode::convert($owner["about"], false, 7));
1453 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $owner["url"]];
1454 XML::addElement($doc, $author, "link", "", $attributes);
1458 "type" => "image/jpeg", // To-Do?
1459 "media:width" => 300,
1460 "media:height" => 300,
1461 "href" => $owner["photo"]];
1462 XML::addElement($doc, $author, "link", "", $attributes);
1464 if (isset($owner["thumb"])) {
1467 "type" => "image/jpeg", // To-Do?
1468 "media:width" => 80,
1469 "media:height" => 80,
1470 "href" => $owner["thumb"]];
1471 XML::addElement($doc, $author, "link", "", $attributes);
1474 XML::addElement($doc, $author, "poco:preferredUsername", $owner["nick"]);
1475 XML::addElement($doc, $author, "poco:displayName", $owner["name"]);
1476 if ($show_profile) {
1477 XML::addElement($doc, $author, "poco:note", BBCode::convert($owner["about"], false, 7));
1479 if (trim($owner["location"]) != "") {
1480 $element = $doc->createElement("poco:address");
1481 XML::addElement($doc, $element, "poco:formatted", $owner["location"]);
1482 $author->appendChild($element);
1486 if (DBA::isResult($profile) && !$show_profile) {
1487 if (trim($profile["homepage"]) != "") {
1488 $urls = $doc->createElement("poco:urls");
1489 XML::addElement($doc, $urls, "poco:type", "homepage");
1490 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
1491 XML::addElement($doc, $urls, "poco:primary", "true");
1492 $author->appendChild($urls);
1495 XML::addElement($doc, $author, "followers", "", ["url" => System::baseUrl() . "/profile/" . $owner["nick"] . "/contacts/followers"]);
1496 XML::addElement($doc, $author, "statusnet:profile_info", "", ["local_id" => $owner["uid"]]);
1498 if ($profile["publish"]) {
1499 XML::addElement($doc, $author, "mastodon:scope", "public");
1507 * @TODO Picture attachments should look like this:
1508 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1509 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1513 * @brief Returns the given activity if present - otherwise returns the "post" activity
1515 * @param array $item Data of the item that is to be posted
1517 * @return string activity
1519 private static function constructVerb(array $item)
1521 if (!empty($item['verb'])) {
1522 return $item['verb'];
1525 return Activity::POST;
1529 * @brief Returns the given object type if present - otherwise returns the "note" object type
1531 * @param array $item Data of the item that is to be posted
1533 * @return string Object type
1535 private static function constructObjecttype(array $item)
1537 if (!empty($item['object-type']) && in_array($item['object-type'], [Activity\ObjectType::NOTE, Activity\ObjectType::COMMENT])) {
1538 return $item['object-type'];
1541 return Activity\ObjectType::NOTE;
1545 * @brief Adds an entry element to the XML document
1547 * @param DOMDocument $doc XML document
1548 * @param array $item Data of the item that is to be posted
1549 * @param array $owner Contact data of the poster
1550 * @param bool $toplevel optional default false
1551 * @param bool $feed_mode Behave like a regular feed for users if true
1553 * @return \DOMElement Entry element
1554 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1555 * @throws \ImagickException
1557 private static function entry(DOMDocument $doc, array $item, array $owner, $toplevel = false, $feed_mode = false)
1561 $repeated_guid = self::getResharedGuid($item);
1562 if ($repeated_guid != "") {
1563 $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel);
1570 if ($item["verb"] == Activity::LIKE) {
1571 return self::likeEntry($doc, $item, $owner, $toplevel);
1572 } elseif (in_array($item["verb"], [Activity::FOLLOW, Activity::O_UNFOLLOW])) {
1573 return self::followEntry($doc, $item, $owner, $toplevel);
1575 return self::noteEntry($doc, $item, $owner, $toplevel, $feed_mode);
1580 * @brief Adds a source entry to the XML document
1582 * @param DOMDocument $doc XML document
1583 * @param array $contact Array of the contact that is added
1585 * @return \DOMElement Source element
1586 * @throws \Exception
1588 private static function sourceEntry(DOMDocument $doc, array $contact)
1590 $source = $doc->createElement("source");
1591 XML::addElement($doc, $source, "id", $contact["poll"]);
1592 XML::addElement($doc, $source, "title", $contact["name"]);
1593 XML::addElement($doc, $source, "link", "", ["rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]]);
1594 XML::addElement($doc, $source, "link", "", ["rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]]);
1595 XML::addElement($doc, $source, "icon", $contact["photo"]);
1596 XML::addElement($doc, $source, "updated", DateTimeFormat::utc($contact["success_update"]."+00:00", DateTimeFormat::ATOM));
1602 * @brief Fetches contact data from the contact or the gcontact table
1604 * @param string $url URL of the contact
1605 * @param array $owner Contact data of the poster
1607 * @return array Contact array
1608 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1609 * @throws \ImagickException
1611 private static function contactEntry($url, array $owner)
1614 "SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1615 DBA::escape(Strings::normaliseLink($url)),
1616 intval($owner["uid"])
1618 if (DBA::isResult($r)) {
1620 $contact["uid"] = -1;
1623 if (!DBA::isResult($r)) {
1624 $gcontact = DBA::selectFirst('gcontact', [], ['nurl' => Strings::normaliseLink($url)]);
1625 if (DBA::isResult($r)) {
1626 $contact = $gcontact;
1627 $contact["uid"] = -1;
1628 $contact["success_update"] = $contact["updated"];
1632 if (!DBA::isResult($r)) {
1636 if (!isset($contact["poll"])) {
1637 $data = Probe::uri($url);
1638 $contact["poll"] = $data["poll"];
1640 if (!$contact["alias"]) {
1641 $contact["alias"] = $data["alias"];
1645 if (!isset($contact["alias"])) {
1646 $contact["alias"] = $contact["url"];
1649 $contact['account-type'] = $owner['account-type'];
1655 * @brief Adds an entry element with reshared content
1657 * @param DOMDocument $doc XML document
1658 * @param array $item Data of the item that is to be posted
1659 * @param array $owner Contact data of the poster
1660 * @param string $repeated_guid guid
1661 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1663 * @return bool Entry element
1664 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1665 * @throws \ImagickException
1667 private static function reshareEntry(DOMDocument $doc, array $item, array $owner, $repeated_guid, $toplevel)
1669 if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1670 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1673 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1675 $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => false,
1676 'network' => [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS]];
1677 $repeated_item = Item::selectFirst([], $condition);
1678 if (!DBA::isResult($repeated_item)) {
1682 $contact = self::contactEntry($repeated_item['author-link'], $owner);
1684 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1686 self::entryContent($doc, $entry, $item, $owner, $title, Activity::SHARE, false);
1688 $as_object = $doc->createElement("activity:object");
1690 XML::addElement($doc, $as_object, "activity:object-type", ActivityNamespace::ACTIVITY_SCHEMA . "activity");
1692 self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false);
1694 $author = self::addAuthor($doc, $contact, false);
1695 $as_object->appendChild($author);
1697 $as_object2 = $doc->createElement("activity:object");
1699 XML::addElement($doc, $as_object2, "activity:object-type", self::constructObjecttype($repeated_item));
1701 $title = sprintf("New comment by %s", $contact["nick"]);
1703 self::entryContent($doc, $as_object2, $repeated_item, $owner, $title);
1705 $as_object->appendChild($as_object2);
1707 self::entryFooter($doc, $as_object, $item, $owner, false);
1709 $source = self::sourceEntry($doc, $contact);
1711 $as_object->appendChild($source);
1713 $entry->appendChild($as_object);
1715 self::entryFooter($doc, $entry, $item, $owner);
1721 * @brief Adds an entry element with a "like"
1723 * @param DOMDocument $doc XML document
1724 * @param array $item Data of the item that is to be posted
1725 * @param array $owner Contact data of the poster
1726 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1728 * @return \DOMElement Entry element with "like"
1729 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1730 * @throws \ImagickException
1732 private static function likeEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1734 if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1735 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1738 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1740 $verb = ActivityNamespace::ACTIVITY_SCHEMA . "favorite";
1741 self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false);
1743 $parent = Item::selectFirst([], ['uri' => $item["thr-parent"], 'uid' => $item["uid"]]);
1744 if (DBA::isResult($parent)) {
1745 $as_object = $doc->createElement("activity:object");
1747 XML::addElement($doc, $as_object, "activity:object-type", self::constructObjecttype($parent));
1749 self::entryContent($doc, $as_object, $parent, $owner, "New entry");
1751 $entry->appendChild($as_object);
1754 self::entryFooter($doc, $entry, $item, $owner);
1760 * @brief Adds the person object element to the XML document
1762 * @param DOMDocument $doc XML document
1763 * @param array $owner Contact data of the poster
1764 * @param array $contact Contact data of the target
1766 * @return object author element
1768 private static function addPersonObject(DOMDocument $doc, array $owner, array $contact)
1770 $object = $doc->createElement("activity:object");
1771 XML::addElement($doc, $object, "activity:object-type", Activity\ObjectType::PERSON);
1773 if ($contact['network'] == Protocol::PHANTOM) {
1774 XML::addElement($doc, $object, "id", $contact['url']);
1778 XML::addElement($doc, $object, "id", $contact["alias"]);
1779 XML::addElement($doc, $object, "title", $contact["nick"]);
1781 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $contact["url"]];
1782 XML::addElement($doc, $object, "link", "", $attributes);
1786 "type" => "image/jpeg", // To-Do?
1787 "media:width" => 300,
1788 "media:height" => 300,
1789 "href" => $contact["photo"]];
1790 XML::addElement($doc, $object, "link", "", $attributes);
1792 XML::addElement($doc, $object, "poco:preferredUsername", $contact["nick"]);
1793 XML::addElement($doc, $object, "poco:displayName", $contact["name"]);
1795 if (trim($contact["location"]) != "") {
1796 $element = $doc->createElement("poco:address");
1797 XML::addElement($doc, $element, "poco:formatted", $contact["location"]);
1798 $object->appendChild($element);
1805 * @brief Adds a follow/unfollow entry element
1807 * @param DOMDocument $doc XML document
1808 * @param array $item Data of the follow/unfollow message
1809 * @param array $owner Contact data of the poster
1810 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1812 * @return \DOMElement Entry element
1813 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1814 * @throws \ImagickException
1816 private static function followEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1818 $item["id"] = $item["parent"] = 0;
1819 $item["created"] = $item["edited"] = date("c");
1820 $item["private"] = true;
1822 $contact = Probe::uri($item['follow']);
1824 if ($contact['alias'] == '') {
1825 $contact['alias'] = $contact["url"];
1827 $item['follow'] = $contact['alias'];
1830 $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($contact["url"])];
1831 $user_contact = DBA::selectFirst('contact', ['id'], $condition);
1833 if (DBA::isResult($user_contact)) {
1834 $connect_id = $user_contact['id'];
1839 if ($item['verb'] == Activity::FOLLOW) {
1840 $message = L10n::t('%s is now following %s.');
1841 $title = L10n::t('following');
1842 $action = "subscription";
1844 $message = L10n::t('%s stopped following %s.');
1845 $title = L10n::t('stopped following');
1846 $action = "unfollow";
1849 $item["uri"] = $item['parent-uri'] = $item['thr-parent']
1850 = 'tag:' . DI::baseUrl()->getHostname()().
1851 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1852 ':person:'.$connect_id.':'.$item['created'];
1854 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1856 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1858 self::entryContent($doc, $entry, $item, $owner, $title);
1860 $object = self::addPersonObject($doc, $owner, $contact);
1861 $entry->appendChild($object);
1863 self::entryFooter($doc, $entry, $item, $owner);
1869 * @brief Adds a regular entry element
1871 * @param DOMDocument $doc XML document
1872 * @param array $item Data of the item that is to be posted
1873 * @param array $owner Contact data of the poster
1874 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1875 * @param bool $feed_mode Behave like a regular feed for users if true
1877 * @return \DOMElement Entry element
1878 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1879 * @throws \ImagickException
1881 private static function noteEntry(DOMDocument $doc, array $item, array $owner, $toplevel, $feed_mode)
1883 if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1884 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1888 if (!empty($item['title'])) {
1889 $title = BBCode::convert($item['title'], false, 7);
1891 $title = sprintf("New note by %s", $owner["nick"]);
1894 $title = sprintf("New comment by %s", $owner["nick"]);
1897 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1899 XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::NOTE);
1901 self::entryContent($doc, $entry, $item, $owner, $title, '', true, $feed_mode);
1903 self::entryFooter($doc, $entry, $item, $owner, !$feed_mode, $feed_mode);
1909 * @brief Adds a header element to the XML document
1911 * @param DOMDocument $doc XML document
1912 * @param array $owner Contact data of the poster
1913 * @param array $item
1914 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1916 * @return \DOMElement The entry element where the elements are added
1917 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1918 * @throws \ImagickException
1920 private static function entryHeader(DOMDocument $doc, array $owner, array $item, $toplevel)
1923 $entry = $doc->createElement("entry");
1925 if ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
1926 $contact = self::contactEntry($item['author-link'], $owner);
1927 $author = self::addAuthor($doc, $contact, false);
1928 $entry->appendChild($author);
1931 $entry = $doc->createElementNS(ActivityNamespace::ATOM1, "entry");
1933 $entry->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
1934 $entry->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
1935 $entry->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
1936 $entry->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
1937 $entry->setAttribute("xmlns:poco", ActivityNamespace::POCO);
1938 $entry->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
1939 $entry->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
1940 $entry->setAttribute("xmlns:mastodon", ActivityNamespace::MASTODON);
1942 $author = self::addAuthor($doc, $owner);
1943 $entry->appendChild($author);
1950 * @brief Adds elements to the XML document
1952 * @param DOMDocument $doc XML document
1953 * @param \DOMElement $entry Entry element where the content is added
1954 * @param array $item Data of the item that is to be posted
1955 * @param array $owner Contact data of the poster
1956 * @param string $title Title for the post
1957 * @param string $verb The activity verb
1958 * @param bool $complete Add the "status_net" element?
1959 * @param bool $feed_mode Behave like a regular feed for users if true
1961 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1963 private static function entryContent(DOMDocument $doc, \DOMElement $entry, array $item, array $owner, $title, $verb = "", $complete = true, $feed_mode = false)
1966 $verb = self::constructVerb($item);
1969 XML::addElement($doc, $entry, "id", $item["uri"]);
1970 XML::addElement($doc, $entry, "title", html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1972 $body = self::formatPicturePost($item['body']);
1974 if (!empty($item['title']) && !$feed_mode) {
1975 $body = "[b]".$item['title']."[/b]\n\n".$body;
1978 $body = BBCode::convert($body, false, 7);
1980 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1982 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1983 "href" => System::baseUrl()."/display/".$item["guid"]]
1986 if (!$feed_mode && $complete && ($item["id"] > 0)) {
1987 XML::addElement($doc, $entry, "status_net", "", ["notice_id" => $item["id"]]);
1991 XML::addElement($doc, $entry, "activity:verb", $verb);
1994 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
1995 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
1999 * @brief Adds the elements at the foot of an entry to the XML document
2001 * @param DOMDocument $doc XML document
2002 * @param object $entry The entry element where the elements are added
2003 * @param array $item Data of the item that is to be posted
2004 * @param array $owner Contact data of the poster
2005 * @param bool $complete default true
2006 * @param bool $feed_mode Behave like a regular feed for users if true
2008 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2010 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner, $complete = true, $feed_mode = false)
2014 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
2015 $parent = Item::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item["parent"]]);
2016 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
2018 $thrparent = Item::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $parent_item]);
2020 if (DBA::isResult($thrparent)) {
2021 $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
2022 $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
2023 $parent_plink = $thrparent["plink"];
2025 $mentioned[$parent["author-link"]] = $parent["author-link"];
2026 $mentioned[$parent["owner-link"]] = $parent["owner-link"];
2027 $parent_plink = System::baseUrl()."/display/".$parent["guid"];
2031 "ref" => $parent_item,
2032 "href" => $parent_plink];
2033 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
2037 "href" => $parent_plink];
2038 XML::addElement($doc, $entry, "link", "", $attributes);
2041 if (!$feed_mode && (intval($item["parent"]) > 0)) {
2042 $conversation_href = $conversation_uri = str_replace('/objects/', '/context/', $item['parent-uri']);
2044 if (isset($parent_item)) {
2045 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $parent_item]);
2046 if (DBA::isResult($conversation)) {
2047 if ($conversation['conversation-uri'] != '') {
2048 $conversation_uri = $conversation['conversation-uri'];
2050 if ($conversation['conversation-href'] != '') {
2051 $conversation_href = $conversation['conversation-href'];
2056 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:conversation", "href" => $conversation_href]);
2059 "href" => $conversation_href,
2060 "local_id" => $item["parent"],
2061 "ref" => $conversation_uri];
2063 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
2066 $tags = item::getFeedTags($item);
2069 foreach ($tags as $t) {
2071 $mentioned[$t[1]] = $t[1];
2076 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2078 foreach ($mentioned as $mention) {
2079 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2080 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2082 $mentioned = $newmentions;
2084 foreach ($mentioned as $mention) {
2085 $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($mention)];
2086 $contact = DBA::selectFirst('contact', ['forum', 'prv', 'self', 'contact-type'], $condition);
2087 if ($contact["forum"] || $contact["prv"] || ($owner['contact-type'] == Contact::TYPE_COMMUNITY) ||
2088 ($contact['self'] && ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY))) {
2089 XML::addElement($doc, $entry, "link", "",
2091 "rel" => "mentioned",
2092 "ostatus:object-type" => Activity\ObjectType::GROUP,
2096 XML::addElement($doc, $entry, "link", "",
2098 "rel" => "mentioned",
2099 "ostatus:object-type" => Activity\ObjectType::PERSON,
2105 if ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
2106 XML::addElement($doc, $entry, "link", "", [
2107 "rel" => "mentioned",
2108 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/group",
2109 "href" => $owner['url']
2113 if (!$item["private"] && !$feed_mode) {
2114 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:attention",
2115 "href" => "http://activityschema.org/collection/public"]);
2116 XML::addElement($doc, $entry, "link", "", ["rel" => "mentioned",
2117 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2118 "href" => "http://activityschema.org/collection/public"]);
2119 XML::addElement($doc, $entry, "mastodon:scope", "public");
2123 foreach ($tags as $t) {
2125 XML::addElement($doc, $entry, "category", "", ["term" => $t[2]]);
2130 self::getAttachment($doc, $entry, $item);
2132 if ($complete && ($item["id"] > 0)) {
2133 $app = $item["app"];
2138 $attributes = ["local_id" => $item["id"], "source" => $app];
2140 if (isset($parent["id"])) {
2141 $attributes["repeat_of"] = $parent["id"];
2144 if ($item["coord"] != "") {
2145 XML::addElement($doc, $entry, "georss:point", $item["coord"]);
2148 XML::addElement($doc, $entry, "statusnet:notice_info", "", $attributes);
2153 * Creates the XML feed for a given nickname
2155 * Supported filters:
2156 * - activity (default): all the public posts
2157 * - posts: all the public top-level posts
2158 * - comments: all the public replies
2160 * Updates the provided last_update parameter if the result comes from the
2161 * cache or it is empty
2163 * @brief Creates the XML feed for a given nickname
2165 * @param string $owner_nick Nickname of the feed owner
2166 * @param string $last_update Date of the last update
2167 * @param integer $max_items Number of maximum items to fetch
2168 * @param string $filter Feed items filter (activity, posts or comments)
2169 * @param boolean $nocache Wether to bypass caching
2170 * @param boolean $feed_mode Behave like a regular feed for users if true
2172 * @return string XML feed
2173 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2174 * @throws \ImagickException
2176 public static function feed($owner_nick, &$last_update, $max_items = 300, $filter = 'activity', $nocache = false, $feed_mode = false)
2178 $stamp = microtime(true);
2180 $owner = User::getOwnerDataByNick($owner_nick);
2185 $cachekey = "ostatus:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
2187 $previous_created = $last_update;
2189 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
2190 if ((time() - strtotime($owner['last-item'])) < 15*60) {
2191 $result = Cache::get($cachekey);
2192 if (!$nocache && !is_null($result)) {
2193 Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', Logger::DEBUG);
2194 $last_update = $result['last_update'];
2195 return $result['feed'];
2199 if (!strlen($last_update)) {
2200 $last_update = 'now -30 days';
2203 $check_date = DateTimeFormat::utc($last_update);
2204 $authorid = Contact::getIdForURL($owner["url"], 0, true);
2206 $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted`
2207 AND NOT `private` AND `visible` AND `wall` AND `parent-network` IN (?, ?)",
2208 $owner["uid"], $check_date, Protocol::OSTATUS, Protocol::DFRN];
2210 if ($filter === 'comments') {
2211 $condition[0] .= " AND `object-type` = ? ";
2212 $condition[] = Activity\ObjectType::COMMENT;
2215 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
2216 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
2217 $condition[] = $owner["id"];
2218 $condition[] = $authorid;
2221 $params = ['order' => ['received' => true], 'limit' => $max_items];
2223 if ($filter === 'posts') {
2224 $ret = Item::selectThread([], $condition, $params);
2226 $ret = Item::select([], $condition, $params);
2229 $items = Item::inArray($ret);
2231 $doc = new DOMDocument('1.0', 'utf-8');
2232 $doc->formatOutput = true;
2234 $root = self::addHeader($doc, $owner, $filter, $feed_mode);
2236 foreach ($items as $item) {
2237 if (Config::get('system', 'ostatus_debug')) {
2238 $item['body'] .= '🍼';
2241 $entry = self::entry($doc, $item, $owner, false, $feed_mode);
2242 $root->appendChild($entry);
2244 if ($last_update < $item['created']) {
2245 $last_update = $item['created'];
2249 $feeddata = trim($doc->saveXML());
2251 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
2252 Cache::set($cachekey, $msg, Cache::QUARTER_HOUR);
2254 Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, Logger::DEBUG);
2260 * @brief Creates the XML for a salmon message
2262 * @param array $item Data of the item that is to be posted
2263 * @param array $owner Contact data of the poster
2265 * @return string XML for the salmon
2266 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2267 * @throws \ImagickException
2269 public static function salmon(array $item, array $owner)
2271 $doc = new DOMDocument('1.0', 'utf-8');
2272 $doc->formatOutput = true;
2274 if (Config::get('system', 'ostatus_debug')) {
2275 $item['body'] .= '🐟';
2278 $entry = self::entry($doc, $item, $owner, true);
2280 $doc->appendChild($entry);
2282 return trim($doc->saveXML());
2286 * Checks if the given contact url does support OStatus
2288 * @param string $url profile url
2289 * @param boolean $update Update the profile
2291 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2292 * @throws \ImagickException
2294 public static function isSupportedByContactUrl($url, $update = false)
2296 $probe = Probe::uri($url, Protocol::OSTATUS, 0, !$update);
2297 return $probe['network'] == Protocol::OSTATUS;