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 object $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
54 private static function fetchAuthor(DOMXPath $xpath, $context, array $importer, array &$contact = null, $onlyfetch)
57 $author["author-link"] = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
58 $author["author-name"] = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $context);
59 $addr = XML::getFirstNodeValue($xpath, 'atom:author/atom:email/text()', $context);
61 $aliaslink = $author["author-link"];
63 $alternate_item = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0);
64 if (is_object($alternate_item)) {
65 foreach ($alternate_item->attributes as $attributes) {
66 if (($attributes->name == "href") && ($attributes->textContent != "")) {
67 $author["author-link"] = $attributes->textContent;
71 $author["author-id"] = Contact::getIdForURL($author["author-link"]);
73 $author["contact-id"] = $contact["id"];
78 This here would be better, but we would get problems with contacts from the statusnet addon
79 This is kept here as a reminder for the future
81 $cid = Contact::getIdForURL($author["author-link"], $importer["uid"]);
83 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
86 if ($aliaslink != '') {
87 $condition = ["`uid` = ? AND `alias` = ? AND `network` != ? AND `rel` IN (?, ?)",
88 $importer["uid"], $aliaslink, Protocol::STATUSNET,
89 Contact::SHARING, Contact::FRIEND];
90 $contact = DBA::selectFirst('contact', [], $condition);
93 if (!DBA::isResult($contact) && $author["author-link"] != '') {
94 if ($aliaslink == "") {
95 $aliaslink = $author["author-link"];
98 $condition = ["`uid` = ? AND `nurl` IN (?, ?) AND `network` != ? AND `rel` IN (?, ?)",
99 $importer["uid"], Strings::normaliseLink($author["author-link"]), Strings::normaliseLink($aliaslink),
100 Protocol::STATUSNET, Contact::SHARING, Contact::FRIEND];
101 $contact = DBA::selectFirst('contact', [], $condition);
104 if (!DBA::isResult($contact) && ($addr != '')) {
105 $condition = ["`uid` = ? AND `addr` = ? AND `network` != ? AND `rel` IN (?, ?)",
106 $importer["uid"], $addr, Protocol::STATUSNET,
107 Contact::SHARING, Contact::FRIEND];
108 $contact = DBA::selectFirst('contact', [], $condition);
111 if (DBA::isResult($contact)) {
112 if ($contact['blocked']) {
115 $author["contact-id"] = $contact["id"];
119 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
120 foreach ($avatars as $avatar) {
123 foreach ($avatar->attributes as $attributes) {
124 if ($attributes->name == "href") {
125 $href = $attributes->textContent;
127 if ($attributes->name == "width") {
128 $width = $attributes->textContent;
132 $avatarlist[$width] = $href;
135 if (count($avatarlist) > 0) {
137 $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
140 $displayname = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
141 if ($displayname != "") {
142 $author["author-name"] = $displayname;
145 $author["owner-id"] = $author["author-id"];
147 // Only update the contacts if it is an OStatus contact
148 if (DBA::isResult($contact) && ($contact['id'] > 0) && !$onlyfetch && ($contact["network"] == Protocol::OSTATUS)) {
150 // Update contact data
152 unset($current['name-date']);
154 // This query doesn't seem to work
155 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
157 // $contact["notify"] = $value;
159 // This query doesn't seem to work as well - I hate these queries
160 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
162 // $contact["poll"] = $value;
164 $contact['url'] = $author["author-link"];
165 $contact['nurl'] = Strings::normaliseLink($contact['url']);
167 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
169 $contact["alias"] = $value;
172 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
174 $contact["name"] = $value;
177 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()', $context);
179 $contact["nick"] = $value;
182 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()', $context);
184 $contact["about"] = HTML::toBBCode($value);
187 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()', $context);
189 $contact["location"] = $value;
192 $contact['name-date'] = DateTimeFormat::utcNow();
194 DBA::update('contact', $contact, ['id' => $contact["id"]], $current);
196 if (!empty($author["author-avatar"]) && ($author["author-avatar"] != $current['avatar'])) {
197 Logger::log("Update profile picture for contact ".$contact["id"], Logger::DEBUG);
198 Contact::updateAvatar($author["author-avatar"], $importer["uid"], $contact["id"]);
201 // Ensure that we are having this contact (with uid=0)
202 $cid = Contact::getIdForURL($aliaslink, 0, true);
205 $fields = ['url', 'nurl', 'name', 'nick', 'alias', 'about', 'location'];
206 $old_contact = DBA::selectFirst('contact', $fields, ['id' => $cid]);
208 // Update it with the current values
209 $fields = ['url' => $author["author-link"], 'name' => $contact["name"],
210 'nurl' => Strings::normaliseLink($author["author-link"]),
211 'nick' => $contact["nick"], 'alias' => $contact["alias"],
212 'about' => $contact["about"], 'location' => $contact["location"],
213 'success_update' => DateTimeFormat::utcNow(), 'last-update' => DateTimeFormat::utcNow()];
215 DBA::update('contact', $fields, ['id' => $cid], $old_contact);
218 if (!empty($author["author-avatar"])) {
219 Contact::updateAvatar($author["author-avatar"], 0, $cid);
223 $contact["generation"] = 2;
224 $contact["hide"] = false; // OStatus contacts are never hidden
225 if (!empty($author["author-avatar"])) {
226 $contact["photo"] = $author["author-avatar"];
228 $gcid = GContact::update($contact);
230 GContact::link($gcid, $contact["uid"], $contact["id"]);
231 } elseif ($contact["network"] != Protocol::DFRN) {
239 * @brief Fetches author data from a given XML string
241 * @param string $xml The XML
242 * @param array $importer user record of the importing user
244 * @return array Array of author related entries for the item
246 public static function salmonAuthor($xml, array $importer)
252 $doc = new DOMDocument();
253 @$doc->loadXML($xml);
255 $xpath = new DOMXPath($doc);
256 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
257 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
258 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
259 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
260 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
261 $xpath->registerNamespace('poco', NAMESPACE_POCO);
262 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
263 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
265 $contact = ["id" => 0];
267 // Fetch the first author
268 $authordata = $xpath->query('//author')->item(0);
269 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, true);
274 * @brief Read attributes from element
276 * @param object $element Element object
278 * @return array attributes
280 private static function readAttributes($element)
284 foreach ($element->attributes as $attributes) {
285 $attribute[$attributes->name] = $attributes->textContent;
292 * @brief Imports an XML string containing OStatus elements
294 * @param string $xml The XML
295 * @param array $importer user record of the importing user
296 * @param array $contact contact
297 * @param string $hub Called by reference, returns the fetched hub data
300 public static function import($xml, array $importer, array &$contact = null, &$hub)
302 self::process($xml, $importer, $contact, $hub);
306 * @brief Internal feed processing
308 * @param string $xml The XML
309 * @param array $importer user record of the importing user
310 * @param array $contact contact
311 * @param string $hub Called by reference, returns the fetched hub data
312 * @param boolean $stored Is the post fresh imported or from the database?
313 * @param boolean $initialize Is it the leading post so that data has to be initialized?
315 * @return boolean Could the XML be processed?
317 private static function process($xml, array $importer, array &$contact = null, &$hub, $stored = false, $initialize = true)
320 self::$itemlist = [];
321 self::$conv_list = [];
324 Logger::log('Import OStatus message for user ' . $importer['uid'], Logger::DEBUG);
329 $doc = new DOMDocument();
330 @$doc->loadXML($xml);
332 $xpath = new DOMXPath($doc);
333 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
334 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
335 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
336 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
337 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
338 $xpath->registerNamespace('poco', NAMESPACE_POCO);
339 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
340 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
343 $hub_items = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0);
344 if (is_object($hub_items)) {
345 $hub_attributes = $hub_items->attributes;
346 if (is_object($hub_attributes)) {
347 foreach ($hub_attributes as $hub_attribute) {
348 if ($hub_attribute->name == "href") {
349 $hub = $hub_attribute->textContent;
350 Logger::log("Found hub ".$hub, Logger::DEBUG);
357 $header["uid"] = $importer["uid"];
358 $header["network"] = Protocol::OSTATUS;
360 $header["origin"] = 0;
361 $header["gravity"] = GRAVITY_COMMENT;
363 if (!is_object($doc->firstChild) || empty($doc->firstChild->tagName)) {
367 $first_child = $doc->firstChild->tagName;
369 if ($first_child == "feed") {
370 $entries = $xpath->query('/atom:feed/atom:entry');
372 $entries = $xpath->query('/atom:entry');
375 if ($entries->length == 1) {
376 // We reformat the XML to make it better readable
377 $doc2 = new DOMDocument();
378 $doc2->loadXML($xml);
379 $doc2->preserveWhiteSpace = false;
380 $doc2->formatOutput = true;
381 $xml2 = $doc2->saveXML();
383 $header["protocol"] = Conversation::PARCEL_SALMON;
384 $header["source"] = $xml2;
385 } elseif (!$initialize) {
389 // Fetch the first author
390 $authordata = $xpath->query('//author')->item(0);
391 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, $stored);
393 $entry = $xpath->query('/atom:entry');
395 // Reverse the order of the entries
398 foreach ($entries as $entry) {
399 $entrylist[] = $entry;
402 foreach (array_reverse($entrylist) as $entry) {
404 $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
406 if ($authorelement->length == 0) {
407 $authorelement = $xpath->query('atom:author', $entry);
410 if ($authorelement->length > 0) {
411 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, $stored);
414 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()', $entry);
418 $nickname = $author["author-name"];
421 $item = array_merge($header, $author);
423 $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
425 $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $entry);
428 if (in_array($item["verb"], ['qvitter-delete-notice', ACTIVITY_DELETE, 'delete'])) {
429 self::deleteNotice($item);
433 if (in_array($item["verb"], [NAMESPACE_OSTATUS."/unfavorite", ACTIVITY_UNFAVORITE])) {
434 // Ignore "Unfavorite" message
435 Logger::log("Ignore unfavorite message ".print_r($item, true), Logger::DEBUG);
439 // Deletions come with the same uri, so we check for duplicates after processing deletions
440 if (Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]])) {
441 Logger::log('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', Logger::DEBUG);
444 Logger::log('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', Logger::DEBUG);
447 if ($item["verb"] == ACTIVITY_JOIN) {
448 // ignore "Join" messages
449 Logger::log("Ignore join message ".print_r($item, true), Logger::DEBUG);
453 if ($item["verb"] == "http://mastodon.social/schema/1.0/block") {
454 // ignore mastodon "block" messages
455 Logger::log("Ignore block message ".print_r($item, true), Logger::DEBUG);
459 if ($item["verb"] == ACTIVITY_FOLLOW) {
460 Contact::addRelationship($importer, $contact, $item, $nickname);
464 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
466 Contact::removeFollower($importer, $contact, $item, $dummy);
470 if ($item["verb"] == ACTIVITY_FAVORITE) {
471 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
472 Logger::log("Favorite ".$orig_uri." ".print_r($item, true));
474 $item["verb"] = ACTIVITY_LIKE;
475 $item["parent-uri"] = $orig_uri;
476 $item["gravity"] = GRAVITY_ACTIVITY;
477 $item["object-type"] = ACTIVITY_OBJ_NOTE;
480 // http://activitystrea.ms/schema/1.0/rsvp-yes
481 if (!in_array($item["verb"], [ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE])) {
482 Logger::log("Unhandled verb ".$item["verb"]." ".print_r($item, true), Logger::DEBUG);
485 self::processPost($xpath, $entry, $item, $importer);
487 if ($initialize && (count(self::$itemlist) > 0)) {
488 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['parent-uri']) {
489 // We will import it everytime, when it is started by our contacts
490 $valid = !empty(self::$itemlist[0]['contact-id']);
492 // If not, then it depends on this setting
493 $valid = !Config::get('system', 'ostatus_full_threads');
495 Logger::log("Item with uri ".self::$itemlist[0]['uri']." will be imported due to the system settings.", Logger::DEBUG);
498 Logger::log("Item with uri ".self::$itemlist[0]['uri']." belongs to a contact (".self::$itemlist[0]['contact-id']."). It will be imported.", Logger::DEBUG);
501 // Never post a thread when the only interaction by our contact was a like
503 $verbs = [ACTIVITY_POST, ACTIVITY_SHARE];
504 foreach (self::$itemlist as $item) {
505 if (!empty($item['contact-id']) && in_array($item['verb'], $verbs)) {
510 Logger::log("Item with uri ".self::$itemlist[0]['uri']." will be imported since the thread contains posts or shares.", Logger::DEBUG);
514 // But we will only import complete threads
515 $valid = Item::exists(['uid' => $importer["uid"], 'uri' => self::$itemlist[0]['parent-uri']]);
517 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);
522 $default_contact = 0;
523 $key = count(self::$itemlist);
524 for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
525 if (empty(self::$itemlist[$key]['contact-id'])) {
526 self::$itemlist[$key]['contact-id'] = $default_contact;
528 $default_contact = $item['contact-id'];
531 foreach (self::$itemlist as $item) {
532 $found = Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]]);
534 Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", Logger::DEBUG);
535 } elseif ($item['contact-id'] < 0) {
536 Logger::log("Item with uri ".$item["uri"]." is from a blocked contact.", Logger::DEBUG);
538 // We are having duplicated entries. Hopefully this solves it.
539 if (Lock::acquire('ostatus_process_item_insert')) {
540 $ret = Item::insert($item);
541 Lock::release('ostatus_process_item_insert');
542 Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret);
544 $ret = Item::insert($item);
545 Logger::log("We couldn't lock - but tried to store the item anyway. Return value is ".$ret);
550 self::$itemlist = [];
552 Logger::log('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.', Logger::DEBUG);
558 * Removes notice item from database
559 * @param array $item item
562 private static function deleteNotice(array $item)
564 $condition = ['uid' => $item['uid'], 'author-id' => $item['author-id'], 'uri' => $item['uri']];
565 if (!Item::exists($condition)) {
566 Logger::log('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it.");
570 Item::delete($condition);
572 Logger::log('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
576 * @brief Processes the XML for a post
578 * @param object $xpath The xpath object
579 * @param object $entry The xml entry that is processed
580 * @param array $item The item array
581 * @param array $importer user record of the importing user
584 private static function processPost(DOMXPath $xpath, $entry, array &$item, array $importer)
586 $item["body"] = HTML::toBBCode(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
587 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $entry);
588 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) || ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
589 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
590 $item["body"] = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
591 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
592 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
595 $item["created"] = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
596 $item["edited"] = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
597 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
599 $conv = $xpath->query('ostatus:conversation', $entry);
600 if (is_object($conv->item(0))) {
601 foreach ($conv->item(0)->attributes as $attributes) {
602 if ($attributes->name == "ref") {
603 $item['conversation-uri'] = $attributes->textContent;
605 if ($attributes->name == "href") {
606 $item['conversation-href'] = $attributes->textContent;
613 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
614 if (is_object($inreplyto->item(0))) {
615 foreach ($inreplyto->item(0)->attributes as $attributes) {
616 if ($attributes->name == "ref") {
617 $item["parent-uri"] = $attributes->textContent;
619 if ($attributes->name == "href") {
620 $related = $attributes->textContent;
625 $georsspoint = $xpath->query('georss:point', $entry);
626 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
627 $item["coord"] = $georsspoint->item(0)->nodeValue;
630 $categories = $xpath->query('atom:category', $entry);
632 foreach ($categories as $category) {
633 foreach ($category->attributes as $attributes) {
634 if ($attributes->name == 'term') {
635 $term = $attributes->textContent;
636 if (!empty($item['tag'])) {
642 $item['tag'] .= '#[url=' . System::baseUrl() . '/search?tag=' . $term . ']' . $term . '[/url]';
651 $links = $xpath->query('atom:link', $entry);
653 $link_data = self::processLinks($links, $item);
654 $self = $link_data['self'];
655 $add_body = $link_data['add_body'];
660 $notice_info = $xpath->query('statusnet:notice_info', $entry);
661 if ($notice_info && ($notice_info->length > 0)) {
662 foreach ($notice_info->item(0)->attributes as $attributes) {
663 if ($attributes->name == "source") {
664 $item["app"] = strip_tags($attributes->textContent);
666 if ($attributes->name == "repeat_of") {
667 $repeat_of = $attributes->textContent;
671 // Is it a repeated post?
672 if (($repeat_of != "") || ($item["verb"] == ACTIVITY_SHARE)) {
673 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
674 if (!empty($link_data['add_body'])) {
675 $add_body .= $link_data['add_body'];
679 $item["body"] .= $add_body;
681 // Only add additional data when there is no picture in the post
682 if (!strstr($item["body"], '[/img]')) {
683 $item["body"] = add_page_info_to_body($item["body"]);
686 // Mastodon Content Warning
687 if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
688 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
689 if (!empty($clear_text)) {
690 $item['content-warning'] = HTML::toBBCode($clear_text);
694 if (($self != '') && empty($item['protocol'])) {
695 self::fetchSelf($self, $item);
698 if (!empty($item["conversation-href"])) {
699 self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
702 if (isset($item["parent-uri"])) {
703 if (!Item::exists(['uid' => $importer["uid"], 'uri' => $item['parent-uri']])) {
704 if ($related != '') {
705 self::fetchRelated($related, $item["parent-uri"], $importer);
708 Logger::log('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', Logger::DEBUG);
711 $item["parent-uri"] = $item["uri"];
712 $item["gravity"] = GRAVITY_PARENT;
715 if (($item['author-link'] != '') && !empty($item['protocol'])) {
716 $item = Conversation::insert($item);
719 self::$itemlist[] = $item;
723 * @brief Fetch the conversation for posts
725 * @param string $conversation The link to the conversation
726 * @param string $conversation_uri The conversation in "uri" format
729 private static function fetchConversation($conversation, $conversation_uri)
731 // Ensure that we only store a conversation once in a process
732 if (isset(self::$conv_list[$conversation])) {
736 self::$conv_list[$conversation] = true;
738 $curlResult = Network::curl($conversation, false, $redirects, ['accept_content' => 'application/atom+xml, text/html']);
740 if (!$curlResult->isSuccess()) {
746 if (stristr($curlResult->getHeader(), 'Content-Type: application/atom+xml')) {
747 $xml = $curlResult->getBody();
751 $doc = new DOMDocument();
752 if (!@$doc->loadHTML($curlResult->getBody())) {
755 $xpath = new DOMXPath($doc);
757 $links = $xpath->query('//link');
760 foreach ($links as $link) {
761 $attribute = self::readAttributes($link);
762 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
763 $file = $attribute['href'];
767 $conversation_atom = Network::curl($attribute['href']);
769 if ($conversation_atom->isSuccess()) {
770 $xml = $conversation_atom->getBody();
780 self::storeConversation($xml, $conversation, $conversation_uri);
784 * @brief Store a feed in several conversation entries
786 * @param string $xml The feed
787 * @param string $conversation conversation
788 * @param string $conversation_uri conversation uri
791 private static function storeConversation($xml, $conversation = '', $conversation_uri = '')
793 $doc = new DOMDocument();
794 @$doc->loadXML($xml);
796 $xpath = new DOMXPath($doc);
797 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
798 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
799 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
801 $entries = $xpath->query('/atom:feed/atom:entry');
803 // Now store the entries
804 foreach ($entries as $entry) {
805 $doc2 = new DOMDocument();
806 $doc2->preserveWhiteSpace = false;
807 $doc2->formatOutput = true;
811 $conv_data['protocol'] = Conversation::PARCEL_SPLIT_CONVERSATION;
812 $conv_data['network'] = Protocol::OSTATUS;
813 $conv_data['uri'] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
815 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
816 if (is_object($inreplyto->item(0))) {
817 foreach ($inreplyto->item(0)->attributes as $attributes) {
818 if ($attributes->name == "ref") {
819 $conv_data['reply-to-uri'] = $attributes->textContent;
824 $conv_data['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
826 $conv = $xpath->query('ostatus:conversation', $entry);
827 if (is_object($conv->item(0))) {
828 foreach ($conv->item(0)->attributes as $attributes) {
829 if ($attributes->name == "ref") {
830 $conv_data['conversation-uri'] = $attributes->textContent;
832 if ($attributes->name == "href") {
833 $conv_data['conversation-href'] = $attributes->textContent;
838 if ($conversation != '') {
839 $conv_data['conversation-uri'] = $conversation;
842 if ($conversation_uri != '') {
843 $conv_data['conversation-uri'] = $conversation_uri;
846 $entry = $doc2->importNode($entry, true);
848 $doc2->appendChild($entry);
850 $conv_data['source'] = $doc2->saveXML();
852 $condition = ['item-uri' => $conv_data['uri'],'protocol' => Conversation::PARCEL_FEED];
853 if (DBA::exists('conversation', $condition)) {
854 Logger::log('Delete deprecated entry for URI '.$conv_data['uri'], Logger::DEBUG);
855 DBA::delete('conversation', ['item-uri' => $conv_data['uri']]);
858 Logger::log('Store conversation data for uri '.$conv_data['uri'], Logger::DEBUG);
859 Conversation::insert($conv_data);
864 * @brief Fetch the own post so that it can be stored later
866 * We want to store the original data for later processing.
867 * This function is meant for cases where we process a feed with multiple entries.
868 * In that case we need to fetch the single posts here.
870 * @param string $self The link to the self item
871 * @param array $item The item array
874 private static function fetchSelf($self, array &$item)
876 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $self, Conversation::PARCEL_DFRN, Conversation::PARCEL_SALMON];
877 if (DBA::exists('conversation', $condition)) {
878 Logger::log('Conversation '.$item['uri'].' is already stored.', Logger::DEBUG);
882 $curlResult = Network::curl($self);
884 if (!$curlResult->isSuccess()) {
888 // We reformat the XML to make it better readable
889 $doc = new DOMDocument();
890 $doc->loadXML($curlResult->getBody());
891 $doc->preserveWhiteSpace = false;
892 $doc->formatOutput = true;
893 $xml = $doc->saveXML();
895 $item["protocol"] = Conversation::PARCEL_SALMON;
896 $item["source"] = $xml;
898 Logger::log('Conversation '.$item['uri'].' is now fetched.', Logger::DEBUG);
902 * @brief Fetch related posts and processes them
904 * @param string $related The link to the related item
905 * @param string $related_uri The related item in "uri" format
906 * @param array $importer user record of the importing user
909 private static function fetchRelated($related, $related_uri, $importer)
911 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, Conversation::PARCEL_DFRN, Conversation::PARCEL_SALMON];
912 $conversation = DBA::selectFirst('conversation', ['source', 'protocol'], $condition);
913 if (DBA::isResult($conversation)) {
915 $xml = $conversation['source'];
916 if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
917 Logger::log('Got valid cached XML for URI '.$related_uri, Logger::DEBUG);
920 if ($conversation['protocol'] == Conversation::PARCEL_SALMON) {
921 Logger::log('Delete invalid cached XML for URI '.$related_uri, Logger::DEBUG);
922 DBA::delete('conversation', ['item-uri' => $related_uri]);
927 $curlResult = Network::curl($related, false, $redirects, ['accept_content' => 'application/atom+xml, text/html']);
929 if (!$curlResult->isSuccess()) {
935 if (stristr($curlResult->getHeader(), 'Content-Type: application/atom+xml')) {
936 Logger::log('Directly fetched XML for URI ' . $related_uri, Logger::DEBUG);
937 $xml = $curlResult->getBody();
941 $doc = new DOMDocument();
942 if (!@$doc->loadHTML($curlResult->getBody())) {
945 $xpath = new DOMXPath($doc);
949 $links = $xpath->query('//link');
951 foreach ($links as $link) {
952 $attribute = self::readAttributes($link);
953 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
954 $atom_file = $attribute['href'];
957 if ($atom_file != '') {
958 $curlResult = Network::curl($atom_file);
960 if ($curlResult->isSuccess()) {
961 Logger::log('Fetched XML for URI ' . $related_uri, Logger::DEBUG);
962 $xml = $curlResult->getBody();
968 // Workaround for older GNU Social servers
969 if (($xml == '') && strstr($related, '/notice/')) {
970 $curlResult = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related).'.atom');
972 if ($curlResult->isSuccess()) {
973 Logger::log('GNU Social workaround to fetch XML for URI ' . $related_uri, Logger::DEBUG);
974 $xml = $curlResult->getBody();
978 // Even more worse workaround for GNU Social ;-)
980 $related_guess = OStatus::convertHref($related_uri);
981 $curlResult = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related_guess).'.atom');
983 if ($curlResult->isSuccess()) {
984 Logger::log('GNU Social workaround 2 to fetch XML for URI ' . $related_uri, Logger::DEBUG);
985 $xml = $curlResult->getBody();
989 // Finally we take the data that we fetched from "ostatus:conversation"
991 $condition = ['item-uri' => $related_uri, 'protocol' => Conversation::PARCEL_SPLIT_CONVERSATION];
992 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
993 if (DBA::isResult($conversation)) {
995 Logger::log('Got cached XML from conversation for URI '.$related_uri, Logger::DEBUG);
996 $xml = $conversation['source'];
1001 self::process($xml, $importer, $contact, $hub, $stored, false);
1003 Logger::log("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, Logger::DEBUG);
1009 * @brief Processes the XML for a repeated post
1011 * @param object $xpath The xpath object
1012 * @param object $entry The xml entry that is processed
1013 * @param array $item The item array
1014 * @param array $importer user record of the importing user
1016 * @return array with data from links
1018 private static function processRepeatedItem(DOMXPath $xpath, $entry, array &$item, array $importer)
1020 $activityobject = $xpath->query('activity:object', $entry)->item(0);
1022 if (!is_object($activityobject)) {
1028 $orig_uri = XML::getFirstNodeValue($xpath, 'atom:id/text()', $activityobject);
1030 $links = $xpath->query("atom:link", $activityobject);
1032 $link_data = self::processLinks($links, $item);
1035 $orig_body = XML::getFirstNodeValue($xpath, 'atom:content/text()', $activityobject);
1036 $orig_created = XML::getFirstNodeValue($xpath, 'atom:published/text()', $activityobject);
1037 $orig_edited = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $activityobject);
1039 $orig_author = self::fetchAuthor($xpath, $activityobject, $importer, $dummy, false);
1041 $item["author-name"] = $orig_author["author-name"];
1042 $item["author-link"] = $orig_author["author-link"];
1043 $item["author-id"] = $orig_author["author-id"];
1045 $item["body"] = HTML::toBBCode($orig_body);
1046 $item["created"] = $orig_created;
1047 $item["edited"] = $orig_edited;
1049 $item["uri"] = $orig_uri;
1051 $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $activityobject);
1053 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $activityobject);
1055 // Mastodon Content Warning
1056 if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $activityobject)) {
1057 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $activityobject);
1058 if (!empty($clear_text)) {
1059 $item['content-warning'] = HTML::toBBCode($clear_text);
1063 $inreplyto = $xpath->query('thr:in-reply-to', $activityobject);
1064 if (is_object($inreplyto->item(0))) {
1065 foreach ($inreplyto->item(0)->attributes as $attributes) {
1066 if ($attributes->name == "ref") {
1067 $item["parent-uri"] = $attributes->textContent;
1076 * @brief Processes links in the XML
1078 * @param object $links The xml data that contain links
1079 * @param array $item The item array
1081 * @return array with data from the links
1083 private static function processLinks($links, array &$item)
1085 $link_data = ['add_body' => '', 'self' => ''];
1087 foreach ($links as $link) {
1088 $attribute = self::readAttributes($link);
1090 if (!empty($attribute['rel']) && !empty($attribute['href'])) {
1091 switch ($attribute['rel']) {
1093 $item["plink"] = $attribute['href'];
1094 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION)
1095 || ($item["object-type"] == ACTIVITY_OBJ_EVENT)
1097 $item["body"] .= add_page_info($attribute['href']);
1100 case "ostatus:conversation":
1101 $link_data['conversation'] = $attribute['href'];
1102 $item['conversation-href'] = $link_data['conversation'];
1103 if (!isset($item['conversation-uri'])) {
1104 $item['conversation-uri'] = $item['conversation-href'];
1108 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
1109 if ($filetype == 'image') {
1110 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1112 if (!empty($item["attach"])) {
1113 $item["attach"] .= ',';
1115 $item["attach"] = '';
1117 if (!isset($attribute['length'])) {
1118 $attribute['length'] = "0";
1120 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.defaults($attribute, 'title', '').'"[/attach]';
1124 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
1125 if (!isset($item["parent-uri"])) {
1126 $item["parent-uri"] = $attribute['href'];
1128 $link_data['related'] = $attribute['href'];
1130 $item["body"] .= add_page_info($attribute['href']);
1134 if (empty($item["plink"])) {
1135 $item["plink"] = $attribute['href'];
1137 $link_data['self'] = $attribute['href'];
1146 * @brief Create an url out of an uri
1148 * @param string $href URI in the format "parameter1:parameter1:..."
1150 * @return string URL in the format http(s)://....
1152 public static function convertHref($href)
1154 $elements = explode(":", $href);
1156 if ((count($elements) <= 2) || ($elements[0] != "tag")) {
1160 $server = explode(",", $elements[1]);
1161 $conversation = explode("=", $elements[2]);
1163 if ((count($elements) == 4) && ($elements[2] == "post")) {
1164 return "http://".$server[0]."/notice/".$elements[3];
1167 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1170 if ($elements[3] == "objectType=thread") {
1171 return "http://".$server[0]."/conversation/".$conversation[1];
1173 return "http://".$server[0]."/notice/".$conversation[1];
1179 * @brief Checks if the current post is a reshare
1181 * @param array $item The item array of thw post
1183 * @return string The guid if the post is a reshare
1185 private static function getResharedGuid(array $item)
1187 $body = trim($item["body"]);
1189 // Skip if it isn't a pure repeated messages
1190 // Does it start with a share?
1191 if (strpos($body, "[share") > 0) {
1195 // Does it end with a share?
1196 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
1200 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
1201 // Skip if there is no shared message in there
1202 if ($body == $attributes) {
1207 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1208 if (!empty($matches[1])) {
1209 $guid = $matches[1];
1212 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1213 if (!empty($matches[1])) {
1214 $guid = $matches[1];
1221 * @brief Cleans the body of a post if it contains picture links
1223 * @param string $body The body
1225 * @return string The cleaned body
1227 private static function formatPicturePost($body)
1229 $siteinfo = BBCode::getAttachedData($body);
1231 if (($siteinfo["type"] == "photo")) {
1232 if (isset($siteinfo["preview"])) {
1233 $preview = $siteinfo["preview"];
1235 $preview = $siteinfo["image"];
1238 // Is it a remote picture? Then make a smaller preview here
1239 $preview = ProxyUtils::proxifyUrl($preview, false, ProxyUtils::SIZE_SMALL);
1241 // Is it a local picture? Then make it smaller here
1242 $preview = str_replace(["-0.jpg", "-0.png"], ["-2.jpg", "-2.png"], $preview);
1243 $preview = str_replace(["-1.jpg", "-1.png"], ["-2.jpg", "-2.png"], $preview);
1245 if (isset($siteinfo["url"])) {
1246 $url = $siteinfo["url"];
1248 $url = $siteinfo["image"];
1251 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1258 * @brief Adds the header elements to the XML document
1260 * @param object $doc XML document
1261 * @param array $owner Contact data of the poster
1262 * @param string $filter The related feed filter (activity, posts or comments)
1263 * @param bool $feed_mode Behave like a regular feed for users if true
1265 * @return object header root element
1267 private static function addHeader(DOMDocument $doc, array $owner, $filter, $feed_mode = false)
1271 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1272 $doc->appendChild($root);
1274 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1275 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1276 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1277 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1278 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1279 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1280 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1281 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1284 $selfUri = '/feed/' . $owner["nick"] . '/';
1287 $title = L10n::t('%s\'s timeline', $owner['name']);
1288 $selfUri .= $filter;
1291 $title = L10n::t('%s\'s posts', $owner['name']);
1294 $title = L10n::t('%s\'s comments', $owner['name']);
1295 $selfUri .= $filter;
1300 $selfUri = "/dfrn_poll/" . $owner["nick"];
1303 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
1304 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1305 XML::addElement($doc, $root, "id", System::baseUrl() . "/profile/" . $owner["nick"]);
1306 XML::addElement($doc, $root, "title", $title);
1307 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], Config::get('config', 'sitename')));
1308 XML::addElement($doc, $root, "logo", $owner["photo"]);
1309 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1311 $author = self::addAuthor($doc, $owner);
1312 $root->appendChild($author);
1314 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1315 XML::addElement($doc, $root, "link", "", $attributes);
1317 /// @TODO We have to find out what this is
1318 /// $attributes = array("href" => System::baseUrl()."/sup",
1319 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1320 /// "type" => "application/json");
1321 /// XML::addElement($doc, $root, "link", "", $attributes);
1323 self::hublinks($doc, $root, $owner["nick"]);
1325 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "salmon"];
1326 XML::addElement($doc, $root, "link", "", $attributes);
1328 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies"];
1329 XML::addElement($doc, $root, "link", "", $attributes);
1331 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention"];
1332 XML::addElement($doc, $root, "link", "", $attributes);
1334 $attributes = ["href" => System::baseUrl() . $selfUri, "rel" => "self", "type" => "application/atom+xml"];
1335 XML::addElement($doc, $root, "link", "", $attributes);
1337 if ($owner['account-type'] == Contact::ACCOUNT_TYPE_COMMUNITY) {
1338 $condition = ['uid' => $owner['uid'], 'self' => false, 'pending' => false,
1339 'archive' => false, 'hidden' => false, 'blocked' => false];
1340 $members = DBA::count('contact', $condition);
1341 XML::addElement($doc, $root, "statusnet:group_info", "", ["member_count" => $members]);
1348 * @brief Add the link to the push hubs to the XML document
1350 * @param object $doc XML document
1351 * @param object $root XML root element where the hub links are added
1352 * @param object $nick nick
1355 public static function hublinks(DOMDocument $doc, $root, $nick)
1357 $h = System::baseUrl() . '/pubsubhubbub/'.$nick;
1358 XML::addElement($doc, $root, "link", "", ["href" => $h, "rel" => "hub"]);
1362 * @brief Adds attachment data to the XML document
1364 * @param object $doc XML document
1365 * @param object $root XML root element where the hub links are added
1366 * @param array $item Data of the item that is to be posted
1369 private static function getAttachment(DOMDocument $doc, $root, $item)
1372 $siteinfo = BBCode::getAttachedData($item["body"]);
1374 switch ($siteinfo["type"]) {
1376 if (!empty($siteinfo["image"])) {
1377 $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1379 $attributes = ["rel" => "enclosure",
1380 "href" => $siteinfo["image"],
1381 "type" => $imgdata["mime"],
1382 "length" => intval($imgdata["size"])];
1383 XML::addElement($doc, $root, "link", "", $attributes);
1388 $attributes = ["rel" => "enclosure",
1389 "href" => $siteinfo["url"],
1390 "type" => "text/html; charset=UTF-8",
1392 "title" => defaults($siteinfo, "title", $siteinfo["url"])];
1393 XML::addElement($doc, $root, "link", "", $attributes);
1399 if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1400 $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1402 $attributes = ["rel" => "enclosure",
1403 "href" => $siteinfo["image"],
1404 "type" => $imgdata["mime"],
1405 "length" => intval($imgdata["size"])];
1407 XML::addElement($doc, $root, "link", "", $attributes);
1411 $arr = explode('[/attach],', $item['attach']);
1413 foreach ($arr as $r) {
1415 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1417 $attributes = ["rel" => "enclosure",
1418 "href" => $matches[1],
1419 "type" => $matches[3]];
1421 if (intval($matches[2])) {
1422 $attributes["length"] = intval($matches[2]);
1424 if (trim($matches[4]) != "") {
1425 $attributes["title"] = trim($matches[4]);
1427 XML::addElement($doc, $root, "link", "", $attributes);
1434 * @brief Adds the author element to the XML document
1436 * @param object $doc XML document
1437 * @param array $owner Contact data of the poster
1438 * @param bool $show_profile Whether to show profile
1440 * @return object author element
1442 private static function addAuthor(DOMDocument $doc, array $owner, $show_profile = true)
1444 $profile = DBA::selectFirst('profile', ['homepage', 'publish'], ['uid' => $owner['uid'], 'is-default' => true]);
1445 $author = $doc->createElement("author");
1446 XML::addElement($doc, $author, "id", $owner["url"]);
1447 if ($owner['account-type'] == Contact::ACCOUNT_TYPE_COMMUNITY) {
1448 XML::addElement($doc, $author, "activity:object-type", ACTIVITY_OBJ_GROUP);
1450 XML::addElement($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1452 XML::addElement($doc, $author, "uri", $owner["url"]);
1453 XML::addElement($doc, $author, "name", $owner["nick"]);
1454 XML::addElement($doc, $author, "email", $owner["addr"]);
1455 if ($show_profile) {
1456 XML::addElement($doc, $author, "summary", BBCode::convert($owner["about"], false, 7));
1459 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $owner["url"]];
1460 XML::addElement($doc, $author, "link", "", $attributes);
1464 "type" => "image/jpeg", // To-Do?
1465 "media:width" => 300,
1466 "media:height" => 300,
1467 "href" => $owner["photo"]];
1468 XML::addElement($doc, $author, "link", "", $attributes);
1470 if (isset($owner["thumb"])) {
1473 "type" => "image/jpeg", // To-Do?
1474 "media:width" => 80,
1475 "media:height" => 80,
1476 "href" => $owner["thumb"]];
1477 XML::addElement($doc, $author, "link", "", $attributes);
1480 XML::addElement($doc, $author, "poco:preferredUsername", $owner["nick"]);
1481 XML::addElement($doc, $author, "poco:displayName", $owner["name"]);
1482 if ($show_profile) {
1483 XML::addElement($doc, $author, "poco:note", BBCode::convert($owner["about"], false, 7));
1485 if (trim($owner["location"]) != "") {
1486 $element = $doc->createElement("poco:address");
1487 XML::addElement($doc, $element, "poco:formatted", $owner["location"]);
1488 $author->appendChild($element);
1492 if (DBA::isResult($profile) && !$show_profile) {
1493 if (trim($profile["homepage"]) != "") {
1494 $urls = $doc->createElement("poco:urls");
1495 XML::addElement($doc, $urls, "poco:type", "homepage");
1496 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
1497 XML::addElement($doc, $urls, "poco:primary", "true");
1498 $author->appendChild($urls);
1501 XML::addElement($doc, $author, "followers", "", ["url" => System::baseUrl()."/viewcontacts/".$owner["nick"]]);
1502 XML::addElement($doc, $author, "statusnet:profile_info", "", ["local_id" => $owner["uid"]]);
1504 if ($profile["publish"]) {
1505 XML::addElement($doc, $author, "mastodon:scope", "public");
1513 * @TODO Picture attachments should look like this:
1514 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1515 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1519 * @brief Returns the given activity if present - otherwise returns the "post" activity
1521 * @param array $item Data of the item that is to be posted
1523 * @return string activity
1525 private static function constructVerb(array $item)
1527 if (!empty($item['verb'])) {
1528 return $item['verb'];
1531 return ACTIVITY_POST;
1535 * @brief Returns the given object type if present - otherwise returns the "note" object type
1537 * @param array $item Data of the item that is to be posted
1539 * @return string Object type
1541 private static function constructObjecttype(array $item)
1543 if (!empty($item['object-type']) && in_array($item['object-type'], [ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT])) {
1544 return $item['object-type'];
1547 return ACTIVITY_OBJ_NOTE;
1551 * @brief Adds an entry element to the XML document
1553 * @param object $doc XML document
1554 * @param array $item Data of the item that is to be posted
1555 * @param array $owner Contact data of the poster
1556 * @param bool $toplevel optional default false
1557 * @param bool $feed_mode Behave like a regular feed for users if true
1559 * @return object Entry element
1561 private static function entry(DOMDocument $doc, array $item, array $owner, $toplevel = false, $feed_mode = false)
1565 $repeated_guid = self::getResharedGuid($item);
1566 if ($repeated_guid != "") {
1567 $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel);
1574 if ($item["verb"] == ACTIVITY_LIKE) {
1575 return self::likeEntry($doc, $item, $owner, $toplevel);
1576 } elseif (in_array($item["verb"], [ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"])) {
1577 return self::followEntry($doc, $item, $owner, $toplevel);
1579 return self::noteEntry($doc, $item, $owner, $toplevel, $feed_mode);
1584 * @brief Adds a source entry to the XML document
1586 * @param object $doc XML document
1587 * @param array $contact Array of the contact that is added
1589 * @return object Source element
1591 private static function sourceEntry(DOMDocument $doc, array $contact)
1593 $source = $doc->createElement("source");
1594 XML::addElement($doc, $source, "id", $contact["poll"]);
1595 XML::addElement($doc, $source, "title", $contact["name"]);
1596 XML::addElement($doc, $source, "link", "", ["rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]]);
1597 XML::addElement($doc, $source, "link", "", ["rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]]);
1598 XML::addElement($doc, $source, "icon", $contact["photo"]);
1599 XML::addElement($doc, $source, "updated", DateTimeFormat::utc($contact["success_update"]."+00:00", DateTimeFormat::ATOM));
1605 * @brief Fetches contact data from the contact or the gcontact table
1607 * @param string $url URL of the contact
1608 * @param array $owner Contact data of the poster
1610 * @return array Contact array
1612 private static function contactEntry($url, array $owner)
1615 "SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1616 DBA::escape(Strings::normaliseLink($url)),
1617 intval($owner["uid"])
1619 if (DBA::isResult($r)) {
1621 $contact["uid"] = -1;
1624 if (!DBA::isResult($r)) {
1625 $gcontact = DBA::selectFirst('gcontact', [], ['nurl' => Strings::normaliseLink($url)]);
1626 if (DBA::isResult($r)) {
1627 $contact = $gcontact;
1628 $contact["uid"] = -1;
1629 $contact["success_update"] = $contact["updated"];
1633 if (!DBA::isResult($r)) {
1637 if (!isset($contact["poll"])) {
1638 $data = Probe::uri($url);
1639 $contact["poll"] = $data["poll"];
1641 if (!$contact["alias"]) {
1642 $contact["alias"] = $data["alias"];
1646 if (!isset($contact["alias"])) {
1647 $contact["alias"] = $contact["url"];
1650 $contact['account-type'] = $owner['account-type'];
1656 * @brief Adds an entry element with reshared content
1658 * @param object $doc XML document
1659 * @param array $item Data of the item that is to be posted
1660 * @param array $owner Contact data of the poster
1661 * @param string $repeated_guid guid
1662 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1664 * @return object Entry element
1666 private static function reshareEntry(DOMDocument $doc, array $item, array $owner, $repeated_guid, $toplevel)
1668 if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1669 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1672 $title = self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1674 $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => false,
1675 'network' => [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS]];
1676 $repeated_item = Item::selectFirst([], $condition);
1677 if (!DBA::isResult($repeated_item)) {
1681 $contact = self::contactEntry($repeated_item['author-link'], $owner);
1683 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1685 self::entryContent($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1687 $as_object = $doc->createElement("activity:object");
1689 XML::addElement($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1691 self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false);
1693 $author = self::addAuthor($doc, $contact, false);
1694 $as_object->appendChild($author);
1696 $as_object2 = $doc->createElement("activity:object");
1698 XML::addElement($doc, $as_object2, "activity:object-type", self::constructObjecttype($repeated_item));
1700 $title = sprintf("New comment by %s", $contact["nick"]);
1702 self::entryContent($doc, $as_object2, $repeated_item, $owner, $title);
1704 $as_object->appendChild($as_object2);
1706 self::entryFooter($doc, $as_object, $item, $owner, false);
1708 $source = self::sourceEntry($doc, $contact);
1710 $as_object->appendChild($source);
1712 $entry->appendChild($as_object);
1714 self::entryFooter($doc, $entry, $item, $owner);
1720 * @brief Adds an entry element with a "like"
1722 * @param object $doc XML document
1723 * @param array $item Data of the item that is to be posted
1724 * @param array $owner Contact data of the poster
1725 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1727 * @return object Entry element with "like"
1729 private static function likeEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1731 if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1732 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1735 $title = self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1737 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1738 self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false);
1740 $as_object = $doc->createElement("activity:object");
1742 $parent = Item::selectFirst([], ['uri' => $item["thr-parent"], 'uid' => $item["uid"]]);
1748 XML::addElement($doc, $as_object, "activity:object-type", self::constructObjecttype($parent));
1750 self::entryContent($doc, $as_object, $parent, $owner, "New entry");
1752 $entry->appendChild($as_object);
1754 self::entryFooter($doc, $entry, $item, $owner);
1760 * @brief Adds the person object element to the XML document
1762 * @param object $doc XML document
1763 * @param array $owner Contact data of the poster
1764 * @param array $contact Contact data of the target
1766 * @return object author element
1768 private static function addPersonObject(DOMDocument $doc, array $owner, array $contact)
1770 $object = $doc->createElement("activity:object");
1771 XML::addElement($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1773 if ($contact['network'] == Protocol::PHANTOM) {
1774 XML::addElement($doc, $object, "id", $contact['url']);
1778 XML::addElement($doc, $object, "id", $contact["alias"]);
1779 XML::addElement($doc, $object, "title", $contact["nick"]);
1781 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $contact["url"]];
1782 XML::addElement($doc, $object, "link", "", $attributes);
1786 "type" => "image/jpeg", // To-Do?
1787 "media:width" => 300,
1788 "media:height" => 300,
1789 "href" => $contact["photo"]];
1790 XML::addElement($doc, $object, "link", "", $attributes);
1792 XML::addElement($doc, $object, "poco:preferredUsername", $contact["nick"]);
1793 XML::addElement($doc, $object, "poco:displayName", $contact["name"]);
1795 if (trim($contact["location"]) != "") {
1796 $element = $doc->createElement("poco:address");
1797 XML::addElement($doc, $element, "poco:formatted", $contact["location"]);
1798 $object->appendChild($element);
1805 * @brief Adds a follow/unfollow entry element
1807 * @param object $doc XML document
1808 * @param array $item Data of the follow/unfollow message
1809 * @param array $owner Contact data of the poster
1810 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1812 * @return object Entry element
1814 private static function followEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1816 $item["id"] = $item["parent"] = 0;
1817 $item["created"] = $item["edited"] = date("c");
1818 $item["private"] = true;
1820 $contact = Probe::uri($item['follow']);
1822 if ($contact['alias'] == '') {
1823 $contact['alias'] = $contact["url"];
1825 $item['follow'] = $contact['alias'];
1828 $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($contact["url"])];
1829 $user_contact = DBA::selectFirst('contact', ['id'], $condition);
1831 if (DBA::isResult($user_contact)) {
1832 $connect_id = $user_contact['id'];
1837 if ($item['verb'] == ACTIVITY_FOLLOW) {
1838 $message = L10n::t('%s is now following %s.');
1839 $title = L10n::t('following');
1840 $action = "subscription";
1842 $message = L10n::t('%s stopped following %s.');
1843 $title = L10n::t('stopped following');
1844 $action = "unfollow";
1847 $item["uri"] = $item['parent-uri'] = $item['thr-parent']
1848 = 'tag:'.get_app()->getHostName().
1849 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1850 ':person:'.$connect_id.':'.$item['created'];
1852 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1854 self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1856 self::entryContent($doc, $entry, $item, $owner, $title);
1858 $object = self::addPersonObject($doc, $owner, $contact);
1859 $entry->appendChild($object);
1861 self::entryFooter($doc, $entry, $item, $owner);
1867 * @brief Adds a regular entry element
1869 * @param object $doc XML document
1870 * @param array $item Data of the item that is to be posted
1871 * @param array $owner Contact data of the poster
1872 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1873 * @param bool $feed_mode Behave like a regular feed for users if true
1875 * @return object Entry element
1877 private static function noteEntry(DOMDocument $doc, array $item, array $owner, $toplevel, $feed_mode)
1879 if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1880 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1883 $title = self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1885 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1887 self::entryContent($doc, $entry, $item, $owner, $title, '', true, $feed_mode);
1889 self::entryFooter($doc, $entry, $item, $owner, !$feed_mode, $feed_mode);
1895 * @brief Adds a header element to the XML document
1897 * @param object $doc XML document
1898 * @param object $entry The entry element where the elements are added
1899 * @param array $owner Contact data of the poster
1900 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1902 * @return string The title for the element
1904 private static function entryHeader(DOMDocument $doc, &$entry, array $owner, array $item, $toplevel)
1906 /// @todo Check if this title stuff is really needed (I guess not)
1908 $entry = $doc->createElement("entry");
1909 if (!empty($item['title'])) {
1910 $title = BBCode::convert($item['title'], false, 7);
1912 $title = sprintf("New note by %s", $owner["nick"]);
1915 if ($owner['account-type'] == Contact::ACCOUNT_TYPE_COMMUNITY) {
1916 $contact = self::contactEntry($item['author-link'], $owner);
1917 $author = self::addAuthor($doc, $contact, false);
1918 $entry->appendChild($author);
1921 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
1923 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1924 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1925 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1926 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1927 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
1928 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1929 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1930 $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1932 $author = self::addAuthor($doc, $owner);
1933 $entry->appendChild($author);
1935 $title = sprintf("New comment by %s", $owner["nick"]);
1941 * @brief Adds elements to the XML document
1943 * @param object $doc XML document
1944 * @param object $entry Entry element where the content is added
1945 * @param array $item Data of the item that is to be posted
1946 * @param array $owner Contact data of the poster
1947 * @param string $title Title for the post
1948 * @param string $verb The activity verb
1949 * @param bool $complete Add the "status_net" element?
1950 * @param bool $feed_mode Behave like a regular feed for users if true
1953 private static function entryContent(DOMDocument $doc, $entry, array $item, array $owner, $title, $verb = "", $complete = true, $feed_mode = false)
1956 $verb = self::constructVerb($item);
1959 XML::addElement($doc, $entry, "id", $item["uri"]);
1960 XML::addElement($doc, $entry, "title", html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1962 $body = self::formatPicturePost($item['body']);
1964 if (!empty($item['title']) && !$feed_mode) {
1965 $body = "[b]".$item['title']."[/b]\n\n".$body;
1968 $body = BBCode::convert($body, false, 7);
1970 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1972 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1973 "href" => System::baseUrl()."/display/".$item["guid"]]
1976 if (!$feed_mode && $complete && ($item["id"] > 0)) {
1977 XML::addElement($doc, $entry, "status_net", "", ["notice_id" => $item["id"]]);
1981 XML::addElement($doc, $entry, "activity:verb", $verb);
1984 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
1985 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
1989 * @brief Adds the elements at the foot of an entry to the XML document
1991 * @param object $doc XML document
1992 * @param object $entry The entry element where the elements are added
1993 * @param array $item Data of the item that is to be posted
1994 * @param array $owner Contact data of the poster
1995 * @param bool $complete default true
1996 * @param bool $feed_mode Behave like a regular feed for users if true
1999 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner, $complete = true, $feed_mode = false)
2003 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
2004 $parent = Item::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item["parent"]]);
2005 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
2007 $thrparent = Item::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $parent_item]);
2009 if (DBA::isResult($thrparent)) {
2010 $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
2011 $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
2012 $parent_plink = $thrparent["plink"];
2014 $mentioned[$parent["author-link"]] = $parent["author-link"];
2015 $mentioned[$parent["owner-link"]] = $parent["owner-link"];
2016 $parent_plink = System::baseUrl()."/display/".$parent["guid"];
2020 "ref" => $parent_item,
2021 "href" => $parent_plink];
2022 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
2026 "href" => $parent_plink];
2027 XML::addElement($doc, $entry, "link", "", $attributes);
2030 if (!$feed_mode && (intval($item["parent"]) > 0)) {
2031 $conversation_href = $conversation_uri = str_replace('/objects/', '/context/', $item['parent-uri']);
2033 if (isset($parent_item)) {
2034 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $parent_item]);
2035 if (DBA::isResult($conversation)) {
2036 if ($conversation['conversation-uri'] != '') {
2037 $conversation_uri = $conversation['conversation-uri'];
2039 if ($conversation['conversation-href'] != '') {
2040 $conversation_href = $conversation['conversation-href'];
2045 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:conversation", "href" => $conversation_href]);
2048 "href" => $conversation_href,
2049 "local_id" => $item["parent"],
2050 "ref" => $conversation_uri];
2052 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
2055 $tags = item::getFeedTags($item);
2058 foreach ($tags as $t) {
2060 $mentioned[$t[1]] = $t[1];
2065 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2067 foreach ($mentioned as $mention) {
2068 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2069 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2071 $mentioned = $newmentions;
2073 foreach ($mentioned as $mention) {
2074 $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($mention)];
2075 $contact = DBA::selectFirst('contact', ['forum', 'prv', 'self', 'contact-type'], $condition);
2076 if ($contact["forum"] || $contact["prv"] || ($owner['contact-type'] == Contact::ACCOUNT_TYPE_COMMUNITY) ||
2077 ($contact['self'] && ($owner['account-type'] == Contact::ACCOUNT_TYPE_COMMUNITY))) {
2078 XML::addElement($doc, $entry, "link", "",
2080 "rel" => "mentioned",
2081 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
2085 XML::addElement($doc, $entry, "link", "",
2087 "rel" => "mentioned",
2088 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
2094 if ($owner['account-type'] == Contact::ACCOUNT_TYPE_COMMUNITY) {
2095 XML::addElement($doc, $entry, "link", "", [
2096 "rel" => "mentioned",
2097 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/group",
2098 "href" => $owner['url']
2102 if (!$item["private"] && !$feed_mode) {
2103 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:attention",
2104 "href" => "http://activityschema.org/collection/public"]);
2105 XML::addElement($doc, $entry, "link", "", ["rel" => "mentioned",
2106 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2107 "href" => "http://activityschema.org/collection/public"]);
2108 XML::addElement($doc, $entry, "mastodon:scope", "public");
2112 foreach ($tags as $t) {
2114 XML::addElement($doc, $entry, "category", "", ["term" => $t[2]]);
2119 self::getAttachment($doc, $entry, $item);
2121 if ($complete && ($item["id"] > 0)) {
2122 $app = $item["app"];
2127 $attributes = ["local_id" => $item["id"], "source" => $app];
2129 if (isset($parent["id"])) {
2130 $attributes["repeat_of"] = $parent["id"];
2133 if ($item["coord"] != "") {
2134 XML::addElement($doc, $entry, "georss:point", $item["coord"]);
2137 XML::addElement($doc, $entry, "statusnet:notice_info", "", $attributes);
2142 * Creates the XML feed for a given nickname
2144 * Supported filters:
2145 * - activity (default): all the public posts
2146 * - posts: all the public top-level posts
2147 * - comments: all the public replies
2149 * Updates the provided last_update parameter if the result comes from the
2150 * cache or it is empty
2152 * @brief Creates the XML feed for a given nickname
2154 * @param string $owner_nick Nickname of the feed owner
2155 * @param string $last_update Date of the last update
2156 * @param integer $max_items Number of maximum items to fetch
2157 * @param string $filter Feed items filter (activity, posts or comments)
2158 * @param boolean $nocache Wether to bypass caching
2159 * @param boolean $feed_mode Behave like a regular feed for users if true
2161 * @return string XML feed
2163 public static function feed($owner_nick, &$last_update, $max_items = 300, $filter = 'activity', $nocache = false, $feed_mode = false)
2165 $stamp = microtime(true);
2167 $owner = User::getOwnerDataByNick($owner_nick);
2172 $cachekey = "ostatus:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
2174 $previous_created = $last_update;
2176 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
2177 if ((time() - strtotime($owner['last-item'])) < 15*60) {
2178 $result = Cache::get($cachekey);
2179 if (!$nocache && !is_null($result)) {
2180 Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', Logger::DEBUG);
2181 $last_update = $result['last_update'];
2182 return $result['feed'];
2186 if (!strlen($last_update)) {
2187 $last_update = 'now -30 days';
2190 $check_date = DateTimeFormat::utc($last_update);
2191 $authorid = Contact::getIdForURL($owner["url"], 0, true);
2193 $condition = ["`uid` = ? AND `created` > ? AND NOT `deleted`
2194 AND NOT `private` AND `visible` AND `wall` AND `parent-network` IN (?, ?)",
2195 $owner["uid"], $check_date, Protocol::OSTATUS, Protocol::DFRN];
2197 if ($filter === 'comments') {
2198 $condition[0] .= " AND `object-type` = ? ";
2199 $condition[] = ACTIVITY_OBJ_COMMENT;
2202 if ($owner['account-type'] != Contact::ACCOUNT_TYPE_COMMUNITY) {
2203 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
2204 $condition[] = $owner["id"];
2205 $condition[] = $authorid;
2208 $params = ['order' => ['created' => true], 'limit' => $max_items];
2210 if ($filter === 'posts') {
2211 $ret = Item::selectThread([], $condition, $params);
2213 $ret = Item::select([], $condition, $params);
2216 $items = Item::inArray($ret);
2218 $doc = new DOMDocument('1.0', 'utf-8');
2219 $doc->formatOutput = true;
2221 $root = self::addHeader($doc, $owner, $filter, $feed_mode);
2223 foreach ($items as $item) {
2224 if (Config::get('system', 'ostatus_debug')) {
2225 $item['body'] .= '🍼';
2228 $entry = self::entry($doc, $item, $owner, false, $feed_mode);
2229 $root->appendChild($entry);
2231 if ($last_update < $item['created']) {
2232 $last_update = $item['created'];
2236 $feeddata = trim($doc->saveXML());
2238 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
2239 Cache::set($cachekey, $msg, Cache::QUARTER_HOUR);
2241 Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, Logger::DEBUG);
2247 * @brief Creates the XML for a salmon message
2249 * @param array $item Data of the item that is to be posted
2250 * @param array $owner Contact data of the poster
2252 * @return string XML for the salmon
2254 public static function salmon(array $item, array $owner)
2256 $doc = new DOMDocument('1.0', 'utf-8');
2257 $doc->formatOutput = true;
2259 if (Config::get('system', 'ostatus_debug')) {
2260 $item['body'] .= '🐟';
2263 $entry = self::entry($doc, $item, $owner, true);
2265 $doc->appendChild($entry);
2267 return trim($doc->saveXML());