2 require_once("include/Contact.php");
3 require_once("include/threads.php");
4 require_once("include/html2bbcode.php");
5 require_once("include/bbcode.php");
6 require_once("include/items.php");
7 require_once("mod/share.php");
8 require_once("include/enotify.php");
9 require_once("include/socgraph.php");
10 require_once("include/Photo.php");
11 require_once("include/Scrape.php");
12 require_once("include/follow.php");
13 require_once("include/api.php");
14 require_once("mod/proxy.php");
15 require_once("include/xml.php");
18 const OSTATUS_DEFAULT_POLL_INTERVAL = 30; // given in minutes
19 const OSTATUS_DEFAULT_POLL_TIMEFRAME = 1440; // given in minutes
20 const OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS = 14400; // given in minutes
22 private function fetchauthor($xpath, $context, $importer, &$contact, $onlyfetch) {
25 $author["author-link"] = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
26 $author["author-name"] = $xpath->evaluate('atom:author/atom:name/text()', $context)->item(0)->nodeValue;
29 $authorlink = $author["author-link"];
31 $alternate = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0)->attributes;
32 if (is_object($alternate))
33 foreach($alternate AS $attributes)
34 if ($attributes->name == "href")
35 $author["author-link"] = $attributes->textContent;
37 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` IN ('%s', '%s') AND `network` != '%s'",
38 intval($importer["uid"]), dbesc(normalise_link($author["author-link"])),
39 dbesc(normalise_link($authorlink)), dbesc(NETWORK_STATUSNET));
42 $author["contact-id"] = $r[0]["id"];
44 $author["contact-id"] = $contact["id"];
46 $avatarlist = array();
47 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
48 foreach($avatars AS $avatar) {
51 foreach($avatar->attributes AS $attributes) {
52 if ($attributes->name == "href")
53 $href = $attributes->textContent;
54 if ($attributes->name == "width")
55 $width = $attributes->textContent;
57 if (($width > 0) AND ($href != ""))
58 $avatarlist[$width] = $href;
60 if (count($avatarlist) > 0) {
62 $author["author-avatar"] = current($avatarlist);
65 $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
66 if ($displayname != "")
67 $author["author-name"] = $displayname;
69 $author["owner-name"] = $author["author-name"];
70 $author["owner-link"] = $author["author-link"];
71 $author["owner-avatar"] = $author["author-avatar"];
73 // Only update the contacts if it is an OStatus contact
74 if ($r AND !$onlyfetch AND ($contact["network"] == NETWORK_OSTATUS)) {
75 // Update contact data
77 $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
79 $contact["notify"] = $value;
81 $value = $xpath->evaluate('atom:author/uri/text()', $context)->item(0)->nodeValue;
83 $contact["alias"] = $value;
85 $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
87 $contact["name"] = $value;
89 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
91 $contact["nick"] = $value;
93 $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
95 $contact["about"] = html2bbcode($value);
97 $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
99 $contact["location"] = $value;
101 if (($contact["name"] != $r[0]["name"]) OR ($contact["nick"] != $r[0]["nick"]) OR ($contact["about"] != $r[0]["about"]) OR ($contact["location"] != $r[0]["location"])) {
103 logger("Update contact data for contact ".$contact["id"], LOGGER_DEBUG);
105 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s', `name-date` = '%s' WHERE `id` = %d",
106 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
107 dbesc(datetime_convert()), intval($contact["id"]));
109 poco_check($contact["url"], $contact["name"], $contact["network"], $author["author-avatar"], $contact["about"], $contact["location"],
110 "", "", "", datetime_convert(), 2, $contact["id"], $contact["uid"]);
113 if (isset($author["author-avatar"]) AND ($author["author-avatar"] != $r[0]['avatar'])) {
114 logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
116 update_contact_avatar($author["author-avatar"], $importer["uid"], $contact["id"]);
119 $contact["generation"] = 2;
120 $contact["photo"] = $author["author-avatar"];
121 update_gcontact($contact);
127 public static function salmon_author($xml, $importer) {
132 $doc = new DOMDocument();
133 @$doc->loadXML($xml);
135 $xpath = new DomXPath($doc);
136 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
137 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
138 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
139 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
140 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
141 $xpath->registerNamespace('poco', NAMESPACE_POCO);
142 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
143 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
145 $entries = $xpath->query('/atom:entry');
147 foreach ($entries AS $entry) {
149 $author = self::fetchauthor($xpath, $entry, $importer, $contact, true);
154 public static function import($xml,$importer,&$contact, &$hub) {
156 logger("Import OStatus message", LOGGER_DEBUG);
161 //$tempfile = tempnam(get_temppath(), "import");
162 //file_put_contents($tempfile, $xml);
164 $doc = new DOMDocument();
165 @$doc->loadXML($xml);
167 $xpath = new DomXPath($doc);
168 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
169 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
170 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
171 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
172 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
173 $xpath->registerNamespace('poco', NAMESPACE_POCO);
174 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
175 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
178 $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
179 if (is_object($hub_attributes))
180 foreach($hub_attributes AS $hub_attribute)
181 if ($hub_attribute->name == "href") {
182 $hub = $hub_attribute->textContent;
183 logger("Found hub ".$hub, LOGGER_DEBUG);
187 $header["uid"] = $importer["uid"];
188 $header["network"] = NETWORK_OSTATUS;
189 $header["type"] = "remote";
191 $header["origin"] = 0;
192 $header["gravity"] = GRAVITY_PARENT;
194 // it could either be a received post or a post we fetched by ourselves
195 // depending on that, the first node is different
196 $first_child = $doc->firstChild->tagName;
198 if ($first_child == "feed")
199 $entries = $xpath->query('/atom:feed/atom:entry');
201 $entries = $xpath->query('/atom:entry');
204 $conversationlist = array();
207 // Reverse the order of the entries
208 $entrylist = array();
210 foreach ($entries AS $entry)
211 $entrylist[] = $entry;
213 foreach (array_reverse($entrylist) AS $entry) {
218 if ($first_child == "feed")
219 $author = self::fetchauthor($xpath, $doc->firstChild, $importer, $contact, false);
221 $author = self::fetchauthor($xpath, $entry, $importer, $contact, false);
223 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
227 $nickname = $author["author-name"];
229 $item = array_merge($header, $author);
232 $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
234 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
235 intval($importer["uid"]), dbesc($item["uri"]));
237 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already existed under id ".$r[0]["id"], LOGGER_DEBUG);
241 $item["body"] = add_page_info_to_body(html2bbcode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue));
242 $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
244 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) OR ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
245 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
246 $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
247 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION)
248 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
250 $item["object"] = $xml;
251 $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
255 if ($item["verb"] == "qvitter-delete-notice") {
256 // ignore "Delete" messages (by now)
257 logger("Ignore delete message ".print_r($item, true));
261 if ($item["verb"] == ACTIVITY_JOIN) {
262 // ignore "Join" messages
263 logger("Ignore join message ".print_r($item, true));
267 if ($item["verb"] == ACTIVITY_FOLLOW) {
268 new_follower($importer, $contact, $item, $nickname);
272 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
273 lose_follower($importer, $contact, $item, $dummy);
277 if ($item["verb"] == ACTIVITY_FAVORITE) {
278 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
279 logger("Favorite ".$orig_uri." ".print_r($item, true));
281 $item["verb"] = ACTIVITY_LIKE;
282 $item["parent-uri"] = $orig_uri;
283 $item["gravity"] = GRAVITY_LIKE;
286 if ($item["verb"] == NAMESPACE_OSTATUS."/unfavorite") {
287 // Ignore "Unfavorite" message
288 logger("Ignore unfavorite message ".print_r($item, true));
292 // http://activitystrea.ms/schema/1.0/rsvp-yes
293 if (!in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE)))
294 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true));
296 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
297 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
298 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
302 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
303 if (is_object($inreplyto->item(0))) {
304 foreach($inreplyto->item(0)->attributes AS $attributes) {
305 if ($attributes->name == "ref")
306 $item["parent-uri"] = $attributes->textContent;
307 if ($attributes->name == "href")
308 $related = $attributes->textContent;
312 $georsspoint = $xpath->query('georss:point', $entry);
314 $item["coord"] = $georsspoint->item(0)->nodeValue;
316 $categories = $xpath->query('atom:category', $entry);
318 foreach ($categories AS $category) {
319 foreach($category->attributes AS $attributes)
320 if ($attributes->name == "term") {
321 $term = $attributes->textContent;
322 if(strlen($item["tag"]))
324 $item["tag"] .= "#[url=".App::get_baseurl()."/search?tag=".$term."]".$term."[/url]";
332 $links = $xpath->query('atom:link', $entry);
339 foreach ($links AS $link) {
340 foreach($link->attributes AS $attributes) {
341 if ($attributes->name == "href")
342 $href = $attributes->textContent;
343 if ($attributes->name == "rel")
344 $rel = $attributes->textContent;
345 if ($attributes->name == "type")
346 $type = $attributes->textContent;
347 if ($attributes->name == "length")
348 $length = $attributes->textContent;
349 if ($attributes->name == "title")
350 $title = $attributes->textContent;
352 if (($rel != "") AND ($href != ""))
355 $item["plink"] = $href;
356 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION) OR
357 ($item["object-type"] == ACTIVITY_OBJ_EVENT))
358 $item["body"] .= add_page_info($href);
360 case "ostatus:conversation":
361 $conversation = $href;
365 if(strlen($item["attach"]))
366 $item["attach"] .= ',';
368 $item["attach"] .= '[attach]href="'.$href.'" length="'.$length.'" type="'.$type.'" title="'.$title.'"[/attach]';
371 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
372 if (!isset($item["parent-uri"]))
373 $item["parent-uri"] = $href;
378 $item["body"] .= add_page_info($href);
384 // Notification check
385 if ($importer["nurl"] == normalise_link($href))
395 $notice_info = $xpath->query('statusnet:notice_info', $entry);
396 if ($notice_info AND ($notice_info->length > 0)) {
397 foreach($notice_info->item(0)->attributes AS $attributes) {
398 if ($attributes->name == "source")
399 $item["app"] = strip_tags($attributes->textContent);
400 if ($attributes->name == "local_id")
401 $local_id = $attributes->textContent;
402 if ($attributes->name == "repeat_of")
403 $repeat_of = $attributes->textContent;
407 // Is it a repeated post?
408 if ($repeat_of != "") {
409 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
411 if (is_object($activityobjects)) {
413 $orig_uri = $xpath->query("activity:object/atom:id", $activityobjects)->item(0)->nodeValue;
414 if (!isset($orig_uri))
415 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
417 $orig_links = $xpath->query("activity:object/atom:link[@rel='alternate']", $activityobjects);
418 if ($orig_links AND ($orig_links->length > 0))
419 foreach($orig_links->item(0)->attributes AS $attributes)
420 if ($attributes->name == "href")
421 $orig_link = $attributes->textContent;
423 if (!isset($orig_link))
424 $orig_link = $xpath->query("atom:link[@rel='alternate']", $activityobjects)->item(0)->nodeValue;
426 if (!isset($orig_link))
427 $orig_link = self::convert_href($orig_uri);
429 $orig_body = $xpath->query('activity:object/atom:content/text()', $activityobjects)->item(0)->nodeValue;
430 if (!isset($orig_body))
431 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
433 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
435 $orig_contact = $contact;
436 $orig_author = self::fetchauthor($xpath, $activityobjects, $importer, $orig_contact, false);
438 $item["author-name"] = $orig_author["author-name"];
439 $item["author-link"] = $orig_author["author-link"];
440 $item["author-avatar"] = $orig_author["author-avatar"];
441 $item["body"] = add_page_info_to_body(html2bbcode($orig_body));
442 $item["created"] = $orig_created;
444 $item["uri"] = $orig_uri;
445 $item["plink"] = $orig_link;
447 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
449 $item["object-type"] = $xpath->query('activity:object/activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
450 if (!isset($item["object-type"]))
451 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
455 //if ($enclosure != "")
456 // $item["body"] .= add_page_info($enclosure);
458 if (isset($item["parent-uri"])) {
459 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
460 intval($importer["uid"]), dbesc($item["parent-uri"]));
462 if (!$r AND ($related != "")) {
463 $reply_path = str_replace("/notice/", "/api/statuses/show/", $related).".atom";
465 if ($reply_path != $related) {
466 logger("Fetching related items for user ".$importer["uid"]." from ".$reply_path, LOGGER_DEBUG);
467 $reply_xml = fetch_url($reply_path);
469 $reply_contact = $contact;
470 self::import($reply_xml,$importer,$reply_contact, $reply_hub);
472 // After the import try to fetch the parent item again
473 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
474 intval($importer["uid"]), dbesc($item["parent-uri"]));
478 $item["type"] = 'remote-comment';
479 $item["gravity"] = GRAVITY_COMMENT;
482 $item["parent-uri"] = $item["uri"];
484 $item_id = self::completion($conversation, $importer["uid"], $item, $self);
487 logger("Error storing item", LOGGER_DEBUG);
491 logger("Item was stored with id ".$item_id, LOGGER_DEBUG);
495 public static function convert_href($href) {
496 $elements = explode(":",$href);
498 if ((count($elements) <= 2) OR ($elements[0] != "tag"))
501 $server = explode(",", $elements[1]);
502 $conversation = explode("=", $elements[2]);
504 if ((count($elements) == 4) AND ($elements[2] == "post"))
505 return "http://".$server[0]."/notice/".$elements[3];
507 if ((count($conversation) != 2) OR ($conversation[1] ==""))
510 if ($elements[3] == "objectType=thread")
511 return "http://".$server[0]."/conversation/".$conversation[1];
513 return "http://".$server[0]."/notice/".$conversation[1];
518 public static function check_conversations($mentions = false, $override = false) {
519 $last = get_config('system','ostatus_last_poll');
521 $poll_interval = intval(get_config('system','ostatus_poll_interval'));
523 $poll_interval = OSTATUS_DEFAULT_POLL_INTERVAL;
525 // Don't poll if the interval is set negative
526 if (($poll_interval < 0) AND !$override)
530 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
531 if (!$poll_timeframe)
532 $poll_timeframe = OSTATUS_DEFAULT_POLL_TIMEFRAME;
534 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
535 if (!$poll_timeframe)
536 $poll_timeframe = OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS;
540 if ($last AND !$override) {
541 $next = $last + ($poll_interval * 60);
542 if ($next > time()) {
543 logger('poll interval not reached');
548 logger('cron_start');
550 $start = date("Y-m-d H:i:s", time() - ($poll_timeframe * 60));
553 $conversations = q("SELECT `term`.`oid`, `term`.`url`, `term`.`uid` FROM `term`
554 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `term`.`oid` AND `thread`.`uid` = `term`.`uid`
555 WHERE `term`.`type` = 7 AND `term`.`term` > '%s' AND `thread`.`mention`
556 GROUP BY `term`.`url`, `term`.`uid` ORDER BY `term`.`term` DESC", dbesc($start));
558 $conversations = q("SELECT `oid`, `url`, `uid` FROM `term`
559 WHERE `type` = 7 AND `term` > '%s'
560 GROUP BY `url`, `uid` ORDER BY `term` DESC", dbesc($start));
562 foreach ($conversations AS $conversation) {
563 self::completion($conversation['url'], $conversation['uid']);
568 set_config('system','ostatus_last_poll', time());
572 * @brief Updates the gcontact table with actor data from the conversation
574 * @param object $actor The actor object that contains the contact data
576 private function conv_fetch_actor($actor) {
578 // We set the generation to "3" since the data here is not as reliable as the data we get on other occasions
579 $contact = array("network" => NETWORK_OSTATUS, "generation" => 3);
581 if (isset($actor->url))
582 $contact["url"] = $actor->url;
584 if (isset($actor->displayName))
585 $contact["name"] = $actor->displayName;
587 if (isset($actor->portablecontacts_net->displayName))
588 $contact["name"] = $actor->portablecontacts_net->displayName;
590 if (isset($actor->portablecontacts_net->preferredUsername))
591 $contact["nick"] = $actor->portablecontacts_net->preferredUsername;
593 if (isset($actor->id))
594 $contact["alias"] = $actor->id;
596 if (isset($actor->summary))
597 $contact["about"] = $actor->summary;
599 if (isset($actor->portablecontacts_net->note))
600 $contact["about"] = $actor->portablecontacts_net->note;
602 if (isset($actor->portablecontacts_net->addresses->formatted))
603 $contact["location"] = $actor->portablecontacts_net->addresses->formatted;
606 if (isset($actor->image->url))
607 $contact["photo"] = $actor->image->url;
609 if (isset($actor->image->width))
610 $avatarwidth = $actor->image->width;
612 if (is_array($actor->status_net->avatarLinks))
613 foreach ($actor->status_net->avatarLinks AS $avatar) {
614 if ($avatarsize < $avatar->width) {
615 $contact["photo"] = $avatar->url;
616 $avatarsize = $avatar->width;
620 update_gcontact($contact);
624 * @brief Fetches the conversation url for a given item link or conversation id
626 * @param string $self The link to the posting
627 * @param string $conversation_id The conversation id
629 * @return string The conversation url
631 private function fetch_conversation($self, $conversation_id = "") {
633 if ($conversation_id != "") {
634 $elements = explode(":", $conversation_id);
636 if ((count($elements) <= 2) OR ($elements[0] != "tag"))
637 return $conversation_id;
643 $json = str_replace(".atom", ".json", $self);
645 $raw = fetch_url($json);
649 $data = json_decode($raw);
650 if (!is_object($data))
653 $conversation_id = $data->statusnet_conversation_id;
655 $pos = strpos($self, "/api/statuses/show/");
656 $base_url = substr($self, 0, $pos);
658 return $base_url."/conversation/".$conversation_id;
662 * @brief Fetches actor details of a given actor and user id
664 * @param string $actor The actor url
665 * @param int $uid The user id
666 * @param int $contact_id The default contact-id
668 * @return array Array with actor details
670 private function get_actor_details($actor, $uid, $contact_id) {
674 $contact = q("SELECT `id`, `rel`, `network` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
675 $uid, normalise_link($actor), NETWORK_STATUSNET);
678 $contact = q("SELECT `id`, `rel`, `network` FROM `contact` WHERE `uid` = %d AND `alias` IN ('%s', '%s') AND `network` != '%s'",
679 $uid, $actor, normalise_link($actor), NETWORK_STATUSNET);
682 logger("Found contact for url ".$actor, LOGGER_DEBUG);
683 $details["contact_id"] = $contact[0]["id"];
684 $details["network"] = $contact[0]["network"];
686 $details["not_following"] = !in_array($contact[0]["rel"], array(CONTACT_IS_SHARING, CONTACT_IS_FRIEND));
688 logger("No contact found for user ".$uid." and url ".$actor, LOGGER_DEBUG);
690 // Adding a global contact
691 /// @TODO Use this data for the post
692 $details["global_contact_id"] = get_contact($actor, 0);
694 logger("Global contact ".$global_contact_id." found for url ".$actor, LOGGER_DEBUG);
696 $details["contact_id"] = $contact_id;
697 $details["network"] = NETWORK_OSTATUS;
699 $details["not_following"] = true;
705 private function completion($conversation_url, $uid, $item = array(), $self = "") {
710 $conversation_url = self::fetch_conversation($self, $conversation_url);
712 // If the thread shouldn't be completed then store the item and go away
713 // Don't do a completion on liked content
714 if (((intval(get_config('system','ostatus_poll_interval')) == -2) AND (count($item) > 0)) OR
715 ($item["verb"] == ACTIVITY_LIKE) OR ($conversation_url == "")) {
716 $item_stored = item_store($item, true);
717 return($item_stored);
721 $parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
722 (SELECT `parent` FROM `item` WHERE `id` IN
723 (SELECT `oid` FROM `term` WHERE `uid` = %d AND `otype` = %d AND `type` = %d AND `url` = '%s'))",
724 intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url));
727 $parent = $parents[0];
728 elseif (count($item) > 0) {
730 $parent["type"] = "remote";
731 $parent["verb"] = ACTIVITY_POST;
732 $parent["visible"] = 1;
735 $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid`=%d", $uid);
741 $parent["parent"] = 0;
743 $parent["contact-id"] = $r[0]["id"];
744 $parent["type"] = "remote";
745 $parent["verb"] = ACTIVITY_POST;
746 $parent["visible"] = 1;
749 $conv = str_replace("/conversation/", "/api/statusnet/conversation/", $conversation_url).".as";
753 logger('fetching conversation url '.$conv.' (Self: '.$self.') for user '.$uid);
756 $conv_arr = z_fetch_url($conv."?page=".$pageno);
758 // If it is a non-ssl site and there is an error, then try ssl or vice versa
759 if (!$conv_arr["success"] AND (substr($conv, 0, 7) == "http://")) {
760 $conv = str_replace("http://", "https://", $conv);
761 $conv_as = fetch_url($conv."?page=".$pageno);
762 } elseif (!$conv_arr["success"] AND (substr($conv, 0, 8) == "https://")) {
763 $conv = str_replace("https://", "http://", $conv);
764 $conv_as = fetch_url($conv."?page=".$pageno);
766 $conv_as = $conv_arr["body"];
768 $conv_as = str_replace(',"statusnet:notice_info":', ',"statusnet_notice_info":', $conv_as);
769 $conv_as = json_decode($conv_as);
771 $no_of_items = sizeof($items);
773 if (@is_array($conv_as->items))
774 foreach ($conv_as->items AS $single_item)
775 $items[$single_item->id] = $single_item;
777 if ($no_of_items == sizeof($items))
784 logger('fetching conversation done. Found '.count($items).' items');
786 if (!sizeof($items)) {
787 if (count($item) > 0) {
788 $item_stored = item_store($item, true);
791 logger("Conversation ".$conversation_url." couldn't be fetched. Item uri ".$item["uri"]." stored: ".$item_stored, LOGGER_DEBUG);
792 self::store_conversation($item_id, $conversation_url);
795 return($item_stored);
800 $items = array_reverse($items);
802 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self`", intval($uid));
807 foreach ($items as $single_conv) {
809 // Update the gcontact table
810 self::conv_fetch_actor($single_conv->actor);
812 // Test - remove before flight
813 //$tempfile = tempnam(get_temppath(), "conversation");
814 //file_put_contents($tempfile, json_encode($single_conv));
818 if (isset($single_conv->object->id))
819 $single_conv->id = $single_conv->object->id;
821 $plink = self::convert_href($single_conv->id);
822 if (isset($single_conv->object->url))
823 $plink = self::convert_href($single_conv->object->url);
825 if (@!$single_conv->id)
828 logger("Got id ".$single_conv->id, LOGGER_DEBUG);
830 if ($first_id == "") {
831 $first_id = $single_conv->id;
833 // The first post of the conversation isn't our first post. There are three options:
834 // 1. Our conversation hasn't the "real" thread starter
835 // 2. This first post is a post inside our thread
836 // 3. This first post is a post inside another thread
837 if (($first_id != $parent["uri"]) AND ($parent["uri"] != "")) {
841 $new_parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
842 (SELECT `parent` FROM `item`
843 WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s')) LIMIT 1",
844 intval($uid), dbesc($first_id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
846 if ($new_parents[0]["parent"] == $parent["parent"]) {
847 // Option 2: This post is already present inside our thread - but not as thread starter
848 logger("Option 2: uri present in our thread: ".$first_id, LOGGER_DEBUG);
849 $first_id = $parent["uri"];
851 // Option 3: Not so good. We have mixed parents. We have to see how to clean this up.
852 // For now just take the new parent.
853 $parent = $new_parents[0];
854 $first_id = $parent["uri"];
855 logger("Option 3: mixed parents for uri ".$first_id, LOGGER_DEBUG);
858 // Option 1: We hadn't got the real thread starter
859 // We have to clean up our existing messages.
861 $parent["uri"] = $first_id;
862 logger("Option 1: we have a new parent: ".$first_id, LOGGER_DEBUG);
864 } elseif ($parent["uri"] == "") {
866 $parent["uri"] = $first_id;
870 $parent_uri = $parent["uri"];
872 // "context" only seems to exist on older servers
873 if (isset($single_conv->context->inReplyTo->id)) {
874 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
875 intval($uid), dbesc($single_conv->context->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
877 $parent_uri = $single_conv->context->inReplyTo->id;
880 // This is the current way
881 if (isset($single_conv->object->inReplyTo->id)) {
882 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
883 intval($uid), dbesc($single_conv->object->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
885 $parent_uri = $single_conv->object->inReplyTo->id;
888 $message_exists = q("SELECT `id`, `parent`, `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
889 intval($uid), dbesc($single_conv->id),
890 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
891 if ($message_exists) {
892 logger("Message ".$single_conv->id." already existed on the system", LOGGER_DEBUG);
894 if ($parent["id"] != 0) {
895 $existing_message = $message_exists[0];
897 // We improved the way we fetch OStatus messages, this shouldn't happen very often now
898 /// @TODO We have to change the shadow copies as well. This way here is really ugly.
899 if ($existing_message["parent"] != $parent["id"]) {
900 logger('updating id '.$existing_message["id"].' with parent '.$existing_message["parent"].' to parent '.$parent["id"].' uri '.$parent["uri"].' thread '.$parent_uri, LOGGER_DEBUG);
902 // Update the parent id of the selected item
903 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `id` = %d",
904 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["id"]));
906 // Update the parent uri in the thread - but only if it points to itself
907 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE `id` = %d AND `uri` = `thr-parent`",
908 dbesc($parent_uri), intval($existing_message["id"]));
910 // try to change all items of the same parent
911 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `parent` = %d",
912 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["parent"]));
914 // Update the parent uri in the thread - but only if it points to itself
915 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE (`parent` = %d) AND (`uri` = `thr-parent`)",
916 dbesc($parent["uri"]), intval($existing_message["parent"]));
918 // Now delete the thread
919 delete_thread($existing_message["parent"]);
923 // The item we are having on the system is the one that we wanted to store via the item array
924 if (isset($item["uri"]) AND ($item["uri"] == $existing_message["uri"])) {
932 if (is_array($single_conv->to))
933 foreach($single_conv->to AS $to)
934 if ($importer["nurl"] == normalise_link($to->id))
937 $actor = $single_conv->actor->id;
938 if (isset($single_conv->actor->url))
939 $actor = $single_conv->actor->url;
941 $details = self::get_actor_details($actor, $uid, $parent["contact-id"]);
943 // Do we only want to import threads that were started by our contacts?
944 if ($details["not_following"] AND $new_parent AND get_config('system','ostatus_full_threads')) {
945 logger("Don't import uri ".$first_id." because user ".$uid." doesn't follow the person ".$actor, LOGGER_DEBUG);
950 $arr["network"] = $details["network"];
951 $arr["uri"] = $single_conv->id;
952 $arr["plink"] = $plink;
954 $arr["contact-id"] = $details["contact_id"];
955 $arr["parent-uri"] = $parent_uri;
956 $arr["created"] = $single_conv->published;
957 $arr["edited"] = $single_conv->published;
958 $arr["owner-name"] = $single_conv->actor->displayName;
959 if ($arr["owner-name"] == '')
960 $arr["owner-name"] = $single_conv->actor->contact->displayName;
961 if ($arr["owner-name"] == '')
962 $arr["owner-name"] = $single_conv->actor->portablecontacts_net->displayName;
964 $arr["owner-link"] = $actor;
965 $arr["owner-avatar"] = $single_conv->actor->image->url;
966 $arr["author-name"] = $arr["owner-name"];
967 $arr["author-link"] = $actor;
968 $arr["author-avatar"] = $single_conv->actor->image->url;
969 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->content));
971 if (isset($single_conv->status_net->notice_info->source))
972 $arr["app"] = strip_tags($single_conv->status_net->notice_info->source);
973 elseif (isset($single_conv->statusnet->notice_info->source))
974 $arr["app"] = strip_tags($single_conv->statusnet->notice_info->source);
975 elseif (isset($single_conv->statusnet_notice_info->source))
976 $arr["app"] = strip_tags($single_conv->statusnet_notice_info->source);
977 elseif (isset($single_conv->provider->displayName))
978 $arr["app"] = $single_conv->provider->displayName;
980 $arr["app"] = "OStatus";
983 $arr["object"] = json_encode($single_conv);
984 $arr["verb"] = $parent["verb"];
985 $arr["visible"] = $parent["visible"];
986 $arr["location"] = $single_conv->location->displayName;
987 $arr["coord"] = trim($single_conv->location->lat." ".$single_conv->location->lon);
989 // Is it a reshared item?
990 if (isset($single_conv->verb) AND ($single_conv->verb == "share") AND isset($single_conv->object)) {
991 if (is_array($single_conv->object))
992 $single_conv->object = $single_conv->object[0];
994 logger("Found reshared item ".$single_conv->object->id);
996 // $single_conv->object->context->conversation;
998 if (isset($single_conv->object->object->id))
999 $arr["uri"] = $single_conv->object->object->id;
1001 $arr["uri"] = $single_conv->object->id;
1003 if (isset($single_conv->object->object->url))
1004 $plink = self::convert_href($single_conv->object->object->url);
1006 $plink = self::convert_href($single_conv->object->url);
1008 if (isset($single_conv->object->object->content))
1009 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->object->content));
1011 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->content));
1013 $arr["plink"] = $plink;
1015 $arr["created"] = $single_conv->object->published;
1016 $arr["edited"] = $single_conv->object->published;
1018 $arr["author-name"] = $single_conv->object->actor->displayName;
1019 if ($arr["owner-name"] == '')
1020 $arr["author-name"] = $single_conv->object->actor->contact->displayName;
1022 $arr["author-link"] = $single_conv->object->actor->url;
1023 $arr["author-avatar"] = $single_conv->object->actor->image->url;
1025 $arr["app"] = $single_conv->object->provider->displayName."#";
1026 //$arr["verb"] = $single_conv->object->verb;
1028 $arr["location"] = $single_conv->object->location->displayName;
1029 $arr["coord"] = trim($single_conv->object->location->lat." ".$single_conv->object->location->lon);
1032 if ($arr["location"] == "")
1033 unset($arr["location"]);
1035 if ($arr["coord"] == "")
1036 unset($arr["coord"]);
1038 // Copy fields from given item array
1039 if (isset($item["uri"]) AND (($item["uri"] == $arr["uri"]) OR ($item["uri"] == $single_conv->id))) {
1040 $copy_fields = array("owner-name", "owner-link", "owner-avatar", "author-name", "author-link", "author-avatar",
1041 "gravity", "body", "object-type", "object", "verb", "created", "edited", "coord", "tag",
1042 "title", "attach", "app", "type", "location", "contact-id", "uri");
1043 foreach ($copy_fields AS $field)
1044 if (isset($item[$field]))
1045 $arr[$field] = $item[$field];
1049 $newitem = item_store($arr);
1051 logger("Item wasn't stored ".print_r($arr, true), LOGGER_DEBUG);
1055 if (isset($item["uri"]) AND ($item["uri"] == $arr["uri"])) {
1057 $item_stored = $newitem;
1060 logger('Stored new item '.$plink.' for parent '.$arr["parent-uri"].' under id '.$newitem, LOGGER_DEBUG);
1062 // Add the conversation entry (but don't fetch the whole conversation)
1063 self::store_conversation($newitem, $conversation_url);
1065 // If the newly created item is the top item then change the parent settings of the thread
1066 // This shouldn't happen anymore. This is supposed to be absolote.
1067 if ($arr["uri"] == $first_id) {
1068 logger('setting new parent to id '.$newitem);
1069 $new_parents = q("SELECT `id`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
1070 intval($uid), intval($newitem));
1072 $parent = $new_parents[0];
1076 if (($item_stored < 0) AND (count($item) > 0)) {
1078 if (get_config('system','ostatus_full_threads')) {
1079 $details = self::get_actor_details($item["owner-link"], $uid, $item["contact-id"]);
1080 if ($details["not_following"]) {
1081 logger("Don't import uri ".$item["uri"]." because user ".$uid." doesn't follow the person ".$item["owner-link"], LOGGER_DEBUG);
1086 $item_stored = item_store($item, true);
1088 logger("Uri ".$item["uri"]." wasn't found in conversation ".$conversation_url, LOGGER_DEBUG);
1089 self::store_conversation($item_stored, $conversation_url);
1093 return($item_stored);
1096 private function store_conversation($itemid, $conversation_url) {
1098 $conversation_url = self::convert_href($conversation_url);
1100 $messages = q("SELECT `uid`, `parent`, `created`, `received`, `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($itemid));
1103 $message = $messages[0];
1105 // Store conversation url if not done before
1106 $conversation = q("SELECT `url` FROM `term` WHERE `uid` = %d AND `oid` = %d AND `otype` = %d AND `type` = %d",
1107 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION));
1109 if (!$conversation) {
1110 $r = q("INSERT INTO `term` (`uid`, `oid`, `otype`, `type`, `term`, `url`, `created`, `received`, `guid`) VALUES (%d, %d, %d, %d, '%s', '%s', '%s', '%s', '%s')",
1111 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION),
1112 dbesc($message["created"]), dbesc($conversation_url), dbesc($message["created"]), dbesc($message["received"]), dbesc($message["guid"]));
1113 logger('Storing conversation url '.$conversation_url.' for id '.$itemid);
1117 private function get_reshared_guid($item) {
1118 $body = trim($item["body"]);
1120 // Skip if it isn't a pure repeated messages
1121 // Does it start with a share?
1122 if (strpos($body, "[share") > 0)
1125 // Does it end with a share?
1126 if (strlen($body) > (strrpos($body, "[/share]") + 8))
1129 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
1130 // Skip if there is no shared message in there
1131 if ($body == $attributes)
1135 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1136 if ($matches[1] != "")
1137 $guid = $matches[1];
1139 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1140 if ($matches[1] != "")
1141 $guid = $matches[1];
1146 private function format_picture_post($body) {
1147 $siteinfo = get_attached_data($body);
1149 if (($siteinfo["type"] == "photo")) {
1150 if (isset($siteinfo["preview"]))
1151 $preview = $siteinfo["preview"];
1153 $preview = $siteinfo["image"];
1155 // Is it a remote picture? Then make a smaller preview here
1156 $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
1158 // Is it a local picture? Then make it smaller here
1159 $preview = str_replace(array("-0.jpg", "-0.png"), array("-2.jpg", "-2.png"), $preview);
1160 $preview = str_replace(array("-1.jpg", "-1.png"), array("-2.jpg", "-2.png"), $preview);
1162 if (isset($siteinfo["url"]))
1163 $url = $siteinfo["url"];
1165 $url = $siteinfo["image"];
1167 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1173 private function add_header($doc, $owner) {
1177 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1178 $doc->appendChild($root);
1180 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1181 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1182 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1183 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1184 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1185 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1186 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1188 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
1189 xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1190 xml::add_element($doc, $root, "id", App::get_baseurl()."/profile/".$owner["nick"]);
1191 xml::add_element($doc, $root, "title", sprintf("%s timeline", $owner["name"]));
1192 xml::add_element($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
1193 xml::add_element($doc, $root, "logo", $owner["photo"]);
1194 xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
1196 $author = self::add_author($doc, $owner);
1197 $root->appendChild($author);
1199 $attributes = array("href" => $owner["url"], "rel" => "alternate", "type" => "text/html");
1200 xml::add_element($doc, $root, "link", "", $attributes);
1202 /// @TODO We have to find out what this is
1203 /// $attributes = array("href" => App::get_baseurl()."/sup",
1204 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1205 /// "type" => "application/json");
1206 /// xml::add_element($doc, $root, "link", "", $attributes);
1208 self::hublinks($doc, $root);
1210 $attributes = array("href" => App::get_baseurl()."/salmon/".$owner["nick"], "rel" => "salmon");
1211 xml::add_element($doc, $root, "link", "", $attributes);
1213 $attributes = array("href" => App::get_baseurl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies");
1214 xml::add_element($doc, $root, "link", "", $attributes);
1216 $attributes = array("href" => App::get_baseurl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention");
1217 xml::add_element($doc, $root, "link", "", $attributes);
1219 $attributes = array("href" => App::get_baseurl()."/api/statuses/user_timeline/".$owner["nick"].".atom",
1220 "rel" => "self", "type" => "application/atom+xml");
1221 xml::add_element($doc, $root, "link", "", $attributes);
1226 public static function hublinks($doc, $root) {
1227 $hub = get_config('system','huburl');
1231 $hubs = explode(',', $hub);
1233 foreach($hubs as $h) {
1237 if ($h === '[internal]')
1238 $h = App::get_baseurl() . '/pubsubhubbub';
1239 xml::add_element($doc, $root, "link", "", array("href" => $h, "rel" => "hub"));
1245 private function get_attachment($doc, $root, $item) {
1247 $siteinfo = get_attached_data($item["body"]);
1249 switch($siteinfo["type"]) {
1251 $attributes = array("rel" => "enclosure",
1252 "href" => $siteinfo["url"],
1253 "type" => "text/html; charset=UTF-8",
1255 "title" => $siteinfo["title"]);
1256 xml::add_element($doc, $root, "link", "", $attributes);
1259 $imgdata = get_photo_info($siteinfo["image"]);
1260 $attributes = array("rel" => "enclosure",
1261 "href" => $siteinfo["image"],
1262 "type" => $imgdata["mime"],
1263 "length" => intval($imgdata["size"]));
1264 xml::add_element($doc, $root, "link", "", $attributes);
1267 $attributes = array("rel" => "enclosure",
1268 "href" => $siteinfo["url"],
1269 "type" => "text/html; charset=UTF-8",
1271 "title" => $siteinfo["title"]);
1272 xml::add_element($doc, $root, "link", "", $attributes);
1278 if (($siteinfo["type"] != "photo") AND isset($siteinfo["image"])) {
1279 $photodata = get_photo_info($siteinfo["image"]);
1281 $attributes = array("rel" => "preview", "href" => $siteinfo["image"], "media:width" => $photodata[0], "media:height" => $photodata[1]);
1282 xml::add_element($doc, $root, "link", "", $attributes);
1286 $arr = explode('[/attach],',$item['attach']);
1288 foreach($arr as $r) {
1290 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches);
1292 $attributes = array("rel" => "enclosure",
1293 "href" => $matches[1],
1294 "type" => $matches[3]);
1296 if(intval($matches[2]))
1297 $attributes["length"] = intval($matches[2]);
1299 if(trim($matches[4]) != "")
1300 $attributes["title"] = trim($matches[4]);
1302 xml::add_element($doc, $root, "link", "", $attributes);
1308 private function add_author($doc, $owner) {
1310 $r = q("SELECT `homepage` FROM `profile` WHERE `uid` = %d AND `is-default` LIMIT 1", intval($owner["uid"]));
1314 $author = $doc->createElement("author");
1315 xml::add_element($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1316 xml::add_element($doc, $author, "uri", $owner["url"]);
1317 xml::add_element($doc, $author, "name", $owner["name"]);
1318 xml::add_element($doc, $author, "summary", bbcode($owner["about"], false, false, 7));
1320 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $owner["url"]);
1321 xml::add_element($doc, $author, "link", "", $attributes);
1323 $attributes = array(
1325 "type" => "image/jpeg", // To-Do?
1326 "media:width" => 175,
1327 "media:height" => 175,
1328 "href" => $owner["photo"]);
1329 xml::add_element($doc, $author, "link", "", $attributes);
1331 if (isset($owner["thumb"])) {
1332 $attributes = array(
1334 "type" => "image/jpeg", // To-Do?
1335 "media:width" => 80,
1336 "media:height" => 80,
1337 "href" => $owner["thumb"]);
1338 xml::add_element($doc, $author, "link", "", $attributes);
1341 xml::add_element($doc, $author, "poco:preferredUsername", $owner["nick"]);
1342 xml::add_element($doc, $author, "poco:displayName", $owner["name"]);
1343 xml::add_element($doc, $author, "poco:note", bbcode($owner["about"], false, false, 7));
1345 if (trim($owner["location"]) != "") {
1346 $element = $doc->createElement("poco:address");
1347 xml::add_element($doc, $element, "poco:formatted", $owner["location"]);
1348 $author->appendChild($element);
1351 if (trim($profile["homepage"]) != "") {
1352 $urls = $doc->createElement("poco:urls");
1353 xml::add_element($doc, $urls, "poco:type", "homepage");
1354 xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
1355 xml::add_element($doc, $urls, "poco:primary", "true");
1356 $author->appendChild($urls);
1359 if (count($profile)) {
1360 xml::add_element($doc, $author, "followers", "", array("url" => App::get_baseurl()."/viewcontacts/".$owner["nick"]));
1361 xml::add_element($doc, $author, "statusnet:profile_info", "", array("local_id" => $owner["uid"]));
1368 * @TODO Picture attachments should look like this:
1369 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1370 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1374 function construct_verb($item) {
1376 return $item['verb'];
1377 return ACTIVITY_POST;
1380 function construct_objecttype($item) {
1381 if (in_array($item['object-type'], array(ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT)))
1382 return $item['object-type'];
1383 return ACTIVITY_OBJ_NOTE;
1386 private function entry($doc, $item, $owner, $toplevel = false) {
1387 $repeated_guid = self::get_reshared_guid($item);
1388 if ($repeated_guid != "")
1389 $xml = self::reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel);
1394 if ($item["verb"] == ACTIVITY_LIKE)
1395 return self::like_entry($doc, $item, $owner, $toplevel);
1397 return self::note_entry($doc, $item, $owner, $toplevel);
1400 private function source_entry($doc, $contact) {
1401 $source = $doc->createElement("source");
1402 xml::add_element($doc, $source, "id", $contact["poll"]);
1403 xml::add_element($doc, $source, "title", $contact["name"]);
1404 xml::add_element($doc, $source, "link", "", array("rel" => "alternate",
1405 "type" => "text/html",
1406 "href" => $contact["alias"]));
1407 xml::add_element($doc, $source, "link", "", array("rel" => "self",
1408 "type" => "application/atom+xml",
1409 "href" => $contact["poll"]));
1410 xml::add_element($doc, $source, "icon", $contact["photo"]);
1411 xml::add_element($doc, $source, "updated", datetime_convert("UTC","UTC",$contact["success_update"]."+00:00",ATOM_TIME));
1416 private function contact_entry($url, $owner) {
1418 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1419 dbesc(normalise_link($url)), intval($owner["uid"]));
1422 $contact["uid"] = -1;
1426 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1427 dbesc(normalise_link($url)));
1430 $contact["uid"] = -1;
1431 $contact["success_update"] = $contact["updated"];
1438 if (!isset($contact["poll"])) {
1439 $data = probe_url($url);
1440 $contact["alias"] = $data["alias"];
1441 $contact["poll"] = $data["poll"];
1444 if (!isset($contact["alias"]))
1445 $contact["alias"] = $contact["url"];
1450 private function reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel) {
1452 if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1453 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1456 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1458 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' AND NOT `private` AND `network` IN ('%s', '%s', '%s') LIMIT 1",
1459 intval($owner["uid"]), dbesc($repeated_guid),
1460 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS));
1462 $repeated_item = $r[0];
1466 $contact = self::contact_entry($repeated_item['author-link'], $owner);
1468 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1470 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1472 self::entry_content($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1474 $as_object = $doc->createElement("activity:object");
1477 // ostatusogu9zg - besser
1478 xml::add_element($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1480 self::entry_content($doc, $as_object, $repeated_item, $owner, "", "", false);
1482 $author = self::add_author($doc, $contact);
1483 $as_object->appendChild($author);
1485 $as_object2 = $doc->createElement("activity:object");
1487 xml::add_element($doc, $as_object2, "activity:object-type", self::construct_objecttype($repeated_item));
1489 $title = sprintf("New comment by %s", $contact["nick"]);
1491 self::entry_content($doc, $as_object2, $repeated_item, $owner, $title);
1493 $as_object->appendChild($as_object2);
1495 self::entry_footer($doc, $as_object, $item, $owner, false);
1497 $source = self::source_entry($doc, $contact);
1499 $as_object->appendChild($source);
1501 $entry->appendChild($as_object);
1503 self::entry_footer($doc, $entry, $item, $owner);
1508 private function like_entry($doc, $item, $owner, $toplevel) {
1510 if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1511 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1514 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1516 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1517 self::entry_content($doc, $entry, $item, $owner, "Favorite", $verb, false);
1519 $as_object = $doc->createElement("activity:object");
1521 $parent = q("SELECT * FROM `item` WHERE `id` = %d", intval($item["parent"]));
1522 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1524 xml::add_element($doc, $as_object, "activity:object-type", self::construct_objecttype($parent[0]));
1526 self::entry_content($doc, $as_object, $parent[0], $owner, "New entry");
1528 $entry->appendChild($as_object);
1530 self::entry_footer($doc, $entry, $item, $owner);
1535 private function note_entry($doc, $item, $owner, $toplevel) {
1537 if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1538 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1541 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1543 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1545 self::entry_content($doc, $entry, $item, $owner, $title);
1547 self::entry_footer($doc, $entry, $item, $owner);
1552 private function entry_header($doc, &$entry, $owner, $toplevel) {
1554 $entry = $doc->createElement("entry");
1555 $title = sprintf("New note by %s", $owner["nick"]);
1557 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
1559 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1560 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1561 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1562 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1563 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
1564 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1565 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1567 $author = self::add_author($doc, $owner);
1568 $entry->appendChild($author);
1570 $title = sprintf("New comment by %s", $owner["nick"]);
1575 private function entry_content($doc, $entry, $item, $owner, $title, $verb = "", $complete = true) {
1578 $verb = self::construct_verb($item);
1580 xml::add_element($doc, $entry, "id", $item["uri"]);
1581 xml::add_element($doc, $entry, "title", $title);
1583 $body = self::format_picture_post($item['body']);
1585 if ($item['title'] != "")
1586 $body = "[b]".$item['title']."[/b]\n\n".$body;
1588 $body = bbcode($body, false, false, 7);
1590 xml::add_element($doc, $entry, "content", $body, array("type" => "html"));
1592 xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
1593 "href" => App::get_baseurl()."/display/".$item["guid"]));
1596 xml::add_element($doc, $entry, "status_net", "", array("notice_id" => $item["id"]));
1598 xml::add_element($doc, $entry, "activity:verb", $verb);
1600 xml::add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
1601 xml::add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
1604 private function entry_footer($doc, $entry, $item, $owner, $complete = true) {
1606 $mentioned = array();
1608 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
1609 $parent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `id` = %d", intval($item["parent"]));
1610 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1612 $attributes = array(
1613 "ref" => $parent_item,
1614 "type" => "text/html",
1615 "href" => App::get_baseurl()."/display/".$parent[0]["guid"]);
1616 xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
1618 $attributes = array(
1620 "href" => App::get_baseurl()."/display/".$parent[0]["guid"]);
1621 xml::add_element($doc, $entry, "link", "", $attributes);
1623 $mentioned[$parent[0]["author-link"]] = $parent[0]["author-link"];
1624 $mentioned[$parent[0]["owner-link"]] = $parent[0]["owner-link"];
1626 $thrparent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
1627 intval($owner["uid"]),
1628 dbesc($parent_item));
1630 $mentioned[$thrparent[0]["author-link"]] = $thrparent[0]["author-link"];
1631 $mentioned[$thrparent[0]["owner-link"]] = $thrparent[0]["owner-link"];
1635 xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:conversation",
1636 "href" => App::get_baseurl()."/display/".$owner["nick"]."/".$item["parent"]));
1637 xml::add_element($doc, $entry, "ostatus:conversation", App::get_baseurl()."/display/".$owner["nick"]."/".$item["parent"]);
1639 $tags = item_getfeedtags($item);
1642 foreach($tags as $t)
1644 $mentioned[$t[1]] = $t[1];
1646 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
1647 $newmentions = array();
1648 foreach ($mentioned AS $mention) {
1649 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
1650 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
1652 $mentioned = $newmentions;
1654 foreach ($mentioned AS $mention) {
1655 $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1656 intval($owner["uid"]),
1657 dbesc(normalise_link($mention)));
1658 if ($r[0]["forum"] OR $r[0]["prv"])
1659 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1660 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1661 "href" => $mention));
1663 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1664 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1665 "href" => $mention));
1668 if (!$item["private"]) {
1669 xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:attention",
1670 "href" => "http://activityschema.org/collection/public"));
1671 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1672 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
1673 "href" => "http://activityschema.org/collection/public"));
1677 foreach($tags as $t)
1679 xml::add_element($doc, $entry, "category", "", array("term" => $t[2]));
1681 self::get_attachment($doc, $entry, $item);
1684 $app = $item["app"];
1688 $attributes = array("local_id" => $item["id"], "source" => $app);
1690 if (isset($parent["id"]))
1691 $attributes["repeat_of"] = $parent["id"];
1693 if ($item["coord"] != "")
1694 xml::add_element($doc, $entry, "georss:point", $item["coord"]);
1696 xml::add_element($doc, $entry, "statusnet:notice_info", "", $attributes);
1700 public static function feed(&$a, $owner_nick, $last_update) {
1702 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
1703 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
1704 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
1705 dbesc($owner_nick));
1711 if(!strlen($last_update))
1712 $last_update = 'now -30 days';
1714 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
1716 $items = q("SELECT STRAIGHT_JOIN `item`.*, `item`.`id` AS `item_id` FROM `item`
1717 INNER JOIN `thread` ON `thread`.`iid` = `item`.`parent`
1718 LEFT JOIN `item` AS `thritem` ON `thritem`.`uri`=`item`.`thr-parent` AND `thritem`.`uid`=`item`.`uid`
1719 WHERE `item`.`uid` = %d AND `item`.`received` > '%s' AND NOT `item`.`private` AND NOT `item`.`deleted`
1720 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1721 AND ((`item`.`wall` AND (`item`.`parent` = `item`.`id`))
1722 OR (`item`.`network` = '%s' AND ((`thread`.`network` IN ('%s', '%s')) OR (`thritem`.`network` IN ('%s', '%s')))) AND `thread`.`mention`)
1723 AND ((`item`.`owner-link` IN ('%s', '%s') AND (`item`.`parent` = `item`.`id`))
1724 OR (`item`.`author-link` IN ('%s', '%s')))
1725 ORDER BY `item`.`received` DESC
1727 intval($owner["uid"]), dbesc($check_date), dbesc(NETWORK_DFRN),
1728 //dbesc(NETWORK_OSTATUS), dbesc(NETWORK_OSTATUS),
1729 //dbesc(NETWORK_OSTATUS), dbesc(NETWORK_OSTATUS),
1730 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN),
1731 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN),
1732 dbesc($owner["nurl"]), dbesc(str_replace("http://", "https://", $owner["nurl"])),
1733 dbesc($owner["nurl"]), dbesc(str_replace("http://", "https://", $owner["nurl"]))
1736 $doc = new DOMDocument('1.0', 'utf-8');
1737 $doc->formatOutput = true;
1739 $root = self::add_header($doc, $owner);
1741 foreach ($items AS $item) {
1742 $entry = self::entry($doc, $item, $owner);
1743 $root->appendChild($entry);
1746 return(trim($doc->saveXML()));
1749 public static function salmon($item,$owner) {
1751 $doc = new DOMDocument('1.0', 'utf-8');
1752 $doc->formatOutput = true;
1754 $entry = self::entry($doc, $item, $owner, true);
1756 $doc->appendChild($entry);
1758 return(trim($doc->saveXML()));