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\XML;
31 require_once 'include/dba.php';
32 require_once 'include/items.php';
33 require_once 'mod/share.php';
34 require_once 'include/enotify.php';
35 require_once 'include/api.php';
38 * @brief This class contain functions for the OStatus protocol
42 private static $itemlist;
43 private static $conv_list = [];
46 * @brief Fetches author data
48 * @param object $xpath The xpath object
49 * @param object $context The xml context of the author details
50 * @param array $importer user record of the importing user
51 * @param array $contact Called by reference, will contain the fetched contact
52 * @param bool $onlyfetch Only fetch the header without updating the contact entries
54 * @return array Array of author related entries for the item
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"], normalise_link($author["author-link"]), normalise_link($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'] = normalise_link($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' => normalise_link($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
248 public static function salmonAuthor($xml, array $importer)
254 $doc = new DOMDocument();
255 @$doc->loadXML($xml);
257 $xpath = new DOMXPath($doc);
258 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
259 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
260 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
261 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
262 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
263 $xpath->registerNamespace('poco', NAMESPACE_POCO);
264 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
265 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
267 $contact = ["id" => 0];
269 // Fetch the first author
270 $authordata = $xpath->query('//author')->item(0);
271 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, true);
276 * @brief Read attributes from element
278 * @param object $element Element object
280 * @return array attributes
282 private static function readAttributes($element)
286 foreach ($element->attributes as $attributes) {
287 $attribute[$attributes->name] = $attributes->textContent;
294 * @brief Imports an XML string containing OStatus elements
296 * @param string $xml The XML
297 * @param array $importer user record of the importing user
298 * @param array $contact contact
299 * @param string $hub Called by reference, returns the fetched hub data
302 public static function import($xml, array $importer, array &$contact = null, &$hub)
304 self::process($xml, $importer, $contact, $hub);
308 * @brief Internal feed processing
310 * @param string $xml The XML
311 * @param array $importer user record of the importing user
312 * @param array $contact contact
313 * @param string $hub Called by reference, returns the fetched hub data
314 * @param boolean $stored Is the post fresh imported or from the database?
315 * @param boolean $initialize Is it the leading post so that data has to be initialized?
317 * @return boolean Could the XML be processed?
319 private static function process($xml, array $importer, array &$contact = null, &$hub, $stored = false, $initialize = true)
322 self::$itemlist = [];
323 self::$conv_list = [];
326 Logger::log('Import OStatus message for user ' . $importer['uid'], Logger::DEBUG);
331 $doc = new DOMDocument();
332 @$doc->loadXML($xml);
334 $xpath = new DOMXPath($doc);
335 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
336 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
337 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
338 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
339 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
340 $xpath->registerNamespace('poco', NAMESPACE_POCO);
341 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
342 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
345 $hub_items = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0);
346 if (is_object($hub_items)) {
347 $hub_attributes = $hub_items->attributes;
348 if (is_object($hub_attributes)) {
349 foreach ($hub_attributes as $hub_attribute) {
350 if ($hub_attribute->name == "href") {
351 $hub = $hub_attribute->textContent;
352 Logger::log("Found hub ".$hub, Logger::DEBUG);
359 $header["uid"] = $importer["uid"];
360 $header["network"] = Protocol::OSTATUS;
362 $header["origin"] = 0;
363 $header["gravity"] = GRAVITY_COMMENT;
365 if (!is_object($doc->firstChild) || empty($doc->firstChild->tagName)) {
369 $first_child = $doc->firstChild->tagName;
371 if ($first_child == "feed") {
372 $entries = $xpath->query('/atom:feed/atom:entry');
374 $entries = $xpath->query('/atom:entry');
377 if ($entries->length == 1) {
378 // We reformat the XML to make it better readable
379 $doc2 = new DOMDocument();
380 $doc2->loadXML($xml);
381 $doc2->preserveWhiteSpace = false;
382 $doc2->formatOutput = true;
383 $xml2 = $doc2->saveXML();
385 $header["protocol"] = Conversation::PARCEL_SALMON;
386 $header["source"] = $xml2;
387 } elseif (!$initialize) {
391 // Fetch the first author
392 $authordata = $xpath->query('//author')->item(0);
393 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, $stored);
395 $entry = $xpath->query('/atom:entry');
397 // Reverse the order of the entries
400 foreach ($entries as $entry) {
401 $entrylist[] = $entry;
404 foreach (array_reverse($entrylist) as $entry) {
406 $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
408 if ($authorelement->length == 0) {
409 $authorelement = $xpath->query('atom:author', $entry);
412 if ($authorelement->length > 0) {
413 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, $stored);
416 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()', $entry);
420 $nickname = $author["author-name"];
423 $item = array_merge($header, $author);
425 $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
427 $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $entry);
430 if (in_array($item["verb"], ['qvitter-delete-notice', ACTIVITY_DELETE, 'delete'])) {
431 self::deleteNotice($item);
435 if (in_array($item["verb"], [NAMESPACE_OSTATUS."/unfavorite", ACTIVITY_UNFAVORITE])) {
436 // Ignore "Unfavorite" message
437 Logger::log("Ignore unfavorite message ".print_r($item, true), Logger::DEBUG);
441 // Deletions come with the same uri, so we check for duplicates after processing deletions
442 if (Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]])) {
443 Logger::log('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', Logger::DEBUG);
446 Logger::log('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', Logger::DEBUG);
449 if ($item["verb"] == ACTIVITY_JOIN) {
450 // ignore "Join" messages
451 Logger::log("Ignore join message ".print_r($item, true), Logger::DEBUG);
455 if ($item["verb"] == "http://mastodon.social/schema/1.0/block") {
456 // ignore mastodon "block" messages
457 Logger::log("Ignore block message ".print_r($item, true), Logger::DEBUG);
461 if ($item["verb"] == ACTIVITY_FOLLOW) {
462 Contact::addRelationship($importer, $contact, $item, $nickname);
466 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
468 Contact::removeFollower($importer, $contact, $item, $dummy);
472 if ($item["verb"] == ACTIVITY_FAVORITE) {
473 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
474 Logger::log("Favorite ".$orig_uri." ".print_r($item, true));
476 $item["verb"] = ACTIVITY_LIKE;
477 $item["parent-uri"] = $orig_uri;
478 $item["gravity"] = GRAVITY_ACTIVITY;
479 $item["object-type"] = ACTIVITY_OBJ_NOTE;
482 // http://activitystrea.ms/schema/1.0/rsvp-yes
483 if (!in_array($item["verb"], [ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE])) {
484 Logger::log("Unhandled verb ".$item["verb"]." ".print_r($item, true), Logger::DEBUG);
487 self::processPost($xpath, $entry, $item, $importer);
489 if ($initialize && (count(self::$itemlist) > 0)) {
490 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['parent-uri']) {
491 // We will import it everytime, when it is started by our contacts
492 $valid = !empty(self::$itemlist[0]['contact-id']);
494 // If not, then it depends on this setting
495 $valid = !Config::get('system', 'ostatus_full_threads');
497 Logger::log("Item with uri ".self::$itemlist[0]['uri']." will be imported due to the system settings.", Logger::DEBUG);
500 Logger::log("Item with uri ".self::$itemlist[0]['uri']." belongs to a contact (".self::$itemlist[0]['contact-id']."). It will be imported.", Logger::DEBUG);
503 // Never post a thread when the only interaction by our contact was a like
505 $verbs = [ACTIVITY_POST, ACTIVITY_SHARE];
506 foreach (self::$itemlist as $item) {
507 if (!empty($item['contact-id']) && in_array($item['verb'], $verbs)) {
512 Logger::log("Item with uri ".self::$itemlist[0]['uri']." will be imported since the thread contains posts or shares.", Logger::DEBUG);
516 // But we will only import complete threads
517 $valid = Item::exists(['uid' => $importer["uid"], 'uri' => self::$itemlist[0]['parent-uri']]);
519 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);
524 $default_contact = 0;
525 $key = count(self::$itemlist);
526 for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
527 if (empty(self::$itemlist[$key]['contact-id'])) {
528 self::$itemlist[$key]['contact-id'] = $default_contact;
530 $default_contact = $item['contact-id'];
533 foreach (self::$itemlist as $item) {
534 $found = Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]]);
536 Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", Logger::DEBUG);
537 } elseif ($item['contact-id'] < 0) {
538 Logger::log("Item with uri ".$item["uri"]." is from a blocked contact.", Logger::DEBUG);
540 // We are having duplicated entries. Hopefully this solves it.
541 if (Lock::acquire('ostatus_process_item_insert')) {
542 $ret = Item::insert($item);
543 Lock::release('ostatus_process_item_insert');
544 Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret);
546 $ret = Item::insert($item);
547 Logger::log("We couldn't lock - but tried to store the item anyway. Return value is ".$ret);
552 self::$itemlist = [];
554 Logger::log('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.', Logger::DEBUG);
560 * Removes notice item from database
561 * @param array $item item
564 private static function deleteNotice(array $item)
566 $condition = ['uid' => $item['uid'], 'author-id' => $item['author-id'], 'uri' => $item['uri']];
567 if (!Item::exists($condition)) {
568 Logger::log('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it.");
572 Item::delete($condition);
574 Logger::log('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
578 * @brief Processes the XML for a post
580 * @param object $xpath The xpath object
581 * @param object $entry The xml entry that is processed
582 * @param array $item The item array
583 * @param array $importer user record of the importing user
586 private static function processPost(DOMXPath $xpath, $entry, array &$item, array $importer)
588 $item["body"] = HTML::toBBCode(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
589 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $entry);
590 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) || ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
591 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
592 $item["body"] = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
593 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
594 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
597 $item["created"] = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
598 $item["edited"] = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
599 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
601 $conv = $xpath->query('ostatus:conversation', $entry);
602 if (is_object($conv->item(0))) {
603 foreach ($conv->item(0)->attributes as $attributes) {
604 if ($attributes->name == "ref") {
605 $item['conversation-uri'] = $attributes->textContent;
607 if ($attributes->name == "href") {
608 $item['conversation-href'] = $attributes->textContent;
615 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
616 if (is_object($inreplyto->item(0))) {
617 foreach ($inreplyto->item(0)->attributes as $attributes) {
618 if ($attributes->name == "ref") {
619 $item["parent-uri"] = $attributes->textContent;
621 if ($attributes->name == "href") {
622 $related = $attributes->textContent;
627 $georsspoint = $xpath->query('georss:point', $entry);
628 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
629 $item["coord"] = $georsspoint->item(0)->nodeValue;
632 $categories = $xpath->query('atom:category', $entry);
634 foreach ($categories as $category) {
635 foreach ($category->attributes as $attributes) {
636 if ($attributes->name == "term") {
637 $term = $attributes->textContent;
638 if (!empty($item["tag"])) {
644 $item["tag"] .= "#[url=".System::baseUrl()."/search?tag=".$term."]".$term."[/url]";
653 $links = $xpath->query('atom:link', $entry);
655 $link_data = self::processLinks($links, $item);
656 $self = $link_data['self'];
657 $add_body = $link_data['add_body'];
662 $notice_info = $xpath->query('statusnet:notice_info', $entry);
663 if ($notice_info && ($notice_info->length > 0)) {
664 foreach ($notice_info->item(0)->attributes as $attributes) {
665 if ($attributes->name == "source") {
666 $item["app"] = strip_tags($attributes->textContent);
668 if ($attributes->name == "repeat_of") {
669 $repeat_of = $attributes->textContent;
673 // Is it a repeated post?
674 if (($repeat_of != "") || ($item["verb"] == ACTIVITY_SHARE)) {
675 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
676 if (!empty($link_data['add_body'])) {
677 $add_body .= $link_data['add_body'];
681 $item["body"] .= $add_body;
683 // Only add additional data when there is no picture in the post
684 if (!strstr($item["body"], '[/img]')) {
685 $item["body"] = add_page_info_to_body($item["body"]);
688 // Mastodon Content Warning
689 if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
690 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
691 if (!empty($clear_text)) {
692 $item['content-warning'] = HTML::toBBCode($clear_text);
696 if (($self != '') && empty($item['protocol'])) {
697 self::fetchSelf($self, $item);
700 if (!empty($item["conversation-href"])) {
701 self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
704 if (isset($item["parent-uri"])) {
705 if (!Item::exists(['uid' => $importer["uid"], 'uri' => $item['parent-uri']])) {
706 if ($related != '') {
707 self::fetchRelated($related, $item["parent-uri"], $importer);
710 Logger::log('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', Logger::DEBUG);
713 $item["parent-uri"] = $item["uri"];
714 $item["gravity"] = GRAVITY_PARENT;
717 if (($item['author-link'] != '') && !empty($item['protocol'])) {
718 $item = Conversation::insert($item);
721 self::$itemlist[] = $item;
725 * @brief Fetch the conversation for posts
727 * @param string $conversation The link to the conversation
728 * @param string $conversation_uri The conversation in "uri" format
731 private static function fetchConversation($conversation, $conversation_uri)
733 // Ensure that we only store a conversation once in a process
734 if (isset(self::$conv_list[$conversation])) {
738 self::$conv_list[$conversation] = true;
740 $curlResult = Network::curl($conversation, false, $redirects, ['accept_content' => 'application/atom+xml, text/html']);
742 if (!$curlResult->isSuccess()) {
748 if (stristr($curlResult->getHeader(), 'Content-Type: application/atom+xml')) {
749 $xml = $curlResult->getBody();
753 $doc = new DOMDocument();
754 if (!@$doc->loadHTML($curlResult->getBody())) {
757 $xpath = new DOMXPath($doc);
759 $links = $xpath->query('//link');
762 foreach ($links as $link) {
763 $attribute = self::readAttributes($link);
764 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
765 $file = $attribute['href'];
769 $conversation_atom = Network::curl($attribute['href']);
771 if ($conversation_atom->isSuccess()) {
772 $xml = $conversation_atom->getBody();
782 self::storeConversation($xml, $conversation, $conversation_uri);
786 * @brief Store a feed in several conversation entries
788 * @param string $xml The feed
789 * @param string $conversation conversation
790 * @param string $conversation_uri conversation uri
793 private static function storeConversation($xml, $conversation = '', $conversation_uri = '')
795 $doc = new DOMDocument();
796 @$doc->loadXML($xml);
798 $xpath = new DOMXPath($doc);
799 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
800 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
801 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
803 $entries = $xpath->query('/atom:feed/atom:entry');
805 // Now store the entries
806 foreach ($entries as $entry) {
807 $doc2 = new DOMDocument();
808 $doc2->preserveWhiteSpace = false;
809 $doc2->formatOutput = true;
813 $conv_data['protocol'] = Conversation::PARCEL_SPLIT_CONVERSATION;
814 $conv_data['network'] = Protocol::OSTATUS;
815 $conv_data['uri'] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
817 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
818 if (is_object($inreplyto->item(0))) {
819 foreach ($inreplyto->item(0)->attributes as $attributes) {
820 if ($attributes->name == "ref") {
821 $conv_data['reply-to-uri'] = $attributes->textContent;
826 $conv_data['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
828 $conv = $xpath->query('ostatus:conversation', $entry);
829 if (is_object($conv->item(0))) {
830 foreach ($conv->item(0)->attributes as $attributes) {
831 if ($attributes->name == "ref") {
832 $conv_data['conversation-uri'] = $attributes->textContent;
834 if ($attributes->name == "href") {
835 $conv_data['conversation-href'] = $attributes->textContent;
840 if ($conversation != '') {
841 $conv_data['conversation-uri'] = $conversation;
844 if ($conversation_uri != '') {
845 $conv_data['conversation-uri'] = $conversation_uri;
848 $entry = $doc2->importNode($entry, true);
850 $doc2->appendChild($entry);
852 $conv_data['source'] = $doc2->saveXML();
854 $condition = ['item-uri' => $conv_data['uri'],'protocol' => Conversation::PARCEL_FEED];
855 if (DBA::exists('conversation', $condition)) {
856 Logger::log('Delete deprecated entry for URI '.$conv_data['uri'], Logger::DEBUG);
857 DBA::delete('conversation', ['item-uri' => $conv_data['uri']]);
860 Logger::log('Store conversation data for uri '.$conv_data['uri'], Logger::DEBUG);
861 Conversation::insert($conv_data);
866 * @brief Fetch the own post so that it can be stored later
868 * We want to store the original data for later processing.
869 * This function is meant for cases where we process a feed with multiple entries.
870 * In that case we need to fetch the single posts here.
872 * @param string $self The link to the self item
873 * @param array $item The item array
876 private static function fetchSelf($self, array &$item)
878 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $self, Conversation::PARCEL_DFRN, Conversation::PARCEL_SALMON];
879 if (DBA::exists('conversation', $condition)) {
880 Logger::log('Conversation '.$item['uri'].' is already stored.', Logger::DEBUG);
884 $curlResult = Network::curl($self);
886 if (!$curlResult->isSuccess()) {
890 // We reformat the XML to make it better readable
891 $doc = new DOMDocument();
892 $doc->loadXML($curlResult->getBody());
893 $doc->preserveWhiteSpace = false;
894 $doc->formatOutput = true;
895 $xml = $doc->saveXML();
897 $item["protocol"] = Conversation::PARCEL_SALMON;
898 $item["source"] = $xml;
900 Logger::log('Conversation '.$item['uri'].' is now fetched.', Logger::DEBUG);
904 * @brief Fetch related posts and processes them
906 * @param string $related The link to the related item
907 * @param string $related_uri The related item in "uri" format
908 * @param array $importer user record of the importing user
911 private static function fetchRelated($related, $related_uri, $importer)
913 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, Conversation::PARCEL_DFRN, Conversation::PARCEL_SALMON];
914 $conversation = DBA::selectFirst('conversation', ['source', 'protocol'], $condition);
915 if (DBA::isResult($conversation)) {
917 $xml = $conversation['source'];
918 if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
919 Logger::log('Got valid cached XML for URI '.$related_uri, Logger::DEBUG);
922 if ($conversation['protocol'] == Conversation::PARCEL_SALMON) {
923 Logger::log('Delete invalid cached XML for URI '.$related_uri, Logger::DEBUG);
924 DBA::delete('conversation', ['item-uri' => $related_uri]);
929 $curlResult = Network::curl($related, false, $redirects, ['accept_content' => 'application/atom+xml, text/html']);
931 if (!$curlResult->isSuccess()) {
937 if (stristr($curlResult->getHeader(), 'Content-Type: application/atom+xml')) {
938 Logger::log('Directly fetched XML for URI ' . $related_uri, Logger::DEBUG);
939 $xml = $curlResult->getBody();
943 $doc = new DOMDocument();
944 if (!@$doc->loadHTML($curlResult->getBody())) {
947 $xpath = new DOMXPath($doc);
951 $links = $xpath->query('//link');
953 foreach ($links as $link) {
954 $attribute = self::readAttributes($link);
955 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
956 $atom_file = $attribute['href'];
959 if ($atom_file != '') {
960 $curlResult = Network::curl($atom_file);
962 if ($curlResult->isSuccess()) {
963 Logger::log('Fetched XML for URI ' . $related_uri, Logger::DEBUG);
964 $xml = $curlResult->getBody();
970 // Workaround for older GNU Social servers
971 if (($xml == '') && strstr($related, '/notice/')) {
972 $curlResult = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related).'.atom');
974 if ($curlResult->isSuccess()) {
975 Logger::log('GNU Social workaround to fetch XML for URI ' . $related_uri, Logger::DEBUG);
976 $xml = $curlResult->getBody();
980 // Even more worse workaround for GNU Social ;-)
982 $related_guess = OStatus::convertHref($related_uri);
983 $curlResult = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related_guess).'.atom');
985 if ($curlResult->isSuccess()) {
986 Logger::log('GNU Social workaround 2 to fetch XML for URI ' . $related_uri, Logger::DEBUG);
987 $xml = $curlResult->getBody();
991 // Finally we take the data that we fetched from "ostatus:conversation"
993 $condition = ['item-uri' => $related_uri, 'protocol' => Conversation::PARCEL_SPLIT_CONVERSATION];
994 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
995 if (DBA::isResult($conversation)) {
997 Logger::log('Got cached XML from conversation for URI '.$related_uri, Logger::DEBUG);
998 $xml = $conversation['source'];
1003 self::process($xml, $importer, $contact, $hub, $stored, false);
1005 Logger::log("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, Logger::DEBUG);
1011 * @brief Processes the XML for a repeated post
1013 * @param object $xpath The xpath object
1014 * @param object $entry The xml entry that is processed
1015 * @param array $item The item array
1016 * @param array $importer user record of the importing user
1018 * @return array with data from links
1020 private static function processRepeatedItem(DOMXPath $xpath, $entry, array &$item, array $importer)
1022 $activityobject = $xpath->query('activity:object', $entry)->item(0);
1024 if (!is_object($activityobject)) {
1030 $orig_uri = XML::getFirstNodeValue($xpath, 'atom:id/text()', $activityobject);
1032 $links = $xpath->query("atom:link", $activityobject);
1034 $link_data = self::processLinks($links, $item);
1037 $orig_body = XML::getFirstNodeValue($xpath, 'atom:content/text()', $activityobject);
1038 $orig_created = XML::getFirstNodeValue($xpath, 'atom:published/text()', $activityobject);
1039 $orig_edited = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $activityobject);
1041 $orig_author = self::fetchAuthor($xpath, $activityobject, $importer, $dummy, false);
1043 $item["author-name"] = $orig_author["author-name"];
1044 $item["author-link"] = $orig_author["author-link"];
1045 $item["author-id"] = $orig_author["author-id"];
1047 $item["body"] = HTML::toBBCode($orig_body);
1048 $item["created"] = $orig_created;
1049 $item["edited"] = $orig_edited;
1051 $item["uri"] = $orig_uri;
1053 $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $activityobject);
1055 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $activityobject);
1057 // Mastodon Content Warning
1058 if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $activityobject)) {
1059 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $activityobject);
1060 if (!empty($clear_text)) {
1061 $item['content-warning'] = HTML::toBBCode($clear_text);
1065 $inreplyto = $xpath->query('thr:in-reply-to', $activityobject);
1066 if (is_object($inreplyto->item(0))) {
1067 foreach ($inreplyto->item(0)->attributes as $attributes) {
1068 if ($attributes->name == "ref") {
1069 $item["parent-uri"] = $attributes->textContent;
1078 * @brief Processes links in the XML
1080 * @param object $links The xml data that contain links
1081 * @param array $item The item array
1083 * @return array with data from the links
1085 private static function processLinks($links, array &$item)
1087 $link_data = ['add_body' => '', 'self' => ''];
1089 foreach ($links as $link) {
1090 $attribute = self::readAttributes($link);
1092 if (!empty($attribute['rel']) && !empty($attribute['href'])) {
1093 switch ($attribute['rel']) {
1095 $item["plink"] = $attribute['href'];
1096 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION)
1097 || ($item["object-type"] == ACTIVITY_OBJ_EVENT)
1099 $item["body"] .= add_page_info($attribute['href']);
1102 case "ostatus:conversation":
1103 $link_data['conversation'] = $attribute['href'];
1104 $item['conversation-href'] = $link_data['conversation'];
1105 if (!isset($item['conversation-uri'])) {
1106 $item['conversation-uri'] = $item['conversation-href'];
1110 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
1111 if ($filetype == 'image') {
1112 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1114 if (!empty($item["attach"])) {
1115 $item["attach"] .= ',';
1117 $item["attach"] = '';
1119 if (!isset($attribute['length'])) {
1120 $attribute['length'] = "0";
1122 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.defaults($attribute, 'title', '').'"[/attach]';
1126 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
1127 if (!isset($item["parent-uri"])) {
1128 $item["parent-uri"] = $attribute['href'];
1130 $link_data['related'] = $attribute['href'];
1132 $item["body"] .= add_page_info($attribute['href']);
1136 if (empty($item["plink"])) {
1137 $item["plink"] = $attribute['href'];
1139 $link_data['self'] = $attribute['href'];
1148 * @brief Create an url out of an uri
1150 * @param string $href URI in the format "parameter1:parameter1:..."
1152 * @return string URL in the format http(s)://....
1154 public static function convertHref($href)
1156 $elements = explode(":", $href);
1158 if ((count($elements) <= 2) || ($elements[0] != "tag")) {
1162 $server = explode(",", $elements[1]);
1163 $conversation = explode("=", $elements[2]);
1165 if ((count($elements) == 4) && ($elements[2] == "post")) {
1166 return "http://".$server[0]."/notice/".$elements[3];
1169 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1172 if ($elements[3] == "objectType=thread") {
1173 return "http://".$server[0]."/conversation/".$conversation[1];
1175 return "http://".$server[0]."/notice/".$conversation[1];
1181 * @brief Checks if the current post is a reshare
1183 * @param array $item The item array of thw post
1185 * @return string The guid if the post is a reshare
1187 private static function getResharedGuid(array $item)
1189 $body = trim($item["body"]);
1191 // Skip if it isn't a pure repeated messages
1192 // Does it start with a share?
1193 if (strpos($body, "[share") > 0) {
1197 // Does it end with a share?
1198 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
1202 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
1203 // Skip if there is no shared message in there
1204 if ($body == $attributes) {
1209 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1210 if (!empty($matches[1])) {
1211 $guid = $matches[1];
1214 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1215 if (!empty($matches[1])) {
1216 $guid = $matches[1];
1223 * @brief Cleans the body of a post if it contains picture links
1225 * @param string $body The body
1227 * @return string The cleaned body
1229 private static function formatPicturePost($body)
1231 $siteinfo = BBCode::getAttachedData($body);
1233 if (($siteinfo["type"] == "photo")) {
1234 if (isset($siteinfo["preview"])) {
1235 $preview = $siteinfo["preview"];
1237 $preview = $siteinfo["image"];
1240 // Is it a remote picture? Then make a smaller preview here
1241 $preview = ProxyUtils::proxifyUrl($preview, false, ProxyUtils::SIZE_SMALL);
1243 // Is it a local picture? Then make it smaller here
1244 $preview = str_replace(["-0.jpg", "-0.png"], ["-2.jpg", "-2.png"], $preview);
1245 $preview = str_replace(["-1.jpg", "-1.png"], ["-2.jpg", "-2.png"], $preview);
1247 if (isset($siteinfo["url"])) {
1248 $url = $siteinfo["url"];
1250 $url = $siteinfo["image"];
1253 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1260 * @brief Adds the header elements to the XML document
1262 * @param object $doc XML document
1263 * @param array $owner Contact data of the poster
1264 * @param string $filter The related feed filter (activity, posts or comments)
1266 * @return object header root element
1268 private static function addHeader(DOMDocument $doc, array $owner, $filter)
1272 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1273 $doc->appendChild($root);
1275 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1276 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1277 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1278 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1279 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1280 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1281 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1282 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1286 case 'activity': $title = L10n::t('%s\'s timeline', $owner['name']); break;
1287 case 'posts' : $title = L10n::t('%s\'s posts' , $owner['name']); break;
1288 case 'comments': $title = L10n::t('%s\'s comments', $owner['name']); break;
1291 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
1292 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1293 XML::addElement($doc, $root, "id", System::baseUrl() . "/profile/" . $owner["nick"]);
1294 XML::addElement($doc, $root, "title", $title);
1295 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], Config::get('config', 'sitename')));
1296 XML::addElement($doc, $root, "logo", $owner["photo"]);
1297 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1299 $author = self::addAuthor($doc, $owner);
1300 $root->appendChild($author);
1302 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1303 XML::addElement($doc, $root, "link", "", $attributes);
1305 /// @TODO We have to find out what this is
1306 /// $attributes = array("href" => System::baseUrl()."/sup",
1307 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1308 /// "type" => "application/json");
1309 /// XML::addElement($doc, $root, "link", "", $attributes);
1311 self::hublinks($doc, $root, $owner["nick"]);
1313 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "salmon"];
1314 XML::addElement($doc, $root, "link", "", $attributes);
1316 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies"];
1317 XML::addElement($doc, $root, "link", "", $attributes);
1319 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention"];
1320 XML::addElement($doc, $root, "link", "", $attributes);
1322 $attributes = ["href" => System::baseUrl() . "/api/statuses/user_timeline/" . $owner["nick"] . ".atom",
1323 "rel" => "self", "type" => "application/atom+xml"];
1324 XML::addElement($doc, $root, "link", "", $attributes);
1326 if ($owner['account-type'] == Contact::ACCOUNT_TYPE_COMMUNITY) {
1327 $condition = ['uid' => $owner['uid'], 'self' => false, 'pending' => false,
1328 'archive' => false, 'hidden' => false, 'blocked' => false];
1329 $members = DBA::count('contact', $condition);
1330 XML::addElement($doc, $root, "statusnet:group_info", "", ["member_count" => $members]);
1337 * @brief Add the link to the push hubs to the XML document
1339 * @param object $doc XML document
1340 * @param object $root XML root element where the hub links are added
1341 * @param object $nick nick
1344 public static function hublinks(DOMDocument $doc, $root, $nick)
1346 $h = System::baseUrl() . '/pubsubhubbub/'.$nick;
1347 XML::addElement($doc, $root, "link", "", ["href" => $h, "rel" => "hub"]);
1351 * @brief Adds attachment data to the XML document
1353 * @param object $doc XML document
1354 * @param object $root XML root element where the hub links are added
1355 * @param array $item Data of the item that is to be posted
1358 private static function getAttachment(DOMDocument $doc, $root, $item)
1361 $siteinfo = BBCode::getAttachedData($item["body"]);
1363 switch ($siteinfo["type"]) {
1365 if (!empty($siteinfo["image"])) {
1366 $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1368 $attributes = ["rel" => "enclosure",
1369 "href" => $siteinfo["image"],
1370 "type" => $imgdata["mime"],
1371 "length" => intval($imgdata["size"])];
1372 XML::addElement($doc, $root, "link", "", $attributes);
1377 $attributes = ["rel" => "enclosure",
1378 "href" => $siteinfo["url"],
1379 "type" => "text/html; charset=UTF-8",
1381 "title" => defaults($siteinfo, "title", $siteinfo["url"])];
1382 XML::addElement($doc, $root, "link", "", $attributes);
1388 if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1389 $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1391 $attributes = ["rel" => "enclosure",
1392 "href" => $siteinfo["image"],
1393 "type" => $imgdata["mime"],
1394 "length" => intval($imgdata["size"])];
1396 XML::addElement($doc, $root, "link", "", $attributes);
1400 $arr = explode('[/attach],', $item['attach']);
1402 foreach ($arr as $r) {
1404 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1406 $attributes = ["rel" => "enclosure",
1407 "href" => $matches[1],
1408 "type" => $matches[3]];
1410 if (intval($matches[2])) {
1411 $attributes["length"] = intval($matches[2]);
1413 if (trim($matches[4]) != "") {
1414 $attributes["title"] = trim($matches[4]);
1416 XML::addElement($doc, $root, "link", "", $attributes);
1423 * @brief Adds the author element to the XML document
1425 * @param object $doc XML document
1426 * @param array $owner Contact data of the poster
1427 * @param bool $show_profile Whether to show profile
1429 * @return object author element
1431 private static function addAuthor(DOMDocument $doc, array $owner, $show_profile = true)
1433 $profile = DBA::selectFirst('profile', ['homepage', 'publish'], ['uid' => $owner['uid'], 'is-default' => true]);
1434 $author = $doc->createElement("author");
1435 XML::addElement($doc, $author, "id", $owner["url"]);
1436 if ($owner['account-type'] == Contact::ACCOUNT_TYPE_COMMUNITY) {
1437 XML::addElement($doc, $author, "activity:object-type", ACTIVITY_OBJ_GROUP);
1439 XML::addElement($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1441 XML::addElement($doc, $author, "uri", $owner["url"]);
1442 XML::addElement($doc, $author, "name", $owner["nick"]);
1443 XML::addElement($doc, $author, "email", $owner["addr"]);
1444 if ($show_profile) {
1445 XML::addElement($doc, $author, "summary", BBCode::convert($owner["about"], false, 7));
1448 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $owner["url"]];
1449 XML::addElement($doc, $author, "link", "", $attributes);
1453 "type" => "image/jpeg", // To-Do?
1454 "media:width" => 300,
1455 "media:height" => 300,
1456 "href" => $owner["photo"]];
1457 XML::addElement($doc, $author, "link", "", $attributes);
1459 if (isset($owner["thumb"])) {
1462 "type" => "image/jpeg", // To-Do?
1463 "media:width" => 80,
1464 "media:height" => 80,
1465 "href" => $owner["thumb"]];
1466 XML::addElement($doc, $author, "link", "", $attributes);
1469 XML::addElement($doc, $author, "poco:preferredUsername", $owner["nick"]);
1470 XML::addElement($doc, $author, "poco:displayName", $owner["name"]);
1471 if ($show_profile) {
1472 XML::addElement($doc, $author, "poco:note", BBCode::convert($owner["about"], false, 7));
1474 if (trim($owner["location"]) != "") {
1475 $element = $doc->createElement("poco:address");
1476 XML::addElement($doc, $element, "poco:formatted", $owner["location"]);
1477 $author->appendChild($element);
1481 if (DBA::isResult($profile) && !$show_profile) {
1482 if (trim($profile["homepage"]) != "") {
1483 $urls = $doc->createElement("poco:urls");
1484 XML::addElement($doc, $urls, "poco:type", "homepage");
1485 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
1486 XML::addElement($doc, $urls, "poco:primary", "true");
1487 $author->appendChild($urls);
1490 XML::addElement($doc, $author, "followers", "", ["url" => System::baseUrl()."/viewcontacts/".$owner["nick"]]);
1491 XML::addElement($doc, $author, "statusnet:profile_info", "", ["local_id" => $owner["uid"]]);
1493 if ($profile["publish"]) {
1494 XML::addElement($doc, $author, "mastodon:scope", "public");
1502 * @TODO Picture attachments should look like this:
1503 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1504 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1508 * @brief Returns the given activity if present - otherwise returns the "post" activity
1510 * @param array $item Data of the item that is to be posted
1512 * @return string activity
1514 private static function constructVerb(array $item)
1516 if (!empty($item['verb'])) {
1517 return $item['verb'];
1520 return ACTIVITY_POST;
1524 * @brief Returns the given object type if present - otherwise returns the "note" object type
1526 * @param array $item Data of the item that is to be posted
1528 * @return string Object type
1530 private static function constructObjecttype(array $item)
1532 if (in_array($item['object-type'], [ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT]))
1533 return $item['object-type'];
1534 return ACTIVITY_OBJ_NOTE;
1538 * @brief Adds an entry element to the XML document
1540 * @param object $doc XML document
1541 * @param array $item Data of the item that is to be posted
1542 * @param array $owner Contact data of the poster
1543 * @param bool $toplevel optional default false
1545 * @return object Entry element
1547 private static function entry(DOMDocument $doc, array $item, array $owner, $toplevel = false)
1551 $repeated_guid = self::getResharedGuid($item);
1552 if ($repeated_guid != "") {
1553 $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel);
1560 if ($item["verb"] == ACTIVITY_LIKE) {
1561 return self::likeEntry($doc, $item, $owner, $toplevel);
1562 } elseif (in_array($item["verb"], [ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"])) {
1563 return self::followEntry($doc, $item, $owner, $toplevel);
1565 return self::noteEntry($doc, $item, $owner, $toplevel);
1570 * @brief Adds a source entry to the XML document
1572 * @param object $doc XML document
1573 * @param array $contact Array of the contact that is added
1575 * @return object Source element
1577 private static function sourceEntry(DOMDocument $doc, array $contact)
1579 $source = $doc->createElement("source");
1580 XML::addElement($doc, $source, "id", $contact["poll"]);
1581 XML::addElement($doc, $source, "title", $contact["name"]);
1582 XML::addElement($doc, $source, "link", "", ["rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]]);
1583 XML::addElement($doc, $source, "link", "", ["rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]]);
1584 XML::addElement($doc, $source, "icon", $contact["photo"]);
1585 XML::addElement($doc, $source, "updated", DateTimeFormat::utc($contact["success_update"]."+00:00", DateTimeFormat::ATOM));
1591 * @brief Fetches contact data from the contact or the gcontact table
1593 * @param string $url URL of the contact
1594 * @param array $owner Contact data of the poster
1596 * @return array Contact array
1598 private static function contactEntry($url, array $owner)
1601 "SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1602 DBA::escape(normalise_link($url)),
1603 intval($owner["uid"])
1605 if (DBA::isResult($r)) {
1607 $contact["uid"] = -1;
1610 if (!DBA::isResult($r)) {
1611 $gcontact = DBA::selectFirst('gcontact', [], ['nurl' => normalise_link($url)]);
1612 if (DBA::isResult($r)) {
1613 $contact = $gcontact;
1614 $contact["uid"] = -1;
1615 $contact["success_update"] = $contact["updated"];
1619 if (!DBA::isResult($r)) {
1623 if (!isset($contact["poll"])) {
1624 $data = Probe::uri($url);
1625 $contact["poll"] = $data["poll"];
1627 if (!$contact["alias"]) {
1628 $contact["alias"] = $data["alias"];
1632 if (!isset($contact["alias"])) {
1633 $contact["alias"] = $contact["url"];
1636 $contact['account-type'] = $owner['account-type'];
1642 * @brief Adds an entry element with reshared content
1644 * @param object $doc XML document
1645 * @param array $item Data of the item that is to be posted
1646 * @param array $owner Contact data of the poster
1647 * @param string $repeated_guid guid
1648 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1650 * @return object Entry element
1652 private static function reshareEntry(DOMDocument $doc, array $item, array $owner, $repeated_guid, $toplevel)
1654 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1655 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1658 $title = self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1660 $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => false,
1661 'network' => [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS]];
1662 $repeated_item = Item::selectFirst([], $condition);
1663 if (!DBA::isResult($repeated_item)) {
1667 $contact = self::contactEntry($repeated_item['author-link'], $owner);
1669 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1671 self::entryContent($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1673 $as_object = $doc->createElement("activity:object");
1675 XML::addElement($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1677 self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false);
1679 $author = self::addAuthor($doc, $contact, false);
1680 $as_object->appendChild($author);
1682 $as_object2 = $doc->createElement("activity:object");
1684 XML::addElement($doc, $as_object2, "activity:object-type", self::constructObjecttype($repeated_item));
1686 $title = sprintf("New comment by %s", $contact["nick"]);
1688 self::entryContent($doc, $as_object2, $repeated_item, $owner, $title);
1690 $as_object->appendChild($as_object2);
1692 self::entryFooter($doc, $as_object, $item, $owner, false);
1694 $source = self::sourceEntry($doc, $contact);
1696 $as_object->appendChild($source);
1698 $entry->appendChild($as_object);
1700 self::entryFooter($doc, $entry, $item, $owner);
1706 * @brief Adds an entry element with a "like"
1708 * @param object $doc XML document
1709 * @param array $item Data of the item that is to be posted
1710 * @param array $owner Contact data of the poster
1711 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1713 * @return object Entry element with "like"
1715 private static function likeEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1717 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1718 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1721 $title = self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1723 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1724 self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false);
1726 $as_object = $doc->createElement("activity:object");
1728 $parent = Item::selectFirst([], ['uri' => $item["thr-parent"], 'uid' => $item["uid"]]);
1734 XML::addElement($doc, $as_object, "activity:object-type", self::constructObjecttype($parent));
1736 self::entryContent($doc, $as_object, $parent, $owner, "New entry");
1738 $entry->appendChild($as_object);
1740 self::entryFooter($doc, $entry, $item, $owner);
1746 * @brief Adds the person object element to the XML document
1748 * @param object $doc XML document
1749 * @param array $owner Contact data of the poster
1750 * @param array $contact Contact data of the target
1752 * @return object author element
1754 private static function addPersonObject(DOMDocument $doc, array $owner, array $contact)
1756 $object = $doc->createElement("activity:object");
1757 XML::addElement($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1759 if ($contact['network'] == Protocol::PHANTOM) {
1760 XML::addElement($doc, $object, "id", $contact['url']);
1764 XML::addElement($doc, $object, "id", $contact["alias"]);
1765 XML::addElement($doc, $object, "title", $contact["nick"]);
1767 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $contact["url"]];
1768 XML::addElement($doc, $object, "link", "", $attributes);
1772 "type" => "image/jpeg", // To-Do?
1773 "media:width" => 300,
1774 "media:height" => 300,
1775 "href" => $contact["photo"]];
1776 XML::addElement($doc, $object, "link", "", $attributes);
1778 XML::addElement($doc, $object, "poco:preferredUsername", $contact["nick"]);
1779 XML::addElement($doc, $object, "poco:displayName", $contact["name"]);
1781 if (trim($contact["location"]) != "") {
1782 $element = $doc->createElement("poco:address");
1783 XML::addElement($doc, $element, "poco:formatted", $contact["location"]);
1784 $object->appendChild($element);
1791 * @brief Adds a follow/unfollow entry element
1793 * @param object $doc XML document
1794 * @param array $item Data of the follow/unfollow message
1795 * @param array $owner Contact data of the poster
1796 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1798 * @return object Entry element
1800 private static function followEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1802 $item["id"] = $item["parent"] = 0;
1803 $item["created"] = $item["edited"] = date("c");
1804 $item["private"] = true;
1806 $contact = Probe::uri($item['follow']);
1808 if ($contact['alias'] == '') {
1809 $contact['alias'] = $contact["url"];
1811 $item['follow'] = $contact['alias'];
1814 $condition = ['uid' => $owner['uid'], 'nurl' => normalise_link($contact["url"])];
1815 $user_contact = DBA::selectFirst('contact', ['id'], $condition);
1817 if (DBA::isResult($user_contact)) {
1818 $connect_id = $user_contact['id'];
1823 if ($item['verb'] == ACTIVITY_FOLLOW) {
1824 $message = L10n::t('%s is now following %s.');
1825 $title = L10n::t('following');
1826 $action = "subscription";
1828 $message = L10n::t('%s stopped following %s.');
1829 $title = L10n::t('stopped following');
1830 $action = "unfollow";
1833 $item["uri"] = $item['parent-uri'] = $item['thr-parent']
1834 = 'tag:'.get_app()->getHostName().
1835 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1836 ':person:'.$connect_id.':'.$item['created'];
1838 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1840 self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1842 self::entryContent($doc, $entry, $item, $owner, $title);
1844 $object = self::addPersonObject($doc, $owner, $contact);
1845 $entry->appendChild($object);
1847 self::entryFooter($doc, $entry, $item, $owner);
1853 * @brief Adds a regular entry element
1855 * @param object $doc XML document
1856 * @param array $item Data of the item that is to be posted
1857 * @param array $owner Contact data of the poster
1858 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1860 * @return object Entry element
1862 private static function noteEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1864 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1865 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1868 $title = self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1870 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1872 self::entryContent($doc, $entry, $item, $owner, $title);
1874 self::entryFooter($doc, $entry, $item, $owner);
1880 * @brief Adds a header element to the XML document
1882 * @param object $doc XML document
1883 * @param object $entry The entry element where the elements are added
1884 * @param array $owner Contact data of the poster
1885 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1887 * @return string The title for the element
1889 private static function entryHeader(DOMDocument $doc, &$entry, array $owner, array $item, $toplevel)
1891 /// @todo Check if this title stuff is really needed (I guess not)
1893 $entry = $doc->createElement("entry");
1894 $title = sprintf("New note by %s", $owner["nick"]);
1896 if ($owner['account-type'] == Contact::ACCOUNT_TYPE_COMMUNITY) {
1897 $contact = self::contactEntry($item['author-link'], $owner);
1898 $author = self::addAuthor($doc, $contact, false);
1899 $entry->appendChild($author);
1902 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
1904 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1905 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1906 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1907 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1908 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
1909 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1910 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1911 $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1913 $author = self::addAuthor($doc, $owner);
1914 $entry->appendChild($author);
1916 $title = sprintf("New comment by %s", $owner["nick"]);
1922 * @brief Adds elements to the XML document
1924 * @param object $doc XML document
1925 * @param object $entry Entry element where the content is added
1926 * @param array $item Data of the item that is to be posted
1927 * @param array $owner Contact data of the poster
1928 * @param string $title Title for the post
1929 * @param string $verb The activity verb
1930 * @param bool $complete Add the "status_net" element?
1933 private static function entryContent(DOMDocument $doc, $entry, array $item, array $owner, $title, $verb = "", $complete = true)
1936 $verb = self::constructVerb($item);
1939 XML::addElement($doc, $entry, "id", $item["uri"]);
1940 XML::addElement($doc, $entry, "title", $title);
1942 $body = self::formatPicturePost($item['body']);
1944 if ($item['title'] != "") {
1945 $body = "[b]".$item['title']."[/b]\n\n".$body;
1948 $body = BBCode::convert($body, false, 7);
1950 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1952 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1953 "href" => System::baseUrl()."/display/".$item["guid"]]
1956 if ($complete && ($item["id"] > 0)) {
1957 XML::addElement($doc, $entry, "status_net", "", ["notice_id" => $item["id"]]);
1960 XML::addElement($doc, $entry, "activity:verb", $verb);
1962 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
1963 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
1967 * @brief Adds the elements at the foot of an entry to the XML document
1969 * @param object $doc XML document
1970 * @param object $entry The entry element where the elements are added
1971 * @param array $item Data of the item that is to be posted
1972 * @param array $owner Contact data of the poster
1973 * @param bool $complete default true
1976 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner, $complete = true)
1980 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
1981 $parent = Item::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item["parent"]]);
1982 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1984 $thrparent = Item::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $parent_item]);
1986 if (DBA::isResult($thrparent)) {
1987 $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
1988 $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
1989 $parent_plink = $thrparent["plink"];
1991 $mentioned[$parent["author-link"]] = $parent["author-link"];
1992 $mentioned[$parent["owner-link"]] = $parent["owner-link"];
1993 $parent_plink = System::baseUrl()."/display/".$parent["guid"];
1997 "ref" => $parent_item,
1998 "href" => $parent_plink];
1999 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
2003 "href" => $parent_plink];
2004 XML::addElement($doc, $entry, "link", "", $attributes);
2007 if (intval($item["parent"]) > 0) {
2008 $conversation_href = $conversation_uri = str_replace('/objects/', '/context/', $item['parent-uri']);
2010 if (isset($parent_item)) {
2011 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $parent_item]);
2012 if (DBA::isResult($conversation)) {
2013 if ($conversation['conversation-uri'] != '') {
2014 $conversation_uri = $conversation['conversation-uri'];
2016 if ($conversation['conversation-href'] != '') {
2017 $conversation_href = $conversation['conversation-href'];
2022 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:conversation", "href" => $conversation_href]);
2025 "href" => $conversation_href,
2026 "local_id" => $item["parent"],
2027 "ref" => $conversation_uri];
2029 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
2032 $tags = item::getFeedTags($item);
2035 foreach ($tags as $t) {
2037 $mentioned[$t[1]] = $t[1];
2042 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2044 foreach ($mentioned as $mention) {
2045 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2046 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2048 $mentioned = $newmentions;
2050 foreach ($mentioned as $mention) {
2051 $condition = ['uid' => $owner['uid'], 'nurl' => normalise_link($mention)];
2052 $contact = DBA::selectFirst('contact', ['forum', 'prv', 'self', 'contact-type'], $condition);
2053 if ($contact["forum"] || $contact["prv"] || ($owner['contact-type'] == Contact::ACCOUNT_TYPE_COMMUNITY) ||
2054 ($contact['self'] && ($owner['account-type'] == Contact::ACCOUNT_TYPE_COMMUNITY))) {
2055 XML::addElement($doc, $entry, "link", "",
2057 "rel" => "mentioned",
2058 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
2062 XML::addElement($doc, $entry, "link", "",
2064 "rel" => "mentioned",
2065 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
2071 if ($owner['account-type'] == Contact::ACCOUNT_TYPE_COMMUNITY) {
2072 XML::addElement($doc, $entry, "link", "", [
2073 "rel" => "mentioned",
2074 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/group",
2075 "href" => $owner['url']
2079 if (!$item["private"]) {
2080 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:attention",
2081 "href" => "http://activityschema.org/collection/public"]);
2082 XML::addElement($doc, $entry, "link", "", ["rel" => "mentioned",
2083 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2084 "href" => "http://activityschema.org/collection/public"]);
2085 XML::addElement($doc, $entry, "mastodon:scope", "public");
2089 foreach ($tags as $t) {
2091 XML::addElement($doc, $entry, "category", "", ["term" => $t[2]]);
2096 self::getAttachment($doc, $entry, $item);
2098 if ($complete && ($item["id"] > 0)) {
2099 $app = $item["app"];
2104 $attributes = ["local_id" => $item["id"], "source" => $app];
2106 if (isset($parent["id"])) {
2107 $attributes["repeat_of"] = $parent["id"];
2110 if ($item["coord"] != "") {
2111 XML::addElement($doc, $entry, "georss:point", $item["coord"]);
2114 XML::addElement($doc, $entry, "statusnet:notice_info", "", $attributes);
2119 * Creates the XML feed for a given nickname
2121 * Supported filters:
2122 * - activity (default): all the public posts
2123 * - posts: all the public top-level posts
2124 * - comments: all the public replies
2126 * Updates the provided last_update parameter if the result comes from the
2127 * cache or it is empty
2129 * @brief Creates the XML feed for a given nickname
2131 * @param string $owner_nick Nickname of the feed owner
2132 * @param string $last_update Date of the last update
2133 * @param integer $max_items Number of maximum items to fetch
2134 * @param string $filter Feed items filter (activity, posts or comments)
2135 * @param boolean $nocache Wether to bypass caching
2137 * @return string XML feed
2139 public static function feed($owner_nick, &$last_update, $max_items = 300, $filter = 'activity', $nocache = false)
2141 $stamp = microtime(true);
2143 $owner = User::getOwnerDataByNick($owner_nick);
2148 $cachekey = "ostatus:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
2150 $previous_created = $last_update;
2152 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
2153 if ((time() - strtotime($owner['last-item'])) < 15*60) {
2154 $result = Cache::get($cachekey);
2155 if (!$nocache && !is_null($result)) {
2156 Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', Logger::DEBUG);
2157 $last_update = $result['last_update'];
2158 return $result['feed'];
2162 if (!strlen($last_update)) {
2163 $last_update = 'now -30 days';
2166 $check_date = DateTimeFormat::utc($last_update);
2167 $authorid = Contact::getIdForURL($owner["url"], 0, true);
2169 $condition = ["`uid` = ? AND `created` > ? AND NOT `deleted`
2170 AND NOT `private` AND `visible` AND `wall` AND `parent-network` IN (?, ?)",
2171 $owner["uid"], $check_date, Protocol::OSTATUS, Protocol::DFRN];
2173 if ($filter === 'comments') {
2174 $condition[0] .= " AND `object-type` = ? ";
2175 $condition[] = ACTIVITY_OBJ_COMMENT;
2178 if ($owner['account-type'] != Contact::ACCOUNT_TYPE_COMMUNITY) {
2179 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
2180 $condition[] = $owner["id"];
2181 $condition[] = $authorid;
2184 $params = ['order' => ['created' => true], 'limit' => $max_items];
2186 if ($filter === 'posts') {
2187 $ret = Item::selectThread([], $condition, $params);
2189 $ret = Item::select([], $condition, $params);
2192 $items = Item::inArray($ret);
2194 $doc = new DOMDocument('1.0', 'utf-8');
2195 $doc->formatOutput = true;
2197 $root = self::addHeader($doc, $owner, $filter);
2199 foreach ($items as $item) {
2200 if (Config::get('system', 'ostatus_debug')) {
2201 $item['body'] .= '🍼';
2203 $entry = self::entry($doc, $item, $owner);
2204 $root->appendChild($entry);
2206 if ($last_update < $item['created']) {
2207 $last_update = $item['created'];
2211 $feeddata = trim($doc->saveXML());
2213 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
2214 Cache::set($cachekey, $msg, Cache::QUARTER_HOUR);
2216 Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, Logger::DEBUG);
2222 * @brief Creates the XML for a salmon message
2224 * @param array $item Data of the item that is to be posted
2225 * @param array $owner Contact data of the poster
2227 * @return string XML for the salmon
2229 public static function salmon(array $item, array $owner)
2231 $doc = new DOMDocument('1.0', 'utf-8');
2232 $doc->formatOutput = true;
2234 if (Config::get('system', 'ostatus_debug')) {
2235 $item['body'] .= '🐟';
2238 $entry = self::entry($doc, $item, $owner, true);
2240 $doc->appendChild($entry);
2242 return trim($doc->saveXML());