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;
20 use Friendica\Model\APContact;
21 use Friendica\Model\Contact;
22 use Friendica\Model\Conversation;
23 use Friendica\Model\GContact;
24 use Friendica\Model\Item;
25 use Friendica\Model\User;
26 use Friendica\Network\Probe;
27 use Friendica\Object\Image;
28 use Friendica\Protocol\ActivityNamespace;
29 use Friendica\Util\DateTimeFormat;
30 use Friendica\Util\Images;
31 use Friendica\Util\Network;
32 use Friendica\Util\Proxy as ProxyUtils;
33 use Friendica\Util\Strings;
34 use Friendica\Util\XML;
36 require_once 'mod/share.php';
37 require_once 'include/api.php';
40 * @brief This class contain functions for the OStatus protocol
44 private static $itemlist;
45 private static $conv_list = [];
48 * @brief Fetches author data
50 * @param DOMXPath $xpath The xpath object
51 * @param object $context The xml context of the author details
52 * @param array $importer user record of the importing user
53 * @param array $contact Called by reference, will contain the fetched contact
54 * @param bool $onlyfetch Only fetch the header without updating the contact entries
56 * @return array Array of author related entries for the item
57 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
58 * @throws \ImagickException
60 private static function fetchAuthor(DOMXPath $xpath, $context, array $importer, array &$contact = null, $onlyfetch)
63 $author["author-link"] = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
64 $author["author-name"] = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $context);
65 $addr = XML::getFirstNodeValue($xpath, 'atom:author/atom:email/text()', $context);
67 $aliaslink = $author["author-link"];
69 $alternate_item = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0);
70 if (is_object($alternate_item)) {
71 foreach ($alternate_item->attributes as $attributes) {
72 if (($attributes->name == "href") && ($attributes->textContent != "")) {
73 $author["author-link"] = $attributes->textContent;
77 $author["author-id"] = Contact::getIdForURL($author["author-link"]);
79 $author['contact-id'] = ($contact['id'] ?? 0) ?: $author['author-id'];
84 This here would be better, but we would get problems with contacts from the statusnet addon
85 This is kept here as a reminder for the future
87 $cid = Contact::getIdForURL($author["author-link"], $importer["uid"]);
89 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
92 if ($aliaslink != '') {
93 $condition = ["`uid` = ? AND `alias` = ? AND `network` != ? AND `rel` IN (?, ?)",
94 $importer["uid"], $aliaslink, Protocol::STATUSNET,
95 Contact::SHARING, Contact::FRIEND];
96 $contact = DBA::selectFirst('contact', [], $condition);
99 if (!DBA::isResult($contact) && $author["author-link"] != '') {
100 if ($aliaslink == "") {
101 $aliaslink = $author["author-link"];
104 $condition = ["`uid` = ? AND `nurl` IN (?, ?) AND `network` != ? AND `rel` IN (?, ?)",
105 $importer["uid"], Strings::normaliseLink($author["author-link"]), Strings::normaliseLink($aliaslink),
106 Protocol::STATUSNET, Contact::SHARING, Contact::FRIEND];
107 $contact = DBA::selectFirst('contact', [], $condition);
110 if (!DBA::isResult($contact) && ($addr != '')) {
111 $condition = ["`uid` = ? AND `addr` = ? AND `network` != ? AND `rel` IN (?, ?)",
112 $importer["uid"], $addr, Protocol::STATUSNET,
113 Contact::SHARING, Contact::FRIEND];
114 $contact = DBA::selectFirst('contact', [], $condition);
117 if (DBA::isResult($contact)) {
118 if ($contact['blocked']) {
120 } elseif (!empty(APContact::getByURL($contact['url'], false))) {
121 ActivityPub\Receiver::switchContact($contact['id'], $importer['uid'], $contact['url']);
123 $author["contact-id"] = $contact["id"];
127 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
128 foreach ($avatars as $avatar) {
131 foreach ($avatar->attributes as $attributes) {
132 if ($attributes->name == "href") {
133 $href = $attributes->textContent;
135 if ($attributes->name == "width") {
136 $width = $attributes->textContent;
140 $avatarlist[$width] = $href;
143 if (count($avatarlist) > 0) {
145 $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
148 $displayname = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
149 if ($displayname != "") {
150 $author["author-name"] = $displayname;
153 $author["owner-id"] = $author["author-id"];
155 // Only update the contacts if it is an OStatus contact
156 if (DBA::isResult($contact) && ($contact['id'] > 0) && !$onlyfetch && ($contact["network"] == Protocol::OSTATUS)) {
158 // Update contact data
160 unset($current['name-date']);
162 // This query doesn't seem to work
163 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
165 // $contact["notify"] = $value;
167 // This query doesn't seem to work as well - I hate these queries
168 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
170 // $contact["poll"] = $value;
172 $contact['url'] = $author["author-link"];
173 $contact['nurl'] = Strings::normaliseLink($contact['url']);
175 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
177 $contact["alias"] = $value;
180 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
182 $contact["name"] = $value;
185 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()', $context);
187 $contact["nick"] = $value;
190 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()', $context);
192 $contact["about"] = HTML::toBBCode($value);
195 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()', $context);
197 $contact["location"] = $value;
200 $contact['name-date'] = DateTimeFormat::utcNow();
202 DBA::update('contact', $contact, ['id' => $contact["id"]], $current);
204 if (!empty($author["author-avatar"]) && ($author["author-avatar"] != $current['avatar'])) {
205 Logger::log("Update profile picture for contact ".$contact["id"], Logger::DEBUG);
206 Contact::updateAvatar($author["author-avatar"], $importer["uid"], $contact["id"]);
209 // Ensure that we are having this contact (with uid=0)
210 $cid = Contact::getIdForURL($aliaslink, 0, true);
213 $fields = ['url', 'nurl', 'name', 'nick', 'alias', 'about', 'location'];
214 $old_contact = DBA::selectFirst('contact', $fields, ['id' => $cid]);
216 // Update it with the current values
217 $fields = ['url' => $author["author-link"], 'name' => $contact["name"],
218 'nurl' => Strings::normaliseLink($author["author-link"]),
219 'nick' => $contact["nick"], 'alias' => $contact["alias"],
220 'about' => $contact["about"], 'location' => $contact["location"],
221 'success_update' => DateTimeFormat::utcNow(), 'last-update' => DateTimeFormat::utcNow()];
223 DBA::update('contact', $fields, ['id' => $cid], $old_contact);
226 if (!empty($author["author-avatar"])) {
227 Contact::updateAvatar($author["author-avatar"], 0, $cid);
231 $contact["generation"] = 2;
232 $contact["hide"] = false; // OStatus contacts are never hidden
233 if (!empty($author["author-avatar"])) {
234 $contact["photo"] = $author["author-avatar"];
236 $gcid = GContact::update($contact);
238 GContact::link($gcid, $contact["uid"], $contact["id"]);
239 } elseif ($contact["network"] != Protocol::DFRN) {
247 * @brief Fetches author data from a given XML string
249 * @param string $xml The XML
250 * @param array $importer user record of the importing user
252 * @return array Array of author related entries for the item
253 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
254 * @throws \ImagickException
256 public static function salmonAuthor($xml, array $importer)
262 $doc = new DOMDocument();
263 @$doc->loadXML($xml);
265 $xpath = new DOMXPath($doc);
266 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
267 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
268 $xpath->registerNamespace('georss', ActivityNamespace::GEORSS);
269 $xpath->registerNamespace('activity', ActivityNamespace::ACTIVITY);
270 $xpath->registerNamespace('media', ActivityNamespace::MEDIA);
271 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
272 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
273 $xpath->registerNamespace('statusnet', ActivityNamespace::STATUSNET);
275 $contact = ["id" => 0];
277 // Fetch the first author
278 $authordata = $xpath->query('//author')->item(0);
279 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, true);
284 * @brief Read attributes from element
286 * @param object $element Element object
288 * @return array attributes
290 private static function readAttributes($element)
294 foreach ($element->attributes as $attributes) {
295 $attribute[$attributes->name] = $attributes->textContent;
302 * @brief Imports an XML string containing OStatus elements
304 * @param string $xml The XML
305 * @param array $importer user record of the importing user
306 * @param array $contact contact
307 * @param string $hub Called by reference, returns the fetched hub data
309 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
310 * @throws \ImagickException
312 public static function import($xml, array $importer, array &$contact, &$hub)
314 self::process($xml, $importer, $contact, $hub);
318 * @brief Internal feed processing
320 * @param string $xml The XML
321 * @param array $importer user record of the importing user
322 * @param array $contact contact
323 * @param string $hub Called by reference, returns the fetched hub data
324 * @param boolean $stored Is the post fresh imported or from the database?
325 * @param boolean $initialize Is it the leading post so that data has to be initialized?
327 * @return boolean Could the XML be processed?
328 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
329 * @throws \ImagickException
331 private static function process($xml, array $importer, array &$contact = null, &$hub, $stored = false, $initialize = true)
334 self::$itemlist = [];
335 self::$conv_list = [];
338 Logger::log('Import OStatus message for user ' . $importer['uid'], Logger::DEBUG);
343 $doc = new DOMDocument();
344 @$doc->loadXML($xml);
346 $xpath = new DOMXPath($doc);
347 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
348 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
349 $xpath->registerNamespace('georss', ActivityNamespace::GEORSS);
350 $xpath->registerNamespace('activity', ActivityNamespace::ACTIVITY);
351 $xpath->registerNamespace('media', ActivityNamespace::MEDIA);
352 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
353 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
354 $xpath->registerNamespace('statusnet', ActivityNamespace::STATUSNET);
357 $hub_items = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0);
358 if (is_object($hub_items)) {
359 $hub_attributes = $hub_items->attributes;
360 if (is_object($hub_attributes)) {
361 foreach ($hub_attributes as $hub_attribute) {
362 if ($hub_attribute->name == "href") {
363 $hub = $hub_attribute->textContent;
364 Logger::log("Found hub ".$hub, Logger::DEBUG);
371 $header["uid"] = $importer["uid"];
372 $header["network"] = Protocol::OSTATUS;
374 $header["origin"] = 0;
375 $header["gravity"] = GRAVITY_COMMENT;
377 if (!is_object($doc->firstChild) || empty($doc->firstChild->tagName)) {
381 $first_child = $doc->firstChild->tagName;
383 if ($first_child == "feed") {
384 $entries = $xpath->query('/atom:feed/atom:entry');
386 $entries = $xpath->query('/atom:entry');
389 if ($entries->length == 1) {
390 // We reformat the XML to make it better readable
391 $doc2 = new DOMDocument();
392 $doc2->loadXML($xml);
393 $doc2->preserveWhiteSpace = false;
394 $doc2->formatOutput = true;
395 $xml2 = $doc2->saveXML();
397 $header["protocol"] = Conversation::PARCEL_SALMON;
398 $header["source"] = $xml2;
399 } elseif (!$initialize) {
403 // Fetch the first author
404 $authordata = $xpath->query('//author')->item(0);
405 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, $stored);
407 // Reverse the order of the entries
410 foreach ($entries as $entry) {
411 $entrylist[] = $entry;
414 foreach (array_reverse($entrylist) as $entry) {
416 $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
418 if ($authorelement->length == 0) {
419 $authorelement = $xpath->query('atom:author', $entry);
422 if ($authorelement->length > 0) {
423 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, $stored);
426 $item = array_merge($header, $author);
428 $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
430 $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $entry);
433 if (in_array($item["verb"], ['qvitter-delete-notice', Activity::DELETE, 'delete'])) {
434 self::deleteNotice($item);
438 if (in_array($item["verb"], [Activity::O_UNFAVOURITE, Activity::UNFAVORITE])) {
439 // Ignore "Unfavorite" message
440 Logger::log("Ignore unfavorite message ".print_r($item, true), Logger::DEBUG);
444 // Deletions come with the same uri, so we check for duplicates after processing deletions
445 if (Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]])) {
446 Logger::log('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', Logger::DEBUG);
449 Logger::log('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', Logger::DEBUG);
452 if ($item["verb"] == Activity::JOIN) {
453 // ignore "Join" messages
454 Logger::log("Ignore join message ".print_r($item, true), Logger::DEBUG);
458 if ($item["verb"] == "http://mastodon.social/schema/1.0/block") {
459 // ignore mastodon "block" messages
460 Logger::log("Ignore block message ".print_r($item, true), Logger::DEBUG);
464 if ($item["verb"] == Activity::FOLLOW) {
465 Contact::addRelationship($importer, $contact, $item);
469 if ($item["verb"] == Activity::O_UNFOLLOW) {
471 Contact::removeFollower($importer, $contact, $item, $dummy);
475 if ($item["verb"] == Activity::FAVORITE) {
476 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
477 Logger::log("Favorite ".$orig_uri." ".print_r($item, true));
479 $item["verb"] = Activity::LIKE;
480 $item["parent-uri"] = $orig_uri;
481 $item["gravity"] = GRAVITY_ACTIVITY;
482 $item["object-type"] = Activity\ObjectType::NOTE;
485 // http://activitystrea.ms/schema/1.0/rsvp-yes
486 if (!in_array($item["verb"], [Activity::POST, Activity::LIKE, Activity::SHARE])) {
487 Logger::log("Unhandled verb ".$item["verb"]." ".print_r($item, true), Logger::DEBUG);
490 self::processPost($xpath, $entry, $item, $importer);
492 if ($initialize && (count(self::$itemlist) > 0)) {
493 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['parent-uri']) {
494 // We will import it everytime, when it is started by our contacts
495 $valid = Contact::isSharingByURL(self::$itemlist[0]['author-link'], self::$itemlist[0]['uid']);
498 // If not, then it depends on this setting
499 $valid = ((self::$itemlist[0]['uid'] == 0) || !PConfig::get(self::$itemlist[0]['uid'], 'system', 'accept_only_sharer', false));
501 Logger::log("Item with uri ".self::$itemlist[0]['uri']." will be imported due to the system settings.", Logger::DEBUG);
504 Logger::log("Item with uri ".self::$itemlist[0]['uri']." belongs to a contact (".self::$itemlist[0]['contact-id']."). It will be imported.", Logger::DEBUG);
507 // Never post a thread when the only interaction by our contact was a like
509 $verbs = [Activity::POST, Activity::SHARE];
510 foreach (self::$itemlist as $item) {
511 if (in_array($item['verb'], $verbs) && Contact::isSharingByURL($item['author-link'], $item['uid'])) {
516 Logger::log("Item with uri ".self::$itemlist[0]['uri']." will be imported since the thread contains posts or shares.", Logger::DEBUG);
520 // But we will only import complete threads
521 $valid = Item::exists(['uid' => $importer["uid"], 'uri' => self::$itemlist[0]['parent-uri']]);
523 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);
528 $default_contact = 0;
529 for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
530 if (empty(self::$itemlist[$key]['contact-id'])) {
531 self::$itemlist[$key]['contact-id'] = $default_contact;
533 $default_contact = $item['contact-id'];
536 foreach (self::$itemlist as $item) {
537 $found = Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]]);
539 Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", Logger::DEBUG);
540 } elseif ($item['contact-id'] < 0) {
541 Logger::log("Item with uri ".$item["uri"]." is from a blocked contact.", Logger::DEBUG);
543 // We are having duplicated entries. Hopefully this solves it.
544 if (Lock::acquire('ostatus_process_item_insert')) {
545 $ret = Item::insert($item);
546 Lock::release('ostatus_process_item_insert');
547 Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret);
549 $ret = Item::insert($item);
550 Logger::log("We couldn't lock - but tried to store the item anyway. Return value is ".$ret);
555 self::$itemlist = [];
557 Logger::log('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.', Logger::DEBUG);
563 * Removes notice item from database
565 * @param array $item item
569 private static function deleteNotice(array $item)
571 $condition = ['uid' => $item['uid'], 'author-id' => $item['author-id'], 'uri' => $item['uri']];
572 if (!Item::exists($condition)) {
573 Logger::log('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it.");
577 Item::delete($condition);
579 Logger::log('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
583 * @brief Processes the XML for a post
585 * @param DOMXPath $xpath The xpath object
586 * @param object $entry The xml entry that is processed
587 * @param array $item The item array
588 * @param array $importer user record of the importing user
590 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
591 * @throws \ImagickException
593 private static function processPost(DOMXPath $xpath, $entry, array &$item, array $importer)
595 $item["body"] = HTML::toBBCode(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
596 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $entry);
597 if (($item["object-type"] == Activity\ObjectType::BOOKMARK) || ($item["object-type"] == Activity\ObjectType::EVENT)) {
598 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
599 $item["body"] = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
600 } elseif ($item["object-type"] == Activity\ObjectType::QUESTION) {
601 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
604 $item["created"] = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
605 $item["edited"] = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
606 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
608 $conv = $xpath->query('ostatus:conversation', $entry);
609 if (is_object($conv->item(0))) {
610 foreach ($conv->item(0)->attributes as $attributes) {
611 if ($attributes->name == "ref") {
612 $item['conversation-uri'] = $attributes->textContent;
614 if ($attributes->name == "href") {
615 $item['conversation-href'] = $attributes->textContent;
622 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
623 if (is_object($inreplyto->item(0))) {
624 foreach ($inreplyto->item(0)->attributes as $attributes) {
625 if ($attributes->name == "ref") {
626 $item["parent-uri"] = $attributes->textContent;
628 if ($attributes->name == "href") {
629 $related = $attributes->textContent;
634 $georsspoint = $xpath->query('georss:point', $entry);
635 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
636 $item["coord"] = $georsspoint->item(0)->nodeValue;
639 $categories = $xpath->query('atom:category', $entry);
641 foreach ($categories as $category) {
642 foreach ($category->attributes as $attributes) {
643 if ($attributes->name == 'term') {
644 $term = $attributes->textContent;
645 if (!empty($item['tag'])) {
651 $item['tag'] .= '#[url=' . System::baseUrl() . '/search?tag=' . $term . ']' . $term . '[/url]';
660 $links = $xpath->query('atom:link', $entry);
662 $link_data = self::processLinks($links, $item);
663 $self = $link_data['self'];
664 $add_body = $link_data['add_body'];
669 $notice_info = $xpath->query('statusnet:notice_info', $entry);
670 if ($notice_info && ($notice_info->length > 0)) {
671 foreach ($notice_info->item(0)->attributes as $attributes) {
672 if ($attributes->name == "source") {
673 $item["app"] = strip_tags($attributes->textContent);
675 if ($attributes->name == "repeat_of") {
676 $repeat_of = $attributes->textContent;
680 // Is it a repeated post?
681 if (($repeat_of != "") || ($item["verb"] == Activity::SHARE)) {
682 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
683 if (!empty($link_data['add_body'])) {
684 $add_body .= $link_data['add_body'];
688 $item["body"] .= $add_body;
690 // Only add additional data when there is no picture in the post
691 if (!strstr($item["body"], '[/img]')) {
692 $item["body"] = add_page_info_to_body($item["body"]);
695 // Mastodon Content Warning
696 if (($item["verb"] == Activity::POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
697 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
698 if (!empty($clear_text)) {
699 $item['content-warning'] = HTML::toBBCode($clear_text);
703 if (($self != '') && empty($item['protocol'])) {
704 self::fetchSelf($self, $item);
707 if (!empty($item["conversation-href"])) {
708 self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
711 if (isset($item["parent-uri"])) {
712 if (!Item::exists(['uid' => $importer["uid"], 'uri' => $item['parent-uri']])) {
713 if ($related != '') {
714 self::fetchRelated($related, $item["parent-uri"], $importer);
717 Logger::log('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', Logger::DEBUG);
720 $item["parent-uri"] = $item["uri"];
721 $item["gravity"] = GRAVITY_PARENT;
724 if (($item['author-link'] != '') && !empty($item['protocol'])) {
725 $item = Conversation::insert($item);
728 self::$itemlist[] = $item;
732 * @brief Fetch the conversation for posts
734 * @param string $conversation The link to the conversation
735 * @param string $conversation_uri The conversation in "uri" format
737 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
739 private static function fetchConversation($conversation, $conversation_uri)
741 // Ensure that we only store a conversation once in a process
742 if (isset(self::$conv_list[$conversation])) {
746 self::$conv_list[$conversation] = true;
748 $curlResult = Network::curl($conversation, false, ['accept_content' => 'application/atom+xml, text/html']);
750 if (!$curlResult->isSuccess()) {
756 if (stristr($curlResult->getHeader(), 'Content-Type: application/atom+xml')) {
757 $xml = $curlResult->getBody();
761 $doc = new DOMDocument();
762 if (!@$doc->loadHTML($curlResult->getBody())) {
765 $xpath = new DOMXPath($doc);
767 $links = $xpath->query('//link');
770 foreach ($links as $link) {
771 $attribute = self::readAttributes($link);
772 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
773 $file = $attribute['href'];
777 $conversation_atom = Network::curl($attribute['href']);
779 if ($conversation_atom->isSuccess()) {
780 $xml = $conversation_atom->getBody();
790 self::storeConversation($xml, $conversation, $conversation_uri);
794 * @brief Store a feed in several conversation entries
796 * @param string $xml The feed
797 * @param string $conversation conversation
798 * @param string $conversation_uri conversation uri
802 private static function storeConversation($xml, $conversation = '', $conversation_uri = '')
804 $doc = new DOMDocument();
805 @$doc->loadXML($xml);
807 $xpath = new DOMXPath($doc);
808 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
809 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
810 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
812 $entries = $xpath->query('/atom:feed/atom:entry');
814 // Now store the entries
815 foreach ($entries as $entry) {
816 $doc2 = new DOMDocument();
817 $doc2->preserveWhiteSpace = false;
818 $doc2->formatOutput = true;
822 $conv_data['protocol'] = Conversation::PARCEL_SPLIT_CONVERSATION;
823 $conv_data['network'] = Protocol::OSTATUS;
824 $conv_data['uri'] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
826 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
827 if (is_object($inreplyto->item(0))) {
828 foreach ($inreplyto->item(0)->attributes as $attributes) {
829 if ($attributes->name == "ref") {
830 $conv_data['reply-to-uri'] = $attributes->textContent;
835 $conv_data['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
837 $conv = $xpath->query('ostatus:conversation', $entry);
838 if (is_object($conv->item(0))) {
839 foreach ($conv->item(0)->attributes as $attributes) {
840 if ($attributes->name == "ref") {
841 $conv_data['conversation-uri'] = $attributes->textContent;
843 if ($attributes->name == "href") {
844 $conv_data['conversation-href'] = $attributes->textContent;
849 if ($conversation != '') {
850 $conv_data['conversation-uri'] = $conversation;
853 if ($conversation_uri != '') {
854 $conv_data['conversation-uri'] = $conversation_uri;
857 $entry = $doc2->importNode($entry, true);
859 $doc2->appendChild($entry);
861 $conv_data['source'] = $doc2->saveXML();
863 $condition = ['item-uri' => $conv_data['uri'],'protocol' => Conversation::PARCEL_FEED];
864 if (DBA::exists('conversation', $condition)) {
865 Logger::log('Delete deprecated entry for URI '.$conv_data['uri'], Logger::DEBUG);
866 DBA::delete('conversation', ['item-uri' => $conv_data['uri']]);
869 Logger::log('Store conversation data for uri '.$conv_data['uri'], Logger::DEBUG);
870 Conversation::insert($conv_data);
875 * @brief Fetch the own post so that it can be stored later
877 * We want to store the original data for later processing.
878 * This function is meant for cases where we process a feed with multiple entries.
879 * In that case we need to fetch the single posts here.
881 * @param string $self The link to the self item
882 * @param array $item The item array
884 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
886 private static function fetchSelf($self, array &$item)
888 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $self, Conversation::PARCEL_DFRN, Conversation::PARCEL_SALMON];
889 if (DBA::exists('conversation', $condition)) {
890 Logger::log('Conversation '.$item['uri'].' is already stored.', Logger::DEBUG);
894 $curlResult = Network::curl($self);
896 if (!$curlResult->isSuccess()) {
900 // We reformat the XML to make it better readable
901 $doc = new DOMDocument();
902 $doc->loadXML($curlResult->getBody());
903 $doc->preserveWhiteSpace = false;
904 $doc->formatOutput = true;
905 $xml = $doc->saveXML();
907 $item["protocol"] = Conversation::PARCEL_SALMON;
908 $item["source"] = $xml;
910 Logger::log('Conversation '.$item['uri'].' is now fetched.', Logger::DEBUG);
914 * @brief Fetch related posts and processes them
916 * @param string $related The link to the related item
917 * @param string $related_uri The related item in "uri" format
918 * @param array $importer user record of the importing user
920 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
921 * @throws \ImagickException
923 private static function fetchRelated($related, $related_uri, $importer)
925 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, Conversation::PARCEL_DFRN, Conversation::PARCEL_SALMON];
926 $conversation = DBA::selectFirst('conversation', ['source', 'protocol'], $condition);
927 if (DBA::isResult($conversation)) {
929 $xml = $conversation['source'];
930 if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
931 Logger::log('Got valid cached XML for URI '.$related_uri, Logger::DEBUG);
934 if ($conversation['protocol'] == Conversation::PARCEL_SALMON) {
935 Logger::log('Delete invalid cached XML for URI '.$related_uri, Logger::DEBUG);
936 DBA::delete('conversation', ['item-uri' => $related_uri]);
941 $curlResult = Network::curl($related, false, ['accept_content' => 'application/atom+xml, text/html']);
943 if (!$curlResult->isSuccess()) {
949 if (stristr($curlResult->getHeader(), 'Content-Type: application/atom+xml')) {
950 Logger::log('Directly fetched XML for URI ' . $related_uri, Logger::DEBUG);
951 $xml = $curlResult->getBody();
955 $doc = new DOMDocument();
956 if (!@$doc->loadHTML($curlResult->getBody())) {
959 $xpath = new DOMXPath($doc);
963 $links = $xpath->query('//link');
965 foreach ($links as $link) {
966 $attribute = self::readAttributes($link);
967 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
968 $atom_file = $attribute['href'];
971 if ($atom_file != '') {
972 $curlResult = Network::curl($atom_file);
974 if ($curlResult->isSuccess()) {
975 Logger::log('Fetched XML for URI ' . $related_uri, Logger::DEBUG);
976 $xml = $curlResult->getBody();
982 // Workaround for older GNU Social servers
983 if (($xml == '') && strstr($related, '/notice/')) {
984 $curlResult = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related).'.atom');
986 if ($curlResult->isSuccess()) {
987 Logger::log('GNU Social workaround to fetch XML for URI ' . $related_uri, Logger::DEBUG);
988 $xml = $curlResult->getBody();
992 // Even more worse workaround for GNU Social ;-)
994 $related_guess = OStatus::convertHref($related_uri);
995 $curlResult = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related_guess).'.atom');
997 if ($curlResult->isSuccess()) {
998 Logger::log('GNU Social workaround 2 to fetch XML for URI ' . $related_uri, Logger::DEBUG);
999 $xml = $curlResult->getBody();
1003 // Finally we take the data that we fetched from "ostatus:conversation"
1005 $condition = ['item-uri' => $related_uri, 'protocol' => Conversation::PARCEL_SPLIT_CONVERSATION];
1006 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1007 if (DBA::isResult($conversation)) {
1009 Logger::log('Got cached XML from conversation for URI '.$related_uri, Logger::DEBUG);
1010 $xml = $conversation['source'];
1015 self::process($xml, $importer, $contact, $hub, $stored, false);
1017 Logger::log("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, Logger::DEBUG);
1023 * @brief Processes the XML for a repeated post
1025 * @param DOMXPath $xpath The xpath object
1026 * @param object $entry The xml entry that is processed
1027 * @param array $item The item array
1028 * @param array $importer user record of the importing user
1030 * @return array with data from links
1031 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1032 * @throws \ImagickException
1034 private static function processRepeatedItem(DOMXPath $xpath, $entry, array &$item, array $importer)
1036 $activityobject = $xpath->query('activity:object', $entry)->item(0);
1038 if (!is_object($activityobject)) {
1044 $orig_uri = XML::getFirstNodeValue($xpath, 'atom:id/text()', $activityobject);
1046 $links = $xpath->query("atom:link", $activityobject);
1048 $link_data = self::processLinks($links, $item);
1051 $orig_body = XML::getFirstNodeValue($xpath, 'atom:content/text()', $activityobject);
1052 $orig_created = XML::getFirstNodeValue($xpath, 'atom:published/text()', $activityobject);
1053 $orig_edited = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $activityobject);
1055 $orig_author = self::fetchAuthor($xpath, $activityobject, $importer, $dummy, false);
1057 $item["author-name"] = $orig_author["author-name"];
1058 $item["author-link"] = $orig_author["author-link"];
1059 $item["author-id"] = $orig_author["author-id"];
1061 $item["body"] = HTML::toBBCode($orig_body);
1062 $item["created"] = $orig_created;
1063 $item["edited"] = $orig_edited;
1065 $item["uri"] = $orig_uri;
1067 $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $activityobject);
1069 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $activityobject);
1071 // Mastodon Content Warning
1072 if (($item["verb"] == Activity::POST) && $xpath->evaluate('boolean(atom:summary)', $activityobject)) {
1073 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $activityobject);
1074 if (!empty($clear_text)) {
1075 $item['content-warning'] = HTML::toBBCode($clear_text);
1079 $inreplyto = $xpath->query('thr:in-reply-to', $activityobject);
1080 if (is_object($inreplyto->item(0))) {
1081 foreach ($inreplyto->item(0)->attributes as $attributes) {
1082 if ($attributes->name == "ref") {
1083 $item["parent-uri"] = $attributes->textContent;
1092 * @brief Processes links in the XML
1094 * @param object $links The xml data that contain links
1095 * @param array $item The item array
1097 * @return array with data from the links
1099 private static function processLinks($links, array &$item)
1101 $link_data = ['add_body' => '', 'self' => ''];
1103 foreach ($links as $link) {
1104 $attribute = self::readAttributes($link);
1106 if (!empty($attribute['rel']) && !empty($attribute['href'])) {
1107 switch ($attribute['rel']) {
1109 $item["plink"] = $attribute['href'];
1110 if (($item["object-type"] == Activity\ObjectType::QUESTION)
1111 || ($item["object-type"] == Activity\ObjectType::EVENT)
1113 $item["body"] .= add_page_info($attribute['href']);
1116 case "ostatus:conversation":
1117 $link_data['conversation'] = $attribute['href'];
1118 $item['conversation-href'] = $link_data['conversation'];
1119 if (!isset($item['conversation-uri'])) {
1120 $item['conversation-uri'] = $item['conversation-href'];
1124 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
1125 if ($filetype == 'image') {
1126 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1128 if (!empty($item["attach"])) {
1129 $item["attach"] .= ',';
1131 $item["attach"] = '';
1133 if (!isset($attribute['length'])) {
1134 $attribute['length'] = "0";
1136 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.($attribute['title'] ?? '') .'"[/attach]';
1140 if ($item["object-type"] != Activity\ObjectType::BOOKMARK) {
1141 if (!isset($item["parent-uri"])) {
1142 $item["parent-uri"] = $attribute['href'];
1144 $link_data['related'] = $attribute['href'];
1146 $item["body"] .= add_page_info($attribute['href']);
1150 if (empty($item["plink"])) {
1151 $item["plink"] = $attribute['href'];
1153 $link_data['self'] = $attribute['href'];
1162 * @brief Create an url out of an uri
1164 * @param string $href URI in the format "parameter1:parameter1:..."
1166 * @return string URL in the format http(s)://....
1168 public static function convertHref($href)
1170 $elements = explode(":", $href);
1172 if ((count($elements) <= 2) || ($elements[0] != "tag")) {
1176 $server = explode(",", $elements[1]);
1177 $conversation = explode("=", $elements[2]);
1179 if ((count($elements) == 4) && ($elements[2] == "post")) {
1180 return "http://".$server[0]."/notice/".$elements[3];
1183 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1186 if ($elements[3] == "objectType=thread") {
1187 return "http://".$server[0]."/conversation/".$conversation[1];
1189 return "http://".$server[0]."/notice/".$conversation[1];
1194 * @brief Checks if the current post is a reshare
1196 * @param array $item The item array of thw post
1198 * @return string The guid if the post is a reshare
1200 private static function getResharedGuid(array $item)
1202 $reshared = Item::getShareArray($item);
1203 if (empty($reshared['guid']) || !empty($reshared['comment'])) {
1207 return $reshared['guid'];
1211 * @brief Cleans the body of a post if it contains picture links
1213 * @param string $body The body
1215 * @return string The cleaned body
1216 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1218 private static function formatPicturePost($body)
1220 $siteinfo = BBCode::getAttachedData($body);
1222 if (($siteinfo["type"] == "photo") && (!empty($siteinfo["preview"]) || !empty($siteinfo["image"]))) {
1223 if (isset($siteinfo["preview"])) {
1224 $preview = $siteinfo["preview"];
1226 $preview = $siteinfo["image"];
1229 // Is it a remote picture? Then make a smaller preview here
1230 $preview = ProxyUtils::proxifyUrl($preview, false, ProxyUtils::SIZE_SMALL);
1232 // Is it a local picture? Then make it smaller here
1233 $preview = str_replace(["-0.jpg", "-0.png"], ["-2.jpg", "-2.png"], $preview);
1234 $preview = str_replace(["-1.jpg", "-1.png"], ["-2.jpg", "-2.png"], $preview);
1236 if (isset($siteinfo["url"])) {
1237 $url = $siteinfo["url"];
1239 $url = $siteinfo["image"];
1242 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1249 * @brief Adds the header elements to the XML document
1251 * @param DOMDocument $doc XML document
1252 * @param array $owner Contact data of the poster
1253 * @param string $filter The related feed filter (activity, posts or comments)
1254 * @param bool $feed_mode Behave like a regular feed for users if true
1256 * @return object header root element
1257 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1259 private static function addHeader(DOMDocument $doc, array $owner, $filter, $feed_mode = false)
1261 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
1262 $doc->appendChild($root);
1264 $root->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
1265 $root->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
1266 $root->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
1267 $root->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
1268 $root->setAttribute("xmlns:poco", ActivityNamespace::POCO);
1269 $root->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
1270 $root->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
1271 $root->setAttribute("xmlns:mastodon", ActivityNamespace::MASTODON);
1274 $selfUri = '/feed/' . $owner["nick"] . '/';
1277 $title = L10n::t('%s\'s timeline', $owner['name']);
1278 $selfUri .= $filter;
1281 $title = L10n::t('%s\'s posts', $owner['name']);
1284 $title = L10n::t('%s\'s comments', $owner['name']);
1285 $selfUri .= $filter;
1290 $selfUri = "/dfrn_poll/" . $owner["nick"];
1293 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
1294 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1295 XML::addElement($doc, $root, "id", System::baseUrl() . "/profile/" . $owner["nick"]);
1296 XML::addElement($doc, $root, "title", $title);
1297 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], Config::get('config', 'sitename')));
1298 XML::addElement($doc, $root, "logo", $owner["photo"]);
1299 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1301 $author = self::addAuthor($doc, $owner);
1302 $root->appendChild($author);
1304 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1305 XML::addElement($doc, $root, "link", "", $attributes);
1307 /// @TODO We have to find out what this is
1308 /// $attributes = array("href" => System::baseUrl()."/sup",
1309 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1310 /// "type" => "application/json");
1311 /// XML::addElement($doc, $root, "link", "", $attributes);
1313 self::hublinks($doc, $root, $owner["nick"]);
1315 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "salmon"];
1316 XML::addElement($doc, $root, "link", "", $attributes);
1318 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies"];
1319 XML::addElement($doc, $root, "link", "", $attributes);
1321 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention"];
1322 XML::addElement($doc, $root, "link", "", $attributes);
1324 $attributes = ["href" => System::baseUrl() . $selfUri, "rel" => "self", "type" => "application/atom+xml"];
1325 XML::addElement($doc, $root, "link", "", $attributes);
1327 if ($owner['account-type'] == Contact::TYPE_COMMUNITY) {
1328 $condition = ['uid' => $owner['uid'], 'self' => false, 'pending' => false,
1329 'archive' => false, 'hidden' => false, 'blocked' => false];
1330 $members = DBA::count('contact', $condition);
1331 XML::addElement($doc, $root, "statusnet:group_info", "", ["member_count" => $members]);
1338 * @brief Add the link to the push hubs to the XML document
1340 * @param DOMDocument $doc XML document
1341 * @param object $root XML root element where the hub links are added
1342 * @param object $nick nick
1344 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1346 public static function hublinks(DOMDocument $doc, $root, $nick)
1348 $h = System::baseUrl() . '/pubsubhubbub/'.$nick;
1349 XML::addElement($doc, $root, "link", "", ["href" => $h, "rel" => "hub"]);
1353 * @brief Adds attachment data to the XML document
1355 * @param DOMDocument $doc XML document
1356 * @param object $root XML root element where the hub links are added
1357 * @param array $item Data of the item that is to be posted
1359 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1361 private static function getAttachment(DOMDocument $doc, $root, $item)
1363 $siteinfo = BBCode::getAttachedData($item["body"]);
1365 switch ($siteinfo["type"]) {
1367 if (!empty($siteinfo["image"])) {
1368 $imgdata = Images::getInfoFromURLCached($siteinfo["image"]);
1370 $attributes = ["rel" => "enclosure",
1371 "href" => $siteinfo["image"],
1372 "type" => $imgdata["mime"],
1373 "length" => intval($imgdata["size"])];
1374 XML::addElement($doc, $root, "link", "", $attributes);
1379 $attributes = ["rel" => "enclosure",
1380 "href" => $siteinfo["url"],
1381 "type" => "text/html; charset=UTF-8",
1383 "title" => ($siteinfo["title"] ?? '') ?: $siteinfo["url"],
1385 XML::addElement($doc, $root, "link", "", $attributes);
1391 if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1392 $imgdata = Images::getInfoFromURLCached($siteinfo["image"]);
1394 $attributes = ["rel" => "enclosure",
1395 "href" => $siteinfo["image"],
1396 "type" => $imgdata["mime"],
1397 "length" => intval($imgdata["size"])];
1399 XML::addElement($doc, $root, "link", "", $attributes);
1403 $arr = explode('[/attach],', $item['attach']);
1405 foreach ($arr as $r) {
1407 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1409 $attributes = ["rel" => "enclosure",
1410 "href" => $matches[1],
1411 "type" => $matches[3]];
1413 if (intval($matches[2])) {
1414 $attributes["length"] = intval($matches[2]);
1416 if (trim($matches[4]) != "") {
1417 $attributes["title"] = trim($matches[4]);
1419 XML::addElement($doc, $root, "link", "", $attributes);
1426 * @brief Adds the author element to the XML document
1428 * @param DOMDocument $doc XML document
1429 * @param array $owner Contact data of the poster
1430 * @param bool $show_profile Whether to show profile
1432 * @return \DOMElement author element
1433 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1435 private static function addAuthor(DOMDocument $doc, array $owner, $show_profile = true)
1437 $profile = DBA::selectFirst('profile', ['homepage', 'publish'], ['uid' => $owner['uid'], 'is-default' => true]);
1438 $author = $doc->createElement("author");
1439 XML::addElement($doc, $author, "id", $owner["url"]);
1440 if ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
1441 XML::addElement($doc, $author, "activity:object-type", Activity\ObjectType::GROUP);
1443 XML::addElement($doc, $author, "activity:object-type", Activity\ObjectType::PERSON);
1445 XML::addElement($doc, $author, "uri", $owner["url"]);
1446 XML::addElement($doc, $author, "name", $owner["nick"]);
1447 XML::addElement($doc, $author, "email", $owner["addr"]);
1448 if ($show_profile) {
1449 XML::addElement($doc, $author, "summary", BBCode::convert($owner["about"], false, 7));
1452 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $owner["url"]];
1453 XML::addElement($doc, $author, "link", "", $attributes);
1457 "type" => "image/jpeg", // To-Do?
1458 "media:width" => 300,
1459 "media:height" => 300,
1460 "href" => $owner["photo"]];
1461 XML::addElement($doc, $author, "link", "", $attributes);
1463 if (isset($owner["thumb"])) {
1466 "type" => "image/jpeg", // To-Do?
1467 "media:width" => 80,
1468 "media:height" => 80,
1469 "href" => $owner["thumb"]];
1470 XML::addElement($doc, $author, "link", "", $attributes);
1473 XML::addElement($doc, $author, "poco:preferredUsername", $owner["nick"]);
1474 XML::addElement($doc, $author, "poco:displayName", $owner["name"]);
1475 if ($show_profile) {
1476 XML::addElement($doc, $author, "poco:note", BBCode::convert($owner["about"], false, 7));
1478 if (trim($owner["location"]) != "") {
1479 $element = $doc->createElement("poco:address");
1480 XML::addElement($doc, $element, "poco:formatted", $owner["location"]);
1481 $author->appendChild($element);
1485 if (DBA::isResult($profile) && !$show_profile) {
1486 if (trim($profile["homepage"]) != "") {
1487 $urls = $doc->createElement("poco:urls");
1488 XML::addElement($doc, $urls, "poco:type", "homepage");
1489 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
1490 XML::addElement($doc, $urls, "poco:primary", "true");
1491 $author->appendChild($urls);
1494 XML::addElement($doc, $author, "followers", "", ["url" => System::baseUrl() . "/profile/" . $owner["nick"] . "/contacts/followers"]);
1495 XML::addElement($doc, $author, "statusnet:profile_info", "", ["local_id" => $owner["uid"]]);
1497 if ($profile["publish"]) {
1498 XML::addElement($doc, $author, "mastodon:scope", "public");
1506 * @TODO Picture attachments should look like this:
1507 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1508 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1512 * @brief Returns the given activity if present - otherwise returns the "post" activity
1514 * @param array $item Data of the item that is to be posted
1516 * @return string activity
1518 private static function constructVerb(array $item)
1520 if (!empty($item['verb'])) {
1521 return $item['verb'];
1524 return Activity::POST;
1528 * @brief Returns the given object type if present - otherwise returns the "note" object type
1530 * @param array $item Data of the item that is to be posted
1532 * @return string Object type
1534 private static function constructObjecttype(array $item)
1536 if (!empty($item['object-type']) && in_array($item['object-type'], [Activity\ObjectType::NOTE, Activity\ObjectType::COMMENT])) {
1537 return $item['object-type'];
1540 return Activity\ObjectType::NOTE;
1544 * @brief Adds an entry element to the XML document
1546 * @param DOMDocument $doc XML document
1547 * @param array $item Data of the item that is to be posted
1548 * @param array $owner Contact data of the poster
1549 * @param bool $toplevel optional default false
1550 * @param bool $feed_mode Behave like a regular feed for users if true
1552 * @return \DOMElement Entry element
1553 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1554 * @throws \ImagickException
1556 private static function entry(DOMDocument $doc, array $item, array $owner, $toplevel = false, $feed_mode = false)
1560 $repeated_guid = self::getResharedGuid($item);
1561 if ($repeated_guid != "") {
1562 $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel);
1569 if ($item["verb"] == Activity::LIKE) {
1570 return self::likeEntry($doc, $item, $owner, $toplevel);
1571 } elseif (in_array($item["verb"], [Activity::FOLLOW, Activity::O_UNFOLLOW])) {
1572 return self::followEntry($doc, $item, $owner, $toplevel);
1574 return self::noteEntry($doc, $item, $owner, $toplevel, $feed_mode);
1579 * @brief Adds a source entry to the XML document
1581 * @param DOMDocument $doc XML document
1582 * @param array $contact Array of the contact that is added
1584 * @return \DOMElement Source element
1585 * @throws \Exception
1587 private static function sourceEntry(DOMDocument $doc, array $contact)
1589 $source = $doc->createElement("source");
1590 XML::addElement($doc, $source, "id", $contact["poll"]);
1591 XML::addElement($doc, $source, "title", $contact["name"]);
1592 XML::addElement($doc, $source, "link", "", ["rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]]);
1593 XML::addElement($doc, $source, "link", "", ["rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]]);
1594 XML::addElement($doc, $source, "icon", $contact["photo"]);
1595 XML::addElement($doc, $source, "updated", DateTimeFormat::utc($contact["success_update"]."+00:00", DateTimeFormat::ATOM));
1601 * @brief Fetches contact data from the contact or the gcontact table
1603 * @param string $url URL of the contact
1604 * @param array $owner Contact data of the poster
1606 * @return array Contact array
1607 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1608 * @throws \ImagickException
1610 private static function contactEntry($url, array $owner)
1613 "SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1614 DBA::escape(Strings::normaliseLink($url)),
1615 intval($owner["uid"])
1617 if (DBA::isResult($r)) {
1619 $contact["uid"] = -1;
1622 if (!DBA::isResult($r)) {
1623 $gcontact = DBA::selectFirst('gcontact', [], ['nurl' => Strings::normaliseLink($url)]);
1624 if (DBA::isResult($r)) {
1625 $contact = $gcontact;
1626 $contact["uid"] = -1;
1627 $contact["success_update"] = $contact["updated"];
1631 if (!DBA::isResult($r)) {
1635 if (!isset($contact["poll"])) {
1636 $data = Probe::uri($url);
1637 $contact["poll"] = $data["poll"];
1639 if (!$contact["alias"]) {
1640 $contact["alias"] = $data["alias"];
1644 if (!isset($contact["alias"])) {
1645 $contact["alias"] = $contact["url"];
1648 $contact['account-type'] = $owner['account-type'];
1654 * @brief Adds an entry element with reshared content
1656 * @param DOMDocument $doc XML document
1657 * @param array $item Data of the item that is to be posted
1658 * @param array $owner Contact data of the poster
1659 * @param string $repeated_guid guid
1660 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1662 * @return bool Entry element
1663 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1664 * @throws \ImagickException
1666 private static function reshareEntry(DOMDocument $doc, array $item, array $owner, $repeated_guid, $toplevel)
1668 if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1669 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1672 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1674 $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => false,
1675 'network' => [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS]];
1676 $repeated_item = Item::selectFirst([], $condition);
1677 if (!DBA::isResult($repeated_item)) {
1681 $contact = self::contactEntry($repeated_item['author-link'], $owner);
1683 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1685 self::entryContent($doc, $entry, $item, $owner, $title, Activity::SHARE, false);
1687 $as_object = $doc->createElement("activity:object");
1689 XML::addElement($doc, $as_object, "activity:object-type", ActivityNamespace::ACTIVITY_SCHEMA . "activity");
1691 self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false);
1693 $author = self::addAuthor($doc, $contact, false);
1694 $as_object->appendChild($author);
1696 $as_object2 = $doc->createElement("activity:object");
1698 XML::addElement($doc, $as_object2, "activity:object-type", self::constructObjecttype($repeated_item));
1700 $title = sprintf("New comment by %s", $contact["nick"]);
1702 self::entryContent($doc, $as_object2, $repeated_item, $owner, $title);
1704 $as_object->appendChild($as_object2);
1706 self::entryFooter($doc, $as_object, $item, $owner, false);
1708 $source = self::sourceEntry($doc, $contact);
1710 $as_object->appendChild($source);
1712 $entry->appendChild($as_object);
1714 self::entryFooter($doc, $entry, $item, $owner);
1720 * @brief Adds an entry element with a "like"
1722 * @param DOMDocument $doc XML document
1723 * @param array $item Data of the item that is to be posted
1724 * @param array $owner Contact data of the poster
1725 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1727 * @return \DOMElement Entry element with "like"
1728 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1729 * @throws \ImagickException
1731 private static function likeEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1733 if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1734 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1737 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1739 $verb = ActivityNamespace::ACTIVITY_SCHEMA . "favorite";
1740 self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false);
1742 $parent = Item::selectFirst([], ['uri' => $item["thr-parent"], 'uid' => $item["uid"]]);
1743 if (DBA::isResult($parent)) {
1744 $as_object = $doc->createElement("activity:object");
1746 XML::addElement($doc, $as_object, "activity:object-type", self::constructObjecttype($parent));
1748 self::entryContent($doc, $as_object, $parent, $owner, "New entry");
1750 $entry->appendChild($as_object);
1753 self::entryFooter($doc, $entry, $item, $owner);
1759 * @brief Adds the person object element to the XML document
1761 * @param DOMDocument $doc XML document
1762 * @param array $owner Contact data of the poster
1763 * @param array $contact Contact data of the target
1765 * @return object author element
1767 private static function addPersonObject(DOMDocument $doc, array $owner, array $contact)
1769 $object = $doc->createElement("activity:object");
1770 XML::addElement($doc, $object, "activity:object-type", Activity\ObjectType::PERSON);
1772 if ($contact['network'] == Protocol::PHANTOM) {
1773 XML::addElement($doc, $object, "id", $contact['url']);
1777 XML::addElement($doc, $object, "id", $contact["alias"]);
1778 XML::addElement($doc, $object, "title", $contact["nick"]);
1780 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $contact["url"]];
1781 XML::addElement($doc, $object, "link", "", $attributes);
1785 "type" => "image/jpeg", // To-Do?
1786 "media:width" => 300,
1787 "media:height" => 300,
1788 "href" => $contact["photo"]];
1789 XML::addElement($doc, $object, "link", "", $attributes);
1791 XML::addElement($doc, $object, "poco:preferredUsername", $contact["nick"]);
1792 XML::addElement($doc, $object, "poco:displayName", $contact["name"]);
1794 if (trim($contact["location"]) != "") {
1795 $element = $doc->createElement("poco:address");
1796 XML::addElement($doc, $element, "poco:formatted", $contact["location"]);
1797 $object->appendChild($element);
1804 * @brief Adds a follow/unfollow entry element
1806 * @param DOMDocument $doc XML document
1807 * @param array $item Data of the follow/unfollow message
1808 * @param array $owner Contact data of the poster
1809 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1811 * @return \DOMElement Entry element
1812 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1813 * @throws \ImagickException
1815 private static function followEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1817 $item["id"] = $item["parent"] = 0;
1818 $item["created"] = $item["edited"] = date("c");
1819 $item["private"] = true;
1821 $contact = Probe::uri($item['follow']);
1823 if ($contact['alias'] == '') {
1824 $contact['alias'] = $contact["url"];
1826 $item['follow'] = $contact['alias'];
1829 $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($contact["url"])];
1830 $user_contact = DBA::selectFirst('contact', ['id'], $condition);
1832 if (DBA::isResult($user_contact)) {
1833 $connect_id = $user_contact['id'];
1838 if ($item['verb'] == Activity::FOLLOW) {
1839 $message = L10n::t('%s is now following %s.');
1840 $title = L10n::t('following');
1841 $action = "subscription";
1843 $message = L10n::t('%s stopped following %s.');
1844 $title = L10n::t('stopped following');
1845 $action = "unfollow";
1848 $item["uri"] = $item['parent-uri'] = $item['thr-parent']
1849 = 'tag:'.get_app()->getHostName().
1850 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1851 ':person:'.$connect_id.':'.$item['created'];
1853 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1855 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1857 self::entryContent($doc, $entry, $item, $owner, $title);
1859 $object = self::addPersonObject($doc, $owner, $contact);
1860 $entry->appendChild($object);
1862 self::entryFooter($doc, $entry, $item, $owner);
1868 * @brief Adds a regular entry element
1870 * @param DOMDocument $doc XML document
1871 * @param array $item Data of the item that is to be posted
1872 * @param array $owner Contact data of the poster
1873 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1874 * @param bool $feed_mode Behave like a regular feed for users if true
1876 * @return \DOMElement Entry element
1877 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1878 * @throws \ImagickException
1880 private static function noteEntry(DOMDocument $doc, array $item, array $owner, $toplevel, $feed_mode)
1882 if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1883 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1887 if (!empty($item['title'])) {
1888 $title = BBCode::convert($item['title'], false, 7);
1890 $title = sprintf("New note by %s", $owner["nick"]);
1893 $title = sprintf("New comment by %s", $owner["nick"]);
1896 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1898 XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::NOTE);
1900 self::entryContent($doc, $entry, $item, $owner, $title, '', true, $feed_mode);
1902 self::entryFooter($doc, $entry, $item, $owner, !$feed_mode, $feed_mode);
1908 * @brief Adds a header element to the XML document
1910 * @param DOMDocument $doc XML document
1911 * @param array $owner Contact data of the poster
1912 * @param array $item
1913 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1915 * @return \DOMElement The entry element where the elements are added
1916 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1917 * @throws \ImagickException
1919 private static function entryHeader(DOMDocument $doc, array $owner, array $item, $toplevel)
1922 $entry = $doc->createElement("entry");
1924 if ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
1925 $contact = self::contactEntry($item['author-link'], $owner);
1926 $author = self::addAuthor($doc, $contact, false);
1927 $entry->appendChild($author);
1930 $entry = $doc->createElementNS(ActivityNamespace::ATOM1, "entry");
1932 $entry->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
1933 $entry->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
1934 $entry->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
1935 $entry->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
1936 $entry->setAttribute("xmlns:poco", ActivityNamespace::POCO);
1937 $entry->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
1938 $entry->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
1939 $entry->setAttribute("xmlns:mastodon", ActivityNamespace::MASTODON);
1941 $author = self::addAuthor($doc, $owner);
1942 $entry->appendChild($author);
1949 * @brief Adds elements to the XML document
1951 * @param DOMDocument $doc XML document
1952 * @param \DOMElement $entry Entry element where the content is added
1953 * @param array $item Data of the item that is to be posted
1954 * @param array $owner Contact data of the poster
1955 * @param string $title Title for the post
1956 * @param string $verb The activity verb
1957 * @param bool $complete Add the "status_net" element?
1958 * @param bool $feed_mode Behave like a regular feed for users if true
1960 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1962 private static function entryContent(DOMDocument $doc, \DOMElement $entry, array $item, array $owner, $title, $verb = "", $complete = true, $feed_mode = false)
1965 $verb = self::constructVerb($item);
1968 XML::addElement($doc, $entry, "id", $item["uri"]);
1969 XML::addElement($doc, $entry, "title", html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1971 $body = self::formatPicturePost($item['body']);
1973 if (!empty($item['title']) && !$feed_mode) {
1974 $body = "[b]".$item['title']."[/b]\n\n".$body;
1977 $body = BBCode::convert($body, false, 7);
1979 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1981 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1982 "href" => System::baseUrl()."/display/".$item["guid"]]
1985 if (!$feed_mode && $complete && ($item["id"] > 0)) {
1986 XML::addElement($doc, $entry, "status_net", "", ["notice_id" => $item["id"]]);
1990 XML::addElement($doc, $entry, "activity:verb", $verb);
1993 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
1994 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
1998 * @brief Adds the elements at the foot of an entry to the XML document
2000 * @param DOMDocument $doc XML document
2001 * @param object $entry The entry element where the elements are added
2002 * @param array $item Data of the item that is to be posted
2003 * @param array $owner Contact data of the poster
2004 * @param bool $complete default true
2005 * @param bool $feed_mode Behave like a regular feed for users if true
2007 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2009 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner, $complete = true, $feed_mode = false)
2013 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
2014 $parent = Item::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item["parent"]]);
2015 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
2017 $thrparent = Item::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $parent_item]);
2019 if (DBA::isResult($thrparent)) {
2020 $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
2021 $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
2022 $parent_plink = $thrparent["plink"];
2024 $mentioned[$parent["author-link"]] = $parent["author-link"];
2025 $mentioned[$parent["owner-link"]] = $parent["owner-link"];
2026 $parent_plink = System::baseUrl()."/display/".$parent["guid"];
2030 "ref" => $parent_item,
2031 "href" => $parent_plink];
2032 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
2036 "href" => $parent_plink];
2037 XML::addElement($doc, $entry, "link", "", $attributes);
2040 if (!$feed_mode && (intval($item["parent"]) > 0)) {
2041 $conversation_href = $conversation_uri = str_replace('/objects/', '/context/', $item['parent-uri']);
2043 if (isset($parent_item)) {
2044 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $parent_item]);
2045 if (DBA::isResult($conversation)) {
2046 if ($conversation['conversation-uri'] != '') {
2047 $conversation_uri = $conversation['conversation-uri'];
2049 if ($conversation['conversation-href'] != '') {
2050 $conversation_href = $conversation['conversation-href'];
2055 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:conversation", "href" => $conversation_href]);
2058 "href" => $conversation_href,
2059 "local_id" => $item["parent"],
2060 "ref" => $conversation_uri];
2062 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
2065 $tags = item::getFeedTags($item);
2068 foreach ($tags as $t) {
2070 $mentioned[$t[1]] = $t[1];
2075 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2077 foreach ($mentioned as $mention) {
2078 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2079 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2081 $mentioned = $newmentions;
2083 foreach ($mentioned as $mention) {
2084 $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($mention)];
2085 $contact = DBA::selectFirst('contact', ['forum', 'prv', 'self', 'contact-type'], $condition);
2086 if ($contact["forum"] || $contact["prv"] || ($owner['contact-type'] == Contact::TYPE_COMMUNITY) ||
2087 ($contact['self'] && ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY))) {
2088 XML::addElement($doc, $entry, "link", "",
2090 "rel" => "mentioned",
2091 "ostatus:object-type" => Activity\ObjectType::GROUP,
2095 XML::addElement($doc, $entry, "link", "",
2097 "rel" => "mentioned",
2098 "ostatus:object-type" => Activity\ObjectType::PERSON,
2104 if ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
2105 XML::addElement($doc, $entry, "link", "", [
2106 "rel" => "mentioned",
2107 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/group",
2108 "href" => $owner['url']
2112 if (!$item["private"] && !$feed_mode) {
2113 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:attention",
2114 "href" => "http://activityschema.org/collection/public"]);
2115 XML::addElement($doc, $entry, "link", "", ["rel" => "mentioned",
2116 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2117 "href" => "http://activityschema.org/collection/public"]);
2118 XML::addElement($doc, $entry, "mastodon:scope", "public");
2122 foreach ($tags as $t) {
2124 XML::addElement($doc, $entry, "category", "", ["term" => $t[2]]);
2129 self::getAttachment($doc, $entry, $item);
2131 if ($complete && ($item["id"] > 0)) {
2132 $app = $item["app"];
2137 $attributes = ["local_id" => $item["id"], "source" => $app];
2139 if (isset($parent["id"])) {
2140 $attributes["repeat_of"] = $parent["id"];
2143 if ($item["coord"] != "") {
2144 XML::addElement($doc, $entry, "georss:point", $item["coord"]);
2147 XML::addElement($doc, $entry, "statusnet:notice_info", "", $attributes);
2152 * Creates the XML feed for a given nickname
2154 * Supported filters:
2155 * - activity (default): all the public posts
2156 * - posts: all the public top-level posts
2157 * - comments: all the public replies
2159 * Updates the provided last_update parameter if the result comes from the
2160 * cache or it is empty
2162 * @brief Creates the XML feed for a given nickname
2164 * @param string $owner_nick Nickname of the feed owner
2165 * @param string $last_update Date of the last update
2166 * @param integer $max_items Number of maximum items to fetch
2167 * @param string $filter Feed items filter (activity, posts or comments)
2168 * @param boolean $nocache Wether to bypass caching
2169 * @param boolean $feed_mode Behave like a regular feed for users if true
2171 * @return string XML feed
2172 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2173 * @throws \ImagickException
2175 public static function feed($owner_nick, &$last_update, $max_items = 300, $filter = 'activity', $nocache = false, $feed_mode = false)
2177 $stamp = microtime(true);
2179 $owner = User::getOwnerDataByNick($owner_nick);
2184 $cachekey = "ostatus:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
2186 $previous_created = $last_update;
2188 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
2189 if ((time() - strtotime($owner['last-item'])) < 15*60) {
2190 $result = Cache::get($cachekey);
2191 if (!$nocache && !is_null($result)) {
2192 Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', Logger::DEBUG);
2193 $last_update = $result['last_update'];
2194 return $result['feed'];
2198 if (!strlen($last_update)) {
2199 $last_update = 'now -30 days';
2202 $check_date = DateTimeFormat::utc($last_update);
2203 $authorid = Contact::getIdForURL($owner["url"], 0, true);
2205 $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted`
2206 AND NOT `private` AND `visible` AND `wall` AND `parent-network` IN (?, ?)",
2207 $owner["uid"], $check_date, Protocol::OSTATUS, Protocol::DFRN];
2209 if ($filter === 'comments') {
2210 $condition[0] .= " AND `object-type` = ? ";
2211 $condition[] = Activity\ObjectType::COMMENT;
2214 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
2215 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
2216 $condition[] = $owner["id"];
2217 $condition[] = $authorid;
2220 $params = ['order' => ['received' => true], 'limit' => $max_items];
2222 if ($filter === 'posts') {
2223 $ret = Item::selectThread([], $condition, $params);
2225 $ret = Item::select([], $condition, $params);
2228 $items = Item::inArray($ret);
2230 $doc = new DOMDocument('1.0', 'utf-8');
2231 $doc->formatOutput = true;
2233 $root = self::addHeader($doc, $owner, $filter, $feed_mode);
2235 foreach ($items as $item) {
2236 if (Config::get('system', 'ostatus_debug')) {
2237 $item['body'] .= '🍼';
2240 $entry = self::entry($doc, $item, $owner, false, $feed_mode);
2241 $root->appendChild($entry);
2243 if ($last_update < $item['created']) {
2244 $last_update = $item['created'];
2248 $feeddata = trim($doc->saveXML());
2250 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
2251 Cache::set($cachekey, $msg, Cache::QUARTER_HOUR);
2253 Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, Logger::DEBUG);
2259 * @brief Creates the XML for a salmon message
2261 * @param array $item Data of the item that is to be posted
2262 * @param array $owner Contact data of the poster
2264 * @return string XML for the salmon
2265 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2266 * @throws \ImagickException
2268 public static function salmon(array $item, array $owner)
2270 $doc = new DOMDocument('1.0', 'utf-8');
2271 $doc->formatOutput = true;
2273 if (Config::get('system', 'ostatus_debug')) {
2274 $item['body'] .= '🐟';
2277 $entry = self::entry($doc, $item, $owner, true);
2279 $doc->appendChild($entry);
2281 return trim($doc->saveXML());
2285 * Checks if the given contact url does support OStatus
2287 * @param string $url profile url
2288 * @param boolean $update Update the profile
2290 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2291 * @throws \ImagickException
2293 public static function isSupportedByContactUrl($url, $update = false)
2295 $probe = Probe::uri($url, Protocol::OSTATUS, 0, !$update);
2296 return $probe['network'] == Protocol::OSTATUS;