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\PConfig;
14 use Friendica\Core\L10n;
15 use Friendica\Core\Logger;
16 use Friendica\Core\Lock;
17 use Friendica\Core\Protocol;
18 use Friendica\Core\System;
19 use Friendica\Database\DBA;
20 use Friendica\Model\Contact;
21 use Friendica\Model\Conversation;
22 use Friendica\Model\GContact;
23 use Friendica\Model\APContact;
24 use Friendica\Model\Item;
25 use Friendica\Model\User;
26 use Friendica\Network\Probe;
27 use Friendica\Object\Image;
28 use Friendica\Util\DateTimeFormat;
29 use Friendica\Util\Network;
30 use Friendica\Util\Proxy as ProxyUtils;
31 use Friendica\Util\Strings;
32 use Friendica\Util\XML;
34 require_once 'mod/share.php';
35 require_once 'include/api.php';
38 * @brief This class contain functions for the OStatus protocol
42 private static $itemlist;
43 private static $conv_list = [];
46 * @brief Fetches author data
48 * @param DOMXPath $xpath The xpath object
49 * @param object $context The xml context of the author details
50 * @param array $importer user record of the importing user
51 * @param array $contact Called by reference, will contain the fetched contact
52 * @param bool $onlyfetch Only fetch the header without updating the contact entries
54 * @return array Array of author related entries for the item
55 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
56 * @throws \ImagickException
58 private static function fetchAuthor(DOMXPath $xpath, $context, array $importer, array &$contact = null, $onlyfetch)
61 $author["author-link"] = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
62 $author["author-name"] = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $context);
63 $addr = XML::getFirstNodeValue($xpath, 'atom:author/atom:email/text()', $context);
65 $aliaslink = $author["author-link"];
67 $alternate_item = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0);
68 if (is_object($alternate_item)) {
69 foreach ($alternate_item->attributes as $attributes) {
70 if (($attributes->name == "href") && ($attributes->textContent != "")) {
71 $author["author-link"] = $attributes->textContent;
75 $author["author-id"] = Contact::getIdForURL($author["author-link"]);
77 $author['contact-id'] = defaults($contact, 'id', $author['author-id']);
82 This here would be better, but we would get problems with contacts from the statusnet addon
83 This is kept here as a reminder for the future
85 $cid = Contact::getIdForURL($author["author-link"], $importer["uid"]);
87 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
90 if ($aliaslink != '') {
91 $condition = ["`uid` = ? AND `alias` = ? AND `network` != ? AND `rel` IN (?, ?)",
92 $importer["uid"], $aliaslink, Protocol::STATUSNET,
93 Contact::SHARING, Contact::FRIEND];
94 $contact = DBA::selectFirst('contact', [], $condition);
97 if (!DBA::isResult($contact) && $author["author-link"] != '') {
98 if ($aliaslink == "") {
99 $aliaslink = $author["author-link"];
102 $condition = ["`uid` = ? AND `nurl` IN (?, ?) AND `network` != ? AND `rel` IN (?, ?)",
103 $importer["uid"], Strings::normaliseLink($author["author-link"]), Strings::normaliseLink($aliaslink),
104 Protocol::STATUSNET, Contact::SHARING, Contact::FRIEND];
105 $contact = DBA::selectFirst('contact', [], $condition);
108 if (!DBA::isResult($contact) && ($addr != '')) {
109 $condition = ["`uid` = ? AND `addr` = ? AND `network` != ? AND `rel` IN (?, ?)",
110 $importer["uid"], $addr, Protocol::STATUSNET,
111 Contact::SHARING, Contact::FRIEND];
112 $contact = DBA::selectFirst('contact', [], $condition);
115 if (DBA::isResult($contact)) {
116 if ($contact['blocked']) {
118 } elseif (!empty(APContact::getByURL($contact['url'], false))) {
119 ActivityPub\Receiver::switchContact($contact['id'], $importer['uid'], $contact['url']);
121 $author["contact-id"] = $contact["id"];
125 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
126 foreach ($avatars as $avatar) {
129 foreach ($avatar->attributes as $attributes) {
130 if ($attributes->name == "href") {
131 $href = $attributes->textContent;
133 if ($attributes->name == "width") {
134 $width = $attributes->textContent;
138 $avatarlist[$width] = $href;
141 if (count($avatarlist) > 0) {
143 $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
146 $displayname = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
147 if ($displayname != "") {
148 $author["author-name"] = $displayname;
151 $author["owner-id"] = $author["author-id"];
153 // Only update the contacts if it is an OStatus contact
154 if (DBA::isResult($contact) && ($contact['id'] > 0) && !$onlyfetch && ($contact["network"] == Protocol::OSTATUS)) {
156 // Update contact data
158 unset($current['name-date']);
160 // This query doesn't seem to work
161 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
163 // $contact["notify"] = $value;
165 // This query doesn't seem to work as well - I hate these queries
166 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
168 // $contact["poll"] = $value;
170 $contact['url'] = $author["author-link"];
171 $contact['nurl'] = Strings::normaliseLink($contact['url']);
173 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
175 $contact["alias"] = $value;
178 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
180 $contact["name"] = $value;
183 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()', $context);
185 $contact["nick"] = $value;
188 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()', $context);
190 $contact["about"] = HTML::toBBCode($value);
193 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()', $context);
195 $contact["location"] = $value;
198 $contact['name-date'] = DateTimeFormat::utcNow();
200 DBA::update('contact', $contact, ['id' => $contact["id"]], $current);
202 if (!empty($author["author-avatar"]) && ($author["author-avatar"] != $current['avatar'])) {
203 Logger::log("Update profile picture for contact ".$contact["id"], Logger::DEBUG);
204 Contact::updateAvatar($author["author-avatar"], $importer["uid"], $contact["id"]);
207 // Ensure that we are having this contact (with uid=0)
208 $cid = Contact::getIdForURL($aliaslink, 0, true);
211 $fields = ['url', 'nurl', 'name', 'nick', 'alias', 'about', 'location'];
212 $old_contact = DBA::selectFirst('contact', $fields, ['id' => $cid]);
214 // Update it with the current values
215 $fields = ['url' => $author["author-link"], 'name' => $contact["name"],
216 'nurl' => Strings::normaliseLink($author["author-link"]),
217 'nick' => $contact["nick"], 'alias' => $contact["alias"],
218 'about' => $contact["about"], 'location' => $contact["location"],
219 'success_update' => DateTimeFormat::utcNow(), 'last-update' => DateTimeFormat::utcNow()];
221 DBA::update('contact', $fields, ['id' => $cid], $old_contact);
224 if (!empty($author["author-avatar"])) {
225 Contact::updateAvatar($author["author-avatar"], 0, $cid);
229 $contact["generation"] = 2;
230 $contact["hide"] = false; // OStatus contacts are never hidden
231 if (!empty($author["author-avatar"])) {
232 $contact["photo"] = $author["author-avatar"];
234 $gcid = GContact::update($contact);
236 GContact::link($gcid, $contact["uid"], $contact["id"]);
237 } elseif ($contact["network"] != Protocol::DFRN) {
245 * @brief Fetches author data from a given XML string
247 * @param string $xml The XML
248 * @param array $importer user record of the importing user
250 * @return array Array of author related entries for the item
251 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
252 * @throws \ImagickException
254 public static function salmonAuthor($xml, array $importer)
260 $doc = new DOMDocument();
261 @$doc->loadXML($xml);
263 $xpath = new DOMXPath($doc);
264 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
265 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
266 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
267 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
268 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
269 $xpath->registerNamespace('poco', NAMESPACE_POCO);
270 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
271 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
273 $contact = ["id" => 0];
275 // Fetch the first author
276 $authordata = $xpath->query('//author')->item(0);
277 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, true);
282 * @brief Read attributes from element
284 * @param object $element Element object
286 * @return array attributes
288 private static function readAttributes($element)
292 foreach ($element->attributes as $attributes) {
293 $attribute[$attributes->name] = $attributes->textContent;
300 * @brief Imports an XML string containing OStatus elements
302 * @param string $xml The XML
303 * @param array $importer user record of the importing user
304 * @param array $contact contact
305 * @param string $hub Called by reference, returns the fetched hub data
307 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
308 * @throws \ImagickException
310 public static function import($xml, array $importer, array &$contact, &$hub)
312 self::process($xml, $importer, $contact, $hub);
316 * @brief Internal feed processing
318 * @param string $xml The XML
319 * @param array $importer user record of the importing user
320 * @param array $contact contact
321 * @param string $hub Called by reference, returns the fetched hub data
322 * @param boolean $stored Is the post fresh imported or from the database?
323 * @param boolean $initialize Is it the leading post so that data has to be initialized?
325 * @return boolean Could the XML be processed?
326 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
327 * @throws \ImagickException
329 private static function process($xml, array $importer, array &$contact = null, &$hub, $stored = false, $initialize = true)
332 self::$itemlist = [];
333 self::$conv_list = [];
336 Logger::log('Import OStatus message for user ' . $importer['uid'], Logger::DEBUG);
341 $doc = new DOMDocument();
342 @$doc->loadXML($xml);
344 $xpath = new DOMXPath($doc);
345 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
346 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
347 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
348 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
349 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
350 $xpath->registerNamespace('poco', NAMESPACE_POCO);
351 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
352 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
355 $hub_items = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0);
356 if (is_object($hub_items)) {
357 $hub_attributes = $hub_items->attributes;
358 if (is_object($hub_attributes)) {
359 foreach ($hub_attributes as $hub_attribute) {
360 if ($hub_attribute->name == "href") {
361 $hub = $hub_attribute->textContent;
362 Logger::log("Found hub ".$hub, Logger::DEBUG);
369 $header["uid"] = $importer["uid"];
370 $header["network"] = Protocol::OSTATUS;
372 $header["origin"] = 0;
373 $header["gravity"] = GRAVITY_COMMENT;
375 if (!is_object($doc->firstChild) || empty($doc->firstChild->tagName)) {
379 $first_child = $doc->firstChild->tagName;
381 if ($first_child == "feed") {
382 $entries = $xpath->query('/atom:feed/atom:entry');
384 $entries = $xpath->query('/atom:entry');
387 if ($entries->length == 1) {
388 // We reformat the XML to make it better readable
389 $doc2 = new DOMDocument();
390 $doc2->loadXML($xml);
391 $doc2->preserveWhiteSpace = false;
392 $doc2->formatOutput = true;
393 $xml2 = $doc2->saveXML();
395 $header["protocol"] = Conversation::PARCEL_SALMON;
396 $header["source"] = $xml2;
397 } elseif (!$initialize) {
401 // Fetch the first author
402 $authordata = $xpath->query('//author')->item(0);
403 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, $stored);
405 // Reverse the order of the entries
408 foreach ($entries as $entry) {
409 $entrylist[] = $entry;
412 foreach (array_reverse($entrylist) as $entry) {
414 $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
416 if ($authorelement->length == 0) {
417 $authorelement = $xpath->query('atom:author', $entry);
420 if ($authorelement->length > 0) {
421 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, $stored);
424 $item = array_merge($header, $author);
426 $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
428 $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $entry);
431 if (in_array($item["verb"], ['qvitter-delete-notice', ACTIVITY_DELETE, 'delete'])) {
432 self::deleteNotice($item);
436 if (in_array($item["verb"], [NAMESPACE_OSTATUS."/unfavorite", ACTIVITY_UNFAVORITE])) {
437 // Ignore "Unfavorite" message
438 Logger::log("Ignore unfavorite message ".print_r($item, true), Logger::DEBUG);
442 // Deletions come with the same uri, so we check for duplicates after processing deletions
443 if (Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]])) {
444 Logger::log('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', Logger::DEBUG);
447 Logger::log('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', Logger::DEBUG);
450 if ($item["verb"] == ACTIVITY_JOIN) {
451 // ignore "Join" messages
452 Logger::log("Ignore join message ".print_r($item, true), Logger::DEBUG);
456 if ($item["verb"] == "http://mastodon.social/schema/1.0/block") {
457 // ignore mastodon "block" messages
458 Logger::log("Ignore block message ".print_r($item, true), Logger::DEBUG);
462 if ($item["verb"] == ACTIVITY_FOLLOW) {
463 Contact::addRelationship($importer, $contact, $item);
467 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
469 Contact::removeFollower($importer, $contact, $item, $dummy);
473 if ($item["verb"] == ACTIVITY_FAVORITE) {
474 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
475 Logger::log("Favorite ".$orig_uri." ".print_r($item, true));
477 $item["verb"] = ACTIVITY_LIKE;
478 $item["parent-uri"] = $orig_uri;
479 $item["gravity"] = GRAVITY_ACTIVITY;
480 $item["object-type"] = ACTIVITY_OBJ_NOTE;
483 // http://activitystrea.ms/schema/1.0/rsvp-yes
484 if (!in_array($item["verb"], [ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE])) {
485 Logger::log("Unhandled verb ".$item["verb"]." ".print_r($item, true), Logger::DEBUG);
488 self::processPost($xpath, $entry, $item, $importer);
490 if ($initialize && (count(self::$itemlist) > 0)) {
491 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['parent-uri']) {
492 // We will import it everytime, when it is started by our contacts
493 $valid = Contact::isSharingByURL(self::$itemlist[0]['author-link'], self::$itemlist[0]['uid']);
496 // If not, then it depends on this setting
497 $valid = ((self::$itemlist[0]['uid'] == 0) || !PConfig::get(self::$itemlist[0]['uid'], 'system', 'accept_only_sharer', false));
499 Logger::log("Item with uri ".self::$itemlist[0]['uri']." will be imported due to the system settings.", Logger::DEBUG);
502 Logger::log("Item with uri ".self::$itemlist[0]['uri']." belongs to a contact (".self::$itemlist[0]['contact-id']."). It will be imported.", Logger::DEBUG);
505 // Never post a thread when the only interaction by our contact was a like
507 $verbs = [ACTIVITY_POST, ACTIVITY_SHARE];
508 foreach (self::$itemlist as $item) {
509 if (in_array($item['verb'], $verbs) && Contact::isSharingByURL($item['author-link'], $item['uid'])) {
514 Logger::log("Item with uri ".self::$itemlist[0]['uri']." will be imported since the thread contains posts or shares.", Logger::DEBUG);
518 // But we will only import complete threads
519 $valid = Item::exists(['uid' => $importer["uid"], 'uri' => self::$itemlist[0]['parent-uri']]);
521 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);
526 $default_contact = 0;
527 for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
528 if (empty(self::$itemlist[$key]['contact-id'])) {
529 self::$itemlist[$key]['contact-id'] = $default_contact;
531 $default_contact = $item['contact-id'];
534 foreach (self::$itemlist as $item) {
535 $found = Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]]);
537 Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", Logger::DEBUG);
538 } elseif ($item['contact-id'] < 0) {
539 Logger::log("Item with uri ".$item["uri"]." is from a blocked contact.", Logger::DEBUG);
541 // We are having duplicated entries. Hopefully this solves it.
542 if (Lock::acquire('ostatus_process_item_insert')) {
543 $ret = Item::insert($item);
544 Lock::release('ostatus_process_item_insert');
545 Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret);
547 $ret = Item::insert($item);
548 Logger::log("We couldn't lock - but tried to store the item anyway. Return value is ".$ret);
553 self::$itemlist = [];
555 Logger::log('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.', Logger::DEBUG);
561 * Removes notice item from database
563 * @param array $item item
567 private static function deleteNotice(array $item)
569 $condition = ['uid' => $item['uid'], 'author-id' => $item['author-id'], 'uri' => $item['uri']];
570 if (!Item::exists($condition)) {
571 Logger::log('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it.");
575 Item::delete($condition);
577 Logger::log('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
581 * @brief Processes the XML for a post
583 * @param DOMXPath $xpath The xpath object
584 * @param object $entry The xml entry that is processed
585 * @param array $item The item array
586 * @param array $importer user record of the importing user
588 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
589 * @throws \ImagickException
591 private static function processPost(DOMXPath $xpath, $entry, array &$item, array $importer)
593 $item["body"] = HTML::toBBCode(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
594 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $entry);
595 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) || ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
596 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
597 $item["body"] = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
598 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
599 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
602 $item["created"] = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
603 $item["edited"] = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
604 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
606 $conv = $xpath->query('ostatus:conversation', $entry);
607 if (is_object($conv->item(0))) {
608 foreach ($conv->item(0)->attributes as $attributes) {
609 if ($attributes->name == "ref") {
610 $item['conversation-uri'] = $attributes->textContent;
612 if ($attributes->name == "href") {
613 $item['conversation-href'] = $attributes->textContent;
620 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
621 if (is_object($inreplyto->item(0))) {
622 foreach ($inreplyto->item(0)->attributes as $attributes) {
623 if ($attributes->name == "ref") {
624 $item["parent-uri"] = $attributes->textContent;
626 if ($attributes->name == "href") {
627 $related = $attributes->textContent;
632 $georsspoint = $xpath->query('georss:point', $entry);
633 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
634 $item["coord"] = $georsspoint->item(0)->nodeValue;
637 $categories = $xpath->query('atom:category', $entry);
639 foreach ($categories as $category) {
640 foreach ($category->attributes as $attributes) {
641 if ($attributes->name == 'term') {
642 $term = $attributes->textContent;
643 if (!empty($item['tag'])) {
649 $item['tag'] .= '#[url=' . System::baseUrl() . '/search?tag=' . $term . ']' . $term . '[/url]';
658 $links = $xpath->query('atom:link', $entry);
660 $link_data = self::processLinks($links, $item);
661 $self = $link_data['self'];
662 $add_body = $link_data['add_body'];
667 $notice_info = $xpath->query('statusnet:notice_info', $entry);
668 if ($notice_info && ($notice_info->length > 0)) {
669 foreach ($notice_info->item(0)->attributes as $attributes) {
670 if ($attributes->name == "source") {
671 $item["app"] = strip_tags($attributes->textContent);
673 if ($attributes->name == "repeat_of") {
674 $repeat_of = $attributes->textContent;
678 // Is it a repeated post?
679 if (($repeat_of != "") || ($item["verb"] == ACTIVITY_SHARE)) {
680 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
681 if (!empty($link_data['add_body'])) {
682 $add_body .= $link_data['add_body'];
686 $item["body"] .= $add_body;
688 // Only add additional data when there is no picture in the post
689 if (!strstr($item["body"], '[/img]')) {
690 $item["body"] = add_page_info_to_body($item["body"]);
693 // Mastodon Content Warning
694 if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
695 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
696 if (!empty($clear_text)) {
697 $item['content-warning'] = HTML::toBBCode($clear_text);
701 if (($self != '') && empty($item['protocol'])) {
702 self::fetchSelf($self, $item);
705 if (!empty($item["conversation-href"])) {
706 self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
709 if (isset($item["parent-uri"])) {
710 if (!Item::exists(['uid' => $importer["uid"], 'uri' => $item['parent-uri']])) {
711 if ($related != '') {
712 self::fetchRelated($related, $item["parent-uri"], $importer);
715 Logger::log('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', Logger::DEBUG);
718 $item["parent-uri"] = $item["uri"];
719 $item["gravity"] = GRAVITY_PARENT;
722 if (($item['author-link'] != '') && !empty($item['protocol'])) {
723 $item = Conversation::insert($item);
726 self::$itemlist[] = $item;
730 * @brief Fetch the conversation for posts
732 * @param string $conversation The link to the conversation
733 * @param string $conversation_uri The conversation in "uri" format
735 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
737 private static function fetchConversation($conversation, $conversation_uri)
739 // Ensure that we only store a conversation once in a process
740 if (isset(self::$conv_list[$conversation])) {
744 self::$conv_list[$conversation] = true;
746 $curlResult = Network::curl($conversation, false, ['accept_content' => 'application/atom+xml, text/html']);
748 if (!$curlResult->isSuccess()) {
754 if (stristr($curlResult->getHeader(), 'Content-Type: application/atom+xml')) {
755 $xml = $curlResult->getBody();
759 $doc = new DOMDocument();
760 if (!@$doc->loadHTML($curlResult->getBody())) {
763 $xpath = new DOMXPath($doc);
765 $links = $xpath->query('//link');
768 foreach ($links as $link) {
769 $attribute = self::readAttributes($link);
770 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
771 $file = $attribute['href'];
775 $conversation_atom = Network::curl($attribute['href']);
777 if ($conversation_atom->isSuccess()) {
778 $xml = $conversation_atom->getBody();
788 self::storeConversation($xml, $conversation, $conversation_uri);
792 * @brief Store a feed in several conversation entries
794 * @param string $xml The feed
795 * @param string $conversation conversation
796 * @param string $conversation_uri conversation uri
800 private static function storeConversation($xml, $conversation = '', $conversation_uri = '')
802 $doc = new DOMDocument();
803 @$doc->loadXML($xml);
805 $xpath = new DOMXPath($doc);
806 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
807 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
808 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
810 $entries = $xpath->query('/atom:feed/atom:entry');
812 // Now store the entries
813 foreach ($entries as $entry) {
814 $doc2 = new DOMDocument();
815 $doc2->preserveWhiteSpace = false;
816 $doc2->formatOutput = true;
820 $conv_data['protocol'] = Conversation::PARCEL_SPLIT_CONVERSATION;
821 $conv_data['network'] = Protocol::OSTATUS;
822 $conv_data['uri'] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
824 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
825 if (is_object($inreplyto->item(0))) {
826 foreach ($inreplyto->item(0)->attributes as $attributes) {
827 if ($attributes->name == "ref") {
828 $conv_data['reply-to-uri'] = $attributes->textContent;
833 $conv_data['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
835 $conv = $xpath->query('ostatus:conversation', $entry);
836 if (is_object($conv->item(0))) {
837 foreach ($conv->item(0)->attributes as $attributes) {
838 if ($attributes->name == "ref") {
839 $conv_data['conversation-uri'] = $attributes->textContent;
841 if ($attributes->name == "href") {
842 $conv_data['conversation-href'] = $attributes->textContent;
847 if ($conversation != '') {
848 $conv_data['conversation-uri'] = $conversation;
851 if ($conversation_uri != '') {
852 $conv_data['conversation-uri'] = $conversation_uri;
855 $entry = $doc2->importNode($entry, true);
857 $doc2->appendChild($entry);
859 $conv_data['source'] = $doc2->saveXML();
861 $condition = ['item-uri' => $conv_data['uri'],'protocol' => Conversation::PARCEL_FEED];
862 if (DBA::exists('conversation', $condition)) {
863 Logger::log('Delete deprecated entry for URI '.$conv_data['uri'], Logger::DEBUG);
864 DBA::delete('conversation', ['item-uri' => $conv_data['uri']]);
867 Logger::log('Store conversation data for uri '.$conv_data['uri'], Logger::DEBUG);
868 Conversation::insert($conv_data);
873 * @brief Fetch the own post so that it can be stored later
875 * We want to store the original data for later processing.
876 * This function is meant for cases where we process a feed with multiple entries.
877 * In that case we need to fetch the single posts here.
879 * @param string $self The link to the self item
880 * @param array $item The item array
882 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
884 private static function fetchSelf($self, array &$item)
886 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $self, Conversation::PARCEL_DFRN, Conversation::PARCEL_SALMON];
887 if (DBA::exists('conversation', $condition)) {
888 Logger::log('Conversation '.$item['uri'].' is already stored.', Logger::DEBUG);
892 $curlResult = Network::curl($self);
894 if (!$curlResult->isSuccess()) {
898 // We reformat the XML to make it better readable
899 $doc = new DOMDocument();
900 $doc->loadXML($curlResult->getBody());
901 $doc->preserveWhiteSpace = false;
902 $doc->formatOutput = true;
903 $xml = $doc->saveXML();
905 $item["protocol"] = Conversation::PARCEL_SALMON;
906 $item["source"] = $xml;
908 Logger::log('Conversation '.$item['uri'].' is now fetched.', Logger::DEBUG);
912 * @brief Fetch related posts and processes them
914 * @param string $related The link to the related item
915 * @param string $related_uri The related item in "uri" format
916 * @param array $importer user record of the importing user
918 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
919 * @throws \ImagickException
921 private static function fetchRelated($related, $related_uri, $importer)
923 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, Conversation::PARCEL_DFRN, Conversation::PARCEL_SALMON];
924 $conversation = DBA::selectFirst('conversation', ['source', 'protocol'], $condition);
925 if (DBA::isResult($conversation)) {
927 $xml = $conversation['source'];
928 if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
929 Logger::log('Got valid cached XML for URI '.$related_uri, Logger::DEBUG);
932 if ($conversation['protocol'] == Conversation::PARCEL_SALMON) {
933 Logger::log('Delete invalid cached XML for URI '.$related_uri, Logger::DEBUG);
934 DBA::delete('conversation', ['item-uri' => $related_uri]);
939 $curlResult = Network::curl($related, false, ['accept_content' => 'application/atom+xml, text/html']);
941 if (!$curlResult->isSuccess()) {
947 if (stristr($curlResult->getHeader(), 'Content-Type: application/atom+xml')) {
948 Logger::log('Directly fetched XML for URI ' . $related_uri, Logger::DEBUG);
949 $xml = $curlResult->getBody();
953 $doc = new DOMDocument();
954 if (!@$doc->loadHTML($curlResult->getBody())) {
957 $xpath = new DOMXPath($doc);
961 $links = $xpath->query('//link');
963 foreach ($links as $link) {
964 $attribute = self::readAttributes($link);
965 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
966 $atom_file = $attribute['href'];
969 if ($atom_file != '') {
970 $curlResult = Network::curl($atom_file);
972 if ($curlResult->isSuccess()) {
973 Logger::log('Fetched XML for URI ' . $related_uri, Logger::DEBUG);
974 $xml = $curlResult->getBody();
980 // Workaround for older GNU Social servers
981 if (($xml == '') && strstr($related, '/notice/')) {
982 $curlResult = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related).'.atom');
984 if ($curlResult->isSuccess()) {
985 Logger::log('GNU Social workaround to fetch XML for URI ' . $related_uri, Logger::DEBUG);
986 $xml = $curlResult->getBody();
990 // Even more worse workaround for GNU Social ;-)
992 $related_guess = OStatus::convertHref($related_uri);
993 $curlResult = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related_guess).'.atom');
995 if ($curlResult->isSuccess()) {
996 Logger::log('GNU Social workaround 2 to fetch XML for URI ' . $related_uri, Logger::DEBUG);
997 $xml = $curlResult->getBody();
1001 // Finally we take the data that we fetched from "ostatus:conversation"
1003 $condition = ['item-uri' => $related_uri, 'protocol' => Conversation::PARCEL_SPLIT_CONVERSATION];
1004 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1005 if (DBA::isResult($conversation)) {
1007 Logger::log('Got cached XML from conversation for URI '.$related_uri, Logger::DEBUG);
1008 $xml = $conversation['source'];
1013 self::process($xml, $importer, $contact, $hub, $stored, false);
1015 Logger::log("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, Logger::DEBUG);
1021 * @brief Processes the XML for a repeated post
1023 * @param DOMXPath $xpath The xpath object
1024 * @param object $entry The xml entry that is processed
1025 * @param array $item The item array
1026 * @param array $importer user record of the importing user
1028 * @return array with data from links
1029 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1030 * @throws \ImagickException
1032 private static function processRepeatedItem(DOMXPath $xpath, $entry, array &$item, array $importer)
1034 $activityobject = $xpath->query('activity:object', $entry)->item(0);
1036 if (!is_object($activityobject)) {
1042 $orig_uri = XML::getFirstNodeValue($xpath, 'atom:id/text()', $activityobject);
1044 $links = $xpath->query("atom:link", $activityobject);
1046 $link_data = self::processLinks($links, $item);
1049 $orig_body = XML::getFirstNodeValue($xpath, 'atom:content/text()', $activityobject);
1050 $orig_created = XML::getFirstNodeValue($xpath, 'atom:published/text()', $activityobject);
1051 $orig_edited = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $activityobject);
1053 $orig_author = self::fetchAuthor($xpath, $activityobject, $importer, $dummy, false);
1055 $item["author-name"] = $orig_author["author-name"];
1056 $item["author-link"] = $orig_author["author-link"];
1057 $item["author-id"] = $orig_author["author-id"];
1059 $item["body"] = HTML::toBBCode($orig_body);
1060 $item["created"] = $orig_created;
1061 $item["edited"] = $orig_edited;
1063 $item["uri"] = $orig_uri;
1065 $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $activityobject);
1067 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $activityobject);
1069 // Mastodon Content Warning
1070 if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $activityobject)) {
1071 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $activityobject);
1072 if (!empty($clear_text)) {
1073 $item['content-warning'] = HTML::toBBCode($clear_text);
1077 $inreplyto = $xpath->query('thr:in-reply-to', $activityobject);
1078 if (is_object($inreplyto->item(0))) {
1079 foreach ($inreplyto->item(0)->attributes as $attributes) {
1080 if ($attributes->name == "ref") {
1081 $item["parent-uri"] = $attributes->textContent;
1090 * @brief Processes links in the XML
1092 * @param object $links The xml data that contain links
1093 * @param array $item The item array
1095 * @return array with data from the links
1097 private static function processLinks($links, array &$item)
1099 $link_data = ['add_body' => '', 'self' => ''];
1101 foreach ($links as $link) {
1102 $attribute = self::readAttributes($link);
1104 if (!empty($attribute['rel']) && !empty($attribute['href'])) {
1105 switch ($attribute['rel']) {
1107 $item["plink"] = $attribute['href'];
1108 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION)
1109 || ($item["object-type"] == ACTIVITY_OBJ_EVENT)
1111 $item["body"] .= add_page_info($attribute['href']);
1114 case "ostatus:conversation":
1115 $link_data['conversation'] = $attribute['href'];
1116 $item['conversation-href'] = $link_data['conversation'];
1117 if (!isset($item['conversation-uri'])) {
1118 $item['conversation-uri'] = $item['conversation-href'];
1122 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
1123 if ($filetype == 'image') {
1124 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1126 if (!empty($item["attach"])) {
1127 $item["attach"] .= ',';
1129 $item["attach"] = '';
1131 if (!isset($attribute['length'])) {
1132 $attribute['length'] = "0";
1134 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.defaults($attribute, 'title', '').'"[/attach]';
1138 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
1139 if (!isset($item["parent-uri"])) {
1140 $item["parent-uri"] = $attribute['href'];
1142 $link_data['related'] = $attribute['href'];
1144 $item["body"] .= add_page_info($attribute['href']);
1148 if (empty($item["plink"])) {
1149 $item["plink"] = $attribute['href'];
1151 $link_data['self'] = $attribute['href'];
1160 * @brief Create an url out of an uri
1162 * @param string $href URI in the format "parameter1:parameter1:..."
1164 * @return string URL in the format http(s)://....
1166 public static function convertHref($href)
1168 $elements = explode(":", $href);
1170 if ((count($elements) <= 2) || ($elements[0] != "tag")) {
1174 $server = explode(",", $elements[1]);
1175 $conversation = explode("=", $elements[2]);
1177 if ((count($elements) == 4) && ($elements[2] == "post")) {
1178 return "http://".$server[0]."/notice/".$elements[3];
1181 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1184 if ($elements[3] == "objectType=thread") {
1185 return "http://".$server[0]."/conversation/".$conversation[1];
1187 return "http://".$server[0]."/notice/".$conversation[1];
1192 * @brief Checks if the current post is a reshare
1194 * @param array $item The item array of thw post
1196 * @return string The guid if the post is a reshare
1198 private static function getResharedGuid(array $item)
1200 $body = trim($item["body"]);
1202 // Skip if it isn't a pure repeated messages
1203 // Does it start with a share?
1204 if (strpos($body, "[share") > 0) {
1208 // Does it end with a share?
1209 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
1213 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
1214 // Skip if there is no shared message in there
1215 if ($body == $attributes) {
1220 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1221 if (!empty($matches[1])) {
1222 $guid = $matches[1];
1225 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1226 if (!empty($matches[1])) {
1227 $guid = $matches[1];
1234 * @brief Cleans the body of a post if it contains picture links
1236 * @param string $body The body
1238 * @return string The cleaned body
1239 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1241 private static function formatPicturePost($body)
1243 $siteinfo = BBCode::getAttachedData($body);
1245 if (($siteinfo["type"] == "photo") && (!empty($siteinfo["preview"]) || !empty($siteinfo["image"]))) {
1246 if (isset($siteinfo["preview"])) {
1247 $preview = $siteinfo["preview"];
1249 $preview = $siteinfo["image"];
1252 // Is it a remote picture? Then make a smaller preview here
1253 $preview = ProxyUtils::proxifyUrl($preview, false, ProxyUtils::SIZE_SMALL);
1255 // Is it a local picture? Then make it smaller here
1256 $preview = str_replace(["-0.jpg", "-0.png"], ["-2.jpg", "-2.png"], $preview);
1257 $preview = str_replace(["-1.jpg", "-1.png"], ["-2.jpg", "-2.png"], $preview);
1259 if (isset($siteinfo["url"])) {
1260 $url = $siteinfo["url"];
1262 $url = $siteinfo["image"];
1265 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1272 * @brief Adds the header elements to the XML document
1274 * @param DOMDocument $doc XML document
1275 * @param array $owner Contact data of the poster
1276 * @param string $filter The related feed filter (activity, posts or comments)
1277 * @param bool $feed_mode Behave like a regular feed for users if true
1279 * @return object header root element
1280 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1282 private static function addHeader(DOMDocument $doc, array $owner, $filter, $feed_mode = false)
1284 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1285 $doc->appendChild($root);
1287 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1288 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1289 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1290 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1291 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1292 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1293 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1294 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1297 $selfUri = '/feed/' . $owner["nick"] . '/';
1300 $title = L10n::t('%s\'s timeline', $owner['name']);
1301 $selfUri .= $filter;
1304 $title = L10n::t('%s\'s posts', $owner['name']);
1307 $title = L10n::t('%s\'s comments', $owner['name']);
1308 $selfUri .= $filter;
1313 $selfUri = "/dfrn_poll/" . $owner["nick"];
1316 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
1317 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1318 XML::addElement($doc, $root, "id", System::baseUrl() . "/profile/" . $owner["nick"]);
1319 XML::addElement($doc, $root, "title", $title);
1320 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], Config::get('config', 'sitename')));
1321 XML::addElement($doc, $root, "logo", $owner["photo"]);
1322 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1324 $author = self::addAuthor($doc, $owner);
1325 $root->appendChild($author);
1327 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1328 XML::addElement($doc, $root, "link", "", $attributes);
1330 /// @TODO We have to find out what this is
1331 /// $attributes = array("href" => System::baseUrl()."/sup",
1332 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1333 /// "type" => "application/json");
1334 /// XML::addElement($doc, $root, "link", "", $attributes);
1336 self::hublinks($doc, $root, $owner["nick"]);
1338 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "salmon"];
1339 XML::addElement($doc, $root, "link", "", $attributes);
1341 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies"];
1342 XML::addElement($doc, $root, "link", "", $attributes);
1344 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention"];
1345 XML::addElement($doc, $root, "link", "", $attributes);
1347 $attributes = ["href" => System::baseUrl() . $selfUri, "rel" => "self", "type" => "application/atom+xml"];
1348 XML::addElement($doc, $root, "link", "", $attributes);
1350 if ($owner['account-type'] == Contact::TYPE_COMMUNITY) {
1351 $condition = ['uid' => $owner['uid'], 'self' => false, 'pending' => false,
1352 'archive' => false, 'hidden' => false, 'blocked' => false];
1353 $members = DBA::count('contact', $condition);
1354 XML::addElement($doc, $root, "statusnet:group_info", "", ["member_count" => $members]);
1361 * @brief Add the link to the push hubs to the XML document
1363 * @param DOMDocument $doc XML document
1364 * @param object $root XML root element where the hub links are added
1365 * @param object $nick nick
1367 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1369 public static function hublinks(DOMDocument $doc, $root, $nick)
1371 $h = System::baseUrl() . '/pubsubhubbub/'.$nick;
1372 XML::addElement($doc, $root, "link", "", ["href" => $h, "rel" => "hub"]);
1376 * @brief Adds attachment data to the XML document
1378 * @param DOMDocument $doc XML document
1379 * @param object $root XML root element where the hub links are added
1380 * @param array $item Data of the item that is to be posted
1382 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1384 private static function getAttachment(DOMDocument $doc, $root, $item)
1386 $siteinfo = BBCode::getAttachedData($item["body"]);
1388 switch ($siteinfo["type"]) {
1390 if (!empty($siteinfo["image"])) {
1391 $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1393 $attributes = ["rel" => "enclosure",
1394 "href" => $siteinfo["image"],
1395 "type" => $imgdata["mime"],
1396 "length" => intval($imgdata["size"])];
1397 XML::addElement($doc, $root, "link", "", $attributes);
1402 $attributes = ["rel" => "enclosure",
1403 "href" => $siteinfo["url"],
1404 "type" => "text/html; charset=UTF-8",
1406 "title" => defaults($siteinfo, "title", $siteinfo["url"])];
1407 XML::addElement($doc, $root, "link", "", $attributes);
1413 if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1414 $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1416 $attributes = ["rel" => "enclosure",
1417 "href" => $siteinfo["image"],
1418 "type" => $imgdata["mime"],
1419 "length" => intval($imgdata["size"])];
1421 XML::addElement($doc, $root, "link", "", $attributes);
1425 $arr = explode('[/attach],', $item['attach']);
1427 foreach ($arr as $r) {
1429 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1431 $attributes = ["rel" => "enclosure",
1432 "href" => $matches[1],
1433 "type" => $matches[3]];
1435 if (intval($matches[2])) {
1436 $attributes["length"] = intval($matches[2]);
1438 if (trim($matches[4]) != "") {
1439 $attributes["title"] = trim($matches[4]);
1441 XML::addElement($doc, $root, "link", "", $attributes);
1448 * @brief Adds the author element to the XML document
1450 * @param DOMDocument $doc XML document
1451 * @param array $owner Contact data of the poster
1452 * @param bool $show_profile Whether to show profile
1454 * @return \DOMElement author element
1455 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1457 private static function addAuthor(DOMDocument $doc, array $owner, $show_profile = true)
1459 $profile = DBA::selectFirst('profile', ['homepage', 'publish'], ['uid' => $owner['uid'], 'is-default' => true]);
1460 $author = $doc->createElement("author");
1461 XML::addElement($doc, $author, "id", $owner["url"]);
1462 if ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
1463 XML::addElement($doc, $author, "activity:object-type", ACTIVITY_OBJ_GROUP);
1465 XML::addElement($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1467 XML::addElement($doc, $author, "uri", $owner["url"]);
1468 XML::addElement($doc, $author, "name", $owner["nick"]);
1469 XML::addElement($doc, $author, "email", $owner["addr"]);
1470 if ($show_profile) {
1471 XML::addElement($doc, $author, "summary", BBCode::convert($owner["about"], false, 7));
1474 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $owner["url"]];
1475 XML::addElement($doc, $author, "link", "", $attributes);
1479 "type" => "image/jpeg", // To-Do?
1480 "media:width" => 300,
1481 "media:height" => 300,
1482 "href" => $owner["photo"]];
1483 XML::addElement($doc, $author, "link", "", $attributes);
1485 if (isset($owner["thumb"])) {
1488 "type" => "image/jpeg", // To-Do?
1489 "media:width" => 80,
1490 "media:height" => 80,
1491 "href" => $owner["thumb"]];
1492 XML::addElement($doc, $author, "link", "", $attributes);
1495 XML::addElement($doc, $author, "poco:preferredUsername", $owner["nick"]);
1496 XML::addElement($doc, $author, "poco:displayName", $owner["name"]);
1497 if ($show_profile) {
1498 XML::addElement($doc, $author, "poco:note", BBCode::convert($owner["about"], false, 7));
1500 if (trim($owner["location"]) != "") {
1501 $element = $doc->createElement("poco:address");
1502 XML::addElement($doc, $element, "poco:formatted", $owner["location"]);
1503 $author->appendChild($element);
1507 if (DBA::isResult($profile) && !$show_profile) {
1508 if (trim($profile["homepage"]) != "") {
1509 $urls = $doc->createElement("poco:urls");
1510 XML::addElement($doc, $urls, "poco:type", "homepage");
1511 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
1512 XML::addElement($doc, $urls, "poco:primary", "true");
1513 $author->appendChild($urls);
1516 XML::addElement($doc, $author, "followers", "", ["url" => System::baseUrl() . "/profile/" . $owner["nick"] . "/contacts/followers"]);
1517 XML::addElement($doc, $author, "statusnet:profile_info", "", ["local_id" => $owner["uid"]]);
1519 if ($profile["publish"]) {
1520 XML::addElement($doc, $author, "mastodon:scope", "public");
1528 * @TODO Picture attachments should look like this:
1529 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1530 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1534 * @brief Returns the given activity if present - otherwise returns the "post" activity
1536 * @param array $item Data of the item that is to be posted
1538 * @return string activity
1540 private static function constructVerb(array $item)
1542 if (!empty($item['verb'])) {
1543 return $item['verb'];
1546 return ACTIVITY_POST;
1550 * @brief Returns the given object type if present - otherwise returns the "note" object type
1552 * @param array $item Data of the item that is to be posted
1554 * @return string Object type
1556 private static function constructObjecttype(array $item)
1558 if (!empty($item['object-type']) && in_array($item['object-type'], [ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT])) {
1559 return $item['object-type'];
1562 return ACTIVITY_OBJ_NOTE;
1566 * @brief Adds an entry element to the XML document
1568 * @param DOMDocument $doc XML document
1569 * @param array $item Data of the item that is to be posted
1570 * @param array $owner Contact data of the poster
1571 * @param bool $toplevel optional default false
1572 * @param bool $feed_mode Behave like a regular feed for users if true
1574 * @return \DOMElement Entry element
1575 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1576 * @throws \ImagickException
1578 private static function entry(DOMDocument $doc, array $item, array $owner, $toplevel = false, $feed_mode = false)
1582 $repeated_guid = self::getResharedGuid($item);
1583 if ($repeated_guid != "") {
1584 $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel);
1591 if ($item["verb"] == ACTIVITY_LIKE) {
1592 return self::likeEntry($doc, $item, $owner, $toplevel);
1593 } elseif (in_array($item["verb"], [ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"])) {
1594 return self::followEntry($doc, $item, $owner, $toplevel);
1596 return self::noteEntry($doc, $item, $owner, $toplevel, $feed_mode);
1601 * @brief Adds a source entry to the XML document
1603 * @param DOMDocument $doc XML document
1604 * @param array $contact Array of the contact that is added
1606 * @return \DOMElement Source element
1607 * @throws \Exception
1609 private static function sourceEntry(DOMDocument $doc, array $contact)
1611 $source = $doc->createElement("source");
1612 XML::addElement($doc, $source, "id", $contact["poll"]);
1613 XML::addElement($doc, $source, "title", $contact["name"]);
1614 XML::addElement($doc, $source, "link", "", ["rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]]);
1615 XML::addElement($doc, $source, "link", "", ["rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]]);
1616 XML::addElement($doc, $source, "icon", $contact["photo"]);
1617 XML::addElement($doc, $source, "updated", DateTimeFormat::utc($contact["success_update"]."+00:00", DateTimeFormat::ATOM));
1623 * @brief Fetches contact data from the contact or the gcontact table
1625 * @param string $url URL of the contact
1626 * @param array $owner Contact data of the poster
1628 * @return array Contact array
1629 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1630 * @throws \ImagickException
1632 private static function contactEntry($url, array $owner)
1635 "SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1636 DBA::escape(Strings::normaliseLink($url)),
1637 intval($owner["uid"])
1639 if (DBA::isResult($r)) {
1641 $contact["uid"] = -1;
1644 if (!DBA::isResult($r)) {
1645 $gcontact = DBA::selectFirst('gcontact', [], ['nurl' => Strings::normaliseLink($url)]);
1646 if (DBA::isResult($r)) {
1647 $contact = $gcontact;
1648 $contact["uid"] = -1;
1649 $contact["success_update"] = $contact["updated"];
1653 if (!DBA::isResult($r)) {
1657 if (!isset($contact["poll"])) {
1658 $data = Probe::uri($url);
1659 $contact["poll"] = $data["poll"];
1661 if (!$contact["alias"]) {
1662 $contact["alias"] = $data["alias"];
1666 if (!isset($contact["alias"])) {
1667 $contact["alias"] = $contact["url"];
1670 $contact['account-type'] = $owner['account-type'];
1676 * @brief Adds an entry element with reshared content
1678 * @param DOMDocument $doc XML document
1679 * @param array $item Data of the item that is to be posted
1680 * @param array $owner Contact data of the poster
1681 * @param string $repeated_guid guid
1682 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1684 * @return bool Entry element
1685 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1686 * @throws \ImagickException
1688 private static function reshareEntry(DOMDocument $doc, array $item, array $owner, $repeated_guid, $toplevel)
1690 if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1691 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1694 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1696 $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => false,
1697 'network' => [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS]];
1698 $repeated_item = Item::selectFirst([], $condition);
1699 if (!DBA::isResult($repeated_item)) {
1703 $contact = self::contactEntry($repeated_item['author-link'], $owner);
1705 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1707 self::entryContent($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1709 $as_object = $doc->createElement("activity:object");
1711 XML::addElement($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1713 self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false);
1715 $author = self::addAuthor($doc, $contact, false);
1716 $as_object->appendChild($author);
1718 $as_object2 = $doc->createElement("activity:object");
1720 XML::addElement($doc, $as_object2, "activity:object-type", self::constructObjecttype($repeated_item));
1722 $title = sprintf("New comment by %s", $contact["nick"]);
1724 self::entryContent($doc, $as_object2, $repeated_item, $owner, $title);
1726 $as_object->appendChild($as_object2);
1728 self::entryFooter($doc, $as_object, $item, $owner, false);
1730 $source = self::sourceEntry($doc, $contact);
1732 $as_object->appendChild($source);
1734 $entry->appendChild($as_object);
1736 self::entryFooter($doc, $entry, $item, $owner);
1742 * @brief Adds an entry element with a "like"
1744 * @param DOMDocument $doc XML document
1745 * @param array $item Data of the item that is to be posted
1746 * @param array $owner Contact data of the poster
1747 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1749 * @return \DOMElement Entry element with "like"
1750 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1751 * @throws \ImagickException
1753 private static function likeEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1755 if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1756 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1759 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1761 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1762 self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false);
1764 $parent = Item::selectFirst([], ['uri' => $item["thr-parent"], 'uid' => $item["uid"]]);
1765 if (DBA::isResult($parent)) {
1766 $as_object = $doc->createElement("activity:object");
1768 XML::addElement($doc, $as_object, "activity:object-type", self::constructObjecttype($parent));
1770 self::entryContent($doc, $as_object, $parent, $owner, "New entry");
1772 $entry->appendChild($as_object);
1775 self::entryFooter($doc, $entry, $item, $owner);
1781 * @brief Adds the person object element to the XML document
1783 * @param DOMDocument $doc XML document
1784 * @param array $owner Contact data of the poster
1785 * @param array $contact Contact data of the target
1787 * @return object author element
1789 private static function addPersonObject(DOMDocument $doc, array $owner, array $contact)
1791 $object = $doc->createElement("activity:object");
1792 XML::addElement($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1794 if ($contact['network'] == Protocol::PHANTOM) {
1795 XML::addElement($doc, $object, "id", $contact['url']);
1799 XML::addElement($doc, $object, "id", $contact["alias"]);
1800 XML::addElement($doc, $object, "title", $contact["nick"]);
1802 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $contact["url"]];
1803 XML::addElement($doc, $object, "link", "", $attributes);
1807 "type" => "image/jpeg", // To-Do?
1808 "media:width" => 300,
1809 "media:height" => 300,
1810 "href" => $contact["photo"]];
1811 XML::addElement($doc, $object, "link", "", $attributes);
1813 XML::addElement($doc, $object, "poco:preferredUsername", $contact["nick"]);
1814 XML::addElement($doc, $object, "poco:displayName", $contact["name"]);
1816 if (trim($contact["location"]) != "") {
1817 $element = $doc->createElement("poco:address");
1818 XML::addElement($doc, $element, "poco:formatted", $contact["location"]);
1819 $object->appendChild($element);
1826 * @brief Adds a follow/unfollow entry element
1828 * @param DOMDocument $doc XML document
1829 * @param array $item Data of the follow/unfollow message
1830 * @param array $owner Contact data of the poster
1831 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1833 * @return \DOMElement Entry element
1834 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1835 * @throws \ImagickException
1837 private static function followEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1839 $item["id"] = $item["parent"] = 0;
1840 $item["created"] = $item["edited"] = date("c");
1841 $item["private"] = true;
1843 $contact = Probe::uri($item['follow']);
1845 if ($contact['alias'] == '') {
1846 $contact['alias'] = $contact["url"];
1848 $item['follow'] = $contact['alias'];
1851 $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($contact["url"])];
1852 $user_contact = DBA::selectFirst('contact', ['id'], $condition);
1854 if (DBA::isResult($user_contact)) {
1855 $connect_id = $user_contact['id'];
1860 if ($item['verb'] == ACTIVITY_FOLLOW) {
1861 $message = L10n::t('%s is now following %s.');
1862 $title = L10n::t('following');
1863 $action = "subscription";
1865 $message = L10n::t('%s stopped following %s.');
1866 $title = L10n::t('stopped following');
1867 $action = "unfollow";
1870 $item["uri"] = $item['parent-uri'] = $item['thr-parent']
1871 = 'tag:'.get_app()->getHostName().
1872 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1873 ':person:'.$connect_id.':'.$item['created'];
1875 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1877 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1879 self::entryContent($doc, $entry, $item, $owner, $title);
1881 $object = self::addPersonObject($doc, $owner, $contact);
1882 $entry->appendChild($object);
1884 self::entryFooter($doc, $entry, $item, $owner);
1890 * @brief Adds a regular entry element
1892 * @param DOMDocument $doc XML document
1893 * @param array $item Data of the item that is to be posted
1894 * @param array $owner Contact data of the poster
1895 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1896 * @param bool $feed_mode Behave like a regular feed for users if true
1898 * @return \DOMElement Entry element
1899 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1900 * @throws \ImagickException
1902 private static function noteEntry(DOMDocument $doc, array $item, array $owner, $toplevel, $feed_mode)
1904 if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1905 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1909 if (!empty($item['title'])) {
1910 $title = BBCode::convert($item['title'], false, 7);
1912 $title = sprintf("New note by %s", $owner["nick"]);
1915 $title = sprintf("New comment by %s", $owner["nick"]);
1918 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1920 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1922 self::entryContent($doc, $entry, $item, $owner, $title, '', true, $feed_mode);
1924 self::entryFooter($doc, $entry, $item, $owner, !$feed_mode, $feed_mode);
1930 * @brief Adds a header element to the XML document
1932 * @param DOMDocument $doc XML document
1933 * @param array $owner Contact data of the poster
1934 * @param array $item
1935 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1937 * @return \DOMElement The entry element where the elements are added
1938 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1939 * @throws \ImagickException
1941 private static function entryHeader(DOMDocument $doc, array $owner, array $item, $toplevel)
1944 $entry = $doc->createElement("entry");
1946 if ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
1947 $contact = self::contactEntry($item['author-link'], $owner);
1948 $author = self::addAuthor($doc, $contact, false);
1949 $entry->appendChild($author);
1952 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
1954 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1955 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1956 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1957 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1958 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
1959 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1960 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1961 $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1963 $author = self::addAuthor($doc, $owner);
1964 $entry->appendChild($author);
1971 * @brief Adds elements to the XML document
1973 * @param DOMDocument $doc XML document
1974 * @param \DOMElement $entry Entry element where the content is added
1975 * @param array $item Data of the item that is to be posted
1976 * @param array $owner Contact data of the poster
1977 * @param string $title Title for the post
1978 * @param string $verb The activity verb
1979 * @param bool $complete Add the "status_net" element?
1980 * @param bool $feed_mode Behave like a regular feed for users if true
1982 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1984 private static function entryContent(DOMDocument $doc, \DOMElement $entry, array $item, array $owner, $title, $verb = "", $complete = true, $feed_mode = false)
1987 $verb = self::constructVerb($item);
1990 XML::addElement($doc, $entry, "id", $item["uri"]);
1991 XML::addElement($doc, $entry, "title", html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1993 $body = self::formatPicturePost($item['body']);
1995 if (!empty($item['title']) && !$feed_mode) {
1996 $body = "[b]".$item['title']."[/b]\n\n".$body;
1999 $body = BBCode::convert($body, false, 7);
2001 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
2003 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
2004 "href" => System::baseUrl()."/display/".$item["guid"]]
2007 if (!$feed_mode && $complete && ($item["id"] > 0)) {
2008 XML::addElement($doc, $entry, "status_net", "", ["notice_id" => $item["id"]]);
2012 XML::addElement($doc, $entry, "activity:verb", $verb);
2015 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
2016 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
2020 * @brief Adds the elements at the foot of an entry to the XML document
2022 * @param DOMDocument $doc XML document
2023 * @param object $entry The entry element where the elements are added
2024 * @param array $item Data of the item that is to be posted
2025 * @param array $owner Contact data of the poster
2026 * @param bool $complete default true
2027 * @param bool $feed_mode Behave like a regular feed for users if true
2029 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2031 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner, $complete = true, $feed_mode = false)
2035 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
2036 $parent = Item::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item["parent"]]);
2037 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
2039 $thrparent = Item::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $parent_item]);
2041 if (DBA::isResult($thrparent)) {
2042 $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
2043 $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
2044 $parent_plink = $thrparent["plink"];
2046 $mentioned[$parent["author-link"]] = $parent["author-link"];
2047 $mentioned[$parent["owner-link"]] = $parent["owner-link"];
2048 $parent_plink = System::baseUrl()."/display/".$parent["guid"];
2052 "ref" => $parent_item,
2053 "href" => $parent_plink];
2054 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
2058 "href" => $parent_plink];
2059 XML::addElement($doc, $entry, "link", "", $attributes);
2062 if (!$feed_mode && (intval($item["parent"]) > 0)) {
2063 $conversation_href = $conversation_uri = str_replace('/objects/', '/context/', $item['parent-uri']);
2065 if (isset($parent_item)) {
2066 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $parent_item]);
2067 if (DBA::isResult($conversation)) {
2068 if ($conversation['conversation-uri'] != '') {
2069 $conversation_uri = $conversation['conversation-uri'];
2071 if ($conversation['conversation-href'] != '') {
2072 $conversation_href = $conversation['conversation-href'];
2077 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:conversation", "href" => $conversation_href]);
2080 "href" => $conversation_href,
2081 "local_id" => $item["parent"],
2082 "ref" => $conversation_uri];
2084 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
2087 $tags = item::getFeedTags($item);
2090 foreach ($tags as $t) {
2092 $mentioned[$t[1]] = $t[1];
2097 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2099 foreach ($mentioned as $mention) {
2100 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2101 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2103 $mentioned = $newmentions;
2105 foreach ($mentioned as $mention) {
2106 $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($mention)];
2107 $contact = DBA::selectFirst('contact', ['forum', 'prv', 'self', 'contact-type'], $condition);
2108 if ($contact["forum"] || $contact["prv"] || ($owner['contact-type'] == Contact::TYPE_COMMUNITY) ||
2109 ($contact['self'] && ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY))) {
2110 XML::addElement($doc, $entry, "link", "",
2112 "rel" => "mentioned",
2113 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
2117 XML::addElement($doc, $entry, "link", "",
2119 "rel" => "mentioned",
2120 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
2126 if ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
2127 XML::addElement($doc, $entry, "link", "", [
2128 "rel" => "mentioned",
2129 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/group",
2130 "href" => $owner['url']
2134 if (!$item["private"] && !$feed_mode) {
2135 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:attention",
2136 "href" => "http://activityschema.org/collection/public"]);
2137 XML::addElement($doc, $entry, "link", "", ["rel" => "mentioned",
2138 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2139 "href" => "http://activityschema.org/collection/public"]);
2140 XML::addElement($doc, $entry, "mastodon:scope", "public");
2144 foreach ($tags as $t) {
2146 XML::addElement($doc, $entry, "category", "", ["term" => $t[2]]);
2151 self::getAttachment($doc, $entry, $item);
2153 if ($complete && ($item["id"] > 0)) {
2154 $app = $item["app"];
2159 $attributes = ["local_id" => $item["id"], "source" => $app];
2161 if (isset($parent["id"])) {
2162 $attributes["repeat_of"] = $parent["id"];
2165 if ($item["coord"] != "") {
2166 XML::addElement($doc, $entry, "georss:point", $item["coord"]);
2169 XML::addElement($doc, $entry, "statusnet:notice_info", "", $attributes);
2174 * Creates the XML feed for a given nickname
2176 * Supported filters:
2177 * - activity (default): all the public posts
2178 * - posts: all the public top-level posts
2179 * - comments: all the public replies
2181 * Updates the provided last_update parameter if the result comes from the
2182 * cache or it is empty
2184 * @brief Creates the XML feed for a given nickname
2186 * @param string $owner_nick Nickname of the feed owner
2187 * @param string $last_update Date of the last update
2188 * @param integer $max_items Number of maximum items to fetch
2189 * @param string $filter Feed items filter (activity, posts or comments)
2190 * @param boolean $nocache Wether to bypass caching
2191 * @param boolean $feed_mode Behave like a regular feed for users if true
2193 * @return string XML feed
2194 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2195 * @throws \ImagickException
2197 public static function feed($owner_nick, &$last_update, $max_items = 300, $filter = 'activity', $nocache = false, $feed_mode = false)
2199 $stamp = microtime(true);
2201 $owner = User::getOwnerDataByNick($owner_nick);
2206 $cachekey = "ostatus:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
2208 $previous_created = $last_update;
2210 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
2211 if ((time() - strtotime($owner['last-item'])) < 15*60) {
2212 $result = Cache::get($cachekey);
2213 if (!$nocache && !is_null($result)) {
2214 Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', Logger::DEBUG);
2215 $last_update = $result['last_update'];
2216 return $result['feed'];
2220 if (!strlen($last_update)) {
2221 $last_update = 'now -30 days';
2224 $check_date = DateTimeFormat::utc($last_update);
2225 $authorid = Contact::getIdForURL($owner["url"], 0, true);
2227 $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted`
2228 AND NOT `private` AND `visible` AND `wall` AND `parent-network` IN (?, ?)",
2229 $owner["uid"], $check_date, Protocol::OSTATUS, Protocol::DFRN];
2231 if ($filter === 'comments') {
2232 $condition[0] .= " AND `object-type` = ? ";
2233 $condition[] = ACTIVITY_OBJ_COMMENT;
2236 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
2237 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
2238 $condition[] = $owner["id"];
2239 $condition[] = $authorid;
2242 $params = ['order' => ['received' => true], 'limit' => $max_items];
2244 if ($filter === 'posts') {
2245 $ret = Item::selectThread([], $condition, $params);
2247 $ret = Item::select([], $condition, $params);
2250 $items = Item::inArray($ret);
2252 $doc = new DOMDocument('1.0', 'utf-8');
2253 $doc->formatOutput = true;
2255 $root = self::addHeader($doc, $owner, $filter, $feed_mode);
2257 foreach ($items as $item) {
2258 if (Config::get('system', 'ostatus_debug')) {
2259 $item['body'] .= '🍼';
2262 $entry = self::entry($doc, $item, $owner, false, $feed_mode);
2263 $root->appendChild($entry);
2265 if ($last_update < $item['created']) {
2266 $last_update = $item['created'];
2270 $feeddata = trim($doc->saveXML());
2272 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
2273 Cache::set($cachekey, $msg, Cache::QUARTER_HOUR);
2275 Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, Logger::DEBUG);
2281 * @brief Creates the XML for a salmon message
2283 * @param array $item Data of the item that is to be posted
2284 * @param array $owner Contact data of the poster
2286 * @return string XML for the salmon
2287 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2288 * @throws \ImagickException
2290 public static function salmon(array $item, array $owner)
2292 $doc = new DOMDocument('1.0', 'utf-8');
2293 $doc->formatOutput = true;
2295 if (Config::get('system', 'ostatus_debug')) {
2296 $item['body'] .= '🐟';
2299 $entry = self::entry($doc, $item, $owner, true);
2301 $doc->appendChild($entry);
2303 return trim($doc->saveXML());
2307 * Checks if the given contact url does support OStatus
2309 * @param string $url profile url
2310 * @param boolean $update Update the profile
2312 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2313 * @throws \ImagickException
2315 public static function isSupportedByContactUrl($url, $update = false)
2317 $probe = Probe::uri($url, Protocol::OSTATUS, 0, !$update);
2318 return $probe['network'] == Protocol::OSTATUS;