3 * @file include/ostatus.php
7 use Friendica\Core\Config;
8 use Friendica\Network\Probe;
10 require_once 'include/Contact.php';
11 require_once 'include/threads.php';
12 require_once 'include/html2bbcode.php';
13 require_once 'include/bbcode.php';
14 require_once 'include/items.php';
15 require_once 'mod/share.php';
16 require_once 'include/enotify.php';
17 require_once 'include/socgraph.php';
18 require_once 'include/Photo.php';
19 require_once 'include/probe.php';
20 require_once 'include/follow.php';
21 require_once 'include/api.php';
22 require_once 'mod/proxy.php';
23 require_once 'include/xml.php';
26 * @brief This class contain functions for the OStatus protocol
30 const OSTATUS_DEFAULT_POLL_INTERVAL = 30; // given in minutes
31 const OSTATUS_DEFAULT_POLL_TIMEFRAME = 1440; // given in minutes
32 const OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS = 14400; // given in minutes
35 * @brief Fetches author data
37 * @param object $xpath The xpath object
38 * @param object $context The xml context of the author detals
39 * @param array $importer user record of the importing user
40 * @param array $contact Called by reference, will contain the fetched contact
41 * @param bool $onlyfetch Only fetch the header without updating the contact entries
43 * @return array Array of author related entries for the item
45 private function fetchauthor($xpath, $context, $importer, &$contact, $onlyfetch) {
48 $author["author-link"] = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
49 $author["author-name"] = $xpath->evaluate('atom:author/atom:name/text()', $context)->item(0)->nodeValue;
50 $addr = $xpath->evaluate('atom:author/atom:email/text()', $context)->item(0)->nodeValue;
52 $aliaslink = $author["author-link"];
54 $alternate = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0)->attributes;
55 if (is_object($alternate)) {
56 foreach ($alternate AS $attributes) {
57 if (($attributes->name == "href") AND ($attributes->textContent != "")) {
58 $author["author-link"] = $attributes->textContent;
63 $author["contact-id"] = $contact["id"];
65 if ($author["author-link"] != "") {
66 if ($aliaslink == "") {
67 $aliaslink = $author["author-link"];
70 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` IN ('%s', '%s') AND `network` != '%s'",
71 intval($importer["uid"]), dbesc(normalise_link($author["author-link"])),
72 dbesc(normalise_link($aliaslink)), dbesc(NETWORK_STATUSNET));
74 if (dbm::is_result($r)) {
76 $author["contact-id"] = $r[0]["id"];
77 $author["author-link"] = $r[0]["url"];
79 } elseif ($addr != "") {
81 $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `uid` = ? AND `addr` = ? AND `network` != ?",
82 $importer["uid"], $addr, NETWORK_STATUSNET);
84 if (dbm::is_result($contact)) {
85 $author["contact-id"] = $contact["id"];
86 $author["author-link"] = $contact["url"];
90 $avatarlist = array();
91 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
92 foreach ($avatars AS $avatar) {
95 foreach ($avatar->attributes AS $attributes) {
96 if ($attributes->name == "href") {
97 $href = $attributes->textContent;
99 if ($attributes->name == "width") {
100 $width = $attributes->textContent;
103 if (($width > 0) AND ($href != "")) {
104 $avatarlist[$width] = $href;
107 if (count($avatarlist) > 0) {
109 $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
112 $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
113 if ($displayname != "") {
114 $author["author-name"] = $displayname;
117 $author["owner-name"] = $author["author-name"];
118 $author["owner-link"] = $author["author-link"];
119 $author["owner-avatar"] = $author["author-avatar"];
121 // Only update the contacts if it is an OStatus contact
122 if ($r AND !$onlyfetch AND ($contact["network"] == NETWORK_OSTATUS)) {
124 // Update contact data
126 // This query doesn't seem to work
127 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
129 // $contact["notify"] = $value;
131 // This query doesn't seem to work as well - I hate these queries
132 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
134 // $contact["poll"] = $value;
136 $value = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
138 $contact["alias"] = $value;
140 $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
142 $contact["name"] = $value;
144 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
146 $contact["nick"] = $value;
148 $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
150 $contact["about"] = html2bbcode($value);
152 $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
154 $contact["location"] = $value;
156 if (($contact["name"] != $r[0]["name"]) OR ($contact["nick"] != $r[0]["nick"]) OR ($contact["about"] != $r[0]["about"]) OR
157 ($contact["alias"] != $r[0]["alias"]) OR ($contact["location"] != $r[0]["location"])) {
159 logger("Update contact data for contact ".$contact["id"], LOGGER_DEBUG);
161 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `alias` = '%s', `about` = '%s', `location` = '%s', `name-date` = '%s' WHERE `id` = %d",
162 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["alias"]),
163 dbesc($contact["about"]), dbesc($contact["location"]),
164 dbesc(datetime_convert()), intval($contact["id"]));
167 if (isset($author["author-avatar"]) AND ($author["author-avatar"] != $r[0]['avatar'])) {
168 logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
170 update_contact_avatar($author["author-avatar"], $importer["uid"], $contact["id"]);
173 // Ensure that we are having this contact (with uid=0)
174 $cid = get_contact($author["author-link"], 0);
177 // Update it with the current values
178 q("UPDATE `contact` SET `url` = '%s', `name` = '%s', `nick` = '%s', `alias` = '%s',
179 `about` = '%s', `location` = '%s',
180 `success_update` = '%s', `last-update` = '%s'
182 dbesc($author["author-link"]), dbesc($contact["name"]), dbesc($contact["nick"]),
183 dbesc($contact["alias"]), dbesc($contact["about"]), dbesc($contact["location"]),
184 dbesc(datetime_convert()), dbesc(datetime_convert()), intval($cid));
187 update_contact_avatar($author["author-avatar"], 0, $cid);
190 $contact["generation"] = 2;
191 $contact["hide"] = false; // OStatus contacts are never hidden
192 $contact["photo"] = $author["author-avatar"];
193 $gcid = update_gcontact($contact);
195 link_gcontact($gcid, $contact["uid"], $contact["id"]);
202 * @brief Fetches author data from a given XML string
204 * @param string $xml The XML
205 * @param array $importer user record of the importing user
207 * @return array Array of author related entries for the item
209 public static function salmon_author($xml, $importer) {
214 $doc = new DOMDocument();
215 @$doc->loadXML($xml);
217 $xpath = new DomXPath($doc);
218 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
219 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
220 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
221 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
222 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
223 $xpath->registerNamespace('poco', NAMESPACE_POCO);
224 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
225 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
227 $entries = $xpath->query('/atom:entry');
229 foreach ($entries AS $entry) {
231 $author = self::fetchauthor($xpath, $entry, $importer, $contact, true);
237 * @brief Read attributes from element
239 * @param object $element Element object
241 * @return array attributes
243 private static function read_attributes($element) {
244 $attribute = array();
246 foreach ($element->attributes AS $attributes) {
247 $attribute[$attributes->name] = $attributes->textContent;
254 * @brief Imports an XML string containing OStatus elements
256 * @param string $xml The XML
257 * @param array $importer user record of the importing user
259 * @param array $hub Called by reference, returns the fetched hub data
261 public static function import($xml,$importer,&$contact, &$hub) {
262 /// @todo this function is too long. It has to be split in many parts
264 logger("Import OStatus message", LOGGER_DEBUG);
269 //$tempfile = tempnam(get_temppath(), "import");
270 //file_put_contents($tempfile, $xml);
272 $doc = new DOMDocument();
273 @$doc->loadXML($xml);
275 $xpath = new DomXPath($doc);
276 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
277 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
278 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
279 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
280 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
281 $xpath->registerNamespace('poco', NAMESPACE_POCO);
282 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
283 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
286 $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
287 if (is_object($hub_attributes)) {
288 foreach ($hub_attributes AS $hub_attribute) {
289 if ($hub_attribute->name == "href") {
290 $hub = $hub_attribute->textContent;
291 logger("Found hub ".$hub, LOGGER_DEBUG);
296 $header["uid"] = $importer["uid"];
297 $header["network"] = NETWORK_OSTATUS;
298 $header["type"] = "remote";
300 $header["origin"] = 0;
301 $header["gravity"] = GRAVITY_PARENT;
303 // it could either be a received post or a post we fetched by ourselves
304 // depending on that, the first node is different
305 $first_child = $doc->firstChild->tagName;
307 if ($first_child == "feed") {
308 $entries = $xpath->query('/atom:feed/atom:entry');
309 $header["protocol"] = PROTOCOL_OSTATUS_FEED;
311 $entries = $xpath->query('/atom:entry');
312 $header["protocol"] = PROTOCOL_OSTATUS_SALMON;
315 $conversationlist = array();
318 // Reverse the order of the entries
319 $entrylist = array();
321 foreach ($entries AS $entry) {
322 $entrylist[] = $entry;
324 foreach (array_reverse($entrylist) AS $entry) {
329 if ($first_child == "feed") {
330 $author = self::fetchauthor($xpath, $doc->firstChild, $importer, $contact, false);
332 $author = self::fetchauthor($xpath, $entry, $importer, $contact, false);
334 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
338 $nickname = $author["author-name"];
340 $item = array_merge($header, $author);
343 $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
345 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
346 intval($importer["uid"]), dbesc($item["uri"]));
347 if (dbm::is_result($r)) {
348 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already existed under id ".$r[0]["id"], LOGGER_DEBUG);
352 $item["body"] = add_page_info_to_body(html2bbcode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue));
353 $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
354 $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
356 // Mastodon Content Warning
357 if (($item["verb"] == ACTIVITY_POST) AND $xpath->evaluate('boolean(atom:summary)', $entry)) {
358 $clear_text = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
360 $item["body"] = html2bbcode($clear_text) . '[spoiler]' . $item["body"] . '[/spoiler]';
363 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) OR ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
364 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
365 $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
366 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
367 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
369 $item["source"] = $xml;
373 if ($item["verb"] == "qvitter-delete-notice" || $item["verb"] == ACTIVITY_DELETE) {
374 // ignore "Delete" messages (by now)
375 logger("Ignore delete message ".print_r($item, true));
379 if ($item["verb"] == ACTIVITY_JOIN) {
380 // ignore "Join" messages
381 logger("Ignore join message ".print_r($item, true));
385 if ($item["verb"] == ACTIVITY_FOLLOW) {
386 new_follower($importer, $contact, $item, $nickname);
390 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
391 lose_follower($importer, $contact, $item, $dummy);
395 if ($item["verb"] == ACTIVITY_FAVORITE) {
396 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
397 logger("Favorite ".$orig_uri." ".print_r($item, true));
399 $item["verb"] = ACTIVITY_LIKE;
400 $item["parent-uri"] = $orig_uri;
401 $item["gravity"] = GRAVITY_LIKE;
404 if ($item["verb"] == NAMESPACE_OSTATUS."/unfavorite") {
405 // Ignore "Unfavorite" message
406 logger("Ignore unfavorite message ".print_r($item, true));
410 // http://activitystrea.ms/schema/1.0/rsvp-yes
411 if (!in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE))) {
412 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true));
414 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
415 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
416 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
417 $item['conversation-uri'] = $conversation;
419 $conv = $xpath->query('ostatus:conversation', $entry);
420 if (is_object($conv->item(0))) {
421 foreach ($conv->item(0)->attributes AS $attributes) {
422 if ($attributes->name == "ref") {
423 $item['conversation-uri'] = $attributes->textContent;
425 if ($attributes->name == "href") {
426 $item['conversation-href'] = $attributes->textContent;
433 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
434 if (is_object($inreplyto->item(0))) {
435 foreach ($inreplyto->item(0)->attributes AS $attributes) {
436 if ($attributes->name == "ref") {
437 $item["parent-uri"] = $attributes->textContent;
439 if ($attributes->name == "href") {
440 $related = $attributes->textContent;
445 $georsspoint = $xpath->query('georss:point', $entry);
447 $item["coord"] = $georsspoint->item(0)->nodeValue;
449 $categories = $xpath->query('atom:category', $entry);
451 foreach ($categories AS $category) {
452 foreach ($category->attributes AS $attributes) {
453 if ($attributes->name == "term") {
454 $term = $attributes->textContent;
455 if (strlen($item["tag"])) {
458 $item["tag"] .= "#[url=".App::get_baseurl()."/search?tag=".$term."]".$term."[/url]";
467 $links = $xpath->query('atom:link', $entry);
469 foreach ($links AS $link) {
470 $attribute = self::read_attributes($link);
472 if (($attribute['rel'] != "") AND ($attribute['href'] != "")) {
473 switch ($attribute['rel']) {
475 $item["plink"] = $attribute['href'];
476 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION) OR
477 ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
478 $item["body"] .= add_page_info($attribute['href']);
481 case "ostatus:conversation":
482 $conversation = $attribute['href'];
483 $item['conversation-href'] = $conversation;
484 if (!isset($item['conversation-uri'])) {
485 $item['conversation-uri'] = $item['conversation-href'];
489 $enclosure = $attribute['href'];
490 if (strlen($item["attach"])) {
491 $item["attach"] .= ',';
493 if (!isset($attribute['length'])) {
494 $attribute['length'] = "0";
496 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
499 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
500 if (!isset($item["parent-uri"])) {
501 $item["parent-uri"] = $attribute['href'];
503 if ($related == "") {
504 $related = $attribute['href'];
507 $item["body"] .= add_page_info($attribute['href']);
511 $self = $attribute['href'];
514 // Notification check
515 if ($importer["nurl"] == normalise_link($attribute['href'])) {
527 $notice_info = $xpath->query('statusnet:notice_info', $entry);
528 if ($notice_info AND ($notice_info->length > 0)) {
529 foreach ($notice_info->item(0)->attributes AS $attributes) {
530 if ($attributes->name == "source") {
531 $item["app"] = strip_tags($attributes->textContent);
533 if ($attributes->name == "local_id") {
534 $local_id = $attributes->textContent;
536 if ($attributes->name == "repeat_of") {
537 $repeat_of = $attributes->textContent;
542 // Is it a repeated post?
543 if (($repeat_of != "") OR ($item["verb"] == ACTIVITY_SHARE)) {
544 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
546 if (is_object($activityobjects)) {
548 $orig_uri = $xpath->query("activity:object/atom:id", $activityobjects)->item(0)->nodeValue;
549 if (!isset($orig_uri)) {
550 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
552 $orig_links = $xpath->query("activity:object/atom:link[@rel='alternate']", $activityobjects);
553 if ($orig_links AND ($orig_links->length > 0)) {
554 foreach ($orig_links->item(0)->attributes AS $attributes) {
555 if ($attributes->name == "href") {
556 $orig_link = $attributes->textContent;
560 if (!isset($orig_link)) {
561 $orig_link = $xpath->query("atom:link[@rel='alternate']", $activityobjects)->item(0)->nodeValue;
563 if (!isset($orig_link)) {
564 $orig_link = self::convert_href($orig_uri);
566 $orig_body = $xpath->query('activity:object/atom:content/text()', $activityobjects)->item(0)->nodeValue;
567 if (!isset($orig_body)) {
568 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
570 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
571 $orig_edited = $xpath->query('atom:updated/text()', $activityobjects)->item(0)->nodeValue;
573 $orig_contact = $contact;
574 $orig_author = self::fetchauthor($xpath, $activityobjects, $importer, $orig_contact, false);
576 $item["author-name"] = $orig_author["author-name"];
577 $item["author-link"] = $orig_author["author-link"];
578 $item["author-avatar"] = $orig_author["author-avatar"];
580 $item["body"] = add_page_info_to_body(html2bbcode($orig_body));
581 $item["created"] = $orig_created;
582 $item["edited"] = $orig_edited;
584 $item["uri"] = $orig_uri;
586 if (!isset($item["plink"])) {
587 $item["plink"] = $orig_link;
590 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
592 $item["object-type"] = $xpath->query('activity:object/activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
593 if (!isset($item["object-type"])) {
594 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
597 $enclosures = $xpath->query("atom:link[@rel='alternate']", $activityobjects);
599 foreach ($enclosures AS $link) {
600 $attribute = self::read_attributes($link);
602 $enclosure = $attribute['href'];
603 if (strlen($item["attach"])) {
604 $item["attach"] .= ',';
606 if (!isset($attribute['length'])) {
607 $attribute['length'] = "0";
609 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
616 //if ($enclosure != "")
617 // $item["body"] .= add_page_info($enclosure);
619 if (isset($item["parent-uri"])) {
620 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
621 intval($importer["uid"]), dbesc($item["parent-uri"]));
623 // Only fetch missing stuff if it is a comment or reshare.
624 if (in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_SHARE)) AND
625 !dbm::is_result($r) AND ($related != "")) {
626 $reply_path = str_replace("/notice/", "/api/statuses/show/", $related).".atom";
628 if ($reply_path != $related) {
629 logger("Fetching related items for user ".$importer["uid"]." from ".$reply_path, LOGGER_DEBUG);
630 $reply_xml = fetch_url($reply_path);
632 $reply_contact = $contact;
633 self::import($reply_xml,$importer,$reply_contact, $reply_hub);
635 // After the import try to fetch the parent item again
636 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
637 intval($importer["uid"]), dbesc($item["parent-uri"]));
640 if (dbm::is_result($r)) {
641 $item["type"] = 'remote-comment';
642 $item["gravity"] = GRAVITY_COMMENT;
645 $item["parent-uri"] = $item["uri"];
647 $item_id = self::completion($conversation, $importer["uid"], $item, $self);
650 logger("Error storing item", LOGGER_DEBUG);
654 logger("Item was stored with id ".$item_id, LOGGER_DEBUG);
659 * @brief Create an url out of an uri
661 * @param string $href URI in the format "parameter1:parameter1:..."
663 * @return string URL in the format http(s)://....
665 public static function convert_href($href) {
666 $elements = explode(":",$href);
668 if ((count($elements) <= 2) OR ($elements[0] != "tag"))
671 $server = explode(",", $elements[1]);
672 $conversation = explode("=", $elements[2]);
674 if ((count($elements) == 4) AND ($elements[2] == "post"))
675 return "http://".$server[0]."/notice/".$elements[3];
677 if ((count($conversation) != 2) OR ($conversation[1] ==""))
680 if ($elements[3] == "objectType=thread")
681 return "http://".$server[0]."/conversation/".$conversation[1];
683 return "http://".$server[0]."/notice/".$conversation[1];
689 * @brief Checks if there are entries in conversations that aren't present on our side
691 * @param bool $mentions Fetch conversations where we are mentioned
692 * @param bool $override Override the interval setting
694 public static function check_conversations($mentions = false, $override = false) {
695 $last = get_config('system','ostatus_last_poll');
697 $poll_interval = intval(get_config('system','ostatus_poll_interval'));
698 if (!$poll_interval) {
699 $poll_interval = self::OSTATUS_DEFAULT_POLL_INTERVAL;
702 // Don't poll if the interval is set negative
703 if (($poll_interval < 0) AND !$override) {
708 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
709 if (!$poll_timeframe) {
710 $poll_timeframe = self::OSTATUS_DEFAULT_POLL_TIMEFRAME;
713 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
714 if (!$poll_timeframe) {
715 $poll_timeframe = self::OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS;
720 if ($last AND !$override) {
721 $next = $last + ($poll_interval * 60);
722 if ($next > time()) {
723 logger('poll interval not reached');
728 logger('cron_start');
730 $start = date("Y-m-d H:i:s", time() - ($poll_timeframe * 60));
733 $conversations = q("SELECT `term`.`oid`, `term`.`url`, `term`.`uid` FROM `term`
734 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `term`.`oid` AND `thread`.`uid` = `term`.`uid`
735 WHERE `term`.`type` = 7 AND `term`.`term` > '%s' AND `thread`.`mention`
736 GROUP BY `term`.`url`, `term`.`uid`, `term`.`oid`, `term`.`term` ORDER BY `term`.`term` DESC", dbesc($start));
738 $conversations = q("SELECT `oid`, `url`, `uid` FROM `term`
739 WHERE `type` = 7 AND `term` > '%s'
740 GROUP BY `url`, `uid`, `oid`, `term` ORDER BY `term` DESC", dbesc($start));
743 foreach ($conversations AS $conversation) {
744 self::completion($conversation['url'], $conversation['uid']);
749 set_config('system','ostatus_last_poll', time());
753 * @brief Updates the gcontact table with actor data from the conversation
755 * @param object $actor The actor object that contains the contact data
757 private function conv_fetch_actor($actor) {
759 // We set the generation to "3" since the data here is not as reliable as the data we get on other occasions
760 $contact = array("network" => NETWORK_OSTATUS, "generation" => 3);
762 if (isset($actor->url))
763 $contact["url"] = $actor->url;
765 if (isset($actor->displayName))
766 $contact["name"] = $actor->displayName;
768 if (isset($actor->portablecontacts_net->displayName))
769 $contact["name"] = $actor->portablecontacts_net->displayName;
771 if (isset($actor->portablecontacts_net->preferredUsername))
772 $contact["nick"] = $actor->portablecontacts_net->preferredUsername;
774 if (isset($actor->id))
775 $contact["alias"] = $actor->id;
777 if (isset($actor->summary))
778 $contact["about"] = $actor->summary;
780 if (isset($actor->portablecontacts_net->note))
781 $contact["about"] = $actor->portablecontacts_net->note;
783 if (isset($actor->portablecontacts_net->addresses->formatted))
784 $contact["location"] = $actor->portablecontacts_net->addresses->formatted;
787 if (isset($actor->image->url))
788 $contact["photo"] = $actor->image->url;
790 if (isset($actor->image->width))
791 $avatarwidth = $actor->image->width;
793 if (is_array($actor->status_net->avatarLinks))
794 foreach ($actor->status_net->avatarLinks AS $avatar) {
795 if ($avatarsize < $avatar->width) {
796 $contact["photo"] = $avatar->url;
797 $avatarsize = $avatar->width;
801 $contact["hide"] = false; // OStatus contacts are never hidden
802 update_gcontact($contact);
806 * @brief Fetches the conversation url for a given item link or conversation id
808 * @param string $self The link to the posting
809 * @param string $conversation_id The conversation id
811 * @return string The conversation url
813 private function fetch_conversation($self, $conversation_id = "") {
815 if ($conversation_id != "") {
816 $elements = explode(":", $conversation_id);
818 if ((count($elements) <= 2) OR ($elements[0] != "tag"))
819 return $conversation_id;
825 $json = str_replace(".atom", ".json", $self);
827 $raw = fetch_url($json);
831 $data = json_decode($raw);
832 if (!is_object($data))
835 $conversation_id = $data->statusnet_conversation_id;
837 $pos = strpos($self, "/api/statuses/show/");
838 $base_url = substr($self, 0, $pos);
840 return $base_url."/conversation/".$conversation_id;
844 * @brief Fetches actor details of a given actor and user id
846 * @param string $actor The actor url
847 * @param int $uid The user id
848 * @param int $contact_id The default contact-id
850 * @return array Array with actor details
852 private function get_actor_details($actor, $uid, $contact_id) {
856 $contact = q("SELECT `id`, `rel`, `network` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
857 $uid, normalise_link($actor), NETWORK_STATUSNET);
860 $contact = q("SELECT `id`, `rel`, `network` FROM `contact` WHERE `uid` = %d AND `alias` IN ('%s', '%s') AND `network` != '%s'",
861 $uid, $actor, normalise_link($actor), NETWORK_STATUSNET);
864 logger("Found contact for url ".$actor, LOGGER_DEBUG);
865 $details["contact_id"] = $contact[0]["id"];
866 $details["network"] = $contact[0]["network"];
868 $details["not_following"] = !in_array($contact[0]["rel"], array(CONTACT_IS_SHARING, CONTACT_IS_FRIEND));
870 logger("No contact found for user ".$uid." and url ".$actor, LOGGER_DEBUG);
872 // Adding a global contact
873 /// @TODO Use this data for the post
874 $details["global_contact_id"] = get_contact($actor, 0);
876 logger("Global contact ".$global_contact_id." found for url ".$actor, LOGGER_DEBUG);
878 $details["contact_id"] = $contact_id;
879 $details["network"] = NETWORK_OSTATUS;
881 $details["not_following"] = true;
888 * @brief Stores an item and completes the thread
890 * @param string $conversation_url The URI of the conversation
891 * @param integer $uid The user id
892 * @param array $item Data of the item that is to be posted
894 * @return integer The item id of the posted item array
896 private function completion($conversation_url, $uid, $item = array(), $self = "") {
898 /// @todo This function is totally ugly and has to be rewritten totally
900 // Import all threads or only threads that were started by our followers?
901 $all_threads = !get_config('system','ostatus_full_threads');
905 $conversation_url = self::fetch_conversation($self, $conversation_url);
907 // If the thread shouldn't be completed then store the item and go away
908 // Don't do a completion on liked content
909 if (((intval(get_config('system','ostatus_poll_interval')) == -2) AND (count($item) > 0)) OR
910 ($item["verb"] == ACTIVITY_LIKE) OR ($conversation_url == "")) {
911 $item_stored = item_store($item, $all_threads);
913 } elseif (count($item) > 0) {
914 $item = store_conversation($item);
918 $parents = q("SELECT `item`.`id`, `item`.`parent`, `item`.`uri`, `item`.`contact-id`, `item`.`type`,
919 `item`.`verb`, `item`.`visible` FROM `term`
920 STRAIGHT_JOIN `item` AS `thritem` ON `thritem`.`parent` = `term`.`oid`
921 STRAIGHT_JOIN `item` ON `item`.`parent` = `thritem`.`parent`
922 WHERE `term`.`uid` = %d AND `term`.`otype` = %d AND `term`.`type` = %d AND `term`.`url` = '%s'",
923 intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url));
925 /* 2016-10-23: The old query will be kept until we are sure that the query above is a good and fast replacement
927 $parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
928 (SELECT `parent` FROM `item` WHERE `id` IN
929 (SELECT `oid` FROM `term` WHERE `uid` = %d AND `otype` = %d AND `type` = %d AND `url` = '%s'))",
930 intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url));
933 $parent = $parents[0];
934 elseif (count($item) > 0) {
936 $parent["type"] = "remote";
937 $parent["verb"] = ACTIVITY_POST;
938 $parent["visible"] = 1;
941 $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid`=%d", $uid);
947 $parent["parent"] = 0;
949 $parent["contact-id"] = $r[0]["id"];
950 $parent["type"] = "remote";
951 $parent["verb"] = ACTIVITY_POST;
952 $parent["visible"] = 1;
955 $conv = str_replace("/conversation/", "/api/statusnet/conversation/", $conversation_url).".as";
959 logger('fetching conversation url '.$conv.' (Self: '.$self.') for user '.$uid);
962 $conv_arr = z_fetch_url($conv."?page=".$pageno);
964 // If it is a non-ssl site and there is an error, then try ssl or vice versa
965 if (!$conv_arr["success"] AND (substr($conv, 0, 7) == "http://")) {
966 $conv = str_replace("http://", "https://", $conv);
967 $conv_as = fetch_url($conv."?page=".$pageno);
968 } elseif (!$conv_arr["success"] AND (substr($conv, 0, 8) == "https://")) {
969 $conv = str_replace("https://", "http://", $conv);
970 $conv_as = fetch_url($conv."?page=".$pageno);
972 $conv_as = $conv_arr["body"];
974 $conv_as = str_replace(',"statusnet:notice_info":', ',"statusnet_notice_info":', $conv_as);
975 $conv_as = json_decode($conv_as);
977 $no_of_items = sizeof($items);
979 if (@is_array($conv_as->items))
980 foreach ($conv_as->items AS $single_item)
981 $items[$single_item->id] = $single_item;
983 if ($no_of_items == sizeof($items))
990 logger('fetching conversation done. Found '.count($items).' items');
992 if (!sizeof($items)) {
993 if (count($item) > 0) {
994 $item_stored = item_store($item, $all_threads);
997 logger("Conversation ".$conversation_url." couldn't be fetched. Item uri ".$item["uri"]." stored: ".$item_stored, LOGGER_DEBUG);
998 self::store_conversation($item_id, $conversation_url);
1001 return($item_stored);
1006 $items = array_reverse($items);
1008 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self`", intval($uid));
1013 foreach ($items as $single_conv) {
1015 // Update the gcontact table
1016 self::conv_fetch_actor($single_conv->actor);
1018 // Test - remove before flight
1019 //$tempfile = tempnam(get_temppath(), "conversation");
1020 //file_put_contents($tempfile, json_encode($single_conv));
1024 if (isset($single_conv->object->id))
1025 $single_conv->id = $single_conv->object->id;
1027 $plink = self::convert_href($single_conv->id);
1028 if (isset($single_conv->object->url))
1029 $plink = self::convert_href($single_conv->object->url);
1031 if (@!$single_conv->id)
1034 logger("Got id ".$single_conv->id, LOGGER_DEBUG);
1036 if ($first_id == "") {
1037 $first_id = $single_conv->id;
1039 // The first post of the conversation isn't our first post. There are three options:
1040 // 1. Our conversation hasn't the "real" thread starter
1041 // 2. This first post is a post inside our thread
1042 // 3. This first post is a post inside another thread
1043 if (($first_id != $parent["uri"]) AND ($parent["uri"] != "")) {
1047 $new_parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
1048 (SELECT `parent` FROM `item`
1049 WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s')) LIMIT 1",
1050 intval($uid), dbesc($first_id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1052 if ($new_parents[0]["parent"] == $parent["parent"]) {
1053 // Option 2: This post is already present inside our thread - but not as thread starter
1054 logger("Option 2: uri present in our thread: ".$first_id, LOGGER_DEBUG);
1055 $first_id = $parent["uri"];
1057 // Option 3: Not so good. We have mixed parents. We have to see how to clean this up.
1058 // For now just take the new parent.
1059 $parent = $new_parents[0];
1060 $first_id = $parent["uri"];
1061 logger("Option 3: mixed parents for uri ".$first_id, LOGGER_DEBUG);
1064 // Option 1: We hadn't got the real thread starter
1065 // We have to clean up our existing messages.
1067 $parent["uri"] = $first_id;
1068 logger("Option 1: we have a new parent: ".$first_id, LOGGER_DEBUG);
1070 } elseif ($parent["uri"] == "") {
1072 $parent["uri"] = $first_id;
1076 $parent_uri = $parent["uri"];
1078 // "context" only seems to exist on older servers
1079 if (isset($single_conv->context->inReplyTo->id)) {
1080 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1081 intval($uid), dbesc($single_conv->context->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1083 $parent_uri = $single_conv->context->inReplyTo->id;
1086 // This is the current way
1087 if (isset($single_conv->object->inReplyTo->id)) {
1088 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1089 intval($uid), dbesc($single_conv->object->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1091 $parent_uri = $single_conv->object->inReplyTo->id;
1094 $message_exists = q("SELECT `id`, `parent`, `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1095 intval($uid), dbesc($single_conv->id),
1096 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1097 if ($message_exists) {
1098 logger("Message ".$single_conv->id." already existed on the system", LOGGER_DEBUG);
1100 if ($parent["id"] != 0) {
1101 $existing_message = $message_exists[0];
1103 // We improved the way we fetch OStatus messages, this shouldn't happen very often now
1104 /// @TODO We have to change the shadow copies as well. This way here is really ugly.
1105 if ($existing_message["parent"] != $parent["id"]) {
1106 logger('updating id '.$existing_message["id"].' with parent '.$existing_message["parent"].' to parent '.$parent["id"].' uri '.$parent["uri"].' thread '.$parent_uri, LOGGER_DEBUG);
1108 // Update the parent id of the selected item
1109 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `id` = %d",
1110 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["id"]));
1112 // Update the parent uri in the thread - but only if it points to itself
1113 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE `id` = %d AND `uri` = `thr-parent`",
1114 dbesc($parent_uri), intval($existing_message["id"]));
1116 // try to change all items of the same parent
1117 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `parent` = %d",
1118 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["parent"]));
1120 // Update the parent uri in the thread - but only if it points to itself
1121 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE (`parent` = %d) AND (`uri` = `thr-parent`)",
1122 dbesc($parent["uri"]), intval($existing_message["parent"]));
1124 // Now delete the thread
1125 delete_thread($existing_message["parent"]);
1129 // The item we are having on the system is the one that we wanted to store via the item array
1130 if (isset($item["uri"]) AND ($item["uri"] == $existing_message["uri"])) {
1138 if (is_array($single_conv->to))
1139 foreach($single_conv->to AS $to)
1140 if ($importer["nurl"] == normalise_link($to->id))
1143 $actor = $single_conv->actor->id;
1144 if (isset($single_conv->actor->url))
1145 $actor = $single_conv->actor->url;
1147 $details = self::get_actor_details($actor, $uid, $parent["contact-id"]);
1149 // Do we only want to import threads that were started by our contacts?
1150 if ($details["not_following"] AND $new_parent AND get_config('system','ostatus_full_threads')) {
1151 logger("Don't import uri ".$first_id." because user ".$uid." doesn't follow the person ".$actor, LOGGER_DEBUG);
1155 /// @TODO One statment is okay (until if () )
1157 $arr["network"] = $details["network"];
1158 $arr["uri"] = $single_conv->id;
1159 $arr["plink"] = $plink;
1161 $arr["contact-id"] = $details["contact_id"];
1162 $arr["parent-uri"] = $parent_uri;
1163 $arr["created"] = $single_conv->published;
1164 $arr["edited"] = $single_conv->published;
1165 $arr["owner-name"] = $single_conv->actor->displayName;
1166 if ($arr["owner-name"] == '')
1167 $arr["owner-name"] = $single_conv->actor->contact->displayName;
1168 if ($arr["owner-name"] == '')
1169 $arr["owner-name"] = $single_conv->actor->portablecontacts_net->displayName;
1171 $arr["owner-link"] = $actor;
1172 $arr["owner-avatar"] = Probe::fixAvatar($single_conv->actor->image->url, $arr["owner-link"]);
1174 $arr["author-name"] = $arr["owner-name"];
1175 $arr["author-link"] = $arr["owner-link"];
1176 $arr["author-avatar"] = $arr["owner-avatar"];
1177 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->content));
1179 if (isset($single_conv->status_net->conversation)) {
1180 $arr['conversation-uri'] = $single_conv->status_net->conversation;
1183 if (isset($single_conv->status_net->notice_info->source))
1184 $arr["app"] = strip_tags($single_conv->status_net->notice_info->source);
1185 elseif (isset($single_conv->statusnet->notice_info->source))
1186 $arr["app"] = strip_tags($single_conv->statusnet->notice_info->source);
1187 elseif (isset($single_conv->statusnet_notice_info->source))
1188 $arr["app"] = strip_tags($single_conv->statusnet_notice_info->source);
1189 elseif (isset($single_conv->provider->displayName))
1190 $arr["app"] = $single_conv->provider->displayName;
1192 $arr["app"] = "OStatus";
1195 $arr["source"] = json_encode($single_conv);
1196 $arr["protocol"] = PROTOCOL_GS_CONVERSATION;
1198 $arr["verb"] = $parent["verb"];
1199 $arr["visible"] = $parent["visible"];
1200 $arr["location"] = $single_conv->location->displayName;
1201 $arr["coord"] = trim($single_conv->location->lat." ".$single_conv->location->lon);
1203 // Is it a reshared item?
1204 if (isset($single_conv->verb) AND ($single_conv->verb == "share") AND isset($single_conv->object)) {
1205 if (is_array($single_conv->object))
1206 $single_conv->object = $single_conv->object[0];
1208 logger("Found reshared item ".$single_conv->object->id);
1210 // $single_conv->object->context->conversation;
1212 if (isset($single_conv->object->object->id))
1213 $arr["uri"] = $single_conv->object->object->id;
1215 $arr["uri"] = $single_conv->object->id;
1217 if (isset($single_conv->object->object->url))
1218 $plink = self::convert_href($single_conv->object->object->url);
1220 $plink = self::convert_href($single_conv->object->url);
1222 if (isset($single_conv->object->object->content))
1223 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->object->content));
1225 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->content));
1227 $arr["plink"] = $plink;
1229 $arr["created"] = $single_conv->object->published;
1230 $arr["edited"] = $single_conv->object->published;
1232 $arr["author-name"] = $single_conv->object->actor->displayName;
1233 if ($arr["owner-name"] == '') {
1234 $arr["author-name"] = $single_conv->object->actor->contact->displayName;
1236 $arr["author-link"] = $single_conv->object->actor->url;
1237 $arr["author-avatar"] = Probe::fixAvatar($single_conv->object->actor->image->url, $arr["author-link"]);
1239 $arr["app"] = $single_conv->object->provider->displayName."#";
1240 //$arr["verb"] = $single_conv->object->verb;
1242 $arr["location"] = $single_conv->object->location->displayName;
1243 $arr["coord"] = trim($single_conv->object->location->lat." ".$single_conv->object->location->lon);
1246 if ($arr["location"] == "")
1247 unset($arr["location"]);
1249 if ($arr["coord"] == "")
1250 unset($arr["coord"]);
1252 // Copy fields from given item array
1253 if (isset($item["uri"]) AND (($item["uri"] == $arr["uri"]) OR ($item["uri"] == $single_conv->id))) {
1254 $copy_fields = array("owner-name", "owner-link", "owner-avatar", "author-name", "author-link", "author-avatar",
1255 "gravity", "body", "object-type", "object", "verb", "created", "edited", "coord", "tag",
1256 "title", "attach", "app", "type", "location", "contact-id", "uri");
1257 foreach ($copy_fields AS $field)
1258 if (isset($item[$field]))
1259 $arr[$field] = $item[$field];
1263 $newitem = item_store($arr);
1265 logger("Item wasn't stored ".print_r($arr, true), LOGGER_DEBUG);
1269 if (isset($item["uri"]) AND ($item["uri"] == $arr["uri"])) {
1271 $item_stored = $newitem;
1274 logger('Stored new item '.$plink.' for parent '.$arr["parent-uri"].' under id '.$newitem, LOGGER_DEBUG);
1276 // Add the conversation entry (but don't fetch the whole conversation)
1277 self::store_conversation($newitem, $conversation_url);
1279 // If the newly created item is the top item then change the parent settings of the thread
1280 // This shouldn't happen anymore. This is supposed to be absolote.
1281 if ($arr["uri"] == $first_id) {
1282 logger('setting new parent to id '.$newitem);
1283 $new_parents = q("SELECT `id`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
1284 intval($uid), intval($newitem));
1286 $parent = $new_parents[0];
1290 if (($item_stored < 0) AND (count($item) > 0)) {
1292 if (get_config('system','ostatus_full_threads')) {
1293 $details = self::get_actor_details($item["owner-link"], $uid, $item["contact-id"]);
1294 if ($details["not_following"]) {
1295 logger("Don't import uri ".$item["uri"]." because user ".$uid." doesn't follow the person ".$item["owner-link"], LOGGER_DEBUG);
1300 $item_stored = item_store($item, $all_threads);
1302 logger("Uri ".$item["uri"]." wasn't found in conversation ".$conversation_url, LOGGER_DEBUG);
1303 self::store_conversation($item_stored, $conversation_url);
1307 return($item_stored);
1311 * @brief Stores conversation data into the database
1313 * @param integer $itemid The id of the item
1314 * @param string $conversation_url The uri of the conversation
1316 private function store_conversation($itemid, $conversation_url) {
1318 $conversation_url = self::convert_href($conversation_url);
1320 $messages = q("SELECT `uid`, `parent`, `created`, `received`, `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($itemid));
1323 $message = $messages[0];
1325 // Store conversation url if not done before
1326 $conversation = q("SELECT `url` FROM `term` WHERE `uid` = %d AND `oid` = %d AND `otype` = %d AND `type` = %d",
1327 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION));
1329 if (!$conversation) {
1330 $r = q("INSERT INTO `term` (`uid`, `oid`, `otype`, `type`, `term`, `url`, `created`, `received`, `guid`) VALUES (%d, %d, %d, %d, '%s', '%s', '%s', '%s', '%s')",
1331 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION),
1332 dbesc($message["created"]), dbesc($conversation_url), dbesc($message["created"]), dbesc($message["received"]), dbesc($message["guid"]));
1333 logger('Storing conversation url '.$conversation_url.' for id '.$itemid);
1338 * @brief Checks if the current post is a reshare
1340 * @param array $item The item array of thw post
1342 * @return string The guid if the post is a reshare
1344 private function get_reshared_guid($item) {
1345 $body = trim($item["body"]);
1347 // Skip if it isn't a pure repeated messages
1348 // Does it start with a share?
1349 if (strpos($body, "[share") > 0)
1352 // Does it end with a share?
1353 if (strlen($body) > (strrpos($body, "[/share]") + 8))
1356 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
1357 // Skip if there is no shared message in there
1358 if ($body == $attributes)
1362 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1363 if ($matches[1] != "")
1364 $guid = $matches[1];
1366 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1367 if ($matches[1] != "")
1368 $guid = $matches[1];
1374 * @brief Cleans the body of a post if it contains picture links
1376 * @param string $body The body
1378 * @return string The cleaned body
1380 private function format_picture_post($body) {
1381 $siteinfo = get_attached_data($body);
1383 if (($siteinfo["type"] == "photo")) {
1384 if (isset($siteinfo["preview"]))
1385 $preview = $siteinfo["preview"];
1387 $preview = $siteinfo["image"];
1389 // Is it a remote picture? Then make a smaller preview here
1390 $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
1392 // Is it a local picture? Then make it smaller here
1393 $preview = str_replace(array("-0.jpg", "-0.png"), array("-2.jpg", "-2.png"), $preview);
1394 $preview = str_replace(array("-1.jpg", "-1.png"), array("-2.jpg", "-2.png"), $preview);
1396 if (isset($siteinfo["url"]))
1397 $url = $siteinfo["url"];
1399 $url = $siteinfo["image"];
1401 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1408 * @brief Adds the header elements to the XML document
1410 * @param object $doc XML document
1411 * @param array $owner Contact data of the poster
1413 * @return object header root element
1415 private function add_header($doc, $owner) {
1419 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1420 $doc->appendChild($root);
1422 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1423 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1424 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1425 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1426 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1427 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1428 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1429 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1431 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
1432 xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1433 xml::add_element($doc, $root, "id", App::get_baseurl()."/profile/".$owner["nick"]);
1434 xml::add_element($doc, $root, "title", sprintf("%s timeline", $owner["name"]));
1435 xml::add_element($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
1436 xml::add_element($doc, $root, "logo", $owner["photo"]);
1437 xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
1439 $author = self::add_author($doc, $owner);
1440 $root->appendChild($author);
1442 $attributes = array("href" => $owner["url"], "rel" => "alternate", "type" => "text/html");
1443 xml::add_element($doc, $root, "link", "", $attributes);
1445 /// @TODO We have to find out what this is
1446 /// $attributes = array("href" => App::get_baseurl()."/sup",
1447 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1448 /// "type" => "application/json");
1449 /// xml::add_element($doc, $root, "link", "", $attributes);
1451 self::hublinks($doc, $root);
1453 $attributes = array("href" => App::get_baseurl()."/salmon/".$owner["nick"], "rel" => "salmon");
1454 xml::add_element($doc, $root, "link", "", $attributes);
1456 $attributes = array("href" => App::get_baseurl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies");
1457 xml::add_element($doc, $root, "link", "", $attributes);
1459 $attributes = array("href" => App::get_baseurl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention");
1460 xml::add_element($doc, $root, "link", "", $attributes);
1462 $attributes = array("href" => App::get_baseurl()."/api/statuses/user_timeline/".$owner["nick"].".atom",
1463 "rel" => "self", "type" => "application/atom+xml");
1464 xml::add_element($doc, $root, "link", "", $attributes);
1470 * @brief Add the link to the push hubs to the XML document
1472 * @param object $doc XML document
1473 * @param object $root XML root element where the hub links are added
1475 public static function hublinks($doc, $root) {
1476 $hub = get_config('system','huburl');
1480 $hubs = explode(',', $hub);
1482 foreach($hubs as $h) {
1486 if ($h === '[internal]')
1487 $h = App::get_baseurl() . '/pubsubhubbub';
1488 xml::add_element($doc, $root, "link", "", array("href" => $h, "rel" => "hub"));
1495 * @brief Adds attachement data to the XML document
1497 * @param object $doc XML document
1498 * @param object $root XML root element where the hub links are added
1499 * @param array $item Data of the item that is to be posted
1501 private function get_attachment($doc, $root, $item) {
1503 $siteinfo = get_attached_data($item["body"]);
1505 switch ($siteinfo["type"]) {
1507 $imgdata = get_photo_info($siteinfo["image"]);
1508 $attributes = array("rel" => "enclosure",
1509 "href" => $siteinfo["image"],
1510 "type" => $imgdata["mime"],
1511 "length" => intval($imgdata["size"]));
1512 xml::add_element($doc, $root, "link", "", $attributes);
1515 $attributes = array("rel" => "enclosure",
1516 "href" => $siteinfo["url"],
1517 "type" => "text/html; charset=UTF-8",
1519 "title" => $siteinfo["title"]);
1520 xml::add_element($doc, $root, "link", "", $attributes);
1526 if (($siteinfo["type"] != "photo") AND isset($siteinfo["image"])) {
1527 $imgdata = get_photo_info($siteinfo["image"]);
1528 $attributes = array("rel" => "enclosure",
1529 "href" => $siteinfo["image"],
1530 "type" => $imgdata["mime"],
1531 "length" => intval($imgdata["size"]));
1533 xml::add_element($doc, $root, "link", "", $attributes);
1536 $arr = explode('[/attach],', $item['attach']);
1538 foreach ($arr as $r) {
1540 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1542 $attributes = array("rel" => "enclosure",
1543 "href" => $matches[1],
1544 "type" => $matches[3]);
1546 if (intval($matches[2])) {
1547 $attributes["length"] = intval($matches[2]);
1549 if (trim($matches[4]) != "") {
1550 $attributes["title"] = trim($matches[4]);
1552 xml::add_element($doc, $root, "link", "", $attributes);
1559 * @brief Adds the author element to the XML document
1561 * @param object $doc XML document
1562 * @param array $owner Contact data of the poster
1564 * @return object author element
1566 private function add_author($doc, $owner) {
1568 $r = q("SELECT `homepage`, `publish` FROM `profile` WHERE `uid` = %d AND `is-default` LIMIT 1", intval($owner["uid"]));
1572 $author = $doc->createElement("author");
1573 xml::add_element($doc, $author, "id", $owner["url"]);
1574 xml::add_element($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1575 xml::add_element($doc, $author, "uri", $owner["url"]);
1576 xml::add_element($doc, $author, "name", $owner["nick"]);
1577 xml::add_element($doc, $author, "email", $owner["addr"]);
1578 xml::add_element($doc, $author, "summary", bbcode($owner["about"], false, false, 7));
1580 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $owner["url"]);
1581 xml::add_element($doc, $author, "link", "", $attributes);
1583 $attributes = array(
1585 "type" => "image/jpeg", // To-Do?
1586 "media:width" => 175,
1587 "media:height" => 175,
1588 "href" => $owner["photo"]);
1589 xml::add_element($doc, $author, "link", "", $attributes);
1591 if (isset($owner["thumb"])) {
1592 $attributes = array(
1594 "type" => "image/jpeg", // To-Do?
1595 "media:width" => 80,
1596 "media:height" => 80,
1597 "href" => $owner["thumb"]);
1598 xml::add_element($doc, $author, "link", "", $attributes);
1601 xml::add_element($doc, $author, "poco:preferredUsername", $owner["nick"]);
1602 xml::add_element($doc, $author, "poco:displayName", $owner["name"]);
1603 xml::add_element($doc, $author, "poco:note", bbcode($owner["about"], false, false, 7));
1605 if (trim($owner["location"]) != "") {
1606 $element = $doc->createElement("poco:address");
1607 xml::add_element($doc, $element, "poco:formatted", $owner["location"]);
1608 $author->appendChild($element);
1611 if (trim($profile["homepage"]) != "") {
1612 $urls = $doc->createElement("poco:urls");
1613 xml::add_element($doc, $urls, "poco:type", "homepage");
1614 xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
1615 xml::add_element($doc, $urls, "poco:primary", "true");
1616 $author->appendChild($urls);
1619 if (count($profile)) {
1620 xml::add_element($doc, $author, "followers", "", array("url" => App::get_baseurl()."/viewcontacts/".$owner["nick"]));
1621 xml::add_element($doc, $author, "statusnet:profile_info", "", array("local_id" => $owner["uid"]));
1624 if ($profile["publish"]) {
1625 xml::add_element($doc, $author, "mastodon:scope", "public");
1631 * @TODO Picture attachments should look like this:
1632 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1633 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1638 * @brief Returns the given activity if present - otherwise returns the "post" activity
1640 * @param array $item Data of the item that is to be posted
1642 * @return string activity
1644 function construct_verb($item) {
1646 return $item['verb'];
1647 return ACTIVITY_POST;
1651 * @brief Returns the given object type if present - otherwise returns the "note" object type
1653 * @param array $item Data of the item that is to be posted
1655 * @return string Object type
1657 function construct_objecttype($item) {
1658 if (in_array($item['object-type'], array(ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT)))
1659 return $item['object-type'];
1660 return ACTIVITY_OBJ_NOTE;
1664 * @brief Adds an entry element to the XML document
1666 * @param object $doc XML document
1667 * @param array $item Data of the item that is to be posted
1668 * @param array $owner Contact data of the poster
1669 * @param bool $toplevel
1671 * @return object Entry element
1673 private function entry($doc, $item, $owner, $toplevel = false) {
1674 $repeated_guid = self::get_reshared_guid($item);
1675 if ($repeated_guid != "")
1676 $xml = self::reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel);
1681 if ($item["verb"] == ACTIVITY_LIKE) {
1682 return self::like_entry($doc, $item, $owner, $toplevel);
1683 } elseif (in_array($item["verb"], array(ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"))) {
1684 return self::follow_entry($doc, $item, $owner, $toplevel);
1686 return self::note_entry($doc, $item, $owner, $toplevel);
1691 * @brief Adds a source entry to the XML document
1693 * @param object $doc XML document
1694 * @param array $contact Array of the contact that is added
1696 * @return object Source element
1698 private function source_entry($doc, $contact) {
1699 $source = $doc->createElement("source");
1700 xml::add_element($doc, $source, "id", $contact["poll"]);
1701 xml::add_element($doc, $source, "title", $contact["name"]);
1702 xml::add_element($doc, $source, "link", "", array("rel" => "alternate",
1703 "type" => "text/html",
1704 "href" => $contact["alias"]));
1705 xml::add_element($doc, $source, "link", "", array("rel" => "self",
1706 "type" => "application/atom+xml",
1707 "href" => $contact["poll"]));
1708 xml::add_element($doc, $source, "icon", $contact["photo"]);
1709 xml::add_element($doc, $source, "updated", datetime_convert("UTC","UTC",$contact["success_update"]."+00:00",ATOM_TIME));
1715 * @brief Fetches contact data from the contact or the gcontact table
1717 * @param string $url URL of the contact
1718 * @param array $owner Contact data of the poster
1720 * @return array Contact array
1722 private function contact_entry($url, $owner) {
1724 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1725 dbesc(normalise_link($url)), intval($owner["uid"]));
1728 $contact["uid"] = -1;
1732 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1733 dbesc(normalise_link($url)));
1736 $contact["uid"] = -1;
1737 $contact["success_update"] = $contact["updated"];
1744 if (!isset($contact["poll"])) {
1745 $data = probe_url($url);
1746 $contact["poll"] = $data["poll"];
1748 if (!$contact["alias"])
1749 $contact["alias"] = $data["alias"];
1752 if (!isset($contact["alias"]))
1753 $contact["alias"] = $contact["url"];
1759 * @brief Adds an entry element with reshared content
1761 * @param object $doc XML document
1762 * @param array $item Data of the item that is to be posted
1763 * @param array $owner Contact data of the poster
1764 * @param $repeated_guid
1765 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1767 * @return object Entry element
1769 private function reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel) {
1771 if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1772 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1775 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1777 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' AND NOT `private` AND `network` IN ('%s', '%s', '%s') LIMIT 1",
1778 intval($owner["uid"]), dbesc($repeated_guid),
1779 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS));
1781 $repeated_item = $r[0];
1785 $contact = self::contact_entry($repeated_item['author-link'], $owner);
1787 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1789 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1791 self::entry_content($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1793 $as_object = $doc->createElement("activity:object");
1795 xml::add_element($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1797 self::entry_content($doc, $as_object, $repeated_item, $owner, "", "", false);
1799 $author = self::add_author($doc, $contact);
1800 $as_object->appendChild($author);
1802 $as_object2 = $doc->createElement("activity:object");
1804 xml::add_element($doc, $as_object2, "activity:object-type", self::construct_objecttype($repeated_item));
1806 $title = sprintf("New comment by %s", $contact["nick"]);
1808 self::entry_content($doc, $as_object2, $repeated_item, $owner, $title);
1810 $as_object->appendChild($as_object2);
1812 self::entry_footer($doc, $as_object, $item, $owner, false);
1814 $source = self::source_entry($doc, $contact);
1816 $as_object->appendChild($source);
1818 $entry->appendChild($as_object);
1820 self::entry_footer($doc, $entry, $item, $owner);
1826 * @brief Adds an entry element with a "like"
1828 * @param object $doc XML document
1829 * @param array $item Data of the item that is to be posted
1830 * @param array $owner Contact data of the poster
1831 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1833 * @return object Entry element with "like"
1835 private function like_entry($doc, $item, $owner, $toplevel) {
1837 if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1838 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1841 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1843 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1844 self::entry_content($doc, $entry, $item, $owner, "Favorite", $verb, false);
1846 $as_object = $doc->createElement("activity:object");
1848 $parent = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
1849 dbesc($item["thr-parent"]), intval($item["uid"]));
1850 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1852 xml::add_element($doc, $as_object, "activity:object-type", self::construct_objecttype($parent[0]));
1854 self::entry_content($doc, $as_object, $parent[0], $owner, "New entry");
1856 $entry->appendChild($as_object);
1858 self::entry_footer($doc, $entry, $item, $owner);
1864 * @brief Adds the person object element to the XML document
1866 * @param object $doc XML document
1867 * @param array $owner Contact data of the poster
1868 * @param array $contact Contact data of the target
1870 * @return object author element
1872 private function add_person_object($doc, $owner, $contact) {
1874 $object = $doc->createElement("activity:object");
1875 xml::add_element($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1877 if ($contact['network'] == NETWORK_PHANTOM) {
1878 xml::add_element($doc, $object, "id", $contact['url']);
1882 xml::add_element($doc, $object, "id", $contact["alias"]);
1883 xml::add_element($doc, $object, "title", $contact["nick"]);
1885 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $contact["url"]);
1886 xml::add_element($doc, $object, "link", "", $attributes);
1888 $attributes = array(
1890 "type" => "image/jpeg", // To-Do?
1891 "media:width" => 175,
1892 "media:height" => 175,
1893 "href" => $contact["photo"]);
1894 xml::add_element($doc, $object, "link", "", $attributes);
1896 xml::add_element($doc, $object, "poco:preferredUsername", $contact["nick"]);
1897 xml::add_element($doc, $object, "poco:displayName", $contact["name"]);
1899 if (trim($contact["location"]) != "") {
1900 $element = $doc->createElement("poco:address");
1901 xml::add_element($doc, $element, "poco:formatted", $contact["location"]);
1902 $object->appendChild($element);
1909 * @brief Adds a follow/unfollow entry element
1911 * @param object $doc XML document
1912 * @param array $item Data of the follow/unfollow message
1913 * @param array $owner Contact data of the poster
1914 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1916 * @return object Entry element
1918 private function follow_entry($doc, $item, $owner, $toplevel) {
1920 $item["id"] = $item["parent"] = 0;
1921 $item["created"] = $item["edited"] = date("c");
1922 $item["private"] = true;
1924 $contact = Probe::uri($item['follow']);
1926 if ($contact['alias'] == '') {
1927 $contact['alias'] = $contact["url"];
1929 $item['follow'] = $contact['alias'];
1932 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1933 intval($owner['uid']), dbesc(normalise_link($contact["url"])));
1935 if (dbm::is_result($r)) {
1936 $connect_id = $r[0]['id'];
1941 if ($item['verb'] == ACTIVITY_FOLLOW) {
1942 $message = t('%s is now following %s.');
1943 $title = t('following');
1944 $action = "subscription";
1946 $message = t('%s stopped following %s.');
1947 $title = t('stopped following');
1948 $action = "unfollow";
1951 $item["uri"] = $item['parent-uri'] = $item['thr-parent'] =
1952 'tag:'.get_app()->get_hostname().
1953 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1954 ':person:'.$connect_id.':'.$item['created'];
1956 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1958 self::entry_header($doc, $entry, $owner, $toplevel);
1960 self::entry_content($doc, $entry, $item, $owner, $title);
1962 $object = self::add_person_object($doc, $owner, $contact);
1963 $entry->appendChild($object);
1965 self::entry_footer($doc, $entry, $item, $owner);
1971 * @brief Adds a regular entry element
1973 * @param object $doc XML document
1974 * @param array $item Data of the item that is to be posted
1975 * @param array $owner Contact data of the poster
1976 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1978 * @return object Entry element
1980 private function note_entry($doc, $item, $owner, $toplevel) {
1982 if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1983 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1986 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1988 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1990 self::entry_content($doc, $entry, $item, $owner, $title);
1992 self::entry_footer($doc, $entry, $item, $owner);
1998 * @brief Adds a header element to the XML document
2000 * @param object $doc XML document
2001 * @param object $entry The entry element where the elements are added
2002 * @param array $owner Contact data of the poster
2003 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
2005 * @return string The title for the element
2007 private function entry_header($doc, &$entry, $owner, $toplevel) {
2008 /// @todo Check if this title stuff is really needed (I guess not)
2010 $entry = $doc->createElement("entry");
2011 $title = sprintf("New note by %s", $owner["nick"]);
2013 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
2015 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
2016 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
2017 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
2018 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
2019 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
2020 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
2021 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
2022 $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
2024 $author = self::add_author($doc, $owner);
2025 $entry->appendChild($author);
2027 $title = sprintf("New comment by %s", $owner["nick"]);
2033 * @brief Adds elements to the XML document
2035 * @param object $doc XML document
2036 * @param object $entry Entry element where the content is added
2037 * @param array $item Data of the item that is to be posted
2038 * @param array $owner Contact data of the poster
2039 * @param string $title Title for the post
2040 * @param string $verb The activity verb
2041 * @param bool $complete Add the "status_net" element?
2043 private function entry_content($doc, $entry, $item, $owner, $title, $verb = "", $complete = true) {
2046 $verb = self::construct_verb($item);
2048 xml::add_element($doc, $entry, "id", $item["uri"]);
2049 xml::add_element($doc, $entry, "title", $title);
2051 $body = self::format_picture_post($item['body']);
2053 if ($item['title'] != "")
2054 $body = "[b]".$item['title']."[/b]\n\n".$body;
2056 $body = bbcode($body, false, false, 7);
2058 xml::add_element($doc, $entry, "content", $body, array("type" => "html"));
2060 xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
2061 "href" => App::get_baseurl()."/display/".$item["guid"]));
2063 if ($complete AND ($item["id"] > 0))
2064 xml::add_element($doc, $entry, "status_net", "", array("notice_id" => $item["id"]));
2066 xml::add_element($doc, $entry, "activity:verb", $verb);
2068 xml::add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
2069 xml::add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
2073 * @brief Adds the elements at the foot of an entry to the XML document
2075 * @param object $doc XML document
2076 * @param object $entry The entry element where the elements are added
2077 * @param array $item Data of the item that is to be posted
2078 * @param array $owner Contact data of the poster
2081 private function entry_footer($doc, $entry, $item, $owner, $complete = true) {
2083 $mentioned = array();
2085 if (($item['parent'] != $item['id']) OR ($item['parent-uri'] !== $item['uri']) OR (($item['thr-parent'] !== '') AND ($item['thr-parent'] !== $item['uri']))) {
2086 $parent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `id` = %d", intval($item["parent"]));
2087 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
2089 $thrparent = q("SELECT `guid`, `author-link`, `owner-link`, `plink` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
2090 intval($owner["uid"]),
2091 dbesc($parent_item));
2093 $mentioned[$thrparent[0]["author-link"]] = $thrparent[0]["author-link"];
2094 $mentioned[$thrparent[0]["owner-link"]] = $thrparent[0]["owner-link"];
2095 $parent_plink = $thrparent[0]["plink"];
2097 $mentioned[$parent[0]["author-link"]] = $parent[0]["author-link"];
2098 $mentioned[$parent[0]["owner-link"]] = $parent[0]["owner-link"];
2099 $parent_plink = App::get_baseurl()."/display/".$parent[0]["guid"];
2102 $attributes = array(
2103 "ref" => $parent_item,
2104 "href" => $parent_plink);
2105 xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
2107 $attributes = array(
2109 "href" => $parent_plink);
2110 xml::add_element($doc, $entry, "link", "", $attributes);
2113 if (intval($item["parent"]) > 0) {
2114 $conversation_href = App::get_baseurl()."/display/".$owner["nick"]."/".$item["parent"];
2115 $conversation_uri = $conversation_href;
2117 if (isset($parent_item)) {
2118 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $parent_item);
2119 if (dbm::is_result($r)) {
2120 if ($r['conversation-uri'] != '') {
2121 $conversation_uri = $r['conversation-uri'];
2123 if ($r['conversation-href'] != '') {
2124 $conversation_href = $r['conversation-href'];
2129 xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:conversation", "href" => $conversation_href));
2131 $attributes = array(
2132 "href" => $conversation_href,
2133 "local_id" => $item["parent"],
2134 "ref" => $conversation_uri);
2136 xml::add_element($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
2139 $tags = item_getfeedtags($item);
2142 foreach($tags as $t)
2144 $mentioned[$t[1]] = $t[1];
2146 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2147 $newmentions = array();
2148 foreach ($mentioned AS $mention) {
2149 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2150 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2152 $mentioned = $newmentions;
2154 foreach ($mentioned AS $mention) {
2155 $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
2156 intval($owner["uid"]),
2157 dbesc(normalise_link($mention)));
2158 if ($r[0]["forum"] OR $r[0]["prv"])
2159 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2160 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
2161 "href" => $mention));
2163 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2164 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
2165 "href" => $mention));
2168 if (!$item["private"]) {
2169 xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:attention",
2170 "href" => "http://activityschema.org/collection/public"));
2171 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2172 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2173 "href" => "http://activityschema.org/collection/public"));
2174 xml::add_element($doc, $entry, "mastodon:scope", "public");
2178 foreach($tags as $t)
2180 xml::add_element($doc, $entry, "category", "", array("term" => $t[2]));
2182 self::get_attachment($doc, $entry, $item);
2184 if ($complete AND ($item["id"] > 0)) {
2185 $app = $item["app"];
2189 $attributes = array("local_id" => $item["id"], "source" => $app);
2191 if (isset($parent["id"]))
2192 $attributes["repeat_of"] = $parent["id"];
2194 if ($item["coord"] != "")
2195 xml::add_element($doc, $entry, "georss:point", $item["coord"]);
2197 xml::add_element($doc, $entry, "statusnet:notice_info", "", $attributes);
2202 * @brief Creates the XML feed for a given nickname
2204 * @param App $a The application class
2205 * @param string $owner_nick Nickname of the feed owner
2206 * @param string $last_update Date of the last update
2208 * @return string XML feed
2210 public static function feed(App $a, $owner_nick, $last_update) {
2212 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
2213 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
2214 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
2215 dbesc($owner_nick));
2221 if (!strlen($last_update))
2222 $last_update = 'now -30 days';
2224 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
2225 $authorid = get_contact($owner["url"], 0);
2227 $items = q("SELECT `item`.*, `item`.`id` AS `item_id` FROM `item` USE INDEX (`uid_contactid_created`)
2228 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2229 WHERE `item`.`uid` = %d AND `item`.`contact-id` = %d AND
2230 `item`.`author-id` = %d AND `item`.`created` > '%s' AND
2231 NOT `item`.`deleted` AND NOT `item`.`private` AND
2232 `thread`.`network` IN ('%s', '%s')
2233 ORDER BY `item`.`created` DESC LIMIT 300",
2234 intval($owner["uid"]), intval($owner["id"]),
2235 intval($authorid), dbesc($check_date),
2236 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
2238 /* 2016-10-23: The old query will be kept until we are sure that the query above is a good and fast replacement
2240 $items = q("SELECT `item`.*, `item`.`id` AS `item_id` FROM `item`
2241 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2242 LEFT JOIN `item` AS `thritem` ON `thritem`.`uri`=`item`.`thr-parent` AND `thritem`.`uid`=`item`.`uid`
2243 WHERE `item`.`uid` = %d AND `item`.`received` > '%s' AND NOT `item`.`private` AND NOT `item`.`deleted`
2244 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
2245 AND ((`item`.`wall` AND (`item`.`parent` = `item`.`id`))
2246 OR (`item`.`network` = '%s' AND ((`thread`.`network` IN ('%s', '%s')) OR (`thritem`.`network` IN ('%s', '%s')))) AND `thread`.`mention`)
2247 AND ((`item`.`owner-link` IN ('%s', '%s') AND (`item`.`parent` = `item`.`id`))
2248 OR (`item`.`author-link` IN ('%s', '%s')))
2249 ORDER BY `item`.`id` DESC
2251 intval($owner["uid"]), dbesc($check_date), dbesc(NETWORK_DFRN),
2252 //dbesc(NETWORK_OSTATUS), dbesc(NETWORK_OSTATUS),
2253 //dbesc(NETWORK_OSTATUS), dbesc(NETWORK_OSTATUS),
2254 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN),
2255 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN),
2256 dbesc($owner["nurl"]), dbesc(str_replace("http://", "https://", $owner["nurl"])),
2257 dbesc($owner["nurl"]), dbesc(str_replace("http://", "https://", $owner["nurl"]))
2260 $doc = new DOMDocument('1.0', 'utf-8');
2261 $doc->formatOutput = true;
2263 $root = self::add_header($doc, $owner);
2265 foreach ($items AS $item) {
2266 if (Config::get('system', 'ostatus_debug')) {
2267 $item['body'] .= '🍼';
2269 $entry = self::entry($doc, $item, $owner);
2270 $root->appendChild($entry);
2273 return(trim($doc->saveXML()));
2277 * @brief Creates the XML for a salmon message
2279 * @param array $item Data of the item that is to be posted
2280 * @param array $owner Contact data of the poster
2282 * @return string XML for the salmon
2284 public static function salmon($item,$owner) {
2286 $doc = new DOMDocument('1.0', 'utf-8');
2287 $doc->formatOutput = true;
2289 if (Config::get('system', 'ostatus_debug')) {
2290 $item['body'] .= '🐟';
2293 $entry = self::entry($doc, $item, $owner, true);
2295 $doc->appendChild($entry);
2297 return(trim($doc->saveXML()));