3 * @file include/ostatus.php
6 use \Friendica\Core\Config;
8 require_once("include/Contact.php");
9 require_once("include/threads.php");
10 require_once("include/html2bbcode.php");
11 require_once("include/bbcode.php");
12 require_once("include/items.php");
13 require_once("mod/share.php");
14 require_once("include/enotify.php");
15 require_once("include/socgraph.php");
16 require_once("include/Photo.php");
17 require_once("include/Scrape.php");
18 require_once("include/follow.php");
19 require_once("include/api.php");
20 require_once("mod/proxy.php");
21 require_once("include/xml.php");
24 * @brief This class contain functions for the OStatus protocol
28 const OSTATUS_DEFAULT_POLL_INTERVAL = 30; // given in minutes
29 const OSTATUS_DEFAULT_POLL_TIMEFRAME = 1440; // given in minutes
30 const OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS = 14400; // given in minutes
33 * @brief Mix two paths together to possibly fix missing parts
35 * @param string $avatar Path to the avatar
36 * @param string $base Another path that is hopefully complete
38 * @return string fixed avatar path
40 public static function fix_avatar($avatar, $base) {
41 $base_parts = parse_url($base);
43 // Remove all parts that could create a problem
44 unset($base_parts['path']);
45 unset($base_parts['query']);
46 unset($base_parts['fragment']);
48 $avatar_parts = parse_url($avatar);
51 $parts = array_merge($base_parts, $avatar_parts);
53 // And put them together again
54 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
55 $host = isset($parts['host']) ? $parts['host'] : '';
56 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
57 $path = isset($parts['path']) ? $parts['path'] : '';
58 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
59 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
61 $fixed = $scheme.$host.$port.$path.$query.$fragment;
63 logger('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, LOGGER_DATA);
69 * @brief Fetches author data
71 * @param object $xpath The xpath object
72 * @param object $context The xml context of the author detals
73 * @param array $importer user record of the importing user
74 * @param array $contact Called by reference, will contain the fetched contact
75 * @param bool $onlyfetch Only fetch the header without updating the contact entries
77 * @return array Array of author related entries for the item
79 private function fetchauthor($xpath, $context, $importer, &$contact, $onlyfetch) {
82 $author["author-link"] = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
83 $author["author-name"] = $xpath->evaluate('atom:author/atom:name/text()', $context)->item(0)->nodeValue;
84 $addr = $xpath->evaluate('atom:author/atom:email/text()', $context)->item(0)->nodeValue;
86 $aliaslink = $author["author-link"];
88 $alternate = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0)->attributes;
89 if (is_object($alternate)) {
90 foreach ($alternate AS $attributes) {
91 if (($attributes->name == "href") AND ($attributes->textContent != "")) {
92 $author["author-link"] = $attributes->textContent;
97 $author["contact-id"] = $contact["id"];
99 if ($author["author-link"] != "") {
100 if ($aliaslink == "") {
101 $aliaslink = $author["author-link"];
104 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` IN ('%s', '%s') AND `network` != '%s'",
105 intval($importer["uid"]), dbesc(normalise_link($author["author-link"])),
106 dbesc(normalise_link($aliaslink)), dbesc(NETWORK_STATUSNET));
107 if (dbm::is_result($r)) {
109 $author["contact-id"] = $r[0]["id"];
110 $author["author-link"] = $r[0]["url"];
112 } elseif ($addr != "") {
114 $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `uid` = ? AND `addr` = ? AND `network` != ?",
115 $importer["uid"], $addr, NETWORK_STATUSNET);
116 if (dbm::is_result($contact)) {
117 $author["contact-id"] = $contact["id"];
118 $author["author-link"] = $contact["url"];
122 $avatarlist = array();
123 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
124 foreach($avatars AS $avatar) {
127 foreach($avatar->attributes AS $attributes) {
128 if ($attributes->name == "href")
129 $href = $attributes->textContent;
130 if ($attributes->name == "width")
131 $width = $attributes->textContent;
133 if (($width > 0) AND ($href != ""))
134 $avatarlist[$width] = $href;
136 if (count($avatarlist) > 0) {
138 $author["author-avatar"] = self::fix_avatar(current($avatarlist), $author["author-link"]);
141 $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
142 if ($displayname != "")
143 $author["author-name"] = $displayname;
145 $author["owner-name"] = $author["author-name"];
146 $author["owner-link"] = $author["author-link"];
147 $author["owner-avatar"] = $author["author-avatar"];
149 // Only update the contacts if it is an OStatus contact
150 if ($r AND !$onlyfetch AND ($contact["network"] == NETWORK_OSTATUS)) {
152 // Update contact data
154 // This query doesn't seem to work
155 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
157 // $contact["notify"] = $value;
159 // This query doesn't seem to work as well - I hate these queries
160 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
162 // $contact["poll"] = $value;
164 $value = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
166 $contact["alias"] = $value;
168 $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
170 $contact["name"] = $value;
172 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
174 $contact["nick"] = $value;
176 $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
178 $contact["about"] = html2bbcode($value);
180 $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
182 $contact["location"] = $value;
184 if (($contact["name"] != $r[0]["name"]) OR ($contact["nick"] != $r[0]["nick"]) OR ($contact["about"] != $r[0]["about"]) OR
185 ($contact["alias"] != $r[0]["alias"]) OR ($contact["location"] != $r[0]["location"])) {
187 logger("Update contact data for contact ".$contact["id"], LOGGER_DEBUG);
189 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `alias` = '%s', `about` = '%s', `location` = '%s', `name-date` = '%s' WHERE `id` = %d",
190 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["alias"]),
191 dbesc($contact["about"]), dbesc($contact["location"]),
192 dbesc(datetime_convert()), intval($contact["id"]));
195 if (isset($author["author-avatar"]) AND ($author["author-avatar"] != $r[0]['avatar'])) {
196 logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
198 update_contact_avatar($author["author-avatar"], $importer["uid"], $contact["id"]);
201 // Ensure that we are having this contact (with uid=0)
202 $cid = get_contact($author["author-link"], 0);
205 // Update it with the current values
206 q("UPDATE `contact` SET `url` = '%s', `name` = '%s', `nick` = '%s', `alias` = '%s',
207 `about` = '%s', `location` = '%s',
208 `success_update` = '%s', `last-update` = '%s'
210 dbesc($author["author-link"]), dbesc($contact["name"]), dbesc($contact["nick"]),
211 dbesc($contact["alias"]), dbesc($contact["about"]), dbesc($contact["location"]),
212 dbesc(datetime_convert()), dbesc(datetime_convert()), intval($cid));
215 update_contact_avatar($author["author-avatar"], 0, $cid);
218 $contact["generation"] = 2;
219 $contact["hide"] = false; // OStatus contacts are never hidden
220 $contact["photo"] = $author["author-avatar"];
221 $gcid = update_gcontact($contact);
223 link_gcontact($gcid, $contact["uid"], $contact["id"]);
230 * @brief Fetches author data from a given XML string
232 * @param string $xml The XML
233 * @param array $importer user record of the importing user
235 * @return array Array of author related entries for the item
237 public static function salmon_author($xml, $importer) {
242 $doc = new DOMDocument();
243 @$doc->loadXML($xml);
245 $xpath = new DomXPath($doc);
246 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
247 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
248 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
249 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
250 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
251 $xpath->registerNamespace('poco', NAMESPACE_POCO);
252 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
253 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
255 $entries = $xpath->query('/atom:entry');
257 foreach ($entries AS $entry) {
259 $author = self::fetchauthor($xpath, $entry, $importer, $contact, true);
265 * @brief Read attributes from element
267 * @param object $element Element object
269 * @return array attributes
271 private static function read_attributes($element) {
272 $attribute = array();
274 foreach ($element->attributes AS $attributes) {
275 $attribute[$attributes->name] = $attributes->textContent;
282 * @brief Imports an XML string containing OStatus elements
284 * @param string $xml The XML
285 * @param array $importer user record of the importing user
287 * @param array $hub Called by reference, returns the fetched hub data
289 public static function import($xml,$importer,&$contact, &$hub) {
290 /// @todo this function is too long. It has to be split in many parts
292 logger("Import OStatus message", LOGGER_DEBUG);
297 //$tempfile = tempnam(get_temppath(), "import");
298 //file_put_contents($tempfile, $xml);
300 $doc = new DOMDocument();
301 @$doc->loadXML($xml);
303 $xpath = new DomXPath($doc);
304 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
305 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
306 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
307 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
308 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
309 $xpath->registerNamespace('poco', NAMESPACE_POCO);
310 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
311 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
314 $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
315 if (is_object($hub_attributes)) {
316 foreach ($hub_attributes AS $hub_attribute) {
317 if ($hub_attribute->name == "href") {
318 $hub = $hub_attribute->textContent;
319 logger("Found hub ".$hub, LOGGER_DEBUG);
324 $header["uid"] = $importer["uid"];
325 $header["network"] = NETWORK_OSTATUS;
326 $header["type"] = "remote";
328 $header["origin"] = 0;
329 $header["gravity"] = GRAVITY_PARENT;
331 // it could either be a received post or a post we fetched by ourselves
332 // depending on that, the first node is different
333 $first_child = $doc->firstChild->tagName;
335 if ($first_child == "feed") {
336 $entries = $xpath->query('/atom:feed/atom:entry');
337 $header["protocol"] = PROTOCOL_OSTATUS_FEED;
339 $entries = $xpath->query('/atom:entry');
340 $header["protocol"] = PROTOCOL_OSTATUS_SALMON;
343 $conversationlist = array();
346 // Reverse the order of the entries
347 $entrylist = array();
349 foreach ($entries AS $entry) {
350 $entrylist[] = $entry;
352 foreach (array_reverse($entrylist) AS $entry) {
357 if ($first_child == "feed") {
358 $author = self::fetchauthor($xpath, $doc->firstChild, $importer, $contact, false);
360 $author = self::fetchauthor($xpath, $entry, $importer, $contact, false);
362 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
366 $nickname = $author["author-name"];
368 $item = array_merge($header, $author);
371 $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
373 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
374 intval($importer["uid"]), dbesc($item["uri"]));
375 if (dbm::is_result($r)) {
376 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already existed under id ".$r[0]["id"], LOGGER_DEBUG);
380 $item["body"] = add_page_info_to_body(html2bbcode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue));
381 $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
382 $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
384 // Mastodon Content Warning
385 if (($item["verb"] == ACTIVITY_POST) AND $xpath->evaluate('boolean(atom:summary)', $entry)) {
386 $clear_text = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
388 $item["body"] = html2bbcode($clear_text) . '[spoiler]' . $item["body"] . '[/spoiler]';
391 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) OR ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
392 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
393 $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
394 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
395 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
397 $item["source"] = $xml;
401 if ($item["verb"] == "qvitter-delete-notice" || $item["verb"] == ACTIVITY_DELETE) {
402 // ignore "Delete" messages (by now)
403 logger("Ignore delete message ".print_r($item, true));
407 if ($item["verb"] == ACTIVITY_JOIN) {
408 // ignore "Join" messages
409 logger("Ignore join message ".print_r($item, true));
413 if ($item["verb"] == ACTIVITY_FOLLOW) {
414 new_follower($importer, $contact, $item, $nickname);
418 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
419 lose_follower($importer, $contact, $item, $dummy);
423 if ($item["verb"] == ACTIVITY_FAVORITE) {
424 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
425 logger("Favorite ".$orig_uri." ".print_r($item, true));
427 $item["verb"] = ACTIVITY_LIKE;
428 $item["parent-uri"] = $orig_uri;
429 $item["gravity"] = GRAVITY_LIKE;
432 if ($item["verb"] == NAMESPACE_OSTATUS."/unfavorite") {
433 // Ignore "Unfavorite" message
434 logger("Ignore unfavorite message ".print_r($item, true));
438 // http://activitystrea.ms/schema/1.0/rsvp-yes
439 if (!in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE))) {
440 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true));
442 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
443 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
444 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
445 $item['conversation-uri'] = $conversation;
447 $conv = $xpath->query('ostatus:conversation', $entry);
448 if (is_object($conv->item(0))) {
449 foreach ($conv->item(0)->attributes AS $attributes) {
450 if ($attributes->name == "ref") {
451 $item['conversation-uri'] = $attributes->textContent;
453 if ($attributes->name == "href") {
454 $item['conversation-href'] = $attributes->textContent;
461 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
462 if (is_object($inreplyto->item(0))) {
463 foreach ($inreplyto->item(0)->attributes AS $attributes) {
464 if ($attributes->name == "ref") {
465 $item["parent-uri"] = $attributes->textContent;
467 if ($attributes->name == "href") {
468 $related = $attributes->textContent;
473 $georsspoint = $xpath->query('georss:point', $entry);
475 $item["coord"] = $georsspoint->item(0)->nodeValue;
477 $categories = $xpath->query('atom:category', $entry);
479 foreach ($categories AS $category) {
480 foreach ($category->attributes AS $attributes) {
481 if ($attributes->name == "term") {
482 $term = $attributes->textContent;
483 if(strlen($item["tag"])) {
486 $item["tag"] .= "#[url=".App::get_baseurl()."/search?tag=".$term."]".$term."[/url]";
495 $links = $xpath->query('atom:link', $entry);
497 foreach ($links AS $link) {
498 $attribute = self::read_attributes($link);
500 if (($attribute['rel'] != "") AND ($attribute['href'] != "")) {
501 switch ($attribute['rel']) {
503 $item["plink"] = $attribute['href'];
504 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION) OR
505 ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
506 $item["body"] .= add_page_info($attribute['href']);
509 case "ostatus:conversation":
510 $conversation = $attribute['href'];
511 $item['conversation-href'] = $conversation;
512 if (!isset($item['conversation-uri'])) {
513 $item['conversation-uri'] = $item['conversation-href'];
517 $enclosure = $attribute['href'];
518 if (strlen($item["attach"])) {
519 $item["attach"] .= ',';
521 if (!isset($attribute['length'])) {
522 $attribute['length'] = "0";
524 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
527 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
528 if (!isset($item["parent-uri"])) {
529 $item["parent-uri"] = $attribute['href'];
531 if ($related == "") {
532 $related = $attribute['href'];
535 $item["body"] .= add_page_info($attribute['href']);
539 $self = $attribute['href'];
542 // Notification check
543 if ($importer["nurl"] == normalise_link($attribute['href'])) {
555 $notice_info = $xpath->query('statusnet:notice_info', $entry);
556 if ($notice_info AND ($notice_info->length > 0)) {
557 foreach ($notice_info->item(0)->attributes AS $attributes) {
558 if ($attributes->name == "source") {
559 $item["app"] = strip_tags($attributes->textContent);
561 if ($attributes->name == "local_id") {
562 $local_id = $attributes->textContent;
564 if ($attributes->name == "repeat_of") {
565 $repeat_of = $attributes->textContent;
570 // Is it a repeated post?
571 if (($repeat_of != "") OR ($item["verb"] == ACTIVITY_SHARE)) {
572 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
574 if (is_object($activityobjects)) {
576 $orig_uri = $xpath->query("activity:object/atom:id", $activityobjects)->item(0)->nodeValue;
577 if (!isset($orig_uri)) {
578 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
580 $orig_links = $xpath->query("activity:object/atom:link[@rel='alternate']", $activityobjects);
581 if ($orig_links AND ($orig_links->length > 0)) {
582 foreach ($orig_links->item(0)->attributes AS $attributes) {
583 if ($attributes->name == "href") {
584 $orig_link = $attributes->textContent;
588 if (!isset($orig_link)) {
589 $orig_link = $xpath->query("atom:link[@rel='alternate']", $activityobjects)->item(0)->nodeValue;
591 if (!isset($orig_link)) {
592 $orig_link = self::convert_href($orig_uri);
594 $orig_body = $xpath->query('activity:object/atom:content/text()', $activityobjects)->item(0)->nodeValue;
595 if (!isset($orig_body)) {
596 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
598 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
599 $orig_edited = $xpath->query('atom:updated/text()', $activityobjects)->item(0)->nodeValue;
601 $orig_contact = $contact;
602 $orig_author = self::fetchauthor($xpath, $activityobjects, $importer, $orig_contact, false);
604 $item["author-name"] = $orig_author["author-name"];
605 $item["author-link"] = $orig_author["author-link"];
606 $item["author-avatar"] = $orig_author["author-avatar"];
608 $item["body"] = add_page_info_to_body(html2bbcode($orig_body));
609 $item["created"] = $orig_created;
610 $item["edited"] = $orig_edited;
612 $item["uri"] = $orig_uri;
614 if (!isset($item["plink"])) {
615 $item["plink"] = $orig_link;
618 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
620 $item["object-type"] = $xpath->query('activity:object/activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
621 if (!isset($item["object-type"])) {
622 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
625 $enclosures = $xpath->query("atom:link[@rel='alternate']", $activityobjects);
627 foreach ($enclosures AS $link) {
628 $attribute = self::read_attributes($link);
630 $enclosure = $attribute['href'];
631 if (strlen($item["attach"])) {
632 $item["attach"] .= ',';
634 if (!isset($attribute['length'])) {
635 $attribute['length'] = "0";
637 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
644 //if ($enclosure != "")
645 // $item["body"] .= add_page_info($enclosure);
647 if (isset($item["parent-uri"])) {
648 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
649 intval($importer["uid"]), dbesc($item["parent-uri"]));
651 // Only fetch missing stuff if it is a comment or reshare.
652 if (in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_SHARE)) AND
653 !dbm::is_result($r) AND ($related != "")) {
654 $reply_path = str_replace("/notice/", "/api/statuses/show/", $related).".atom";
656 if ($reply_path != $related) {
657 logger("Fetching related items for user ".$importer["uid"]." from ".$reply_path, LOGGER_DEBUG);
658 $reply_xml = fetch_url($reply_path);
660 $reply_contact = $contact;
661 self::import($reply_xml,$importer,$reply_contact, $reply_hub);
663 // After the import try to fetch the parent item again
664 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
665 intval($importer["uid"]), dbesc($item["parent-uri"]));
668 if (dbm::is_result($r)) {
669 $item["type"] = 'remote-comment';
670 $item["gravity"] = GRAVITY_COMMENT;
673 $item["parent-uri"] = $item["uri"];
675 $item_id = self::completion($conversation, $importer["uid"], $item, $self);
678 logger("Error storing item", LOGGER_DEBUG);
682 logger("Item was stored with id ".$item_id, LOGGER_DEBUG);
687 * @brief Create an url out of an uri
689 * @param string $href URI in the format "parameter1:parameter1:..."
691 * @return string URL in the format http(s)://....
693 public static function convert_href($href) {
694 $elements = explode(":",$href);
696 if ((count($elements) <= 2) OR ($elements[0] != "tag"))
699 $server = explode(",", $elements[1]);
700 $conversation = explode("=", $elements[2]);
702 if ((count($elements) == 4) AND ($elements[2] == "post"))
703 return "http://".$server[0]."/notice/".$elements[3];
705 if ((count($conversation) != 2) OR ($conversation[1] ==""))
708 if ($elements[3] == "objectType=thread")
709 return "http://".$server[0]."/conversation/".$conversation[1];
711 return "http://".$server[0]."/notice/".$conversation[1];
717 * @brief Checks if there are entries in conversations that aren't present on our side
719 * @param bool $mentions Fetch conversations where we are mentioned
720 * @param bool $override Override the interval setting
722 public static function check_conversations($mentions = false, $override = false) {
723 $last = get_config('system','ostatus_last_poll');
725 $poll_interval = intval(get_config('system','ostatus_poll_interval'));
726 if (!$poll_interval) {
727 $poll_interval = self::OSTATUS_DEFAULT_POLL_INTERVAL;
730 // Don't poll if the interval is set negative
731 if (($poll_interval < 0) AND !$override) {
736 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
737 if (!$poll_timeframe) {
738 $poll_timeframe = self::OSTATUS_DEFAULT_POLL_TIMEFRAME;
741 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
742 if (!$poll_timeframe) {
743 $poll_timeframe = self::OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS;
748 if ($last AND !$override) {
749 $next = $last + ($poll_interval * 60);
750 if ($next > time()) {
751 logger('poll interval not reached');
756 logger('cron_start');
758 $start = date("Y-m-d H:i:s", time() - ($poll_timeframe * 60));
761 $conversations = q("SELECT `term`.`oid`, `term`.`url`, `term`.`uid` FROM `term`
762 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `term`.`oid` AND `thread`.`uid` = `term`.`uid`
763 WHERE `term`.`type` = 7 AND `term`.`term` > '%s' AND `thread`.`mention`
764 GROUP BY `term`.`url`, `term`.`uid`, `term`.`oid`, `term`.`term` ORDER BY `term`.`term` DESC", dbesc($start));
766 $conversations = q("SELECT `oid`, `url`, `uid` FROM `term`
767 WHERE `type` = 7 AND `term` > '%s'
768 GROUP BY `url`, `uid`, `oid`, `term` ORDER BY `term` DESC", dbesc($start));
771 foreach ($conversations AS $conversation) {
772 self::completion($conversation['url'], $conversation['uid']);
777 set_config('system','ostatus_last_poll', time());
781 * @brief Updates the gcontact table with actor data from the conversation
783 * @param object $actor The actor object that contains the contact data
785 private function conv_fetch_actor($actor) {
787 // We set the generation to "3" since the data here is not as reliable as the data we get on other occasions
788 $contact = array("network" => NETWORK_OSTATUS, "generation" => 3);
790 if (isset($actor->url))
791 $contact["url"] = $actor->url;
793 if (isset($actor->displayName))
794 $contact["name"] = $actor->displayName;
796 if (isset($actor->portablecontacts_net->displayName))
797 $contact["name"] = $actor->portablecontacts_net->displayName;
799 if (isset($actor->portablecontacts_net->preferredUsername))
800 $contact["nick"] = $actor->portablecontacts_net->preferredUsername;
802 if (isset($actor->id))
803 $contact["alias"] = $actor->id;
805 if (isset($actor->summary))
806 $contact["about"] = $actor->summary;
808 if (isset($actor->portablecontacts_net->note))
809 $contact["about"] = $actor->portablecontacts_net->note;
811 if (isset($actor->portablecontacts_net->addresses->formatted))
812 $contact["location"] = $actor->portablecontacts_net->addresses->formatted;
815 if (isset($actor->image->url))
816 $contact["photo"] = $actor->image->url;
818 if (isset($actor->image->width))
819 $avatarwidth = $actor->image->width;
821 if (is_array($actor->status_net->avatarLinks))
822 foreach ($actor->status_net->avatarLinks AS $avatar) {
823 if ($avatarsize < $avatar->width) {
824 $contact["photo"] = $avatar->url;
825 $avatarsize = $avatar->width;
829 $contact["hide"] = false; // OStatus contacts are never hidden
830 update_gcontact($contact);
834 * @brief Fetches the conversation url for a given item link or conversation id
836 * @param string $self The link to the posting
837 * @param string $conversation_id The conversation id
839 * @return string The conversation url
841 private function fetch_conversation($self, $conversation_id = "") {
843 if ($conversation_id != "") {
844 $elements = explode(":", $conversation_id);
846 if ((count($elements) <= 2) OR ($elements[0] != "tag"))
847 return $conversation_id;
853 $json = str_replace(".atom", ".json", $self);
855 $raw = fetch_url($json);
859 $data = json_decode($raw);
860 if (!is_object($data))
863 $conversation_id = $data->statusnet_conversation_id;
865 $pos = strpos($self, "/api/statuses/show/");
866 $base_url = substr($self, 0, $pos);
868 return $base_url."/conversation/".$conversation_id;
872 * @brief Fetches actor details of a given actor and user id
874 * @param string $actor The actor url
875 * @param int $uid The user id
876 * @param int $contact_id The default contact-id
878 * @return array Array with actor details
880 private function get_actor_details($actor, $uid, $contact_id) {
884 $contact = q("SELECT `id`, `rel`, `network` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
885 $uid, normalise_link($actor), NETWORK_STATUSNET);
888 $contact = q("SELECT `id`, `rel`, `network` FROM `contact` WHERE `uid` = %d AND `alias` IN ('%s', '%s') AND `network` != '%s'",
889 $uid, $actor, normalise_link($actor), NETWORK_STATUSNET);
892 logger("Found contact for url ".$actor, LOGGER_DEBUG);
893 $details["contact_id"] = $contact[0]["id"];
894 $details["network"] = $contact[0]["network"];
896 $details["not_following"] = !in_array($contact[0]["rel"], array(CONTACT_IS_SHARING, CONTACT_IS_FRIEND));
898 logger("No contact found for user ".$uid." and url ".$actor, LOGGER_DEBUG);
900 // Adding a global contact
901 /// @TODO Use this data for the post
902 $details["global_contact_id"] = get_contact($actor, 0);
904 logger("Global contact ".$global_contact_id." found for url ".$actor, LOGGER_DEBUG);
906 $details["contact_id"] = $contact_id;
907 $details["network"] = NETWORK_OSTATUS;
909 $details["not_following"] = true;
916 * @brief Stores an item and completes the thread
918 * @param string $conversation_url The URI of the conversation
919 * @param integer $uid The user id
920 * @param array $item Data of the item that is to be posted
922 * @return integer The item id of the posted item array
924 private function completion($conversation_url, $uid, $item = array(), $self = "") {
926 /// @todo This function is totally ugly and has to be rewritten totally
928 // Import all threads or only threads that were started by our followers?
929 $all_threads = !get_config('system','ostatus_full_threads');
933 $conversation_url = self::fetch_conversation($self, $conversation_url);
935 // If the thread shouldn't be completed then store the item and go away
936 // Don't do a completion on liked content
937 if (((intval(get_config('system','ostatus_poll_interval')) == -2) AND (count($item) > 0)) OR
938 ($item["verb"] == ACTIVITY_LIKE) OR ($conversation_url == "")) {
939 $item_stored = item_store($item, $all_threads);
941 } elseif (count($item) > 0) {
942 $item = store_conversation($item);
946 $parents = q("SELECT `item`.`id`, `item`.`parent`, `item`.`uri`, `item`.`contact-id`, `item`.`type`,
947 `item`.`verb`, `item`.`visible` FROM `term`
948 STRAIGHT_JOIN `item` AS `thritem` ON `thritem`.`parent` = `term`.`oid`
949 STRAIGHT_JOIN `item` ON `item`.`parent` = `thritem`.`parent`
950 WHERE `term`.`uid` = %d AND `term`.`otype` = %d AND `term`.`type` = %d AND `term`.`url` = '%s'",
951 intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url));
953 /* 2016-10-23: The old query will be kept until we are sure that the query above is a good and fast replacement
955 $parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
956 (SELECT `parent` FROM `item` WHERE `id` IN
957 (SELECT `oid` FROM `term` WHERE `uid` = %d AND `otype` = %d AND `type` = %d AND `url` = '%s'))",
958 intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url));
961 $parent = $parents[0];
962 elseif (count($item) > 0) {
964 $parent["type"] = "remote";
965 $parent["verb"] = ACTIVITY_POST;
966 $parent["visible"] = 1;
969 $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid`=%d", $uid);
975 $parent["parent"] = 0;
977 $parent["contact-id"] = $r[0]["id"];
978 $parent["type"] = "remote";
979 $parent["verb"] = ACTIVITY_POST;
980 $parent["visible"] = 1;
983 $conv = str_replace("/conversation/", "/api/statusnet/conversation/", $conversation_url).".as";
987 logger('fetching conversation url '.$conv.' (Self: '.$self.') for user '.$uid);
990 $conv_arr = z_fetch_url($conv."?page=".$pageno);
992 // If it is a non-ssl site and there is an error, then try ssl or vice versa
993 if (!$conv_arr["success"] AND (substr($conv, 0, 7) == "http://")) {
994 $conv = str_replace("http://", "https://", $conv);
995 $conv_as = fetch_url($conv."?page=".$pageno);
996 } elseif (!$conv_arr["success"] AND (substr($conv, 0, 8) == "https://")) {
997 $conv = str_replace("https://", "http://", $conv);
998 $conv_as = fetch_url($conv."?page=".$pageno);
1000 $conv_as = $conv_arr["body"];
1002 $conv_as = str_replace(',"statusnet:notice_info":', ',"statusnet_notice_info":', $conv_as);
1003 $conv_as = json_decode($conv_as);
1005 $no_of_items = sizeof($items);
1007 if (@is_array($conv_as->items))
1008 foreach ($conv_as->items AS $single_item)
1009 $items[$single_item->id] = $single_item;
1011 if ($no_of_items == sizeof($items))
1018 logger('fetching conversation done. Found '.count($items).' items');
1020 if (!sizeof($items)) {
1021 if (count($item) > 0) {
1022 $item_stored = item_store($item, $all_threads);
1025 logger("Conversation ".$conversation_url." couldn't be fetched. Item uri ".$item["uri"]." stored: ".$item_stored, LOGGER_DEBUG);
1026 self::store_conversation($item_id, $conversation_url);
1029 return($item_stored);
1034 $items = array_reverse($items);
1036 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self`", intval($uid));
1041 foreach ($items as $single_conv) {
1043 // Update the gcontact table
1044 self::conv_fetch_actor($single_conv->actor);
1046 // Test - remove before flight
1047 //$tempfile = tempnam(get_temppath(), "conversation");
1048 //file_put_contents($tempfile, json_encode($single_conv));
1052 if (isset($single_conv->object->id))
1053 $single_conv->id = $single_conv->object->id;
1055 $plink = self::convert_href($single_conv->id);
1056 if (isset($single_conv->object->url))
1057 $plink = self::convert_href($single_conv->object->url);
1059 if (@!$single_conv->id)
1062 logger("Got id ".$single_conv->id, LOGGER_DEBUG);
1064 if ($first_id == "") {
1065 $first_id = $single_conv->id;
1067 // The first post of the conversation isn't our first post. There are three options:
1068 // 1. Our conversation hasn't the "real" thread starter
1069 // 2. This first post is a post inside our thread
1070 // 3. This first post is a post inside another thread
1071 if (($first_id != $parent["uri"]) AND ($parent["uri"] != "")) {
1075 $new_parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
1076 (SELECT `parent` FROM `item`
1077 WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s')) LIMIT 1",
1078 intval($uid), dbesc($first_id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1080 if ($new_parents[0]["parent"] == $parent["parent"]) {
1081 // Option 2: This post is already present inside our thread - but not as thread starter
1082 logger("Option 2: uri present in our thread: ".$first_id, LOGGER_DEBUG);
1083 $first_id = $parent["uri"];
1085 // Option 3: Not so good. We have mixed parents. We have to see how to clean this up.
1086 // For now just take the new parent.
1087 $parent = $new_parents[0];
1088 $first_id = $parent["uri"];
1089 logger("Option 3: mixed parents for uri ".$first_id, LOGGER_DEBUG);
1092 // Option 1: We hadn't got the real thread starter
1093 // We have to clean up our existing messages.
1095 $parent["uri"] = $first_id;
1096 logger("Option 1: we have a new parent: ".$first_id, LOGGER_DEBUG);
1098 } elseif ($parent["uri"] == "") {
1100 $parent["uri"] = $first_id;
1104 $parent_uri = $parent["uri"];
1106 // "context" only seems to exist on older servers
1107 if (isset($single_conv->context->inReplyTo->id)) {
1108 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1109 intval($uid), dbesc($single_conv->context->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1111 $parent_uri = $single_conv->context->inReplyTo->id;
1114 // This is the current way
1115 if (isset($single_conv->object->inReplyTo->id)) {
1116 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1117 intval($uid), dbesc($single_conv->object->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1119 $parent_uri = $single_conv->object->inReplyTo->id;
1122 $message_exists = q("SELECT `id`, `parent`, `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1123 intval($uid), dbesc($single_conv->id),
1124 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1125 if ($message_exists) {
1126 logger("Message ".$single_conv->id." already existed on the system", LOGGER_DEBUG);
1128 if ($parent["id"] != 0) {
1129 $existing_message = $message_exists[0];
1131 // We improved the way we fetch OStatus messages, this shouldn't happen very often now
1132 /// @TODO We have to change the shadow copies as well. This way here is really ugly.
1133 if ($existing_message["parent"] != $parent["id"]) {
1134 logger('updating id '.$existing_message["id"].' with parent '.$existing_message["parent"].' to parent '.$parent["id"].' uri '.$parent["uri"].' thread '.$parent_uri, LOGGER_DEBUG);
1136 // Update the parent id of the selected item
1137 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `id` = %d",
1138 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["id"]));
1140 // Update the parent uri in the thread - but only if it points to itself
1141 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE `id` = %d AND `uri` = `thr-parent`",
1142 dbesc($parent_uri), intval($existing_message["id"]));
1144 // try to change all items of the same parent
1145 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `parent` = %d",
1146 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["parent"]));
1148 // Update the parent uri in the thread - but only if it points to itself
1149 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE (`parent` = %d) AND (`uri` = `thr-parent`)",
1150 dbesc($parent["uri"]), intval($existing_message["parent"]));
1152 // Now delete the thread
1153 delete_thread($existing_message["parent"]);
1157 // The item we are having on the system is the one that we wanted to store via the item array
1158 if (isset($item["uri"]) AND ($item["uri"] == $existing_message["uri"])) {
1166 if (is_array($single_conv->to))
1167 foreach($single_conv->to AS $to)
1168 if ($importer["nurl"] == normalise_link($to->id))
1171 $actor = $single_conv->actor->id;
1172 if (isset($single_conv->actor->url))
1173 $actor = $single_conv->actor->url;
1175 $details = self::get_actor_details($actor, $uid, $parent["contact-id"]);
1177 // Do we only want to import threads that were started by our contacts?
1178 if ($details["not_following"] AND $new_parent AND get_config('system','ostatus_full_threads')) {
1179 logger("Don't import uri ".$first_id." because user ".$uid." doesn't follow the person ".$actor, LOGGER_DEBUG);
1184 $arr["network"] = $details["network"];
1185 $arr["uri"] = $single_conv->id;
1186 $arr["plink"] = $plink;
1188 $arr["contact-id"] = $details["contact_id"];
1189 $arr["parent-uri"] = $parent_uri;
1190 $arr["created"] = $single_conv->published;
1191 $arr["edited"] = $single_conv->published;
1192 $arr["owner-name"] = $single_conv->actor->displayName;
1193 if ($arr["owner-name"] == '')
1194 $arr["owner-name"] = $single_conv->actor->contact->displayName;
1195 if ($arr["owner-name"] == '')
1196 $arr["owner-name"] = $single_conv->actor->portablecontacts_net->displayName;
1198 $arr["owner-link"] = $actor;
1199 $arr["owner-avatar"] = self::fix_avatar($single_conv->actor->image->url, $arr["owner-link"]);
1201 $arr["author-name"] = $arr["owner-name"];
1202 $arr["author-link"] = $arr["owner-link"];
1203 $arr["author-avatar"] = $arr["owner-avatar"];
1204 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->content));
1206 if (isset($single_conv->status_net->conversation)) {
1207 $arr['conversation-uri'] = $single_conv->status_net->conversation;
1210 if (isset($single_conv->status_net->notice_info->source))
1211 $arr["app"] = strip_tags($single_conv->status_net->notice_info->source);
1212 elseif (isset($single_conv->statusnet->notice_info->source))
1213 $arr["app"] = strip_tags($single_conv->statusnet->notice_info->source);
1214 elseif (isset($single_conv->statusnet_notice_info->source))
1215 $arr["app"] = strip_tags($single_conv->statusnet_notice_info->source);
1216 elseif (isset($single_conv->provider->displayName))
1217 $arr["app"] = $single_conv->provider->displayName;
1219 $arr["app"] = "OStatus";
1222 $arr["source"] = json_encode($single_conv);
1223 $arr["protocol"] = PROTOCOL_GS_CONVERSATION;
1225 $arr["verb"] = $parent["verb"];
1226 $arr["visible"] = $parent["visible"];
1227 $arr["location"] = $single_conv->location->displayName;
1228 $arr["coord"] = trim($single_conv->location->lat." ".$single_conv->location->lon);
1230 // Is it a reshared item?
1231 if (isset($single_conv->verb) AND ($single_conv->verb == "share") AND isset($single_conv->object)) {
1232 if (is_array($single_conv->object))
1233 $single_conv->object = $single_conv->object[0];
1235 logger("Found reshared item ".$single_conv->object->id);
1237 // $single_conv->object->context->conversation;
1239 if (isset($single_conv->object->object->id))
1240 $arr["uri"] = $single_conv->object->object->id;
1242 $arr["uri"] = $single_conv->object->id;
1244 if (isset($single_conv->object->object->url))
1245 $plink = self::convert_href($single_conv->object->object->url);
1247 $plink = self::convert_href($single_conv->object->url);
1249 if (isset($single_conv->object->object->content))
1250 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->object->content));
1252 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->content));
1254 $arr["plink"] = $plink;
1256 $arr["created"] = $single_conv->object->published;
1257 $arr["edited"] = $single_conv->object->published;
1259 $arr["author-name"] = $single_conv->object->actor->displayName;
1260 if ($arr["owner-name"] == '') {
1261 $arr["author-name"] = $single_conv->object->actor->contact->displayName;
1263 $arr["author-link"] = $single_conv->object->actor->url;
1264 $arr["author-avatar"] = self::fix_avatar($single_conv->object->actor->image->url, $arr["author-link"]);
1266 $arr["app"] = $single_conv->object->provider->displayName."#";
1267 //$arr["verb"] = $single_conv->object->verb;
1269 $arr["location"] = $single_conv->object->location->displayName;
1270 $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 $copy_fields = array("owner-name", "owner-link", "owner-avatar", "author-name", "author-link", "author-avatar",
1282 "gravity", "body", "object-type", "object", "verb", "created", "edited", "coord", "tag",
1283 "title", "attach", "app", "type", "location", "contact-id", "uri");
1284 foreach ($copy_fields AS $field)
1285 if (isset($item[$field]))
1286 $arr[$field] = $item[$field];
1290 $newitem = item_store($arr);
1292 logger("Item wasn't stored ".print_r($arr, true), LOGGER_DEBUG);
1296 if (isset($item["uri"]) AND ($item["uri"] == $arr["uri"])) {
1298 $item_stored = $newitem;
1301 logger('Stored new item '.$plink.' for parent '.$arr["parent-uri"].' under id '.$newitem, LOGGER_DEBUG);
1303 // Add the conversation entry (but don't fetch the whole conversation)
1304 self::store_conversation($newitem, $conversation_url);
1306 // If the newly created item is the top item then change the parent settings of the thread
1307 // This shouldn't happen anymore. This is supposed to be absolote.
1308 if ($arr["uri"] == $first_id) {
1309 logger('setting new parent to id '.$newitem);
1310 $new_parents = q("SELECT `id`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
1311 intval($uid), intval($newitem));
1313 $parent = $new_parents[0];
1317 if (($item_stored < 0) AND (count($item) > 0)) {
1319 if (get_config('system','ostatus_full_threads')) {
1320 $details = self::get_actor_details($item["owner-link"], $uid, $item["contact-id"]);
1321 if ($details["not_following"]) {
1322 logger("Don't import uri ".$item["uri"]." because user ".$uid." doesn't follow the person ".$item["owner-link"], LOGGER_DEBUG);
1327 $item_stored = item_store($item, $all_threads);
1329 logger("Uri ".$item["uri"]." wasn't found in conversation ".$conversation_url, LOGGER_DEBUG);
1330 self::store_conversation($item_stored, $conversation_url);
1334 return($item_stored);
1338 * @brief Stores conversation data into the database
1340 * @param integer $itemid The id of the item
1341 * @param string $conversation_url The uri of the conversation
1343 private function store_conversation($itemid, $conversation_url) {
1345 $conversation_url = self::convert_href($conversation_url);
1347 $messages = q("SELECT `uid`, `parent`, `created`, `received`, `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($itemid));
1350 $message = $messages[0];
1352 // Store conversation url if not done before
1353 $conversation = q("SELECT `url` FROM `term` WHERE `uid` = %d AND `oid` = %d AND `otype` = %d AND `type` = %d",
1354 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION));
1356 if (!$conversation) {
1357 $r = q("INSERT INTO `term` (`uid`, `oid`, `otype`, `type`, `term`, `url`, `created`, `received`, `guid`) VALUES (%d, %d, %d, %d, '%s', '%s', '%s', '%s', '%s')",
1358 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION),
1359 dbesc($message["created"]), dbesc($conversation_url), dbesc($message["created"]), dbesc($message["received"]), dbesc($message["guid"]));
1360 logger('Storing conversation url '.$conversation_url.' for id '.$itemid);
1365 * @brief Checks if the current post is a reshare
1367 * @param array $item The item array of thw post
1369 * @return string The guid if the post is a reshare
1371 private function get_reshared_guid($item) {
1372 $body = trim($item["body"]);
1374 // Skip if it isn't a pure repeated messages
1375 // Does it start with a share?
1376 if (strpos($body, "[share") > 0)
1379 // Does it end with a share?
1380 if (strlen($body) > (strrpos($body, "[/share]") + 8))
1383 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
1384 // Skip if there is no shared message in there
1385 if ($body == $attributes)
1389 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1390 if ($matches[1] != "")
1391 $guid = $matches[1];
1393 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1394 if ($matches[1] != "")
1395 $guid = $matches[1];
1401 * @brief Cleans the body of a post if it contains picture links
1403 * @param string $body The body
1405 * @return string The cleaned body
1407 private function format_picture_post($body) {
1408 $siteinfo = get_attached_data($body);
1410 if (($siteinfo["type"] == "photo")) {
1411 if (isset($siteinfo["preview"]))
1412 $preview = $siteinfo["preview"];
1414 $preview = $siteinfo["image"];
1416 // Is it a remote picture? Then make a smaller preview here
1417 $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
1419 // Is it a local picture? Then make it smaller here
1420 $preview = str_replace(array("-0.jpg", "-0.png"), array("-2.jpg", "-2.png"), $preview);
1421 $preview = str_replace(array("-1.jpg", "-1.png"), array("-2.jpg", "-2.png"), $preview);
1423 if (isset($siteinfo["url"]))
1424 $url = $siteinfo["url"];
1426 $url = $siteinfo["image"];
1428 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1435 * @brief Adds the header elements to the XML document
1437 * @param object $doc XML document
1438 * @param array $owner Contact data of the poster
1440 * @return object header root element
1442 private function add_header($doc, $owner) {
1446 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1447 $doc->appendChild($root);
1449 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1450 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1451 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1452 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1453 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1454 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1455 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1456 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1458 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
1459 xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1460 xml::add_element($doc, $root, "id", App::get_baseurl()."/profile/".$owner["nick"]);
1461 xml::add_element($doc, $root, "title", sprintf("%s timeline", $owner["name"]));
1462 xml::add_element($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
1463 xml::add_element($doc, $root, "logo", $owner["photo"]);
1464 xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
1466 $author = self::add_author($doc, $owner);
1467 $root->appendChild($author);
1469 $attributes = array("href" => $owner["url"], "rel" => "alternate", "type" => "text/html");
1470 xml::add_element($doc, $root, "link", "", $attributes);
1472 /// @TODO We have to find out what this is
1473 /// $attributes = array("href" => App::get_baseurl()."/sup",
1474 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1475 /// "type" => "application/json");
1476 /// xml::add_element($doc, $root, "link", "", $attributes);
1478 self::hublinks($doc, $root);
1480 $attributes = array("href" => App::get_baseurl()."/salmon/".$owner["nick"], "rel" => "salmon");
1481 xml::add_element($doc, $root, "link", "", $attributes);
1483 $attributes = array("href" => App::get_baseurl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies");
1484 xml::add_element($doc, $root, "link", "", $attributes);
1486 $attributes = array("href" => App::get_baseurl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention");
1487 xml::add_element($doc, $root, "link", "", $attributes);
1489 $attributes = array("href" => App::get_baseurl()."/api/statuses/user_timeline/".$owner["nick"].".atom",
1490 "rel" => "self", "type" => "application/atom+xml");
1491 xml::add_element($doc, $root, "link", "", $attributes);
1497 * @brief Add the link to the push hubs to the XML document
1499 * @param object $doc XML document
1500 * @param object $root XML root element where the hub links are added
1502 public static function hublinks($doc, $root) {
1503 $hub = get_config('system','huburl');
1507 $hubs = explode(',', $hub);
1509 foreach($hubs as $h) {
1513 if ($h === '[internal]')
1514 $h = App::get_baseurl() . '/pubsubhubbub';
1515 xml::add_element($doc, $root, "link", "", array("href" => $h, "rel" => "hub"));
1522 * @brief Adds attachement data to the XML document
1524 * @param object $doc XML document
1525 * @param object $root XML root element where the hub links are added
1526 * @param array $item Data of the item that is to be posted
1528 private function get_attachment($doc, $root, $item) {
1530 $siteinfo = get_attached_data($item["body"]);
1532 switch ($siteinfo["type"]) {
1534 $imgdata = get_photo_info($siteinfo["image"]);
1535 $attributes = array("rel" => "enclosure",
1536 "href" => $siteinfo["image"],
1537 "type" => $imgdata["mime"],
1538 "length" => intval($imgdata["size"]));
1539 xml::add_element($doc, $root, "link", "", $attributes);
1542 $attributes = array("rel" => "enclosure",
1543 "href" => $siteinfo["url"],
1544 "type" => "text/html; charset=UTF-8",
1546 "title" => $siteinfo["title"]);
1547 xml::add_element($doc, $root, "link", "", $attributes);
1553 if (($siteinfo["type"] != "photo") AND isset($siteinfo["image"])) {
1554 $imgdata = get_photo_info($siteinfo["image"]);
1555 $attributes = array("rel" => "enclosure",
1556 "href" => $siteinfo["image"],
1557 "type" => $imgdata["mime"],
1558 "length" => intval($imgdata["size"]));
1560 xml::add_element($doc, $root, "link", "", $attributes);
1563 $arr = explode('[/attach],', $item['attach']);
1565 foreach ($arr as $r) {
1567 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1569 $attributes = array("rel" => "enclosure",
1570 "href" => $matches[1],
1571 "type" => $matches[3]);
1573 if (intval($matches[2])) {
1574 $attributes["length"] = intval($matches[2]);
1576 if (trim($matches[4]) != "") {
1577 $attributes["title"] = trim($matches[4]);
1579 xml::add_element($doc, $root, "link", "", $attributes);
1586 * @brief Adds the author element to the XML document
1588 * @param object $doc XML document
1589 * @param array $owner Contact data of the poster
1591 * @return object author element
1593 private function add_author($doc, $owner) {
1595 $r = q("SELECT `homepage`, `publish` FROM `profile` WHERE `uid` = %d AND `is-default` LIMIT 1", intval($owner["uid"]));
1599 $author = $doc->createElement("author");
1600 xml::add_element($doc, $author, "id", $owner["url"]);
1601 xml::add_element($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1602 xml::add_element($doc, $author, "uri", $owner["url"]);
1603 xml::add_element($doc, $author, "name", $owner["nick"]);
1604 xml::add_element($doc, $author, "email", $owner["addr"]);
1605 xml::add_element($doc, $author, "summary", bbcode($owner["about"], false, false, 7));
1607 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $owner["url"]);
1608 xml::add_element($doc, $author, "link", "", $attributes);
1610 $attributes = array(
1612 "type" => "image/jpeg", // To-Do?
1613 "media:width" => 175,
1614 "media:height" => 175,
1615 "href" => $owner["photo"]);
1616 xml::add_element($doc, $author, "link", "", $attributes);
1618 if (isset($owner["thumb"])) {
1619 $attributes = array(
1621 "type" => "image/jpeg", // To-Do?
1622 "media:width" => 80,
1623 "media:height" => 80,
1624 "href" => $owner["thumb"]);
1625 xml::add_element($doc, $author, "link", "", $attributes);
1628 xml::add_element($doc, $author, "poco:preferredUsername", $owner["nick"]);
1629 xml::add_element($doc, $author, "poco:displayName", $owner["name"]);
1630 xml::add_element($doc, $author, "poco:note", bbcode($owner["about"], false, false, 7));
1632 if (trim($owner["location"]) != "") {
1633 $element = $doc->createElement("poco:address");
1634 xml::add_element($doc, $element, "poco:formatted", $owner["location"]);
1635 $author->appendChild($element);
1638 if (trim($profile["homepage"]) != "") {
1639 $urls = $doc->createElement("poco:urls");
1640 xml::add_element($doc, $urls, "poco:type", "homepage");
1641 xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
1642 xml::add_element($doc, $urls, "poco:primary", "true");
1643 $author->appendChild($urls);
1646 if (count($profile)) {
1647 xml::add_element($doc, $author, "followers", "", array("url" => App::get_baseurl()."/viewcontacts/".$owner["nick"]));
1648 xml::add_element($doc, $author, "statusnet:profile_info", "", array("local_id" => $owner["uid"]));
1651 if ($profile["publish"]) {
1652 xml::add_element($doc, $author, "mastodon:scope", "public");
1658 * @TODO Picture attachments should look like this:
1659 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1660 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1665 * @brief Returns the given activity if present - otherwise returns the "post" activity
1667 * @param array $item Data of the item that is to be posted
1669 * @return string activity
1671 function construct_verb($item) {
1673 return $item['verb'];
1674 return ACTIVITY_POST;
1678 * @brief Returns the given object type if present - otherwise returns the "note" object type
1680 * @param array $item Data of the item that is to be posted
1682 * @return string Object type
1684 function construct_objecttype($item) {
1685 if (in_array($item['object-type'], array(ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT)))
1686 return $item['object-type'];
1687 return ACTIVITY_OBJ_NOTE;
1691 * @brief Adds an entry element to the XML document
1693 * @param object $doc XML document
1694 * @param array $item Data of the item that is to be posted
1695 * @param array $owner Contact data of the poster
1696 * @param bool $toplevel
1698 * @return object Entry element
1700 private function entry($doc, $item, $owner, $toplevel = false) {
1701 $repeated_guid = self::get_reshared_guid($item);
1702 if ($repeated_guid != "")
1703 $xml = self::reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel);
1708 if ($item["verb"] == ACTIVITY_LIKE) {
1709 return self::like_entry($doc, $item, $owner, $toplevel);
1710 } elseif (in_array($item["verb"], array(ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"))) {
1711 return self::follow_entry($doc, $item, $owner, $toplevel);
1713 return self::note_entry($doc, $item, $owner, $toplevel);
1718 * @brief Adds a source entry to the XML document
1720 * @param object $doc XML document
1721 * @param array $contact Array of the contact that is added
1723 * @return object Source element
1725 private function source_entry($doc, $contact) {
1726 $source = $doc->createElement("source");
1727 xml::add_element($doc, $source, "id", $contact["poll"]);
1728 xml::add_element($doc, $source, "title", $contact["name"]);
1729 xml::add_element($doc, $source, "link", "", array("rel" => "alternate",
1730 "type" => "text/html",
1731 "href" => $contact["alias"]));
1732 xml::add_element($doc, $source, "link", "", array("rel" => "self",
1733 "type" => "application/atom+xml",
1734 "href" => $contact["poll"]));
1735 xml::add_element($doc, $source, "icon", $contact["photo"]);
1736 xml::add_element($doc, $source, "updated", datetime_convert("UTC","UTC",$contact["success_update"]."+00:00",ATOM_TIME));
1742 * @brief Fetches contact data from the contact or the gcontact table
1744 * @param string $url URL of the contact
1745 * @param array $owner Contact data of the poster
1747 * @return array Contact array
1749 private function contact_entry($url, $owner) {
1751 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1752 dbesc(normalise_link($url)), intval($owner["uid"]));
1755 $contact["uid"] = -1;
1759 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1760 dbesc(normalise_link($url)));
1763 $contact["uid"] = -1;
1764 $contact["success_update"] = $contact["updated"];
1771 if (!isset($contact["poll"])) {
1772 $data = probe_url($url);
1773 $contact["poll"] = $data["poll"];
1775 if (!$contact["alias"])
1776 $contact["alias"] = $data["alias"];
1779 if (!isset($contact["alias"]))
1780 $contact["alias"] = $contact["url"];
1786 * @brief Adds an entry element with reshared content
1788 * @param object $doc XML document
1789 * @param array $item Data of the item that is to be posted
1790 * @param array $owner Contact data of the poster
1791 * @param $repeated_guid
1792 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1794 * @return object Entry element
1796 private function reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel) {
1798 if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1799 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1802 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1804 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' AND NOT `private` AND `network` IN ('%s', '%s', '%s') LIMIT 1",
1805 intval($owner["uid"]), dbesc($repeated_guid),
1806 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS));
1808 $repeated_item = $r[0];
1812 $contact = self::contact_entry($repeated_item['author-link'], $owner);
1814 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1816 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1818 self::entry_content($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1820 $as_object = $doc->createElement("activity:object");
1822 xml::add_element($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1824 self::entry_content($doc, $as_object, $repeated_item, $owner, "", "", false);
1826 $author = self::add_author($doc, $contact);
1827 $as_object->appendChild($author);
1829 $as_object2 = $doc->createElement("activity:object");
1831 xml::add_element($doc, $as_object2, "activity:object-type", self::construct_objecttype($repeated_item));
1833 $title = sprintf("New comment by %s", $contact["nick"]);
1835 self::entry_content($doc, $as_object2, $repeated_item, $owner, $title);
1837 $as_object->appendChild($as_object2);
1839 self::entry_footer($doc, $as_object, $item, $owner, false);
1841 $source = self::source_entry($doc, $contact);
1843 $as_object->appendChild($source);
1845 $entry->appendChild($as_object);
1847 self::entry_footer($doc, $entry, $item, $owner);
1853 * @brief Adds an entry element with a "like"
1855 * @param object $doc XML document
1856 * @param array $item Data of the item that is to be posted
1857 * @param array $owner Contact data of the poster
1858 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1860 * @return object Entry element with "like"
1862 private function like_entry($doc, $item, $owner, $toplevel) {
1864 if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1865 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1868 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1870 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1871 self::entry_content($doc, $entry, $item, $owner, "Favorite", $verb, false);
1873 $as_object = $doc->createElement("activity:object");
1875 $parent = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
1876 dbesc($item["thr-parent"]), intval($item["uid"]));
1877 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1879 xml::add_element($doc, $as_object, "activity:object-type", self::construct_objecttype($parent[0]));
1881 self::entry_content($doc, $as_object, $parent[0], $owner, "New entry");
1883 $entry->appendChild($as_object);
1885 self::entry_footer($doc, $entry, $item, $owner);
1891 * @brief Adds the person object element to the XML document
1893 * @param object $doc XML document
1894 * @param array $owner Contact data of the poster
1895 * @param array $contact Contact data of the target
1897 * @return object author element
1899 private function add_person_object($doc, $owner, $contact) {
1901 $object = $doc->createElement("activity:object");
1902 xml::add_element($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1904 if ($contact['network'] == NETWORK_PHANTOM) {
1905 xml::add_element($doc, $object, "id", $contact['url']);
1909 xml::add_element($doc, $object, "id", $contact["alias"]);
1910 xml::add_element($doc, $object, "title", $contact["nick"]);
1912 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $contact["url"]);
1913 xml::add_element($doc, $object, "link", "", $attributes);
1915 $attributes = array(
1917 "type" => "image/jpeg", // To-Do?
1918 "media:width" => 175,
1919 "media:height" => 175,
1920 "href" => $contact["photo"]);
1921 xml::add_element($doc, $object, "link", "", $attributes);
1923 xml::add_element($doc, $object, "poco:preferredUsername", $contact["nick"]);
1924 xml::add_element($doc, $object, "poco:displayName", $contact["name"]);
1926 if (trim($contact["location"]) != "") {
1927 $element = $doc->createElement("poco:address");
1928 xml::add_element($doc, $element, "poco:formatted", $contact["location"]);
1929 $object->appendChild($element);
1936 * @brief Adds a follow/unfollow entry element
1938 * @param object $doc XML document
1939 * @param array $item Data of the follow/unfollow message
1940 * @param array $owner Contact data of the poster
1941 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1943 * @return object Entry element
1945 private function follow_entry($doc, $item, $owner, $toplevel) {
1947 $item["id"] = $item["parent"] = 0;
1948 $item["created"] = $item["edited"] = date("c");
1949 $item["private"] = true;
1951 $contact = Probe::uri($item['follow']);
1953 if ($contact['alias'] == '') {
1954 $contact['alias'] = $contact["url"];
1956 $item['follow'] = $contact['alias'];
1959 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1960 intval($owner['uid']), dbesc(normalise_link($contact["url"])));
1962 if (dbm::is_result($r)) {
1963 $connect_id = $r[0]['id'];
1968 if ($item['verb'] == ACTIVITY_FOLLOW) {
1969 $message = t('%s is now following %s.');
1970 $title = t('following');
1971 $action = "subscription";
1973 $message = t('%s stopped following %s.');
1974 $title = t('stopped following');
1975 $action = "unfollow";
1978 $item["uri"] = $item['parent-uri'] = $item['thr-parent'] =
1979 'tag:'.get_app()->get_hostname().
1980 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1981 ':person:'.$connect_id.':'.$item['created'];
1983 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1985 self::entry_header($doc, $entry, $owner, $toplevel);
1987 self::entry_content($doc, $entry, $item, $owner, $title);
1989 $object = self::add_person_object($doc, $owner, $contact);
1990 $entry->appendChild($object);
1992 self::entry_footer($doc, $entry, $item, $owner);
1998 * @brief Adds a regular entry element
2000 * @param object $doc XML document
2001 * @param array $item Data of the item that is to be posted
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 object Entry element
2007 private function note_entry($doc, $item, $owner, $toplevel) {
2009 if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
2010 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
2013 $title = self::entry_header($doc, $entry, $owner, $toplevel);
2015 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
2017 self::entry_content($doc, $entry, $item, $owner, $title);
2019 self::entry_footer($doc, $entry, $item, $owner);
2025 * @brief Adds a header element to the XML document
2027 * @param object $doc XML document
2028 * @param object $entry The entry element where the elements are added
2029 * @param array $owner Contact data of the poster
2030 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
2032 * @return string The title for the element
2034 private function entry_header($doc, &$entry, $owner, $toplevel) {
2035 /// @todo Check if this title stuff is really needed (I guess not)
2037 $entry = $doc->createElement("entry");
2038 $title = sprintf("New note by %s", $owner["nick"]);
2040 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
2042 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
2043 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
2044 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
2045 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
2046 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
2047 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
2048 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
2049 $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
2051 $author = self::add_author($doc, $owner);
2052 $entry->appendChild($author);
2054 $title = sprintf("New comment by %s", $owner["nick"]);
2060 * @brief Adds elements to the XML document
2062 * @param object $doc XML document
2063 * @param object $entry Entry element where the content is added
2064 * @param array $item Data of the item that is to be posted
2065 * @param array $owner Contact data of the poster
2066 * @param string $title Title for the post
2067 * @param string $verb The activity verb
2068 * @param bool $complete Add the "status_net" element?
2070 private function entry_content($doc, $entry, $item, $owner, $title, $verb = "", $complete = true) {
2073 $verb = self::construct_verb($item);
2075 xml::add_element($doc, $entry, "id", $item["uri"]);
2076 xml::add_element($doc, $entry, "title", $title);
2078 $body = self::format_picture_post($item['body']);
2080 if ($item['title'] != "")
2081 $body = "[b]".$item['title']."[/b]\n\n".$body;
2083 $body = bbcode($body, false, false, 7);
2085 xml::add_element($doc, $entry, "content", $body, array("type" => "html"));
2087 xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
2088 "href" => App::get_baseurl()."/display/".$item["guid"]));
2090 if ($complete AND ($item["id"] > 0))
2091 xml::add_element($doc, $entry, "status_net", "", array("notice_id" => $item["id"]));
2093 xml::add_element($doc, $entry, "activity:verb", $verb);
2095 xml::add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
2096 xml::add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
2100 * @brief Adds the elements at the foot of an entry to the XML document
2102 * @param object $doc XML document
2103 * @param object $entry The entry element where the elements are added
2104 * @param array $item Data of the item that is to be posted
2105 * @param array $owner Contact data of the poster
2108 private function entry_footer($doc, $entry, $item, $owner, $complete = true) {
2110 $mentioned = array();
2112 if (($item['parent'] != $item['id']) OR ($item['parent-uri'] !== $item['uri']) OR (($item['thr-parent'] !== '') AND ($item['thr-parent'] !== $item['uri']))) {
2113 $parent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `id` = %d", intval($item["parent"]));
2114 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
2116 $thrparent = q("SELECT `guid`, `author-link`, `owner-link`, `plink` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
2117 intval($owner["uid"]),
2118 dbesc($parent_item));
2120 $mentioned[$thrparent[0]["author-link"]] = $thrparent[0]["author-link"];
2121 $mentioned[$thrparent[0]["owner-link"]] = $thrparent[0]["owner-link"];
2122 $parent_plink = $thrparent[0]["plink"];
2124 $mentioned[$parent[0]["author-link"]] = $parent[0]["author-link"];
2125 $mentioned[$parent[0]["owner-link"]] = $parent[0]["owner-link"];
2126 $parent_plink = App::get_baseurl()."/display/".$parent[0]["guid"];
2129 $attributes = array(
2130 "ref" => $parent_item,
2131 "href" => $parent_plink);
2132 xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
2134 $attributes = array(
2136 "href" => $parent_plink);
2137 xml::add_element($doc, $entry, "link", "", $attributes);
2140 if (intval($item["parent"]) > 0) {
2141 $conversation_href = App::get_baseurl()."/display/".$owner["nick"]."/".$item["parent"];
2142 $conversation_uri = $conversation_href;
2144 if (isset($parent_item)) {
2145 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $parent_item);
2146 if (dbm::is_result($r)) {
2147 if ($r['conversation-uri'] != '') {
2148 $conversation_uri = $r['conversation-uri'];
2150 if ($r['conversation-href'] != '') {
2151 $conversation_href = $r['conversation-href'];
2156 xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:conversation", "href" => $conversation_href));
2158 $attributes = array(
2159 "href" => $conversation_href,
2160 "local_id" => $item["parent"],
2161 "ref" => $conversation_uri);
2163 xml::add_element($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
2166 $tags = item_getfeedtags($item);
2169 foreach($tags as $t)
2171 $mentioned[$t[1]] = $t[1];
2173 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2174 $newmentions = array();
2175 foreach ($mentioned AS $mention) {
2176 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2177 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2179 $mentioned = $newmentions;
2181 foreach ($mentioned AS $mention) {
2182 $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
2183 intval($owner["uid"]),
2184 dbesc(normalise_link($mention)));
2185 if ($r[0]["forum"] OR $r[0]["prv"])
2186 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2187 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
2188 "href" => $mention));
2190 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2191 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
2192 "href" => $mention));
2195 if (!$item["private"]) {
2196 xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:attention",
2197 "href" => "http://activityschema.org/collection/public"));
2198 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2199 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2200 "href" => "http://activityschema.org/collection/public"));
2201 xml::add_element($doc, $entry, "mastodon:scope", "public");
2205 foreach($tags as $t)
2207 xml::add_element($doc, $entry, "category", "", array("term" => $t[2]));
2209 self::get_attachment($doc, $entry, $item);
2211 if ($complete AND ($item["id"] > 0)) {
2212 $app = $item["app"];
2216 $attributes = array("local_id" => $item["id"], "source" => $app);
2218 if (isset($parent["id"]))
2219 $attributes["repeat_of"] = $parent["id"];
2221 if ($item["coord"] != "")
2222 xml::add_element($doc, $entry, "georss:point", $item["coord"]);
2224 xml::add_element($doc, $entry, "statusnet:notice_info", "", $attributes);
2229 * @brief Creates the XML feed for a given nickname
2231 * @param app $a The application class
2232 * @param string $owner_nick Nickname of the feed owner
2233 * @param string $last_update Date of the last update
2235 * @return string XML feed
2237 public static function feed(App $a, $owner_nick, $last_update) {
2239 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
2240 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
2241 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
2242 dbesc($owner_nick));
2248 if(!strlen($last_update))
2249 $last_update = 'now -30 days';
2251 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
2252 $authorid = get_contact($owner["url"], 0);
2254 $items = q("SELECT `item`.*, `item`.`id` AS `item_id` FROM `item` USE INDEX (`uid_contactid_created`)
2255 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2256 WHERE `item`.`uid` = %d AND `item`.`contact-id` = %d AND
2257 `item`.`author-id` = %d AND `item`.`created` > '%s' AND
2258 NOT `item`.`deleted` AND NOT `item`.`private` AND
2259 `thread`.`network` IN ('%s', '%s')
2260 ORDER BY `item`.`created` DESC LIMIT 300",
2261 intval($owner["uid"]), intval($owner["id"]),
2262 intval($authorid), dbesc($check_date),
2263 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
2265 /* 2016-10-23: The old query will be kept until we are sure that the query above is a good and fast replacement
2267 $items = q("SELECT `item`.*, `item`.`id` AS `item_id` FROM `item`
2268 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2269 LEFT JOIN `item` AS `thritem` ON `thritem`.`uri`=`item`.`thr-parent` AND `thritem`.`uid`=`item`.`uid`
2270 WHERE `item`.`uid` = %d AND `item`.`received` > '%s' AND NOT `item`.`private` AND NOT `item`.`deleted`
2271 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
2272 AND ((`item`.`wall` AND (`item`.`parent` = `item`.`id`))
2273 OR (`item`.`network` = '%s' AND ((`thread`.`network` IN ('%s', '%s')) OR (`thritem`.`network` IN ('%s', '%s')))) AND `thread`.`mention`)
2274 AND ((`item`.`owner-link` IN ('%s', '%s') AND (`item`.`parent` = `item`.`id`))
2275 OR (`item`.`author-link` IN ('%s', '%s')))
2276 ORDER BY `item`.`id` DESC
2278 intval($owner["uid"]), dbesc($check_date), dbesc(NETWORK_DFRN),
2279 //dbesc(NETWORK_OSTATUS), dbesc(NETWORK_OSTATUS),
2280 //dbesc(NETWORK_OSTATUS), dbesc(NETWORK_OSTATUS),
2281 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN),
2282 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN),
2283 dbesc($owner["nurl"]), dbesc(str_replace("http://", "https://", $owner["nurl"])),
2284 dbesc($owner["nurl"]), dbesc(str_replace("http://", "https://", $owner["nurl"]))
2287 $doc = new DOMDocument('1.0', 'utf-8');
2288 $doc->formatOutput = true;
2290 $root = self::add_header($doc, $owner);
2292 foreach ($items AS $item) {
2293 if (Config::get('system', 'ostatus_debug')) {
2294 $item['body'] .= '🍼';
2296 $entry = self::entry($doc, $item, $owner);
2297 $root->appendChild($entry);
2300 return(trim($doc->saveXML()));
2304 * @brief Creates the XML for a salmon message
2306 * @param array $item Data of the item that is to be posted
2307 * @param array $owner Contact data of the poster
2309 * @return string XML for the salmon
2311 public static function salmon($item,$owner) {
2313 $doc = new DOMDocument('1.0', 'utf-8');
2314 $doc->formatOutput = true;
2316 if (Config::get('system', 'ostatus_debug')) {
2317 $item['body'] .= '🐟';
2320 $entry = self::entry($doc, $item, $owner, true);
2322 $doc->appendChild($entry);
2324 return(trim($doc->saveXML()));