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\Logger;
15 use Friendica\Core\Lock;
16 use Friendica\Core\Protocol;
17 use Friendica\Core\System;
18 use Friendica\Database\DBA;
19 use Friendica\Model\Contact;
20 use Friendica\Model\Conversation;
21 use Friendica\Model\GContact;
22 use Friendica\Model\Item;
23 use Friendica\Model\User;
24 use Friendica\Network\Probe;
25 use Friendica\Object\Image;
26 use Friendica\Util\DateTimeFormat;
27 use Friendica\Util\Network;
28 use Friendica\Util\Proxy as ProxyUtils;
29 use Friendica\Util\Strings;
30 use Friendica\Util\XML;
32 require_once 'mod/share.php';
33 require_once 'include/api.php';
36 * @brief This class contain functions for the OStatus protocol
40 private static $itemlist;
41 private static $conv_list = [];
44 * @brief Fetches author data
46 * @param DOMXPath $xpath The xpath object
47 * @param object $context The xml context of the author details
48 * @param array $importer user record of the importing user
49 * @param array $contact Called by reference, will contain the fetched contact
50 * @param bool $onlyfetch Only fetch the header without updating the contact entries
52 * @return array Array of author related entries for the item
53 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
54 * @throws \ImagickException
56 private static function fetchAuthor(DOMXPath $xpath, $context, array $importer, array &$contact = null, $onlyfetch)
59 $author["author-link"] = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
60 $author["author-name"] = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $context);
61 $addr = XML::getFirstNodeValue($xpath, 'atom:author/atom:email/text()', $context);
63 $aliaslink = $author["author-link"];
65 $alternate_item = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0);
66 if (is_object($alternate_item)) {
67 foreach ($alternate_item->attributes as $attributes) {
68 if (($attributes->name == "href") && ($attributes->textContent != "")) {
69 $author["author-link"] = $attributes->textContent;
73 $author["author-id"] = Contact::getIdForURL($author["author-link"]);
75 $author["contact-id"] = $contact["id"];
80 This here would be better, but we would get problems with contacts from the statusnet addon
81 This is kept here as a reminder for the future
83 $cid = Contact::getIdForURL($author["author-link"], $importer["uid"]);
85 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
88 if ($aliaslink != '') {
89 $condition = ["`uid` = ? AND `alias` = ? AND `network` != ? AND `rel` IN (?, ?)",
90 $importer["uid"], $aliaslink, Protocol::STATUSNET,
91 Contact::SHARING, Contact::FRIEND];
92 $contact = DBA::selectFirst('contact', [], $condition);
95 if (!DBA::isResult($contact) && $author["author-link"] != '') {
96 if ($aliaslink == "") {
97 $aliaslink = $author["author-link"];
100 $condition = ["`uid` = ? AND `nurl` IN (?, ?) AND `network` != ? AND `rel` IN (?, ?)",
101 $importer["uid"], Strings::normaliseLink($author["author-link"]), Strings::normaliseLink($aliaslink),
102 Protocol::STATUSNET, Contact::SHARING, Contact::FRIEND];
103 $contact = DBA::selectFirst('contact', [], $condition);
106 if (!DBA::isResult($contact) && ($addr != '')) {
107 $condition = ["`uid` = ? AND `addr` = ? AND `network` != ? AND `rel` IN (?, ?)",
108 $importer["uid"], $addr, Protocol::STATUSNET,
109 Contact::SHARING, Contact::FRIEND];
110 $contact = DBA::selectFirst('contact', [], $condition);
113 if (DBA::isResult($contact)) {
114 if ($contact['blocked']) {
117 $author["contact-id"] = $contact["id"];
121 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
122 foreach ($avatars as $avatar) {
125 foreach ($avatar->attributes as $attributes) {
126 if ($attributes->name == "href") {
127 $href = $attributes->textContent;
129 if ($attributes->name == "width") {
130 $width = $attributes->textContent;
134 $avatarlist[$width] = $href;
137 if (count($avatarlist) > 0) {
139 $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
142 $displayname = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
143 if ($displayname != "") {
144 $author["author-name"] = $displayname;
147 $author["owner-id"] = $author["author-id"];
149 // Only update the contacts if it is an OStatus contact
150 if (DBA::isResult($contact) && ($contact['id'] > 0) && !$onlyfetch && ($contact["network"] == Protocol::OSTATUS)) {
152 // Update contact data
154 unset($current['name-date']);
156 // This query doesn't seem to work
157 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
159 // $contact["notify"] = $value;
161 // This query doesn't seem to work as well - I hate these queries
162 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
164 // $contact["poll"] = $value;
166 $contact['url'] = $author["author-link"];
167 $contact['nurl'] = Strings::normaliseLink($contact['url']);
169 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
171 $contact["alias"] = $value;
174 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
176 $contact["name"] = $value;
179 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()', $context);
181 $contact["nick"] = $value;
184 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()', $context);
186 $contact["about"] = HTML::toBBCode($value);
189 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()', $context);
191 $contact["location"] = $value;
194 $contact['name-date'] = DateTimeFormat::utcNow();
196 DBA::update('contact', $contact, ['id' => $contact["id"]], $current);
198 if (!empty($author["author-avatar"]) && ($author["author-avatar"] != $current['avatar'])) {
199 Logger::log("Update profile picture for contact ".$contact["id"], Logger::DEBUG);
200 Contact::updateAvatar($author["author-avatar"], $importer["uid"], $contact["id"]);
203 // Ensure that we are having this contact (with uid=0)
204 $cid = Contact::getIdForURL($aliaslink, 0, true);
207 $fields = ['url', 'nurl', 'name', 'nick', 'alias', 'about', 'location'];
208 $old_contact = DBA::selectFirst('contact', $fields, ['id' => $cid]);
210 // Update it with the current values
211 $fields = ['url' => $author["author-link"], 'name' => $contact["name"],
212 'nurl' => Strings::normaliseLink($author["author-link"]),
213 'nick' => $contact["nick"], 'alias' => $contact["alias"],
214 'about' => $contact["about"], 'location' => $contact["location"],
215 'success_update' => DateTimeFormat::utcNow(), 'last-update' => DateTimeFormat::utcNow()];
217 DBA::update('contact', $fields, ['id' => $cid], $old_contact);
220 if (!empty($author["author-avatar"])) {
221 Contact::updateAvatar($author["author-avatar"], 0, $cid);
225 $contact["generation"] = 2;
226 $contact["hide"] = false; // OStatus contacts are never hidden
227 if (!empty($author["author-avatar"])) {
228 $contact["photo"] = $author["author-avatar"];
230 $gcid = GContact::update($contact);
232 GContact::link($gcid, $contact["uid"], $contact["id"]);
233 } elseif ($contact["network"] != Protocol::DFRN) {
241 * @brief Fetches author data from a given XML string
243 * @param string $xml The XML
244 * @param array $importer user record of the importing user
246 * @return array Array of author related entries for the item
247 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
248 * @throws \ImagickException
250 public static function salmonAuthor($xml, array $importer)
256 $doc = new DOMDocument();
257 @$doc->loadXML($xml);
259 $xpath = new DOMXPath($doc);
260 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
261 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
262 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
263 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
264 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
265 $xpath->registerNamespace('poco', NAMESPACE_POCO);
266 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
267 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
269 $contact = ["id" => 0];
271 // Fetch the first author
272 $authordata = $xpath->query('//author')->item(0);
273 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, true);
278 * @brief Read attributes from element
280 * @param object $element Element object
282 * @return array attributes
284 private static function readAttributes($element)
288 foreach ($element->attributes as $attributes) {
289 $attribute[$attributes->name] = $attributes->textContent;
296 * @brief Imports an XML string containing OStatus elements
298 * @param string $xml The XML
299 * @param array $importer user record of the importing user
300 * @param array $contact contact
301 * @param string $hub Called by reference, returns the fetched hub data
303 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
304 * @throws \ImagickException
306 public static function import($xml, array $importer, array &$contact = null, &$hub)
308 self::process($xml, $importer, $contact, $hub);
312 * @brief Internal feed processing
314 * @param string $xml The XML
315 * @param array $importer user record of the importing user
316 * @param array $contact contact
317 * @param string $hub Called by reference, returns the fetched hub data
318 * @param boolean $stored Is the post fresh imported or from the database?
319 * @param boolean $initialize Is it the leading post so that data has to be initialized?
321 * @return boolean Could the XML be processed?
322 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
323 * @throws \ImagickException
325 private static function process($xml, array $importer, array &$contact = null, &$hub, $stored = false, $initialize = true)
328 self::$itemlist = [];
329 self::$conv_list = [];
332 Logger::log('Import OStatus message for user ' . $importer['uid'], Logger::DEBUG);
337 $doc = new DOMDocument();
338 @$doc->loadXML($xml);
340 $xpath = new DOMXPath($doc);
341 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
342 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
343 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
344 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
345 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
346 $xpath->registerNamespace('poco', NAMESPACE_POCO);
347 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
348 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
351 $hub_items = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0);
352 if (is_object($hub_items)) {
353 $hub_attributes = $hub_items->attributes;
354 if (is_object($hub_attributes)) {
355 foreach ($hub_attributes as $hub_attribute) {
356 if ($hub_attribute->name == "href") {
357 $hub = $hub_attribute->textContent;
358 Logger::log("Found hub ".$hub, Logger::DEBUG);
365 $header["uid"] = $importer["uid"];
366 $header["network"] = Protocol::OSTATUS;
368 $header["origin"] = 0;
369 $header["gravity"] = GRAVITY_COMMENT;
371 if (!is_object($doc->firstChild) || empty($doc->firstChild->tagName)) {
375 $first_child = $doc->firstChild->tagName;
377 if ($first_child == "feed") {
378 $entries = $xpath->query('/atom:feed/atom:entry');
380 $entries = $xpath->query('/atom:entry');
383 if ($entries->length == 1) {
384 // We reformat the XML to make it better readable
385 $doc2 = new DOMDocument();
386 $doc2->loadXML($xml);
387 $doc2->preserveWhiteSpace = false;
388 $doc2->formatOutput = true;
389 $xml2 = $doc2->saveXML();
391 $header["protocol"] = Conversation::PARCEL_SALMON;
392 $header["source"] = $xml2;
393 } elseif (!$initialize) {
397 // Fetch the first author
398 $authordata = $xpath->query('//author')->item(0);
399 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, $stored);
401 $entry = $xpath->query('/atom:entry');
403 // Reverse the order of the entries
406 foreach ($entries as $entry) {
407 $entrylist[] = $entry;
410 foreach (array_reverse($entrylist) as $entry) {
412 $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
414 if ($authorelement->length == 0) {
415 $authorelement = $xpath->query('atom:author', $entry);
418 if ($authorelement->length > 0) {
419 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, $stored);
422 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()', $entry);
426 $nickname = $author["author-name"];
429 $item = array_merge($header, $author);
431 $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
433 $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $entry);
436 if (in_array($item["verb"], ['qvitter-delete-notice', ACTIVITY_DELETE, 'delete'])) {
437 self::deleteNotice($item);
441 if (in_array($item["verb"], [NAMESPACE_OSTATUS."/unfavorite", ACTIVITY_UNFAVORITE])) {
442 // Ignore "Unfavorite" message
443 Logger::log("Ignore unfavorite message ".print_r($item, true), Logger::DEBUG);
447 // Deletions come with the same uri, so we check for duplicates after processing deletions
448 if (Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]])) {
449 Logger::log('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', Logger::DEBUG);
452 Logger::log('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', Logger::DEBUG);
455 if ($item["verb"] == ACTIVITY_JOIN) {
456 // ignore "Join" messages
457 Logger::log("Ignore join message ".print_r($item, true), Logger::DEBUG);
461 if ($item["verb"] == "http://mastodon.social/schema/1.0/block") {
462 // ignore mastodon "block" messages
463 Logger::log("Ignore block message ".print_r($item, true), Logger::DEBUG);
467 if ($item["verb"] == ACTIVITY_FOLLOW) {
468 Contact::addRelationship($importer, $contact, $item, $nickname);
472 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
474 Contact::removeFollower($importer, $contact, $item, $dummy);
478 if ($item["verb"] == ACTIVITY_FAVORITE) {
479 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
480 Logger::log("Favorite ".$orig_uri." ".print_r($item, true));
482 $item["verb"] = ACTIVITY_LIKE;
483 $item["parent-uri"] = $orig_uri;
484 $item["gravity"] = GRAVITY_ACTIVITY;
485 $item["object-type"] = ACTIVITY_OBJ_NOTE;
488 // http://activitystrea.ms/schema/1.0/rsvp-yes
489 if (!in_array($item["verb"], [ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE])) {
490 Logger::log("Unhandled verb ".$item["verb"]." ".print_r($item, true), Logger::DEBUG);
493 self::processPost($xpath, $entry, $item, $importer);
495 if ($initialize && (count(self::$itemlist) > 0)) {
496 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['parent-uri']) {
497 // We will import it everytime, when it is started by our contacts
498 $valid = !empty(self::$itemlist[0]['contact-id']);
500 // If not, then it depends on this setting
501 $valid = !Config::get('system', 'ostatus_full_threads');
503 Logger::log("Item with uri ".self::$itemlist[0]['uri']." will be imported due to the system settings.", Logger::DEBUG);
506 Logger::log("Item with uri ".self::$itemlist[0]['uri']." belongs to a contact (".self::$itemlist[0]['contact-id']."). It will be imported.", Logger::DEBUG);
509 // Never post a thread when the only interaction by our contact was a like
511 $verbs = [ACTIVITY_POST, ACTIVITY_SHARE];
512 foreach (self::$itemlist as $item) {
513 if (!empty($item['contact-id']) && in_array($item['verb'], $verbs)) {
518 Logger::log("Item with uri ".self::$itemlist[0]['uri']." will be imported since the thread contains posts or shares.", Logger::DEBUG);
522 // But we will only import complete threads
523 $valid = Item::exists(['uid' => $importer["uid"], 'uri' => self::$itemlist[0]['parent-uri']]);
525 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);
530 $default_contact = 0;
531 $key = count(self::$itemlist);
532 for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
533 if (empty(self::$itemlist[$key]['contact-id'])) {
534 self::$itemlist[$key]['contact-id'] = $default_contact;
536 $default_contact = $item['contact-id'];
539 foreach (self::$itemlist as $item) {
540 $found = Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]]);
542 Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", Logger::DEBUG);
543 } elseif ($item['contact-id'] < 0) {
544 Logger::log("Item with uri ".$item["uri"]." is from a blocked contact.", Logger::DEBUG);
546 // We are having duplicated entries. Hopefully this solves it.
547 if (Lock::acquire('ostatus_process_item_insert')) {
548 $ret = Item::insert($item);
549 Lock::release('ostatus_process_item_insert');
550 Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret);
552 $ret = Item::insert($item);
553 Logger::log("We couldn't lock - but tried to store the item anyway. Return value is ".$ret);
558 self::$itemlist = [];
560 Logger::log('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.', Logger::DEBUG);
566 * Removes notice item from database
568 * @param array $item item
572 private static function deleteNotice(array $item)
574 $condition = ['uid' => $item['uid'], 'author-id' => $item['author-id'], 'uri' => $item['uri']];
575 if (!Item::exists($condition)) {
576 Logger::log('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it.");
580 Item::delete($condition);
582 Logger::log('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
586 * @brief Processes the XML for a post
588 * @param DOMXPath $xpath The xpath object
589 * @param object $entry The xml entry that is processed
590 * @param array $item The item array
591 * @param array $importer user record of the importing user
593 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
594 * @throws \ImagickException
596 private static function processPost(DOMXPath $xpath, $entry, array &$item, array $importer)
598 $item["body"] = HTML::toBBCode(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
599 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $entry);
600 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) || ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
601 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
602 $item["body"] = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
603 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
604 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
607 $item["created"] = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
608 $item["edited"] = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
609 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
611 $conv = $xpath->query('ostatus:conversation', $entry);
612 if (is_object($conv->item(0))) {
613 foreach ($conv->item(0)->attributes as $attributes) {
614 if ($attributes->name == "ref") {
615 $item['conversation-uri'] = $attributes->textContent;
617 if ($attributes->name == "href") {
618 $item['conversation-href'] = $attributes->textContent;
625 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
626 if (is_object($inreplyto->item(0))) {
627 foreach ($inreplyto->item(0)->attributes as $attributes) {
628 if ($attributes->name == "ref") {
629 $item["parent-uri"] = $attributes->textContent;
631 if ($attributes->name == "href") {
632 $related = $attributes->textContent;
637 $georsspoint = $xpath->query('georss:point', $entry);
638 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
639 $item["coord"] = $georsspoint->item(0)->nodeValue;
642 $categories = $xpath->query('atom:category', $entry);
644 foreach ($categories as $category) {
645 foreach ($category->attributes as $attributes) {
646 if ($attributes->name == 'term') {
647 $term = $attributes->textContent;
648 if (!empty($item['tag'])) {
654 $item['tag'] .= '#[url=' . System::baseUrl() . '/search?tag=' . $term . ']' . $term . '[/url]';
663 $links = $xpath->query('atom:link', $entry);
665 $link_data = self::processLinks($links, $item);
666 $self = $link_data['self'];
667 $add_body = $link_data['add_body'];
672 $notice_info = $xpath->query('statusnet:notice_info', $entry);
673 if ($notice_info && ($notice_info->length > 0)) {
674 foreach ($notice_info->item(0)->attributes as $attributes) {
675 if ($attributes->name == "source") {
676 $item["app"] = strip_tags($attributes->textContent);
678 if ($attributes->name == "repeat_of") {
679 $repeat_of = $attributes->textContent;
683 // Is it a repeated post?
684 if (($repeat_of != "") || ($item["verb"] == ACTIVITY_SHARE)) {
685 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
686 if (!empty($link_data['add_body'])) {
687 $add_body .= $link_data['add_body'];
691 $item["body"] .= $add_body;
693 // Only add additional data when there is no picture in the post
694 if (!strstr($item["body"], '[/img]')) {
695 $item["body"] = add_page_info_to_body($item["body"]);
698 // Mastodon Content Warning
699 if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
700 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
701 if (!empty($clear_text)) {
702 $item['content-warning'] = HTML::toBBCode($clear_text);
706 if (($self != '') && empty($item['protocol'])) {
707 self::fetchSelf($self, $item);
710 if (!empty($item["conversation-href"])) {
711 self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
714 if (isset($item["parent-uri"])) {
715 if (!Item::exists(['uid' => $importer["uid"], 'uri' => $item['parent-uri']])) {
716 if ($related != '') {
717 self::fetchRelated($related, $item["parent-uri"], $importer);
720 Logger::log('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', Logger::DEBUG);
723 $item["parent-uri"] = $item["uri"];
724 $item["gravity"] = GRAVITY_PARENT;
727 if (($item['author-link'] != '') && !empty($item['protocol'])) {
728 $item = Conversation::insert($item);
731 self::$itemlist[] = $item;
735 * @brief Fetch the conversation for posts
737 * @param string $conversation The link to the conversation
738 * @param string $conversation_uri The conversation in "uri" format
740 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
742 private static function fetchConversation($conversation, $conversation_uri)
744 // Ensure that we only store a conversation once in a process
745 if (isset(self::$conv_list[$conversation])) {
749 self::$conv_list[$conversation] = true;
751 $curlResult = Network::curl($conversation, false, $redirects, ['accept_content' => 'application/atom+xml, text/html']);
753 if (!$curlResult->isSuccess()) {
759 if (stristr($curlResult->getHeader(), 'Content-Type: application/atom+xml')) {
760 $xml = $curlResult->getBody();
764 $doc = new DOMDocument();
765 if (!@$doc->loadHTML($curlResult->getBody())) {
768 $xpath = new DOMXPath($doc);
770 $links = $xpath->query('//link');
773 foreach ($links as $link) {
774 $attribute = self::readAttributes($link);
775 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
776 $file = $attribute['href'];
780 $conversation_atom = Network::curl($attribute['href']);
782 if ($conversation_atom->isSuccess()) {
783 $xml = $conversation_atom->getBody();
793 self::storeConversation($xml, $conversation, $conversation_uri);
797 * @brief Store a feed in several conversation entries
799 * @param string $xml The feed
800 * @param string $conversation conversation
801 * @param string $conversation_uri conversation uri
805 private static function storeConversation($xml, $conversation = '', $conversation_uri = '')
807 $doc = new DOMDocument();
808 @$doc->loadXML($xml);
810 $xpath = new DOMXPath($doc);
811 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
812 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
813 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
815 $entries = $xpath->query('/atom:feed/atom:entry');
817 // Now store the entries
818 foreach ($entries as $entry) {
819 $doc2 = new DOMDocument();
820 $doc2->preserveWhiteSpace = false;
821 $doc2->formatOutput = true;
825 $conv_data['protocol'] = Conversation::PARCEL_SPLIT_CONVERSATION;
826 $conv_data['network'] = Protocol::OSTATUS;
827 $conv_data['uri'] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
829 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
830 if (is_object($inreplyto->item(0))) {
831 foreach ($inreplyto->item(0)->attributes as $attributes) {
832 if ($attributes->name == "ref") {
833 $conv_data['reply-to-uri'] = $attributes->textContent;
838 $conv_data['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
840 $conv = $xpath->query('ostatus:conversation', $entry);
841 if (is_object($conv->item(0))) {
842 foreach ($conv->item(0)->attributes as $attributes) {
843 if ($attributes->name == "ref") {
844 $conv_data['conversation-uri'] = $attributes->textContent;
846 if ($attributes->name == "href") {
847 $conv_data['conversation-href'] = $attributes->textContent;
852 if ($conversation != '') {
853 $conv_data['conversation-uri'] = $conversation;
856 if ($conversation_uri != '') {
857 $conv_data['conversation-uri'] = $conversation_uri;
860 $entry = $doc2->importNode($entry, true);
862 $doc2->appendChild($entry);
864 $conv_data['source'] = $doc2->saveXML();
866 $condition = ['item-uri' => $conv_data['uri'],'protocol' => Conversation::PARCEL_FEED];
867 if (DBA::exists('conversation', $condition)) {
868 Logger::log('Delete deprecated entry for URI '.$conv_data['uri'], Logger::DEBUG);
869 DBA::delete('conversation', ['item-uri' => $conv_data['uri']]);
872 Logger::log('Store conversation data for uri '.$conv_data['uri'], Logger::DEBUG);
873 Conversation::insert($conv_data);
878 * @brief Fetch the own post so that it can be stored later
880 * We want to store the original data for later processing.
881 * This function is meant for cases where we process a feed with multiple entries.
882 * In that case we need to fetch the single posts here.
884 * @param string $self The link to the self item
885 * @param array $item The item array
887 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
889 private static function fetchSelf($self, array &$item)
891 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $self, Conversation::PARCEL_DFRN, Conversation::PARCEL_SALMON];
892 if (DBA::exists('conversation', $condition)) {
893 Logger::log('Conversation '.$item['uri'].' is already stored.', Logger::DEBUG);
897 $curlResult = Network::curl($self);
899 if (!$curlResult->isSuccess()) {
903 // We reformat the XML to make it better readable
904 $doc = new DOMDocument();
905 $doc->loadXML($curlResult->getBody());
906 $doc->preserveWhiteSpace = false;
907 $doc->formatOutput = true;
908 $xml = $doc->saveXML();
910 $item["protocol"] = Conversation::PARCEL_SALMON;
911 $item["source"] = $xml;
913 Logger::log('Conversation '.$item['uri'].' is now fetched.', Logger::DEBUG);
917 * @brief Fetch related posts and processes them
919 * @param string $related The link to the related item
920 * @param string $related_uri The related item in "uri" format
921 * @param array $importer user record of the importing user
923 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
924 * @throws \ImagickException
926 private static function fetchRelated($related, $related_uri, $importer)
928 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, Conversation::PARCEL_DFRN, Conversation::PARCEL_SALMON];
929 $conversation = DBA::selectFirst('conversation', ['source', 'protocol'], $condition);
930 if (DBA::isResult($conversation)) {
932 $xml = $conversation['source'];
933 if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
934 Logger::log('Got valid cached XML for URI '.$related_uri, Logger::DEBUG);
937 if ($conversation['protocol'] == Conversation::PARCEL_SALMON) {
938 Logger::log('Delete invalid cached XML for URI '.$related_uri, Logger::DEBUG);
939 DBA::delete('conversation', ['item-uri' => $related_uri]);
944 $curlResult = Network::curl($related, false, $redirects, ['accept_content' => 'application/atom+xml, text/html']);
946 if (!$curlResult->isSuccess()) {
952 if (stristr($curlResult->getHeader(), 'Content-Type: application/atom+xml')) {
953 Logger::log('Directly fetched XML for URI ' . $related_uri, Logger::DEBUG);
954 $xml = $curlResult->getBody();
958 $doc = new DOMDocument();
959 if (!@$doc->loadHTML($curlResult->getBody())) {
962 $xpath = new DOMXPath($doc);
966 $links = $xpath->query('//link');
968 foreach ($links as $link) {
969 $attribute = self::readAttributes($link);
970 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
971 $atom_file = $attribute['href'];
974 if ($atom_file != '') {
975 $curlResult = Network::curl($atom_file);
977 if ($curlResult->isSuccess()) {
978 Logger::log('Fetched XML for URI ' . $related_uri, Logger::DEBUG);
979 $xml = $curlResult->getBody();
985 // Workaround for older GNU Social servers
986 if (($xml == '') && strstr($related, '/notice/')) {
987 $curlResult = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related).'.atom');
989 if ($curlResult->isSuccess()) {
990 Logger::log('GNU Social workaround to fetch XML for URI ' . $related_uri, Logger::DEBUG);
991 $xml = $curlResult->getBody();
995 // Even more worse workaround for GNU Social ;-)
997 $related_guess = OStatus::convertHref($related_uri);
998 $curlResult = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related_guess).'.atom');
1000 if ($curlResult->isSuccess()) {
1001 Logger::log('GNU Social workaround 2 to fetch XML for URI ' . $related_uri, Logger::DEBUG);
1002 $xml = $curlResult->getBody();
1006 // Finally we take the data that we fetched from "ostatus:conversation"
1008 $condition = ['item-uri' => $related_uri, 'protocol' => Conversation::PARCEL_SPLIT_CONVERSATION];
1009 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1010 if (DBA::isResult($conversation)) {
1012 Logger::log('Got cached XML from conversation for URI '.$related_uri, Logger::DEBUG);
1013 $xml = $conversation['source'];
1018 self::process($xml, $importer, $contact, $hub, $stored, false);
1020 Logger::log("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, Logger::DEBUG);
1026 * @brief Processes the XML for a repeated post
1028 * @param DOMXPath $xpath The xpath object
1029 * @param object $entry The xml entry that is processed
1030 * @param array $item The item array
1031 * @param array $importer user record of the importing user
1033 * @return array with data from links
1034 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1035 * @throws \ImagickException
1037 private static function processRepeatedItem(DOMXPath $xpath, $entry, array &$item, array $importer)
1039 $activityobject = $xpath->query('activity:object', $entry)->item(0);
1041 if (!is_object($activityobject)) {
1047 $orig_uri = XML::getFirstNodeValue($xpath, 'atom:id/text()', $activityobject);
1049 $links = $xpath->query("atom:link", $activityobject);
1051 $link_data = self::processLinks($links, $item);
1054 $orig_body = XML::getFirstNodeValue($xpath, 'atom:content/text()', $activityobject);
1055 $orig_created = XML::getFirstNodeValue($xpath, 'atom:published/text()', $activityobject);
1056 $orig_edited = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $activityobject);
1058 $orig_author = self::fetchAuthor($xpath, $activityobject, $importer, $dummy, false);
1060 $item["author-name"] = $orig_author["author-name"];
1061 $item["author-link"] = $orig_author["author-link"];
1062 $item["author-id"] = $orig_author["author-id"];
1064 $item["body"] = HTML::toBBCode($orig_body);
1065 $item["created"] = $orig_created;
1066 $item["edited"] = $orig_edited;
1068 $item["uri"] = $orig_uri;
1070 $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $activityobject);
1072 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $activityobject);
1074 // Mastodon Content Warning
1075 if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $activityobject)) {
1076 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $activityobject);
1077 if (!empty($clear_text)) {
1078 $item['content-warning'] = HTML::toBBCode($clear_text);
1082 $inreplyto = $xpath->query('thr:in-reply-to', $activityobject);
1083 if (is_object($inreplyto->item(0))) {
1084 foreach ($inreplyto->item(0)->attributes as $attributes) {
1085 if ($attributes->name == "ref") {
1086 $item["parent-uri"] = $attributes->textContent;
1095 * @brief Processes links in the XML
1097 * @param object $links The xml data that contain links
1098 * @param array $item The item array
1100 * @return array with data from the links
1102 private static function processLinks($links, array &$item)
1104 $link_data = ['add_body' => '', 'self' => ''];
1106 foreach ($links as $link) {
1107 $attribute = self::readAttributes($link);
1109 if (!empty($attribute['rel']) && !empty($attribute['href'])) {
1110 switch ($attribute['rel']) {
1112 $item["plink"] = $attribute['href'];
1113 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION)
1114 || ($item["object-type"] == ACTIVITY_OBJ_EVENT)
1116 $item["body"] .= add_page_info($attribute['href']);
1119 case "ostatus:conversation":
1120 $link_data['conversation'] = $attribute['href'];
1121 $item['conversation-href'] = $link_data['conversation'];
1122 if (!isset($item['conversation-uri'])) {
1123 $item['conversation-uri'] = $item['conversation-href'];
1127 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
1128 if ($filetype == 'image') {
1129 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1131 if (!empty($item["attach"])) {
1132 $item["attach"] .= ',';
1134 $item["attach"] = '';
1136 if (!isset($attribute['length'])) {
1137 $attribute['length'] = "0";
1139 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.defaults($attribute, 'title', '').'"[/attach]';
1143 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
1144 if (!isset($item["parent-uri"])) {
1145 $item["parent-uri"] = $attribute['href'];
1147 $link_data['related'] = $attribute['href'];
1149 $item["body"] .= add_page_info($attribute['href']);
1153 if (empty($item["plink"])) {
1154 $item["plink"] = $attribute['href'];
1156 $link_data['self'] = $attribute['href'];
1165 * @brief Create an url out of an uri
1167 * @param string $href URI in the format "parameter1:parameter1:..."
1169 * @return string URL in the format http(s)://....
1171 public static function convertHref($href)
1173 $elements = explode(":", $href);
1175 if ((count($elements) <= 2) || ($elements[0] != "tag")) {
1179 $server = explode(",", $elements[1]);
1180 $conversation = explode("=", $elements[2]);
1182 if ((count($elements) == 4) && ($elements[2] == "post")) {
1183 return "http://".$server[0]."/notice/".$elements[3];
1186 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1189 if ($elements[3] == "objectType=thread") {
1190 return "http://".$server[0]."/conversation/".$conversation[1];
1192 return "http://".$server[0]."/notice/".$conversation[1];
1198 * @brief Checks if the current post is a reshare
1200 * @param array $item The item array of thw post
1202 * @return string The guid if the post is a reshare
1204 private static function getResharedGuid(array $item)
1206 $body = trim($item["body"]);
1208 // Skip if it isn't a pure repeated messages
1209 // Does it start with a share?
1210 if (strpos($body, "[share") > 0) {
1214 // Does it end with a share?
1215 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
1219 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
1220 // Skip if there is no shared message in there
1221 if ($body == $attributes) {
1226 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1227 if (!empty($matches[1])) {
1228 $guid = $matches[1];
1231 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1232 if (!empty($matches[1])) {
1233 $guid = $matches[1];
1240 * @brief Cleans the body of a post if it contains picture links
1242 * @param string $body The body
1244 * @return string The cleaned body
1245 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1247 private static function formatPicturePost($body)
1249 $siteinfo = BBCode::getAttachedData($body);
1251 if (($siteinfo["type"] == "photo") && (!empty($siteinfo["preview"]) || !empty($siteinfo["image"]))) {
1252 if (isset($siteinfo["preview"])) {
1253 $preview = $siteinfo["preview"];
1255 $preview = $siteinfo["image"];
1258 // Is it a remote picture? Then make a smaller preview here
1259 $preview = ProxyUtils::proxifyUrl($preview, false, ProxyUtils::SIZE_SMALL);
1261 // Is it a local picture? Then make it smaller here
1262 $preview = str_replace(["-0.jpg", "-0.png"], ["-2.jpg", "-2.png"], $preview);
1263 $preview = str_replace(["-1.jpg", "-1.png"], ["-2.jpg", "-2.png"], $preview);
1265 if (isset($siteinfo["url"])) {
1266 $url = $siteinfo["url"];
1268 $url = $siteinfo["image"];
1271 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1278 * @brief Adds the header elements to the XML document
1280 * @param DOMDocument $doc XML document
1281 * @param array $owner Contact data of the poster
1282 * @param string $filter The related feed filter (activity, posts or comments)
1283 * @param bool $feed_mode Behave like a regular feed for users if true
1285 * @return object header root element
1286 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1288 private static function addHeader(DOMDocument $doc, array $owner, $filter, $feed_mode = false)
1292 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1293 $doc->appendChild($root);
1295 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1296 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1297 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1298 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1299 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1300 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1301 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1302 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1305 $selfUri = '/feed/' . $owner["nick"] . '/';
1308 $title = L10n::t('%s\'s timeline', $owner['name']);
1309 $selfUri .= $filter;
1312 $title = L10n::t('%s\'s posts', $owner['name']);
1315 $title = L10n::t('%s\'s comments', $owner['name']);
1316 $selfUri .= $filter;
1321 $selfUri = "/dfrn_poll/" . $owner["nick"];
1324 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
1325 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1326 XML::addElement($doc, $root, "id", System::baseUrl() . "/profile/" . $owner["nick"]);
1327 XML::addElement($doc, $root, "title", $title);
1328 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], Config::get('config', 'sitename')));
1329 XML::addElement($doc, $root, "logo", $owner["photo"]);
1330 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1332 $author = self::addAuthor($doc, $owner);
1333 $root->appendChild($author);
1335 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1336 XML::addElement($doc, $root, "link", "", $attributes);
1338 /// @TODO We have to find out what this is
1339 /// $attributes = array("href" => System::baseUrl()."/sup",
1340 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1341 /// "type" => "application/json");
1342 /// XML::addElement($doc, $root, "link", "", $attributes);
1344 self::hublinks($doc, $root, $owner["nick"]);
1346 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "salmon"];
1347 XML::addElement($doc, $root, "link", "", $attributes);
1349 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies"];
1350 XML::addElement($doc, $root, "link", "", $attributes);
1352 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention"];
1353 XML::addElement($doc, $root, "link", "", $attributes);
1355 $attributes = ["href" => System::baseUrl() . $selfUri, "rel" => "self", "type" => "application/atom+xml"];
1356 XML::addElement($doc, $root, "link", "", $attributes);
1358 if ($owner['account-type'] == Contact::ACCOUNT_TYPE_COMMUNITY) {
1359 $condition = ['uid' => $owner['uid'], 'self' => false, 'pending' => false,
1360 'archive' => false, 'hidden' => false, 'blocked' => false];
1361 $members = DBA::count('contact', $condition);
1362 XML::addElement($doc, $root, "statusnet:group_info", "", ["member_count" => $members]);
1369 * @brief Add the link to the push hubs to the XML document
1371 * @param DOMDocument $doc XML document
1372 * @param object $root XML root element where the hub links are added
1373 * @param object $nick nick
1375 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1377 public static function hublinks(DOMDocument $doc, $root, $nick)
1379 $h = System::baseUrl() . '/pubsubhubbub/'.$nick;
1380 XML::addElement($doc, $root, "link", "", ["href" => $h, "rel" => "hub"]);
1384 * @brief Adds attachment data to the XML document
1386 * @param DOMDocument $doc XML document
1387 * @param object $root XML root element where the hub links are added
1388 * @param array $item Data of the item that is to be posted
1390 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1392 private static function getAttachment(DOMDocument $doc, $root, $item)
1394 $siteinfo = BBCode::getAttachedData($item["body"]);
1396 switch ($siteinfo["type"]) {
1398 if (!empty($siteinfo["image"])) {
1399 $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1401 $attributes = ["rel" => "enclosure",
1402 "href" => $siteinfo["image"],
1403 "type" => $imgdata["mime"],
1404 "length" => intval($imgdata["size"])];
1405 XML::addElement($doc, $root, "link", "", $attributes);
1410 $attributes = ["rel" => "enclosure",
1411 "href" => $siteinfo["url"],
1412 "type" => "text/html; charset=UTF-8",
1414 "title" => defaults($siteinfo, "title", $siteinfo["url"])];
1415 XML::addElement($doc, $root, "link", "", $attributes);
1421 if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1422 $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1424 $attributes = ["rel" => "enclosure",
1425 "href" => $siteinfo["image"],
1426 "type" => $imgdata["mime"],
1427 "length" => intval($imgdata["size"])];
1429 XML::addElement($doc, $root, "link", "", $attributes);
1433 $arr = explode('[/attach],', $item['attach']);
1435 foreach ($arr as $r) {
1437 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1439 $attributes = ["rel" => "enclosure",
1440 "href" => $matches[1],
1441 "type" => $matches[3]];
1443 if (intval($matches[2])) {
1444 $attributes["length"] = intval($matches[2]);
1446 if (trim($matches[4]) != "") {
1447 $attributes["title"] = trim($matches[4]);
1449 XML::addElement($doc, $root, "link", "", $attributes);
1456 * @brief Adds the author element to the XML document
1458 * @param DOMDocument $doc XML document
1459 * @param array $owner Contact data of the poster
1460 * @param bool $show_profile Whether to show profile
1462 * @return object author element
1463 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1465 private static function addAuthor(DOMDocument $doc, array $owner, $show_profile = true)
1467 $profile = DBA::selectFirst('profile', ['homepage', 'publish'], ['uid' => $owner['uid'], 'is-default' => true]);
1468 $author = $doc->createElement("author");
1469 XML::addElement($doc, $author, "id", $owner["url"]);
1470 if ($owner['account-type'] == Contact::ACCOUNT_TYPE_COMMUNITY) {
1471 XML::addElement($doc, $author, "activity:object-type", ACTIVITY_OBJ_GROUP);
1473 XML::addElement($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1475 XML::addElement($doc, $author, "uri", $owner["url"]);
1476 XML::addElement($doc, $author, "name", $owner["nick"]);
1477 XML::addElement($doc, $author, "email", $owner["addr"]);
1478 if ($show_profile) {
1479 XML::addElement($doc, $author, "summary", BBCode::convert($owner["about"], false, 7));
1482 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $owner["url"]];
1483 XML::addElement($doc, $author, "link", "", $attributes);
1487 "type" => "image/jpeg", // To-Do?
1488 "media:width" => 300,
1489 "media:height" => 300,
1490 "href" => $owner["photo"]];
1491 XML::addElement($doc, $author, "link", "", $attributes);
1493 if (isset($owner["thumb"])) {
1496 "type" => "image/jpeg", // To-Do?
1497 "media:width" => 80,
1498 "media:height" => 80,
1499 "href" => $owner["thumb"]];
1500 XML::addElement($doc, $author, "link", "", $attributes);
1503 XML::addElement($doc, $author, "poco:preferredUsername", $owner["nick"]);
1504 XML::addElement($doc, $author, "poco:displayName", $owner["name"]);
1505 if ($show_profile) {
1506 XML::addElement($doc, $author, "poco:note", BBCode::convert($owner["about"], false, 7));
1508 if (trim($owner["location"]) != "") {
1509 $element = $doc->createElement("poco:address");
1510 XML::addElement($doc, $element, "poco:formatted", $owner["location"]);
1511 $author->appendChild($element);
1515 if (DBA::isResult($profile) && !$show_profile) {
1516 if (trim($profile["homepage"]) != "") {
1517 $urls = $doc->createElement("poco:urls");
1518 XML::addElement($doc, $urls, "poco:type", "homepage");
1519 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
1520 XML::addElement($doc, $urls, "poco:primary", "true");
1521 $author->appendChild($urls);
1524 XML::addElement($doc, $author, "followers", "", ["url" => System::baseUrl()."/viewcontacts/".$owner["nick"]]);
1525 XML::addElement($doc, $author, "statusnet:profile_info", "", ["local_id" => $owner["uid"]]);
1527 if ($profile["publish"]) {
1528 XML::addElement($doc, $author, "mastodon:scope", "public");
1536 * @TODO Picture attachments should look like this:
1537 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1538 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1542 * @brief Returns the given activity if present - otherwise returns the "post" activity
1544 * @param array $item Data of the item that is to be posted
1546 * @return string activity
1548 private static function constructVerb(array $item)
1550 if (!empty($item['verb'])) {
1551 return $item['verb'];
1554 return ACTIVITY_POST;
1558 * @brief Returns the given object type if present - otherwise returns the "note" object type
1560 * @param array $item Data of the item that is to be posted
1562 * @return string Object type
1564 private static function constructObjecttype(array $item)
1566 if (!empty($item['object-type']) && in_array($item['object-type'], [ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT])) {
1567 return $item['object-type'];
1570 return ACTIVITY_OBJ_NOTE;
1574 * @brief Adds an entry element to the XML document
1576 * @param DOMDocument $doc XML document
1577 * @param array $item Data of the item that is to be posted
1578 * @param array $owner Contact data of the poster
1579 * @param bool $toplevel optional default false
1580 * @param bool $feed_mode Behave like a regular feed for users if true
1582 * @return object Entry element
1583 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1584 * @throws \ImagickException
1586 private static function entry(DOMDocument $doc, array $item, array $owner, $toplevel = false, $feed_mode = false)
1590 $repeated_guid = self::getResharedGuid($item);
1591 if ($repeated_guid != "") {
1592 $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel);
1599 if ($item["verb"] == ACTIVITY_LIKE) {
1600 return self::likeEntry($doc, $item, $owner, $toplevel);
1601 } elseif (in_array($item["verb"], [ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"])) {
1602 return self::followEntry($doc, $item, $owner, $toplevel);
1604 return self::noteEntry($doc, $item, $owner, $toplevel, $feed_mode);
1609 * @brief Adds a source entry to the XML document
1611 * @param DOMDocument $doc XML document
1612 * @param array $contact Array of the contact that is added
1614 * @return object Source element
1615 * @throws \Exception
1617 private static function sourceEntry(DOMDocument $doc, array $contact)
1619 $source = $doc->createElement("source");
1620 XML::addElement($doc, $source, "id", $contact["poll"]);
1621 XML::addElement($doc, $source, "title", $contact["name"]);
1622 XML::addElement($doc, $source, "link", "", ["rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]]);
1623 XML::addElement($doc, $source, "link", "", ["rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]]);
1624 XML::addElement($doc, $source, "icon", $contact["photo"]);
1625 XML::addElement($doc, $source, "updated", DateTimeFormat::utc($contact["success_update"]."+00:00", DateTimeFormat::ATOM));
1631 * @brief Fetches contact data from the contact or the gcontact table
1633 * @param string $url URL of the contact
1634 * @param array $owner Contact data of the poster
1636 * @return array Contact array
1637 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1638 * @throws \ImagickException
1640 private static function contactEntry($url, array $owner)
1643 "SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1644 DBA::escape(Strings::normaliseLink($url)),
1645 intval($owner["uid"])
1647 if (DBA::isResult($r)) {
1649 $contact["uid"] = -1;
1652 if (!DBA::isResult($r)) {
1653 $gcontact = DBA::selectFirst('gcontact', [], ['nurl' => Strings::normaliseLink($url)]);
1654 if (DBA::isResult($r)) {
1655 $contact = $gcontact;
1656 $contact["uid"] = -1;
1657 $contact["success_update"] = $contact["updated"];
1661 if (!DBA::isResult($r)) {
1665 if (!isset($contact["poll"])) {
1666 $data = Probe::uri($url);
1667 $contact["poll"] = $data["poll"];
1669 if (!$contact["alias"]) {
1670 $contact["alias"] = $data["alias"];
1674 if (!isset($contact["alias"])) {
1675 $contact["alias"] = $contact["url"];
1678 $contact['account-type'] = $owner['account-type'];
1684 * @brief Adds an entry element with reshared content
1686 * @param DOMDocument $doc XML document
1687 * @param array $item Data of the item that is to be posted
1688 * @param array $owner Contact data of the poster
1689 * @param string $repeated_guid guid
1690 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1692 * @return bool Entry element
1693 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1694 * @throws \ImagickException
1696 private static function reshareEntry(DOMDocument $doc, array $item, array $owner, $repeated_guid, $toplevel)
1698 if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1699 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1702 $title = self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1704 $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => false,
1705 'network' => [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS]];
1706 $repeated_item = Item::selectFirst([], $condition);
1707 if (!DBA::isResult($repeated_item)) {
1711 $contact = self::contactEntry($repeated_item['author-link'], $owner);
1713 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1715 self::entryContent($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1717 $as_object = $doc->createElement("activity:object");
1719 XML::addElement($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1721 self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false);
1723 $author = self::addAuthor($doc, $contact, false);
1724 $as_object->appendChild($author);
1726 $as_object2 = $doc->createElement("activity:object");
1728 XML::addElement($doc, $as_object2, "activity:object-type", self::constructObjecttype($repeated_item));
1730 $title = sprintf("New comment by %s", $contact["nick"]);
1732 self::entryContent($doc, $as_object2, $repeated_item, $owner, $title);
1734 $as_object->appendChild($as_object2);
1736 self::entryFooter($doc, $as_object, $item, $owner, false);
1738 $source = self::sourceEntry($doc, $contact);
1740 $as_object->appendChild($source);
1742 $entry->appendChild($as_object);
1744 self::entryFooter($doc, $entry, $item, $owner);
1750 * @brief Adds an entry element with a "like"
1752 * @param DOMDocument $doc XML document
1753 * @param array $item Data of the item that is to be posted
1754 * @param array $owner Contact data of the poster
1755 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1757 * @return object Entry element with "like"
1758 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1759 * @throws \ImagickException
1761 private static function likeEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1763 if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1764 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1767 $title = self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1769 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1770 self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false);
1772 $as_object = $doc->createElement("activity:object");
1774 $parent = Item::selectFirst([], ['uri' => $item["thr-parent"], 'uid' => $item["uid"]]);
1780 XML::addElement($doc, $as_object, "activity:object-type", self::constructObjecttype($parent));
1782 self::entryContent($doc, $as_object, $parent, $owner, "New entry");
1784 $entry->appendChild($as_object);
1786 self::entryFooter($doc, $entry, $item, $owner);
1792 * @brief Adds the person object element to the XML document
1794 * @param DOMDocument $doc XML document
1795 * @param array $owner Contact data of the poster
1796 * @param array $contact Contact data of the target
1798 * @return object author element
1800 private static function addPersonObject(DOMDocument $doc, array $owner, array $contact)
1802 $object = $doc->createElement("activity:object");
1803 XML::addElement($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1805 if ($contact['network'] == Protocol::PHANTOM) {
1806 XML::addElement($doc, $object, "id", $contact['url']);
1810 XML::addElement($doc, $object, "id", $contact["alias"]);
1811 XML::addElement($doc, $object, "title", $contact["nick"]);
1813 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $contact["url"]];
1814 XML::addElement($doc, $object, "link", "", $attributes);
1818 "type" => "image/jpeg", // To-Do?
1819 "media:width" => 300,
1820 "media:height" => 300,
1821 "href" => $contact["photo"]];
1822 XML::addElement($doc, $object, "link", "", $attributes);
1824 XML::addElement($doc, $object, "poco:preferredUsername", $contact["nick"]);
1825 XML::addElement($doc, $object, "poco:displayName", $contact["name"]);
1827 if (trim($contact["location"]) != "") {
1828 $element = $doc->createElement("poco:address");
1829 XML::addElement($doc, $element, "poco:formatted", $contact["location"]);
1830 $object->appendChild($element);
1837 * @brief Adds a follow/unfollow entry element
1839 * @param DOMDocument $doc XML document
1840 * @param array $item Data of the follow/unfollow message
1841 * @param array $owner Contact data of the poster
1842 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1844 * @return object Entry element
1845 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1846 * @throws \ImagickException
1848 private static function followEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1850 $item["id"] = $item["parent"] = 0;
1851 $item["created"] = $item["edited"] = date("c");
1852 $item["private"] = true;
1854 $contact = Probe::uri($item['follow']);
1856 if ($contact['alias'] == '') {
1857 $contact['alias'] = $contact["url"];
1859 $item['follow'] = $contact['alias'];
1862 $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($contact["url"])];
1863 $user_contact = DBA::selectFirst('contact', ['id'], $condition);
1865 if (DBA::isResult($user_contact)) {
1866 $connect_id = $user_contact['id'];
1871 if ($item['verb'] == ACTIVITY_FOLLOW) {
1872 $message = L10n::t('%s is now following %s.');
1873 $title = L10n::t('following');
1874 $action = "subscription";
1876 $message = L10n::t('%s stopped following %s.');
1877 $title = L10n::t('stopped following');
1878 $action = "unfollow";
1881 $item["uri"] = $item['parent-uri'] = $item['thr-parent']
1882 = 'tag:'.get_app()->getHostName().
1883 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1884 ':person:'.$connect_id.':'.$item['created'];
1886 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1888 self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1890 self::entryContent($doc, $entry, $item, $owner, $title);
1892 $object = self::addPersonObject($doc, $owner, $contact);
1893 $entry->appendChild($object);
1895 self::entryFooter($doc, $entry, $item, $owner);
1901 * @brief Adds a regular entry element
1903 * @param DOMDocument $doc XML document
1904 * @param array $item Data of the item that is to be posted
1905 * @param array $owner Contact data of the poster
1906 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1907 * @param bool $feed_mode Behave like a regular feed for users if true
1909 * @return object Entry element
1910 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1911 * @throws \ImagickException
1913 private static function noteEntry(DOMDocument $doc, array $item, array $owner, $toplevel, $feed_mode)
1915 if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1916 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1919 $title = self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1921 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1923 self::entryContent($doc, $entry, $item, $owner, $title, '', true, $feed_mode);
1925 self::entryFooter($doc, $entry, $item, $owner, !$feed_mode, $feed_mode);
1931 * @brief Adds a header element to the XML document
1933 * @param DOMDocument $doc XML document
1934 * @param object $entry The entry element where the elements are added
1935 * @param array $owner Contact data of the poster
1936 * @param array $item
1937 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1939 * @return string The title for the element
1940 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1941 * @throws \ImagickException
1943 private static function entryHeader(DOMDocument $doc, &$entry, array $owner, array $item, $toplevel)
1945 /// @todo Check if this title stuff is really needed (I guess not)
1947 $entry = $doc->createElement("entry");
1948 if (!empty($item['title'])) {
1949 $title = BBCode::convert($item['title'], false, 7);
1951 $title = sprintf("New note by %s", $owner["nick"]);
1954 if ($owner['account-type'] == Contact::ACCOUNT_TYPE_COMMUNITY) {
1955 $contact = self::contactEntry($item['author-link'], $owner);
1956 $author = self::addAuthor($doc, $contact, false);
1957 $entry->appendChild($author);
1960 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
1962 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1963 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1964 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1965 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1966 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
1967 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1968 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1969 $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1971 $author = self::addAuthor($doc, $owner);
1972 $entry->appendChild($author);
1974 $title = sprintf("New comment by %s", $owner["nick"]);
1980 * @brief Adds elements to the XML document
1982 * @param DOMDocument $doc XML document
1983 * @param object $entry Entry element where the content is added
1984 * @param array $item Data of the item that is to be posted
1985 * @param array $owner Contact data of the poster
1986 * @param string $title Title for the post
1987 * @param string $verb The activity verb
1988 * @param bool $complete Add the "status_net" element?
1989 * @param bool $feed_mode Behave like a regular feed for users if true
1991 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1993 private static function entryContent(DOMDocument $doc, $entry, array $item, array $owner, $title, $verb = "", $complete = true, $feed_mode = false)
1996 $verb = self::constructVerb($item);
1999 XML::addElement($doc, $entry, "id", $item["uri"]);
2000 XML::addElement($doc, $entry, "title", html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
2002 $body = self::formatPicturePost($item['body']);
2004 if (!empty($item['title']) && !$feed_mode) {
2005 $body = "[b]".$item['title']."[/b]\n\n".$body;
2008 $body = BBCode::convert($body, false, 7);
2010 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
2012 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
2013 "href" => System::baseUrl()."/display/".$item["guid"]]
2016 if (!$feed_mode && $complete && ($item["id"] > 0)) {
2017 XML::addElement($doc, $entry, "status_net", "", ["notice_id" => $item["id"]]);
2021 XML::addElement($doc, $entry, "activity:verb", $verb);
2024 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
2025 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
2029 * @brief Adds the elements at the foot of an entry to the XML document
2031 * @param DOMDocument $doc XML document
2032 * @param object $entry The entry element where the elements are added
2033 * @param array $item Data of the item that is to be posted
2034 * @param array $owner Contact data of the poster
2035 * @param bool $complete default true
2036 * @param bool $feed_mode Behave like a regular feed for users if true
2038 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2040 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner, $complete = true, $feed_mode = false)
2044 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
2045 $parent = Item::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item["parent"]]);
2046 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
2048 $thrparent = Item::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $parent_item]);
2050 if (DBA::isResult($thrparent)) {
2051 $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
2052 $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
2053 $parent_plink = $thrparent["plink"];
2055 $mentioned[$parent["author-link"]] = $parent["author-link"];
2056 $mentioned[$parent["owner-link"]] = $parent["owner-link"];
2057 $parent_plink = System::baseUrl()."/display/".$parent["guid"];
2061 "ref" => $parent_item,
2062 "href" => $parent_plink];
2063 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
2067 "href" => $parent_plink];
2068 XML::addElement($doc, $entry, "link", "", $attributes);
2071 if (!$feed_mode && (intval($item["parent"]) > 0)) {
2072 $conversation_href = $conversation_uri = str_replace('/objects/', '/context/', $item['parent-uri']);
2074 if (isset($parent_item)) {
2075 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $parent_item]);
2076 if (DBA::isResult($conversation)) {
2077 if ($conversation['conversation-uri'] != '') {
2078 $conversation_uri = $conversation['conversation-uri'];
2080 if ($conversation['conversation-href'] != '') {
2081 $conversation_href = $conversation['conversation-href'];
2086 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:conversation", "href" => $conversation_href]);
2089 "href" => $conversation_href,
2090 "local_id" => $item["parent"],
2091 "ref" => $conversation_uri];
2093 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
2096 $tags = item::getFeedTags($item);
2099 foreach ($tags as $t) {
2101 $mentioned[$t[1]] = $t[1];
2106 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2108 foreach ($mentioned as $mention) {
2109 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2110 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2112 $mentioned = $newmentions;
2114 foreach ($mentioned as $mention) {
2115 $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($mention)];
2116 $contact = DBA::selectFirst('contact', ['forum', 'prv', 'self', 'contact-type'], $condition);
2117 if ($contact["forum"] || $contact["prv"] || ($owner['contact-type'] == Contact::ACCOUNT_TYPE_COMMUNITY) ||
2118 ($contact['self'] && ($owner['account-type'] == Contact::ACCOUNT_TYPE_COMMUNITY))) {
2119 XML::addElement($doc, $entry, "link", "",
2121 "rel" => "mentioned",
2122 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
2126 XML::addElement($doc, $entry, "link", "",
2128 "rel" => "mentioned",
2129 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
2135 if ($owner['account-type'] == Contact::ACCOUNT_TYPE_COMMUNITY) {
2136 XML::addElement($doc, $entry, "link", "", [
2137 "rel" => "mentioned",
2138 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/group",
2139 "href" => $owner['url']
2143 if (!$item["private"] && !$feed_mode) {
2144 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:attention",
2145 "href" => "http://activityschema.org/collection/public"]);
2146 XML::addElement($doc, $entry, "link", "", ["rel" => "mentioned",
2147 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2148 "href" => "http://activityschema.org/collection/public"]);
2149 XML::addElement($doc, $entry, "mastodon:scope", "public");
2153 foreach ($tags as $t) {
2155 XML::addElement($doc, $entry, "category", "", ["term" => $t[2]]);
2160 self::getAttachment($doc, $entry, $item);
2162 if ($complete && ($item["id"] > 0)) {
2163 $app = $item["app"];
2168 $attributes = ["local_id" => $item["id"], "source" => $app];
2170 if (isset($parent["id"])) {
2171 $attributes["repeat_of"] = $parent["id"];
2174 if ($item["coord"] != "") {
2175 XML::addElement($doc, $entry, "georss:point", $item["coord"]);
2178 XML::addElement($doc, $entry, "statusnet:notice_info", "", $attributes);
2183 * Creates the XML feed for a given nickname
2185 * Supported filters:
2186 * - activity (default): all the public posts
2187 * - posts: all the public top-level posts
2188 * - comments: all the public replies
2190 * Updates the provided last_update parameter if the result comes from the
2191 * cache or it is empty
2193 * @brief Creates the XML feed for a given nickname
2195 * @param string $owner_nick Nickname of the feed owner
2196 * @param string $last_update Date of the last update
2197 * @param integer $max_items Number of maximum items to fetch
2198 * @param string $filter Feed items filter (activity, posts or comments)
2199 * @param boolean $nocache Wether to bypass caching
2200 * @param boolean $feed_mode Behave like a regular feed for users if true
2202 * @return string XML feed
2203 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2204 * @throws \ImagickException
2206 public static function feed($owner_nick, &$last_update, $max_items = 300, $filter = 'activity', $nocache = false, $feed_mode = false)
2208 $stamp = microtime(true);
2210 $owner = User::getOwnerDataByNick($owner_nick);
2215 $cachekey = "ostatus:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
2217 $previous_created = $last_update;
2219 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
2220 if ((time() - strtotime($owner['last-item'])) < 15*60) {
2221 $result = Cache::get($cachekey);
2222 if (!$nocache && !is_null($result)) {
2223 Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', Logger::DEBUG);
2224 $last_update = $result['last_update'];
2225 return $result['feed'];
2229 if (!strlen($last_update)) {
2230 $last_update = 'now -30 days';
2233 $check_date = DateTimeFormat::utc($last_update);
2234 $authorid = Contact::getIdForURL($owner["url"], 0, true);
2236 $condition = ["`uid` = ? AND `created` > ? AND NOT `deleted`
2237 AND NOT `private` AND `visible` AND `wall` AND `parent-network` IN (?, ?)",
2238 $owner["uid"], $check_date, Protocol::OSTATUS, Protocol::DFRN];
2240 if ($filter === 'comments') {
2241 $condition[0] .= " AND `object-type` = ? ";
2242 $condition[] = ACTIVITY_OBJ_COMMENT;
2245 if ($owner['account-type'] != Contact::ACCOUNT_TYPE_COMMUNITY) {
2246 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
2247 $condition[] = $owner["id"];
2248 $condition[] = $authorid;
2251 $params = ['order' => ['created' => true], 'limit' => $max_items];
2253 if ($filter === 'posts') {
2254 $ret = Item::selectThread([], $condition, $params);
2256 $ret = Item::select([], $condition, $params);
2259 $items = Item::inArray($ret);
2261 $doc = new DOMDocument('1.0', 'utf-8');
2262 $doc->formatOutput = true;
2264 $root = self::addHeader($doc, $owner, $filter, $feed_mode);
2266 foreach ($items as $item) {
2267 if (Config::get('system', 'ostatus_debug')) {
2268 $item['body'] .= '🍼';
2271 $entry = self::entry($doc, $item, $owner, false, $feed_mode);
2272 $root->appendChild($entry);
2274 if ($last_update < $item['created']) {
2275 $last_update = $item['created'];
2279 $feeddata = trim($doc->saveXML());
2281 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
2282 Cache::set($cachekey, $msg, Cache::QUARTER_HOUR);
2284 Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, Logger::DEBUG);
2290 * @brief Creates the XML for a salmon message
2292 * @param array $item Data of the item that is to be posted
2293 * @param array $owner Contact data of the poster
2295 * @return string XML for the salmon
2296 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2297 * @throws \ImagickException
2299 public static function salmon(array $item, array $owner)
2301 $doc = new DOMDocument('1.0', 'utf-8');
2302 $doc->formatOutput = true;
2304 if (Config::get('system', 'ostatus_debug')) {
2305 $item['body'] .= '🐟';
2308 $entry = self::entry($doc, $item, $owner, true);
2310 $doc->appendChild($entry);
2312 return trim($doc->saveXML());