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 // Store the conversation data. This is normally done in "item_store"
651 // but since something went wrong, we want to be sure to save the data.
652 store_conversation($item);
653 logger("Error storing item", LOGGER_DEBUG);
657 logger("Item was stored with id ".$item_id, LOGGER_DEBUG);
662 * @brief Create an url out of an uri
664 * @param string $href URI in the format "parameter1:parameter1:..."
666 * @return string URL in the format http(s)://....
668 public static function convert_href($href) {
669 $elements = explode(":",$href);
671 if ((count($elements) <= 2) OR ($elements[0] != "tag"))
674 $server = explode(",", $elements[1]);
675 $conversation = explode("=", $elements[2]);
677 if ((count($elements) == 4) AND ($elements[2] == "post"))
678 return "http://".$server[0]."/notice/".$elements[3];
680 if ((count($conversation) != 2) OR ($conversation[1] ==""))
683 if ($elements[3] == "objectType=thread")
684 return "http://".$server[0]."/conversation/".$conversation[1];
686 return "http://".$server[0]."/notice/".$conversation[1];
692 * @brief Checks if there are entries in conversations that aren't present on our side
694 * @param bool $mentions Fetch conversations where we are mentioned
695 * @param bool $override Override the interval setting
697 public static function check_conversations($mentions = false, $override = false) {
698 $last = get_config('system','ostatus_last_poll');
700 $poll_interval = intval(get_config('system','ostatus_poll_interval'));
701 if (!$poll_interval) {
702 $poll_interval = self::OSTATUS_DEFAULT_POLL_INTERVAL;
705 // Don't poll if the interval is set negative
706 if (($poll_interval < 0) AND !$override) {
711 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
712 if (!$poll_timeframe) {
713 $poll_timeframe = self::OSTATUS_DEFAULT_POLL_TIMEFRAME;
716 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
717 if (!$poll_timeframe) {
718 $poll_timeframe = self::OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS;
723 if ($last AND !$override) {
724 $next = $last + ($poll_interval * 60);
725 if ($next > time()) {
726 logger('poll interval not reached');
731 logger('cron_start');
733 $start = date("Y-m-d H:i:s", time() - ($poll_timeframe * 60));
736 $conversations = q("SELECT `term`.`oid`, `term`.`url`, `term`.`uid` FROM `term`
737 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `term`.`oid` AND `thread`.`uid` = `term`.`uid`
738 WHERE `term`.`type` = 7 AND `term`.`term` > '%s' AND `thread`.`mention`
739 GROUP BY `term`.`url`, `term`.`uid`, `term`.`oid`, `term`.`term` ORDER BY `term`.`term` DESC", dbesc($start));
741 $conversations = q("SELECT `oid`, `url`, `uid` FROM `term`
742 WHERE `type` = 7 AND `term` > '%s'
743 GROUP BY `url`, `uid`, `oid`, `term` ORDER BY `term` DESC", dbesc($start));
746 foreach ($conversations AS $conversation) {
747 self::completion($conversation['url'], $conversation['uid']);
752 set_config('system','ostatus_last_poll', time());
756 * @brief Updates the gcontact table with actor data from the conversation
758 * @param object $actor The actor object that contains the contact data
760 private function conv_fetch_actor($actor) {
762 // We set the generation to "3" since the data here is not as reliable as the data we get on other occasions
763 $contact = array("network" => NETWORK_OSTATUS, "generation" => 3);
765 if (isset($actor->url))
766 $contact["url"] = $actor->url;
768 if (isset($actor->displayName))
769 $contact["name"] = $actor->displayName;
771 if (isset($actor->portablecontacts_net->displayName))
772 $contact["name"] = $actor->portablecontacts_net->displayName;
774 if (isset($actor->portablecontacts_net->preferredUsername))
775 $contact["nick"] = $actor->portablecontacts_net->preferredUsername;
777 if (isset($actor->id))
778 $contact["alias"] = $actor->id;
780 if (isset($actor->summary))
781 $contact["about"] = $actor->summary;
783 if (isset($actor->portablecontacts_net->note))
784 $contact["about"] = $actor->portablecontacts_net->note;
786 if (isset($actor->portablecontacts_net->addresses->formatted))
787 $contact["location"] = $actor->portablecontacts_net->addresses->formatted;
790 if (isset($actor->image->url))
791 $contact["photo"] = $actor->image->url;
793 if (isset($actor->image->width))
794 $avatarwidth = $actor->image->width;
796 if (is_array($actor->status_net->avatarLinks))
797 foreach ($actor->status_net->avatarLinks AS $avatar) {
798 if ($avatarsize < $avatar->width) {
799 $contact["photo"] = $avatar->url;
800 $avatarsize = $avatar->width;
804 $contact["hide"] = false; // OStatus contacts are never hidden
805 update_gcontact($contact);
809 * @brief Fetches the conversation url for a given item link or conversation id
811 * @param string $self The link to the posting
812 * @param string $conversation_id The conversation id
814 * @return string The conversation url
816 private function fetch_conversation($self, $conversation_id = "") {
818 if ($conversation_id != "") {
819 $elements = explode(":", $conversation_id);
821 if ((count($elements) <= 2) OR ($elements[0] != "tag"))
822 return $conversation_id;
828 $json = str_replace(".atom", ".json", $self);
830 $raw = fetch_url($json);
834 $data = json_decode($raw);
835 if (!is_object($data))
838 $conversation_id = $data->statusnet_conversation_id;
840 $pos = strpos($self, "/api/statuses/show/");
841 $base_url = substr($self, 0, $pos);
843 return $base_url."/conversation/".$conversation_id;
847 * @brief Fetches a shared object from a given conversation object
849 * Sometimes GNU Social seems to fail when returning shared objects.
850 * Then they don't contains all needed data.
851 * We then try to find this object in the conversation
853 * @param string $id Message id
854 * @param object $conversation Conversation object
856 * @return object The shared object
858 private function shared_object($id, $conversation) {
859 if (!is_array($conversation->items)) {
862 foreach ($conversation->items AS $single_conv) {
863 if ($single_conv->id == $id) {
871 * @brief Fetches actor details of a given actor and user id
873 * @param string $actor The actor url
874 * @param int $uid The user id
875 * @param int $contact_id The default contact-id
877 * @return array Array with actor details
879 private function get_actor_details($actor, $uid, $contact_id) {
883 $contact = q("SELECT `id`, `rel`, `network` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
884 $uid, normalise_link($actor), NETWORK_STATUSNET);
887 $contact = q("SELECT `id`, `rel`, `network` FROM `contact` WHERE `uid` = %d AND `alias` IN ('%s', '%s') AND `network` != '%s'",
888 $uid, $actor, normalise_link($actor), NETWORK_STATUSNET);
891 logger("Found contact for url ".$actor, LOGGER_DEBUG);
892 $details["contact_id"] = $contact[0]["id"];
893 $details["network"] = $contact[0]["network"];
895 $details["not_following"] = !in_array($contact[0]["rel"], array(CONTACT_IS_SHARING, CONTACT_IS_FRIEND));
897 logger("No contact found for user ".$uid." and url ".$actor, LOGGER_DEBUG);
899 // Adding a global contact
900 /// @TODO Use this data for the post
901 $details["global_contact_id"] = get_contact($actor, 0);
903 logger("Global contact ".$global_contact_id." found for url ".$actor, LOGGER_DEBUG);
905 $details["contact_id"] = $contact_id;
906 $details["network"] = NETWORK_OSTATUS;
908 $details["not_following"] = true;
915 * @brief Stores an item and completes the thread
917 * @param string $conversation_url The URI of the conversation
918 * @param integer $uid The user id
919 * @param array $item Data of the item that is to be posted
921 * @return integer The item id of the posted item array
923 private function completion($conversation_url, $uid, $item = array(), $self = "") {
925 /// @todo This function is totally ugly and has to be rewritten totally
927 // Import all threads or only threads that were started by our followers?
928 $all_threads = !get_config('system','ostatus_full_threads');
932 $conversation_url = self::fetch_conversation($self, $conversation_url);
934 // If the thread shouldn't be completed then store the item and go away
935 // Don't do a completion on liked content
936 if (((intval(get_config('system','ostatus_poll_interval')) == -2) AND (count($item) > 0)) OR
937 ($item["verb"] == ACTIVITY_LIKE) OR ($conversation_url == "")) {
938 $item_stored = item_store($item, $all_threads);
943 $parents = q("SELECT `item`.`id`, `item`.`parent`, `item`.`uri`, `item`.`contact-id`, `item`.`type`,
944 `item`.`verb`, `item`.`visible` FROM `term`
945 STRAIGHT_JOIN `item` AS `thritem` ON `thritem`.`parent` = `term`.`oid`
946 STRAIGHT_JOIN `item` ON `item`.`parent` = `thritem`.`parent`
947 WHERE `term`.`uid` = %d AND `term`.`otype` = %d AND `term`.`type` = %d AND `term`.`url` = '%s'",
948 intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url));
950 $parent = $parents[0];
951 elseif (count($item) > 0) {
953 $parent["type"] = "remote";
954 $parent["verb"] = ACTIVITY_POST;
955 $parent["visible"] = 1;
958 $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid`=%d", $uid);
964 $parent["parent"] = 0;
966 $parent["contact-id"] = $r[0]["id"];
967 $parent["type"] = "remote";
968 $parent["verb"] = ACTIVITY_POST;
969 $parent["visible"] = 1;
972 $conv = str_replace("/conversation/", "/api/statusnet/conversation/", $conversation_url).".as";
976 logger('fetching conversation url '.$conv.' (Self: '.$self.') for user '.$uid);
979 $conv_arr = z_fetch_url($conv."?page=".$pageno);
981 // If it is a non-ssl site and there is an error, then try ssl or vice versa
982 if (!$conv_arr["success"] AND (substr($conv, 0, 7) == "http://")) {
983 $conv = str_replace("http://", "https://", $conv);
984 $conv_as = fetch_url($conv."?page=".$pageno);
985 } elseif (!$conv_arr["success"] AND (substr($conv, 0, 8) == "https://")) {
986 $conv = str_replace("https://", "http://", $conv);
987 $conv_as = fetch_url($conv."?page=".$pageno);
989 $conv_as = $conv_arr["body"];
991 $conv_as = str_replace(',"statusnet:notice_info":', ',"statusnet_notice_info":', $conv_as);
992 $conv_as = json_decode($conv_as);
994 $no_of_items = sizeof($items);
996 if (@is_array($conv_as->items))
997 foreach ($conv_as->items AS $single_item)
998 $items[$single_item->id] = $single_item;
1000 if ($no_of_items == sizeof($items))
1007 logger('fetching conversation done. Found '.count($items).' items');
1009 if (!sizeof($items)) {
1010 if (count($item) > 0) {
1011 $item_stored = item_store($item, $all_threads);
1014 logger("Conversation ".$conversation_url." couldn't be fetched. Item uri ".$item["uri"]." stored: ".$item_stored, LOGGER_DEBUG);
1015 self::store_conversation($item_id, $conversation_url);
1018 return($item_stored);
1023 $items = array_reverse($items);
1025 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self`", intval($uid));
1030 foreach ($items as $single_conv) {
1032 // Update the gcontact table
1033 self::conv_fetch_actor($single_conv->actor);
1035 // Test - remove before flight
1036 //$tempfile = tempnam(get_temppath(), "conversation");
1037 //file_put_contents($tempfile, json_encode($single_conv));
1041 if (isset($single_conv->object->id))
1042 $single_conv->id = $single_conv->object->id;
1044 $plink = self::convert_href($single_conv->id);
1045 if (isset($single_conv->object->url))
1046 $plink = self::convert_href($single_conv->object->url);
1048 if (@!$single_conv->id)
1051 logger("Got id ".$single_conv->id, LOGGER_DEBUG);
1053 if ($first_id == "") {
1054 $first_id = $single_conv->id;
1056 // The first post of the conversation isn't our first post. There are three options:
1057 // 1. Our conversation hasn't the "real" thread starter
1058 // 2. This first post is a post inside our thread
1059 // 3. This first post is a post inside another thread
1060 if (($first_id != $parent["uri"]) AND ($parent["uri"] != "")) {
1064 $new_parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
1065 (SELECT `parent` FROM `item`
1066 WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s')) LIMIT 1",
1067 intval($uid), dbesc($first_id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1069 if ($new_parents[0]["parent"] == $parent["parent"]) {
1070 // Option 2: This post is already present inside our thread - but not as thread starter
1071 logger("Option 2: uri present in our thread: ".$first_id, LOGGER_DEBUG);
1072 $first_id = $parent["uri"];
1074 // Option 3: Not so good. We have mixed parents. We have to see how to clean this up.
1075 // For now just take the new parent.
1076 $parent = $new_parents[0];
1077 $first_id = $parent["uri"];
1078 logger("Option 3: mixed parents for uri ".$first_id, LOGGER_DEBUG);
1081 // Option 1: We hadn't got the real thread starter
1082 // We have to clean up our existing messages.
1084 $parent["uri"] = $first_id;
1085 logger("Option 1: we have a new parent: ".$first_id, LOGGER_DEBUG);
1087 } elseif ($parent["uri"] == "") {
1089 $parent["uri"] = $first_id;
1093 $parent_uri = $parent["uri"];
1095 // "context" only seems to exist on older servers
1096 if (isset($single_conv->context->inReplyTo->id)) {
1097 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1098 intval($uid), dbesc($single_conv->context->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1100 $parent_uri = $single_conv->context->inReplyTo->id;
1103 // This is the current way
1104 if (isset($single_conv->object->inReplyTo->id)) {
1105 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1106 intval($uid), dbesc($single_conv->object->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1108 $parent_uri = $single_conv->object->inReplyTo->id;
1111 $message_exists = q("SELECT `id`, `parent`, `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1112 intval($uid), dbesc($single_conv->id),
1113 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1114 if ($message_exists) {
1115 logger("Message ".$single_conv->id." already existed on the system", LOGGER_DEBUG);
1117 if ($parent["id"] != 0) {
1118 $existing_message = $message_exists[0];
1120 // We improved the way we fetch OStatus messages, this shouldn't happen very often now
1121 /// @TODO We have to change the shadow copies as well. This way here is really ugly.
1122 if ($existing_message["parent"] != $parent["id"]) {
1123 logger('updating id '.$existing_message["id"].' with parent '.$existing_message["parent"].' to parent '.$parent["id"].' uri '.$parent["uri"].' thread '.$parent_uri, LOGGER_DEBUG);
1125 // Update the parent id of the selected item
1126 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `id` = %d",
1127 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["id"]));
1129 // Update the parent uri in the thread - but only if it points to itself
1130 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE `id` = %d AND `uri` = `thr-parent`",
1131 dbesc($parent_uri), intval($existing_message["id"]));
1133 // try to change all items of the same parent
1134 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `parent` = %d",
1135 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["parent"]));
1137 // Update the parent uri in the thread - but only if it points to itself
1138 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE (`parent` = %d) AND (`uri` = `thr-parent`)",
1139 dbesc($parent["uri"]), intval($existing_message["parent"]));
1141 // Now delete the thread
1142 delete_thread($existing_message["parent"]);
1146 // The item we are having on the system is the one that we wanted to store via the item array
1147 if (isset($item["uri"]) AND ($item["uri"] == $existing_message["uri"])) {
1155 if (is_array($single_conv->to))
1156 foreach($single_conv->to AS $to)
1157 if ($importer["nurl"] == normalise_link($to->id))
1160 $actor = $single_conv->actor->id;
1161 if (isset($single_conv->actor->url))
1162 $actor = $single_conv->actor->url;
1164 $details = self::get_actor_details($actor, $uid, $parent["contact-id"]);
1166 // Do we only want to import threads that were started by our contacts?
1167 if ($details["not_following"] AND $new_parent AND get_config('system','ostatus_full_threads')) {
1168 logger("Don't import uri ".$first_id." because user ".$uid." doesn't follow the person ".$actor, LOGGER_DEBUG);
1172 /// @TODO One statment is okay (until if () )
1174 $arr["network"] = $details["network"];
1175 $arr["uri"] = $single_conv->id;
1176 $arr["plink"] = $plink;
1178 $arr["contact-id"] = $details["contact_id"];
1179 $arr["parent-uri"] = $parent_uri;
1180 $arr["created"] = $single_conv->published;
1181 $arr["edited"] = $single_conv->published;
1182 $arr["owner-name"] = $single_conv->actor->displayName;
1183 if ($arr["owner-name"] == '')
1184 $arr["owner-name"] = $single_conv->actor->contact->displayName;
1185 if ($arr["owner-name"] == '')
1186 $arr["owner-name"] = $single_conv->actor->portablecontacts_net->displayName;
1188 $arr["owner-link"] = $actor;
1189 $arr["owner-avatar"] = Probe::fixAvatar($single_conv->actor->image->url, $arr["owner-link"]);
1191 $arr["author-name"] = $arr["owner-name"];
1192 $arr["author-link"] = $arr["owner-link"];
1193 $arr["author-avatar"] = $arr["owner-avatar"];
1194 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->content));
1196 if (isset($single_conv->status_net->conversation)) {
1197 $arr['conversation-uri'] = $single_conv->status_net->conversation;
1200 if (isset($single_conv->status_net->notice_info->source))
1201 $arr["app"] = strip_tags($single_conv->status_net->notice_info->source);
1202 elseif (isset($single_conv->statusnet->notice_info->source))
1203 $arr["app"] = strip_tags($single_conv->statusnet->notice_info->source);
1204 elseif (isset($single_conv->statusnet_notice_info->source))
1205 $arr["app"] = strip_tags($single_conv->statusnet_notice_info->source);
1206 elseif (isset($single_conv->provider->displayName))
1207 $arr["app"] = $single_conv->provider->displayName;
1209 $arr["app"] = "OStatus";
1212 $arr["source"] = json_encode($single_conv);
1213 $arr["protocol"] = PROTOCOL_GS_CONVERSATION;
1215 $arr["verb"] = $parent["verb"];
1216 $arr["visible"] = $parent["visible"];
1217 $arr["location"] = $single_conv->location->displayName;
1218 $arr["coord"] = trim($single_conv->location->lat." ".$single_conv->location->lon);
1220 // Is it a reshared item?
1221 if (isset($single_conv->verb) AND ($single_conv->verb == "share") AND isset($single_conv->object)) {
1222 if (is_array($single_conv->object))
1223 $single_conv->object = $single_conv->object[0];
1225 // Sometimes GNU Social doesn't returns a complete object
1226 if (!isset($single_conv->object->actor->url)) {
1227 $object = self::shared_object($single_conv->object->id, $conversation);
1228 if (is_object($object)) {
1229 $single_conv->object = $object;
1233 if (isset($single_conv->object->actor->url)) {
1234 logger("Found reshared item ".$single_conv->object->id);
1236 // $single_conv->object->context->conversation;
1238 if (isset($single_conv->object->object->id)) {
1239 $arr["uri"] = $single_conv->object->object->id;
1241 $arr["uri"] = $single_conv->object->id;
1243 if (isset($single_conv->object->object->url)) {
1244 $plink = self::convert_href($single_conv->object->object->url);
1246 $plink = self::convert_href($single_conv->object->url);
1248 if (isset($single_conv->object->object->content)) {
1249 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->object->content));
1251 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->content));
1253 $arr["plink"] = $plink;
1255 $arr["created"] = $single_conv->object->published;
1256 $arr["edited"] = $single_conv->object->published;
1258 $arr["author-name"] = $single_conv->object->actor->displayName;
1259 if ($arr["owner-name"] == '') {
1260 $arr["author-name"] = $single_conv->object->actor->contact->displayName;
1262 $arr["author-link"] = $single_conv->object->actor->url;
1263 $arr["author-avatar"] = Probe::fixAvatar($single_conv->object->actor->image->url, $arr["author-link"]);
1265 $arr["app"] = $single_conv->object->provider->displayName."#";
1266 //$arr["verb"] = $single_conv->object->verb;
1268 $arr["location"] = $single_conv->object->location->displayName;
1269 $arr["coord"] = trim($single_conv->object->location->lat." ".$single_conv->object->location->lon);
1273 if ($arr["location"] == "")
1274 unset($arr["location"]);
1276 if ($arr["coord"] == "")
1277 unset($arr["coord"]);
1279 // Copy fields from given item array
1280 if (isset($item["uri"]) AND (($item["uri"] == $arr["uri"]) OR ($item["uri"] == $single_conv->id))) {
1281 logger('Use stored item array for item with URI '.$item["uri"], LOGGER_DEBUG);
1282 $newitem = item_store($item);
1284 $item_stored = $newitem;
1286 $newitem = item_store($arr);
1290 logger("Item wasn't stored ".print_r($arr, true), LOGGER_DEBUG);
1294 logger('Stored new item '.$plink.' for parent '.$arr["parent-uri"].' under id '.$newitem, LOGGER_DEBUG);
1296 // Add the conversation entry (but don't fetch the whole conversation)
1297 self::store_conversation($newitem, $conversation_url);
1299 // If the newly created item is the top item then change the parent settings of the thread
1300 // This shouldn't happen anymore. This is supposed to be absolote.
1301 if ($arr["uri"] == $first_id) {
1302 logger('setting new parent to id '.$newitem);
1303 $new_parents = q("SELECT `id`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
1304 intval($uid), intval($newitem));
1306 $parent = $new_parents[0];
1310 if (($item_stored < 0) AND (count($item) > 0)) {
1312 if (get_config('system','ostatus_full_threads')) {
1313 $details = self::get_actor_details($item["owner-link"], $uid, $item["contact-id"]);
1314 if ($details["not_following"]) {
1315 logger("Don't import uri ".$item["uri"]." because user ".$uid." doesn't follow the person ".$item["owner-link"], LOGGER_DEBUG);
1320 $item_stored = item_store($item, $all_threads);
1322 logger("Uri ".$item["uri"]." wasn't found in conversation ".$conversation_url, LOGGER_DEBUG);
1323 self::store_conversation($item_stored, $conversation_url);
1327 return($item_stored);
1331 * @brief Stores conversation data into the database
1333 * @param integer $itemid The id of the item
1334 * @param string $conversation_url The uri of the conversation
1336 private function store_conversation($itemid, $conversation_url) {
1338 $conversation_url = self::convert_href($conversation_url);
1340 $messages = q("SELECT `uid`, `parent`, `created`, `received`, `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($itemid));
1343 $message = $messages[0];
1345 // Store conversation url if not done before
1346 $conversation = q("SELECT `url` FROM `term` WHERE `uid` = %d AND `oid` = %d AND `otype` = %d AND `type` = %d",
1347 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION));
1349 if (!$conversation) {
1350 $r = q("INSERT INTO `term` (`uid`, `oid`, `otype`, `type`, `term`, `url`, `created`, `received`, `guid`) VALUES (%d, %d, %d, %d, '%s', '%s', '%s', '%s', '%s')",
1351 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION),
1352 dbesc($message["created"]), dbesc($conversation_url), dbesc($message["created"]), dbesc($message["received"]), dbesc($message["guid"]));
1353 logger('Storing conversation url '.$conversation_url.' for id '.$itemid);
1358 * @brief Checks if the current post is a reshare
1360 * @param array $item The item array of thw post
1362 * @return string The guid if the post is a reshare
1364 private function get_reshared_guid($item) {
1365 $body = trim($item["body"]);
1367 // Skip if it isn't a pure repeated messages
1368 // Does it start with a share?
1369 if (strpos($body, "[share") > 0)
1372 // Does it end with a share?
1373 if (strlen($body) > (strrpos($body, "[/share]") + 8))
1376 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
1377 // Skip if there is no shared message in there
1378 if ($body == $attributes)
1382 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1383 if ($matches[1] != "")
1384 $guid = $matches[1];
1386 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1387 if ($matches[1] != "")
1388 $guid = $matches[1];
1394 * @brief Cleans the body of a post if it contains picture links
1396 * @param string $body The body
1398 * @return string The cleaned body
1400 private function format_picture_post($body) {
1401 $siteinfo = get_attached_data($body);
1403 if (($siteinfo["type"] == "photo")) {
1404 if (isset($siteinfo["preview"]))
1405 $preview = $siteinfo["preview"];
1407 $preview = $siteinfo["image"];
1409 // Is it a remote picture? Then make a smaller preview here
1410 $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
1412 // Is it a local picture? Then make it smaller here
1413 $preview = str_replace(array("-0.jpg", "-0.png"), array("-2.jpg", "-2.png"), $preview);
1414 $preview = str_replace(array("-1.jpg", "-1.png"), array("-2.jpg", "-2.png"), $preview);
1416 if (isset($siteinfo["url"]))
1417 $url = $siteinfo["url"];
1419 $url = $siteinfo["image"];
1421 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1428 * @brief Adds the header elements to the XML document
1430 * @param object $doc XML document
1431 * @param array $owner Contact data of the poster
1433 * @return object header root element
1435 private function add_header($doc, $owner) {
1439 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1440 $doc->appendChild($root);
1442 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1443 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1444 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1445 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1446 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1447 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1448 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1449 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1451 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
1452 xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1453 xml::add_element($doc, $root, "id", App::get_baseurl()."/profile/".$owner["nick"]);
1454 xml::add_element($doc, $root, "title", sprintf("%s timeline", $owner["name"]));
1455 xml::add_element($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
1456 xml::add_element($doc, $root, "logo", $owner["photo"]);
1457 xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
1459 $author = self::add_author($doc, $owner);
1460 $root->appendChild($author);
1462 $attributes = array("href" => $owner["url"], "rel" => "alternate", "type" => "text/html");
1463 xml::add_element($doc, $root, "link", "", $attributes);
1465 /// @TODO We have to find out what this is
1466 /// $attributes = array("href" => App::get_baseurl()."/sup",
1467 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1468 /// "type" => "application/json");
1469 /// xml::add_element($doc, $root, "link", "", $attributes);
1471 self::hublinks($doc, $root);
1473 $attributes = array("href" => App::get_baseurl()."/salmon/".$owner["nick"], "rel" => "salmon");
1474 xml::add_element($doc, $root, "link", "", $attributes);
1476 $attributes = array("href" => App::get_baseurl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies");
1477 xml::add_element($doc, $root, "link", "", $attributes);
1479 $attributes = array("href" => App::get_baseurl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention");
1480 xml::add_element($doc, $root, "link", "", $attributes);
1482 $attributes = array("href" => App::get_baseurl()."/api/statuses/user_timeline/".$owner["nick"].".atom",
1483 "rel" => "self", "type" => "application/atom+xml");
1484 xml::add_element($doc, $root, "link", "", $attributes);
1490 * @brief Add the link to the push hubs to the XML document
1492 * @param object $doc XML document
1493 * @param object $root XML root element where the hub links are added
1495 public static function hublinks($doc, $root) {
1496 $hub = get_config('system','huburl');
1500 $hubs = explode(',', $hub);
1502 foreach($hubs as $h) {
1506 if ($h === '[internal]')
1507 $h = App::get_baseurl() . '/pubsubhubbub';
1508 xml::add_element($doc, $root, "link", "", array("href" => $h, "rel" => "hub"));
1515 * @brief Adds attachement data to the XML document
1517 * @param object $doc XML document
1518 * @param object $root XML root element where the hub links are added
1519 * @param array $item Data of the item that is to be posted
1521 private function get_attachment($doc, $root, $item) {
1523 $siteinfo = get_attached_data($item["body"]);
1525 switch ($siteinfo["type"]) {
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"]));
1532 xml::add_element($doc, $root, "link", "", $attributes);
1535 $attributes = array("rel" => "enclosure",
1536 "href" => $siteinfo["url"],
1537 "type" => "text/html; charset=UTF-8",
1539 "title" => $siteinfo["title"]);
1540 xml::add_element($doc, $root, "link", "", $attributes);
1546 if (($siteinfo["type"] != "photo") AND isset($siteinfo["image"])) {
1547 $imgdata = get_photo_info($siteinfo["image"]);
1548 $attributes = array("rel" => "enclosure",
1549 "href" => $siteinfo["image"],
1550 "type" => $imgdata["mime"],
1551 "length" => intval($imgdata["size"]));
1553 xml::add_element($doc, $root, "link", "", $attributes);
1556 $arr = explode('[/attach],', $item['attach']);
1558 foreach ($arr as $r) {
1560 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1562 $attributes = array("rel" => "enclosure",
1563 "href" => $matches[1],
1564 "type" => $matches[3]);
1566 if (intval($matches[2])) {
1567 $attributes["length"] = intval($matches[2]);
1569 if (trim($matches[4]) != "") {
1570 $attributes["title"] = trim($matches[4]);
1572 xml::add_element($doc, $root, "link", "", $attributes);
1579 * @brief Adds the author element to the XML document
1581 * @param object $doc XML document
1582 * @param array $owner Contact data of the poster
1584 * @return object author element
1586 private function add_author($doc, $owner) {
1588 $r = q("SELECT `homepage`, `publish` FROM `profile` WHERE `uid` = %d AND `is-default` LIMIT 1", intval($owner["uid"]));
1592 $author = $doc->createElement("author");
1593 xml::add_element($doc, $author, "id", $owner["url"]);
1594 xml::add_element($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1595 xml::add_element($doc, $author, "uri", $owner["url"]);
1596 xml::add_element($doc, $author, "name", $owner["nick"]);
1597 xml::add_element($doc, $author, "email", $owner["addr"]);
1598 xml::add_element($doc, $author, "summary", bbcode($owner["about"], false, false, 7));
1600 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $owner["url"]);
1601 xml::add_element($doc, $author, "link", "", $attributes);
1603 $attributes = array(
1605 "type" => "image/jpeg", // To-Do?
1606 "media:width" => 175,
1607 "media:height" => 175,
1608 "href" => $owner["photo"]);
1609 xml::add_element($doc, $author, "link", "", $attributes);
1611 if (isset($owner["thumb"])) {
1612 $attributes = array(
1614 "type" => "image/jpeg", // To-Do?
1615 "media:width" => 80,
1616 "media:height" => 80,
1617 "href" => $owner["thumb"]);
1618 xml::add_element($doc, $author, "link", "", $attributes);
1621 xml::add_element($doc, $author, "poco:preferredUsername", $owner["nick"]);
1622 xml::add_element($doc, $author, "poco:displayName", $owner["name"]);
1623 xml::add_element($doc, $author, "poco:note", bbcode($owner["about"], false, false, 7));
1625 if (trim($owner["location"]) != "") {
1626 $element = $doc->createElement("poco:address");
1627 xml::add_element($doc, $element, "poco:formatted", $owner["location"]);
1628 $author->appendChild($element);
1631 if (trim($profile["homepage"]) != "") {
1632 $urls = $doc->createElement("poco:urls");
1633 xml::add_element($doc, $urls, "poco:type", "homepage");
1634 xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
1635 xml::add_element($doc, $urls, "poco:primary", "true");
1636 $author->appendChild($urls);
1639 if (count($profile)) {
1640 xml::add_element($doc, $author, "followers", "", array("url" => App::get_baseurl()."/viewcontacts/".$owner["nick"]));
1641 xml::add_element($doc, $author, "statusnet:profile_info", "", array("local_id" => $owner["uid"]));
1644 if ($profile["publish"]) {
1645 xml::add_element($doc, $author, "mastodon:scope", "public");
1651 * @TODO Picture attachments should look like this:
1652 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1653 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1658 * @brief Returns the given activity if present - otherwise returns the "post" activity
1660 * @param array $item Data of the item that is to be posted
1662 * @return string activity
1664 function construct_verb($item) {
1666 return $item['verb'];
1667 return ACTIVITY_POST;
1671 * @brief Returns the given object type if present - otherwise returns the "note" object type
1673 * @param array $item Data of the item that is to be posted
1675 * @return string Object type
1677 function construct_objecttype($item) {
1678 if (in_array($item['object-type'], array(ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT)))
1679 return $item['object-type'];
1680 return ACTIVITY_OBJ_NOTE;
1684 * @brief Adds an entry element to the XML document
1686 * @param object $doc XML document
1687 * @param array $item Data of the item that is to be posted
1688 * @param array $owner Contact data of the poster
1689 * @param bool $toplevel
1691 * @return object Entry element
1693 private function entry($doc, $item, $owner, $toplevel = false) {
1694 $repeated_guid = self::get_reshared_guid($item);
1695 if ($repeated_guid != "")
1696 $xml = self::reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel);
1701 if ($item["verb"] == ACTIVITY_LIKE) {
1702 return self::like_entry($doc, $item, $owner, $toplevel);
1703 } elseif (in_array($item["verb"], array(ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"))) {
1704 return self::follow_entry($doc, $item, $owner, $toplevel);
1706 return self::note_entry($doc, $item, $owner, $toplevel);
1711 * @brief Adds a source entry to the XML document
1713 * @param object $doc XML document
1714 * @param array $contact Array of the contact that is added
1716 * @return object Source element
1718 private function source_entry($doc, $contact) {
1719 $source = $doc->createElement("source");
1720 xml::add_element($doc, $source, "id", $contact["poll"]);
1721 xml::add_element($doc, $source, "title", $contact["name"]);
1722 xml::add_element($doc, $source, "link", "", array("rel" => "alternate",
1723 "type" => "text/html",
1724 "href" => $contact["alias"]));
1725 xml::add_element($doc, $source, "link", "", array("rel" => "self",
1726 "type" => "application/atom+xml",
1727 "href" => $contact["poll"]));
1728 xml::add_element($doc, $source, "icon", $contact["photo"]);
1729 xml::add_element($doc, $source, "updated", datetime_convert("UTC","UTC",$contact["success_update"]."+00:00",ATOM_TIME));
1735 * @brief Fetches contact data from the contact or the gcontact table
1737 * @param string $url URL of the contact
1738 * @param array $owner Contact data of the poster
1740 * @return array Contact array
1742 private function contact_entry($url, $owner) {
1744 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1745 dbesc(normalise_link($url)), intval($owner["uid"]));
1748 $contact["uid"] = -1;
1752 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1753 dbesc(normalise_link($url)));
1756 $contact["uid"] = -1;
1757 $contact["success_update"] = $contact["updated"];
1764 if (!isset($contact["poll"])) {
1765 $data = probe_url($url);
1766 $contact["poll"] = $data["poll"];
1768 if (!$contact["alias"])
1769 $contact["alias"] = $data["alias"];
1772 if (!isset($contact["alias"]))
1773 $contact["alias"] = $contact["url"];
1779 * @brief Adds an entry element with reshared content
1781 * @param object $doc XML document
1782 * @param array $item Data of the item that is to be posted
1783 * @param array $owner Contact data of the poster
1784 * @param $repeated_guid
1785 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1787 * @return object Entry element
1789 private function reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel) {
1791 if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1792 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1795 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1797 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' AND NOT `private` AND `network` IN ('%s', '%s', '%s') LIMIT 1",
1798 intval($owner["uid"]), dbesc($repeated_guid),
1799 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS));
1801 $repeated_item = $r[0];
1805 $contact = self::contact_entry($repeated_item['author-link'], $owner);
1807 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1809 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1811 self::entry_content($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1813 $as_object = $doc->createElement("activity:object");
1815 xml::add_element($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1817 self::entry_content($doc, $as_object, $repeated_item, $owner, "", "", false);
1819 $author = self::add_author($doc, $contact);
1820 $as_object->appendChild($author);
1822 $as_object2 = $doc->createElement("activity:object");
1824 xml::add_element($doc, $as_object2, "activity:object-type", self::construct_objecttype($repeated_item));
1826 $title = sprintf("New comment by %s", $contact["nick"]);
1828 self::entry_content($doc, $as_object2, $repeated_item, $owner, $title);
1830 $as_object->appendChild($as_object2);
1832 self::entry_footer($doc, $as_object, $item, $owner, false);
1834 $source = self::source_entry($doc, $contact);
1836 $as_object->appendChild($source);
1838 $entry->appendChild($as_object);
1840 self::entry_footer($doc, $entry, $item, $owner);
1846 * @brief Adds an entry element with a "like"
1848 * @param object $doc XML document
1849 * @param array $item Data of the item that is to be posted
1850 * @param array $owner Contact data of the poster
1851 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1853 * @return object Entry element with "like"
1855 private function like_entry($doc, $item, $owner, $toplevel) {
1857 if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1858 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1861 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1863 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1864 self::entry_content($doc, $entry, $item, $owner, "Favorite", $verb, false);
1866 $as_object = $doc->createElement("activity:object");
1868 $parent = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
1869 dbesc($item["thr-parent"]), intval($item["uid"]));
1870 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1872 xml::add_element($doc, $as_object, "activity:object-type", self::construct_objecttype($parent[0]));
1874 self::entry_content($doc, $as_object, $parent[0], $owner, "New entry");
1876 $entry->appendChild($as_object);
1878 self::entry_footer($doc, $entry, $item, $owner);
1884 * @brief Adds the person object element to the XML document
1886 * @param object $doc XML document
1887 * @param array $owner Contact data of the poster
1888 * @param array $contact Contact data of the target
1890 * @return object author element
1892 private function add_person_object($doc, $owner, $contact) {
1894 $object = $doc->createElement("activity:object");
1895 xml::add_element($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1897 if ($contact['network'] == NETWORK_PHANTOM) {
1898 xml::add_element($doc, $object, "id", $contact['url']);
1902 xml::add_element($doc, $object, "id", $contact["alias"]);
1903 xml::add_element($doc, $object, "title", $contact["nick"]);
1905 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $contact["url"]);
1906 xml::add_element($doc, $object, "link", "", $attributes);
1908 $attributes = array(
1910 "type" => "image/jpeg", // To-Do?
1911 "media:width" => 175,
1912 "media:height" => 175,
1913 "href" => $contact["photo"]);
1914 xml::add_element($doc, $object, "link", "", $attributes);
1916 xml::add_element($doc, $object, "poco:preferredUsername", $contact["nick"]);
1917 xml::add_element($doc, $object, "poco:displayName", $contact["name"]);
1919 if (trim($contact["location"]) != "") {
1920 $element = $doc->createElement("poco:address");
1921 xml::add_element($doc, $element, "poco:formatted", $contact["location"]);
1922 $object->appendChild($element);
1929 * @brief Adds a follow/unfollow entry element
1931 * @param object $doc XML document
1932 * @param array $item Data of the follow/unfollow message
1933 * @param array $owner Contact data of the poster
1934 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1936 * @return object Entry element
1938 private function follow_entry($doc, $item, $owner, $toplevel) {
1940 $item["id"] = $item["parent"] = 0;
1941 $item["created"] = $item["edited"] = date("c");
1942 $item["private"] = true;
1944 $contact = Probe::uri($item['follow']);
1946 if ($contact['alias'] == '') {
1947 $contact['alias'] = $contact["url"];
1949 $item['follow'] = $contact['alias'];
1952 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1953 intval($owner['uid']), dbesc(normalise_link($contact["url"])));
1955 if (dbm::is_result($r)) {
1956 $connect_id = $r[0]['id'];
1961 if ($item['verb'] == ACTIVITY_FOLLOW) {
1962 $message = t('%s is now following %s.');
1963 $title = t('following');
1964 $action = "subscription";
1966 $message = t('%s stopped following %s.');
1967 $title = t('stopped following');
1968 $action = "unfollow";
1971 $item["uri"] = $item['parent-uri'] = $item['thr-parent'] =
1972 'tag:'.get_app()->get_hostname().
1973 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1974 ':person:'.$connect_id.':'.$item['created'];
1976 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1978 self::entry_header($doc, $entry, $owner, $toplevel);
1980 self::entry_content($doc, $entry, $item, $owner, $title);
1982 $object = self::add_person_object($doc, $owner, $contact);
1983 $entry->appendChild($object);
1985 self::entry_footer($doc, $entry, $item, $owner);
1991 * @brief Adds a regular entry element
1993 * @param object $doc XML document
1994 * @param array $item Data of the item that is to be posted
1995 * @param array $owner Contact data of the poster
1996 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1998 * @return object Entry element
2000 private function note_entry($doc, $item, $owner, $toplevel) {
2002 if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
2003 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
2006 $title = self::entry_header($doc, $entry, $owner, $toplevel);
2008 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
2010 self::entry_content($doc, $entry, $item, $owner, $title);
2012 self::entry_footer($doc, $entry, $item, $owner);
2018 * @brief Adds a header element to the XML document
2020 * @param object $doc XML document
2021 * @param object $entry The entry element where the elements are added
2022 * @param array $owner Contact data of the poster
2023 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
2025 * @return string The title for the element
2027 private function entry_header($doc, &$entry, $owner, $toplevel) {
2028 /// @todo Check if this title stuff is really needed (I guess not)
2030 $entry = $doc->createElement("entry");
2031 $title = sprintf("New note by %s", $owner["nick"]);
2033 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
2035 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
2036 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
2037 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
2038 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
2039 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
2040 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
2041 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
2042 $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
2044 $author = self::add_author($doc, $owner);
2045 $entry->appendChild($author);
2047 $title = sprintf("New comment by %s", $owner["nick"]);
2053 * @brief Adds elements to the XML document
2055 * @param object $doc XML document
2056 * @param object $entry Entry element where the content is added
2057 * @param array $item Data of the item that is to be posted
2058 * @param array $owner Contact data of the poster
2059 * @param string $title Title for the post
2060 * @param string $verb The activity verb
2061 * @param bool $complete Add the "status_net" element?
2063 private function entry_content($doc, $entry, $item, $owner, $title, $verb = "", $complete = true) {
2066 $verb = self::construct_verb($item);
2068 xml::add_element($doc, $entry, "id", $item["uri"]);
2069 xml::add_element($doc, $entry, "title", $title);
2071 $body = self::format_picture_post($item['body']);
2073 if ($item['title'] != "")
2074 $body = "[b]".$item['title']."[/b]\n\n".$body;
2076 $body = bbcode($body, false, false, 7);
2078 xml::add_element($doc, $entry, "content", $body, array("type" => "html"));
2080 xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
2081 "href" => App::get_baseurl()."/display/".$item["guid"]));
2083 if ($complete AND ($item["id"] > 0))
2084 xml::add_element($doc, $entry, "status_net", "", array("notice_id" => $item["id"]));
2086 xml::add_element($doc, $entry, "activity:verb", $verb);
2088 xml::add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
2089 xml::add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
2093 * @brief Adds the elements at the foot of an entry to the XML document
2095 * @param object $doc XML document
2096 * @param object $entry The entry element where the elements are added
2097 * @param array $item Data of the item that is to be posted
2098 * @param array $owner Contact data of the poster
2101 private function entry_footer($doc, $entry, $item, $owner, $complete = true) {
2103 $mentioned = array();
2105 if (($item['parent'] != $item['id']) OR ($item['parent-uri'] !== $item['uri']) OR (($item['thr-parent'] !== '') AND ($item['thr-parent'] !== $item['uri']))) {
2106 $parent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `id` = %d", intval($item["parent"]));
2107 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
2109 $thrparent = q("SELECT `guid`, `author-link`, `owner-link`, `plink` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
2110 intval($owner["uid"]),
2111 dbesc($parent_item));
2113 $mentioned[$thrparent[0]["author-link"]] = $thrparent[0]["author-link"];
2114 $mentioned[$thrparent[0]["owner-link"]] = $thrparent[0]["owner-link"];
2115 $parent_plink = $thrparent[0]["plink"];
2117 $mentioned[$parent[0]["author-link"]] = $parent[0]["author-link"];
2118 $mentioned[$parent[0]["owner-link"]] = $parent[0]["owner-link"];
2119 $parent_plink = App::get_baseurl()."/display/".$parent[0]["guid"];
2122 $attributes = array(
2123 "ref" => $parent_item,
2124 "href" => $parent_plink);
2125 xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
2127 $attributes = array(
2129 "href" => $parent_plink);
2130 xml::add_element($doc, $entry, "link", "", $attributes);
2133 if (intval($item["parent"]) > 0) {
2134 $conversation_href = App::get_baseurl()."/display/".$owner["nick"]."/".$item["parent"];
2135 $conversation_uri = $conversation_href;
2137 if (isset($parent_item)) {
2138 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $parent_item);
2139 if (dbm::is_result($r)) {
2140 if ($r['conversation-uri'] != '') {
2141 $conversation_uri = $r['conversation-uri'];
2143 if ($r['conversation-href'] != '') {
2144 $conversation_href = $r['conversation-href'];
2149 xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:conversation", "href" => $conversation_href));
2151 $attributes = array(
2152 "href" => $conversation_href,
2153 "local_id" => $item["parent"],
2154 "ref" => $conversation_uri);
2156 xml::add_element($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
2159 $tags = item_getfeedtags($item);
2162 foreach($tags as $t)
2164 $mentioned[$t[1]] = $t[1];
2166 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2167 $newmentions = array();
2168 foreach ($mentioned AS $mention) {
2169 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2170 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2172 $mentioned = $newmentions;
2174 foreach ($mentioned AS $mention) {
2175 $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
2176 intval($owner["uid"]),
2177 dbesc(normalise_link($mention)));
2178 if ($r[0]["forum"] OR $r[0]["prv"])
2179 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2180 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
2181 "href" => $mention));
2183 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2184 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
2185 "href" => $mention));
2188 if (!$item["private"]) {
2189 xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:attention",
2190 "href" => "http://activityschema.org/collection/public"));
2191 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2192 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2193 "href" => "http://activityschema.org/collection/public"));
2194 xml::add_element($doc, $entry, "mastodon:scope", "public");
2198 foreach($tags as $t)
2200 xml::add_element($doc, $entry, "category", "", array("term" => $t[2]));
2202 self::get_attachment($doc, $entry, $item);
2204 if ($complete AND ($item["id"] > 0)) {
2205 $app = $item["app"];
2209 $attributes = array("local_id" => $item["id"], "source" => $app);
2211 if (isset($parent["id"]))
2212 $attributes["repeat_of"] = $parent["id"];
2214 if ($item["coord"] != "")
2215 xml::add_element($doc, $entry, "georss:point", $item["coord"]);
2217 xml::add_element($doc, $entry, "statusnet:notice_info", "", $attributes);
2222 * @brief Creates the XML feed for a given nickname
2224 * @param App $a The application class
2225 * @param string $owner_nick Nickname of the feed owner
2226 * @param string $last_update Date of the last update
2228 * @return string XML feed
2230 public static function feed(App $a, $owner_nick, $last_update) {
2232 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
2233 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
2234 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
2235 dbesc($owner_nick));
2241 if (!strlen($last_update))
2242 $last_update = 'now -30 days';
2244 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
2245 $authorid = get_contact($owner["url"], 0);
2247 $items = q("SELECT `item`.*, `item`.`id` AS `item_id` FROM `item` USE INDEX (`uid_contactid_created`)
2248 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2249 WHERE `item`.`uid` = %d AND `item`.`contact-id` = %d AND
2250 `item`.`author-id` = %d AND `item`.`created` > '%s' AND
2251 NOT `item`.`deleted` AND NOT `item`.`private` AND
2252 `thread`.`network` IN ('%s', '%s')
2253 ORDER BY `item`.`created` DESC LIMIT 300",
2254 intval($owner["uid"]), intval($owner["id"]),
2255 intval($authorid), dbesc($check_date),
2256 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
2258 /* 2016-10-23: The old query will be kept until we are sure that the query above is a good and fast replacement
2260 $items = q("SELECT `item`.*, `item`.`id` AS `item_id` FROM `item`
2261 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2262 LEFT JOIN `item` AS `thritem` ON `thritem`.`uri`=`item`.`thr-parent` AND `thritem`.`uid`=`item`.`uid`
2263 WHERE `item`.`uid` = %d AND `item`.`received` > '%s' AND NOT `item`.`private` AND NOT `item`.`deleted`
2264 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
2265 AND ((`item`.`wall` AND (`item`.`parent` = `item`.`id`))
2266 OR (`item`.`network` = '%s' AND ((`thread`.`network` IN ('%s', '%s')) OR (`thritem`.`network` IN ('%s', '%s')))) AND `thread`.`mention`)
2267 AND ((`item`.`owner-link` IN ('%s', '%s') AND (`item`.`parent` = `item`.`id`))
2268 OR (`item`.`author-link` IN ('%s', '%s')))
2269 ORDER BY `item`.`id` DESC
2271 intval($owner["uid"]), dbesc($check_date), dbesc(NETWORK_DFRN),
2272 //dbesc(NETWORK_OSTATUS), dbesc(NETWORK_OSTATUS),
2273 //dbesc(NETWORK_OSTATUS), dbesc(NETWORK_OSTATUS),
2274 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN),
2275 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN),
2276 dbesc($owner["nurl"]), dbesc(str_replace("http://", "https://", $owner["nurl"])),
2277 dbesc($owner["nurl"]), dbesc(str_replace("http://", "https://", $owner["nurl"]))
2280 $doc = new DOMDocument('1.0', 'utf-8');
2281 $doc->formatOutput = true;
2283 $root = self::add_header($doc, $owner);
2285 foreach ($items AS $item) {
2286 if (Config::get('system', 'ostatus_debug')) {
2287 $item['body'] .= '🍼';
2289 $entry = self::entry($doc, $item, $owner);
2290 $root->appendChild($entry);
2293 return(trim($doc->saveXML()));
2297 * @brief Creates the XML for a salmon message
2299 * @param array $item Data of the item that is to be posted
2300 * @param array $owner Contact data of the poster
2302 * @return string XML for the salmon
2304 public static function salmon($item,$owner) {
2306 $doc = new DOMDocument('1.0', 'utf-8');
2307 $doc->formatOutput = true;
2309 if (Config::get('system', 'ostatus_debug')) {
2310 $item['body'] .= '🐟';
2313 $entry = self::entry($doc, $item, $owner, true);
2315 $doc->appendChild($entry);
2317 return(trim($doc->saveXML()));