3 * @file include/dfrn.php
4 * @brief The implementation of the dfrn protocol
6 * https://github.com/friendica/friendica/wiki/Protocol
9 require_once("include/Contact.php");
10 require_once("include/ostatus.php");
11 require_once("include/enotify.php");
12 require_once("include/threads.php");
13 require_once("include/socgraph.php");
14 require_once("include/items.php");
15 require_once("include/tags.php");
16 require_once("include/files.php");
17 require_once("include/event.php");
18 require_once("include/text.php");
19 require_once("include/oembed.php");
20 require_once("include/html2bbcode.php");
21 require_once("include/bbcode.php");
22 require_once("include/xml.php");
25 * @brief This class contain functions to create and send DFRN XML files
30 const DFRN_TOP_LEVEL = 0; // Top level posting
31 const DFRN_REPLY = 1; // Regular reply that is stored locally
32 const DFRN_REPLY_RC = 2; // Reply that will be relayed
35 * @brief Generates the atom entries for delivery.php
37 * This function is used whenever content is transmitted via DFRN.
39 * @param array $items Item elements
40 * @param array $owner Owner record
42 * @return string DFRN entries
44 public static function entries($items,$owner) {
46 $doc = new DOMDocument('1.0', 'utf-8');
47 $doc->formatOutput = true;
49 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
52 return trim($doc->saveXML());
54 foreach($items as $item) {
55 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
56 $root->appendChild($entry);
59 return(trim($doc->saveXML()));
63 * @brief Generate an atom feed for the given user
65 * This function is called when another server is pulling data from the user feed.
67 * @param string $dfrn_id DFRN ID from the requesting party
68 * @param string $owner_nick Owner nick name
69 * @param string $last_update Date of the last update
70 * @param int $direction Can be -1, 0 or 1.
72 * @return string DFRN feed entries
74 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0) {
78 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
79 $public_feed = (($dfrn_id) ? false : true);
80 $starred = false; // not yet implemented, possible security issues
83 if($public_feed && $a->argc > 2) {
84 for($x = 2; $x < $a->argc; $x++) {
85 if($a->argv[$x] == 'converse')
87 if($a->argv[$x] == 'starred')
89 if($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1]))
90 $category = $a->argv[$x+1];
96 // default permissions - anonymous user
98 $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = '' ";
100 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
101 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
102 WHERE `contact`.`self` = 1 AND `user`.`nickname` = '%s' LIMIT 1",
110 $owner_id = $owner['uid'];
111 $owner_nick = $owner['nickname'];
113 $sql_post_table = "";
121 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
125 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
126 $my_id = '1:' . $dfrn_id;
129 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
130 $my_id = '0:' . $dfrn_id;
137 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `contact`.`uid` = %d $sql_extra LIMIT 1",
145 require_once('include/security.php');
146 $groups = init_groups_visitor($contact['id']);
149 for($x = 0; $x < count($groups); $x ++)
150 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
151 $gs = implode('|', $groups);
153 $gs = '<<>>' ; // Impossible to match
155 $sql_extra = sprintf("
156 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
157 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
158 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
159 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
161 intval($contact['id']),
162 intval($contact['id']),
173 $date_field = "`changed`";
174 $sql_order = "`item`.`parent` ".$sort.", `item`.`created` ASC";
176 if(! strlen($last_update))
177 $last_update = 'now -30 days';
179 if(isset($category)) {
180 $sql_post_table = sprintf("INNER JOIN (SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d ORDER BY `tid` DESC) AS `term` ON `item`.`id` = `term`.`oid` ",
181 dbesc(protect_sprintf($category)), intval(TERM_OBJ_POST), intval(TERM_CATEGORY), intval($owner_id));
182 //$sql_extra .= file_tag_file_query('item',$category,'category');
187 $sql_extra .= " AND `contact`.`self` = 1 ";
190 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
192 // AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
193 // dbesc($check_date),
195 $r = q("SELECT STRAIGHT_JOIN `item`.*, `item`.`id` AS `item_id`,
196 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
197 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
198 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
199 `contact`.`id` AS `contact-id`, `contact`.`uid` AS `contact-uid`,
200 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
201 FROM `item` $sql_post_table
202 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
203 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
204 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
205 WHERE `item`.`uid` = %d AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`parent` != 0
206 AND ((`item`.`wall` = 1) $visibility) AND `item`.$date_field > '%s'
208 ORDER BY $sql_order LIMIT 0, 300",
214 // Will check further below if this actually returned results.
215 // We will provide an empty feed if that is the case.
219 $doc = new DOMDocument('1.0', 'utf-8');
220 $doc->formatOutput = true;
222 $alternatelink = $owner['url'];
225 $alternatelink .= "/category/".$category;
228 $author = "dfrn:owner";
232 $root = self::add_header($doc, $owner, $author, $alternatelink, true);
234 // This hook can't work anymore
235 // call_hooks('atom_feed', $atom);
237 if(! count($items)) {
238 $atom = trim($doc->saveXML());
240 call_hooks('atom_feed_end', $atom);
245 foreach($items as $item) {
247 // prevent private email from leaking.
248 if($item['network'] == NETWORK_MAIL)
251 // public feeds get html, our own nodes use bbcode
255 // catch any email that's in a public conversation and make sure it doesn't leak
261 $entry = self::entry($doc, $type, $item, $owner, true);
262 $root->appendChild($entry);
266 $atom = trim($doc->saveXML());
268 call_hooks('atom_feed_end', $atom);
274 * @brief Create XML text for DFRN mails
276 * @param array $item message elements
277 * @param array $owner Owner record
279 * @return string DFRN mail
281 public static function mail($item, $owner) {
282 $doc = new DOMDocument('1.0', 'utf-8');
283 $doc->formatOutput = true;
285 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
287 $mail = $doc->createElement("dfrn:mail");
288 $sender = $doc->createElement("dfrn:sender");
290 xml::add_element($doc, $sender, "dfrn:name", $owner['name']);
291 xml::add_element($doc, $sender, "dfrn:uri", $owner['url']);
292 xml::add_element($doc, $sender, "dfrn:avatar", $owner['thumb']);
294 $mail->appendChild($sender);
296 xml::add_element($doc, $mail, "dfrn:id", $item['uri']);
297 xml::add_element($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
298 xml::add_element($doc, $mail, "dfrn:sentdate", datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME));
299 xml::add_element($doc, $mail, "dfrn:subject", $item['title']);
300 xml::add_element($doc, $mail, "dfrn:content", $item['body']);
302 $root->appendChild($mail);
304 return(trim($doc->saveXML()));
308 * @brief Create XML text for DFRN friend suggestions
310 * @param array $item suggestion elements
311 * @param array $owner Owner record
313 * @return string DFRN suggestions
315 public static function fsuggest($item, $owner) {
316 $doc = new DOMDocument('1.0', 'utf-8');
317 $doc->formatOutput = true;
319 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
321 $suggest = $doc->createElement("dfrn:suggest");
323 xml::add_element($doc, $suggest, "dfrn:url", $item['url']);
324 xml::add_element($doc, $suggest, "dfrn:name", $item['name']);
325 xml::add_element($doc, $suggest, "dfrn:photo", $item['photo']);
326 xml::add_element($doc, $suggest, "dfrn:request", $item['request']);
327 xml::add_element($doc, $suggest, "dfrn:note", $item['note']);
329 $root->appendChild($suggest);
331 return(trim($doc->saveXML()));
335 * @brief Create XML text for DFRN relocations
337 * @param array $owner Owner record
338 * @param int $uid User ID
340 * @return string DFRN relocations
342 public static function relocate($owner, $uid) {
344 /* get site pubkey. this could be a new installation with no site keys*/
345 $pubkey = get_config('system','site_pubkey');
347 $res = new_keypair(1024);
348 set_config('system','site_prvkey', $res['prvkey']);
349 set_config('system','site_pubkey', $res['pubkey']);
352 $rp = q("SELECT `resource-id` , `scale`, type FROM `photo`
353 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;", $uid);
355 $ext = Photo::supportedTypes();
358 $photos[$p['scale']] = app::get_baseurl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
362 $doc = new DOMDocument('1.0', 'utf-8');
363 $doc->formatOutput = true;
365 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
367 $relocate = $doc->createElement("dfrn:relocate");
369 xml::add_element($doc, $relocate, "dfrn:url", $owner['url']);
370 xml::add_element($doc, $relocate, "dfrn:name", $owner['name']);
371 xml::add_element($doc, $relocate, "dfrn:photo", $photos[4]);
372 xml::add_element($doc, $relocate, "dfrn:thumb", $photos[5]);
373 xml::add_element($doc, $relocate, "dfrn:micro", $photos[6]);
374 xml::add_element($doc, $relocate, "dfrn:request", $owner['request']);
375 xml::add_element($doc, $relocate, "dfrn:confirm", $owner['confirm']);
376 xml::add_element($doc, $relocate, "dfrn:notify", $owner['notify']);
377 xml::add_element($doc, $relocate, "dfrn:poll", $owner['poll']);
378 xml::add_element($doc, $relocate, "dfrn:sitepubkey", get_config('system','site_pubkey'));
380 $root->appendChild($relocate);
382 return(trim($doc->saveXML()));
386 * @brief Adds the header elements for the DFRN protocol
388 * @param object $doc XML document
389 * @param array $owner Owner record
390 * @param string $authorelement Element name for the author
391 * @param string $alternatelink link to profile or category
392 * @param bool $public Is it a header for public posts?
394 * @return object XML root object
396 private function add_header($doc, $owner, $authorelement, $alternatelink = "", $public = false) {
398 if ($alternatelink == "")
399 $alternatelink = $owner['url'];
401 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
402 $doc->appendChild($root);
404 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
405 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
406 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
407 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
408 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
409 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
410 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
411 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
412 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
414 xml::add_element($doc, $root, "id", app::get_baseurl()."/profile/".$owner["nick"]);
415 xml::add_element($doc, $root, "title", $owner["name"]);
417 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
418 xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
420 $attributes = array("rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/");
421 xml::add_element($doc, $root, "link", "", $attributes);
423 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $alternatelink);
424 xml::add_element($doc, $root, "link", "", $attributes);
428 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
429 ostatus::hublinks($doc, $root);
431 $attributes = array("rel" => "salmon", "href" => app::get_baseurl()."/salmon/".$owner["nick"]);
432 xml::add_element($doc, $root, "link", "", $attributes);
434 $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => app::get_baseurl()."/salmon/".$owner["nick"]);
435 xml::add_element($doc, $root, "link", "", $attributes);
437 $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => app::get_baseurl()."/salmon/".$owner["nick"]);
438 xml::add_element($doc, $root, "link", "", $attributes);
441 if ($owner['page-flags'] == PAGE_COMMUNITY)
442 xml::add_element($doc, $root, "dfrn:community", 1);
444 /// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
446 xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
448 $author = self::add_author($doc, $owner, $authorelement, $public);
449 $root->appendChild($author);
455 * @brief Adds the author element in the header for the DFRN protocol
457 * @param object $doc XML document
458 * @param array $owner Owner record
459 * @param string $authorelement Element name for the author
461 * @return object XML author object
463 private function add_author($doc, $owner, $authorelement, $public) {
465 $author = $doc->createElement($authorelement);
467 $namdate = datetime_convert('UTC', 'UTC', $owner['name-date'].'+00:00' , ATOM_TIME);
468 $uridate = datetime_convert('UTC', 'UTC', $owner['uri-date'].'+00:00', ATOM_TIME);
469 $picdate = datetime_convert('UTC', 'UTC', $owner['avatar-date'].'+00:00', ATOM_TIME);
471 $attributes = array("dfrn:updated" => $namdate);
472 xml::add_element($doc, $author, "name", $owner["name"], $attributes);
474 $attributes = array("dfrn:updated" => $namdate);
475 xml::add_element($doc, $author, "uri", app::get_baseurl().'/profile/'.$owner["nickname"], $attributes);
477 $attributes = array("dfrn:updated" => $namdate);
478 xml::add_element($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
480 $attributes = array("rel" => "photo", "type" => "image/jpeg", "dfrn:updated" => $picdate,
481 "media:width" => 175, "media:height" => 175, "href" => $owner['photo']);
482 xml::add_element($doc, $author, "link", "", $attributes);
484 $attributes = array("rel" => "avatar", "type" => "image/jpeg", "dfrn:updated" => $picdate,
485 "media:width" => 175, "media:height" => 175, "href" => $owner['photo']);
486 xml::add_element($doc, $author, "link", "", $attributes);
488 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
491 xml::add_element($doc, $author, "dfrn:birthday", $birthday);
493 // The following fields will only be generated if this isn't for a public feed
497 // Only show contact details when we are allowed to
498 $r = q("SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`, `user`.`timezone`,
499 `profile`.`locality`, `profile`.`region`, `profile`.`country-name`, `profile`.`pub_keywords`, `profile`.`dob`
501 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
502 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
503 intval($owner['uid']));
506 xml::add_element($doc, $author, "poco:displayName", $profile["name"]);
507 xml::add_element($doc, $author, "poco:updated", $namdate);
509 if (trim($profile["dob"]) != "0000-00-00")
510 xml::add_element($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
512 xml::add_element($doc, $author, "poco:note", $profile["about"]);
513 xml::add_element($doc, $author, "poco:preferredUsername", $profile["nickname"]);
515 $savetz = date_default_timezone_get();
516 date_default_timezone_set($profile["timezone"]);
517 xml::add_element($doc, $author, "poco:utcOffset", date("P"));
518 date_default_timezone_set($savetz);
520 if (trim($profile["homepage"]) != "") {
521 $urls = $doc->createElement("poco:urls");
522 xml::add_element($doc, $urls, "poco:type", "homepage");
523 xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
524 xml::add_element($doc, $urls, "poco:primary", "true");
525 $author->appendChild($urls);
528 if (trim($profile["pub_keywords"]) != "") {
529 $keywords = explode(",", $profile["pub_keywords"]);
531 foreach ($keywords AS $keyword)
532 xml::add_element($doc, $author, "poco:tags", trim($keyword));
536 /// @todo When we are having the XMPP address in the profile we should propagate it here
538 if (trim($xmpp) != "") {
539 $ims = $doc->createElement("poco:ims");
540 xml::add_element($doc, $ims, "poco:type", "xmpp");
541 xml::add_element($doc, $ims, "poco:value", $xmpp);
542 xml::add_element($doc, $ims, "poco:primary", "true");
543 $author->appendChild($ims);
546 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
547 $element = $doc->createElement("poco:address");
549 xml::add_element($doc, $element, "poco:formatted", formatted_location($profile));
551 if (trim($profile["locality"]) != "")
552 xml::add_element($doc, $element, "poco:locality", $profile["locality"]);
554 if (trim($profile["region"]) != "")
555 xml::add_element($doc, $element, "poco:region", $profile["region"]);
557 if (trim($profile["country-name"]) != "")
558 xml::add_element($doc, $element, "poco:country", $profile["country-name"]);
560 $author->appendChild($element);
568 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
570 * @param object $doc XML document
571 * @param string $element Element name for the author
572 * @param string $contact_url Link of the contact
573 * @param array $items Item elements
575 * @return object XML author object
577 private function add_entry_author($doc, $element, $contact_url, $item) {
579 $contact = get_contact_details_by_url($contact_url, $item["uid"]);
581 $author = $doc->createElement($element);
582 xml::add_element($doc, $author, "name", $contact["name"]);
583 xml::add_element($doc, $author, "uri", $contact["url"]);
584 xml::add_element($doc, $author, "dfrn:handle", $contact["addr"]);
587 /// - Check real image type and image size
588 /// - Check which of these boths elements we should use
591 "type" => "image/jpeg",
593 "media:height" => 80,
594 "href" => $contact["photo"]);
595 xml::add_element($doc, $author, "link", "", $attributes);
599 "type" => "image/jpeg",
601 "media:height" => 80,
602 "href" => $contact["photo"]);
603 xml::add_element($doc, $author, "link", "", $attributes);
609 * @brief Adds the activity elements
611 * @param object $doc XML document
612 * @param string $element Element name for the activity
613 * @param string $activity activity value
615 * @return object XML activity object
617 private function create_activity($doc, $element, $activity) {
620 $entry = $doc->createElement($element);
622 $r = parse_xml_string($activity, false);
626 xml::add_element($doc, $entry, "activity:object-type", $r->type);
628 xml::add_element($doc, $entry, "id", $r->id);
630 xml::add_element($doc, $entry, "title", $r->title);
632 if(substr($r->link,0,1) == '<') {
633 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
634 $r->link = str_replace('&','&', $r->link);
636 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
638 // XML does need a single element as root element so we add a dummy element here
639 $data = parse_xml_string("<dummy>".$r->link."</dummy>", false);
640 if (is_object($data)) {
641 foreach ($data->link AS $link) {
642 $attributes = array();
643 foreach ($link->attributes() AS $parameter => $value)
644 $attributes[$parameter] = $value;
645 xml::add_element($doc, $entry, "link", "", $attributes);
649 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $r->link);
650 xml::add_element($doc, $entry, "link", "", $attributes);
654 xml::add_element($doc, $entry, "content", bbcode($r->content), array("type" => "html"));
663 * @brief Adds the elements for attachments
665 * @param object $doc XML document
666 * @param object $root XML root
667 * @param array $item Item element
669 * @return object XML attachment object
671 private function get_attachment($doc, $root, $item) {
672 $arr = explode('[/attach],',$item['attach']);
674 foreach($arr as $r) {
676 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches);
678 $attributes = array("rel" => "enclosure",
679 "href" => $matches[1],
680 "type" => $matches[3]);
682 if(intval($matches[2]))
683 $attributes["length"] = intval($matches[2]);
685 if(trim($matches[4]) != "")
686 $attributes["title"] = trim($matches[4]);
688 xml::add_element($doc, $root, "link", "", $attributes);
695 * @brief Adds the "entry" elements for the DFRN protocol
697 * @param object $doc XML document
698 * @param string $type "text" or "html"
699 * @param array $item Item element
700 * @param array $owner Owner record
701 * @param bool $comment Trigger the sending of the "comment" element
702 * @param int $cid Contact ID of the recipient
704 * @return object XML entry object
706 private function entry($doc, $type, $item, $owner, $comment = false, $cid = 0) {
708 $mentioned = array();
713 if($item['deleted']) {
714 $attributes = array("ref" => $item['uri'], "when" => datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME));
715 return xml::create_element($doc, "at:deleted-entry", "", $attributes);
718 $entry = $doc->createElement("entry");
720 if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
721 $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
723 $body = $item['body'];
725 // Remove the abstract element. It is only locally important.
726 $body = remove_abstract($body);
728 if ($type == 'html') {
731 if ($item['title'] != "")
732 $htmlbody = "[b]".$item['title']."[/b]\n\n".$htmlbody;
734 $htmlbody = bbcode($htmlbody, false, false, 7);
737 $author = self::add_entry_author($doc, "author", $item["author-link"], $item);
738 $entry->appendChild($author);
740 $dfrnowner = self::add_entry_author($doc, "dfrn:owner", $item["owner-link"], $item);
741 $entry->appendChild($dfrnowner);
743 if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
744 $parent = q("SELECT `guid` FROM `item` WHERE `id` = %d", intval($item["parent"]));
745 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
746 $attributes = array("ref" => $parent_item, "type" => "text/html",
747 "href" => app::get_baseurl().'/display/'.$parent[0]['guid'],
748 "dfrn:diaspora_guid" => $parent[0]['guid']);
749 xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
752 xml::add_element($doc, $entry, "id", $item["uri"]);
753 xml::add_element($doc, $entry, "title", $item["title"]);
755 xml::add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
756 xml::add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
758 // "dfrn:env" is used to read the content
759 xml::add_element($doc, $entry, "dfrn:env", base64url_encode($body, true));
761 // The "content" field is not read by the receiver. We could remove it when the type is "text"
762 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
763 xml::add_element($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), array("type" => $type));
765 // We save this value in "plink". Maybe we should read it from there as well?
766 xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
767 "href" => app::get_baseurl()."/display/".$item["guid"]));
769 // "comment-allow" is some old fashioned stuff for old Friendica versions.
770 // It is included in the rewritten code for completeness
772 xml::add_element($doc, $entry, "dfrn:comment-allow", intval($item['last-child']));
774 if($item['location'])
775 xml::add_element($doc, $entry, "dfrn:location", $item['location']);
778 xml::add_element($doc, $entry, "georss:point", $item['coord']);
780 if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
781 xml::add_element($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
784 xml::add_element($doc, $entry, "dfrn:extid", $item['extid']);
786 if($item['bookmark'])
787 xml::add_element($doc, $entry, "dfrn:bookmark", "true");
790 xml::add_element($doc, $entry, "statusnet:notice_info", "", array("local_id" => $item['id'], "source" => $item['app']));
792 xml::add_element($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
794 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
795 // It is needed for relayed comments to Diaspora.
796 if($item['signed_text']) {
797 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
798 xml::add_element($doc, $entry, "dfrn:diaspora_signature", $sign);
801 xml::add_element($doc, $entry, "activity:verb", construct_verb($item));
803 if ($item['object-type'] != "")
804 xml::add_element($doc, $entry, "activity:object-type", $item['object-type']);
805 elseif ($item['id'] == $item['parent'])
806 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
808 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
810 $actobj = self::create_activity($doc, "activity:object", $item['object']);
812 $entry->appendChild($actobj);
814 $actarg = self::create_activity($doc, "activity:target", $item['target']);
816 $entry->appendChild($actarg);
818 $tags = item_getfeedtags($item);
822 if (($type != 'html') OR ($t[0] != "@"))
823 xml::add_element($doc, $entry, "category", "", array("scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]));
829 $mentioned[$t[1]] = $t[1];
831 foreach ($mentioned AS $mention) {
832 $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
833 intval($owner["uid"]),
834 dbesc(normalise_link($mention)));
835 if ($r[0]["forum"] OR $r[0]["prv"])
836 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
837 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
838 "href" => $mention));
840 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
841 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
842 "href" => $mention));
845 self::get_attachment($doc, $entry, $item);
851 * @brief Delivers the atom content to the contacts
853 * @param array $owner Owner record
854 * @param array $contactr Contact record of the receiver
855 * @param string $atom Content that will be transmitted
856 * @param bool $dissolve (to be documented)
858 * @return int Deliver status. -1 means an error.
860 public static function deliver($owner,$contact,$atom, $dissolve = false) {
864 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
866 if($contact['duplex'] && $contact['dfrn-id'])
867 $idtosend = '0:' . $orig_id;
868 if($contact['duplex'] && $contact['issued-id'])
869 $idtosend = '1:' . $orig_id;
872 $rino = get_config('system','rino_encrypt');
873 $rino = intval($rino);
874 // use RINO1 if mcrypt isn't installed and RINO2 was selected
875 if ($rino==2 and !function_exists('mcrypt_create_iv')) $rino=1;
877 logger("Local rino version: ". $rino, LOGGER_DEBUG);
879 $ssl_val = intval(get_config('system','ssl_policy'));
883 case SSL_POLICY_FULL:
884 $ssl_policy = 'full';
886 case SSL_POLICY_SELFSIGN:
887 $ssl_policy = 'self';
889 case SSL_POLICY_NONE:
891 $ssl_policy = 'none';
895 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
897 logger('dfrn_deliver: ' . $url);
899 $xml = fetch_url($url);
901 $curl_stat = $a->get_curl_code();
903 return(-1); // timed out
905 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
910 if(strpos($xml,'<?xml') === false) {
911 logger('dfrn_deliver: no valid XML returned');
912 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
916 $res = parse_xml_string($xml);
918 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
919 return (($res->status) ? $res->status : 3);
922 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
923 $challenge = hex2bin((string) $res->challenge);
924 $perm = (($res->perm) ? $res->perm : null);
925 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
926 $rino_remote_version = intval($res->rino);
927 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
929 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
931 if($owner['page-flags'] == PAGE_PRVGROUP)
937 if((($perm == 'rw') && (! intval($contact['writable'])))
938 || (($perm == 'r') && (intval($contact['writable'])))) {
939 q("update contact set writable = %d where id = %d",
940 intval(($perm == 'rw') ? 1 : 0),
941 intval($contact['id'])
943 $contact['writable'] = (string) 1 - intval($contact['writable']);
947 if(($contact['duplex'] && strlen($contact['pubkey']))
948 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
949 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
950 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
951 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
953 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
954 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
957 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
959 if(strpos($final_dfrn_id,':') == 1)
960 $final_dfrn_id = substr($final_dfrn_id,2);
962 if($final_dfrn_id != $orig_id) {
963 logger('dfrn_deliver: wrong dfrn_id.');
964 // did not decode properly - cannot trust this site
968 $postvars['dfrn_id'] = $idtosend;
969 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
971 $postvars['dissolve'] = '1';
974 if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
975 $postvars['data'] = $atom;
976 $postvars['perm'] = 'rw';
978 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
979 $postvars['perm'] = 'r';
982 $postvars['ssl_policy'] = $ssl_policy;
985 $postvars['page'] = $page;
988 if($rino>0 && $rino_remote_version>0 && (! $dissolve)) {
989 logger('rino version: '. $rino_remote_version);
991 switch($rino_remote_version) {
993 // Deprecated rino version!
994 $key = substr(random_string(),0,16);
995 $data = aes_encrypt($postvars['data'],$key);
998 // RINO 2 based on php-encryption
1000 $key = Crypto::createNewRandomKey();
1001 } catch (CryptoTestFailed $ex) {
1002 logger('Cannot safely create a key');
1004 } catch (CannotPerformOperation $ex) {
1005 logger('Cannot safely create a key');
1009 $data = Crypto::encrypt($postvars['data'], $key);
1010 } catch (CryptoTestFailed $ex) {
1011 logger('Cannot safely perform encryption');
1013 } catch (CannotPerformOperation $ex) {
1014 logger('Cannot safely perform encryption');
1019 logger("rino: invalid requested verision '$rino_remote_version'");
1023 $postvars['rino'] = $rino_remote_version;
1024 $postvars['data'] = bin2hex($data);
1026 #logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1029 if($dfrn_version >= 2.1) {
1030 if(($contact['duplex'] && strlen($contact['pubkey']))
1031 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1032 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey'])))
1034 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1036 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1039 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY))
1040 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1042 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1046 logger('md5 rawkey ' . md5($postvars['key']));
1048 $postvars['key'] = bin2hex($postvars['key']);
1052 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1054 $xml = post_url($contact['notify'],$postvars);
1056 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1058 $curl_stat = $a->get_curl_code();
1059 if((! $curl_stat) || (! strlen($xml)))
1060 return(-1); // timed out
1062 if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
1065 if(strpos($xml,'<?xml') === false) {
1066 logger('dfrn_deliver: phase 2: no valid XML returned');
1067 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1071 if($contact['term-date'] != '0000-00-00 00:00:00') {
1072 logger("dfrn_deliver: $url back from the dead - removing mark for death");
1073 require_once('include/Contact.php');
1074 unmark_for_death($contact);
1077 $res = parse_xml_string($xml);
1079 return $res->status;
1083 * @brief Add new birthday event for this person
1085 * @param array $contact Contact record
1086 * @param string $birthday Birthday of the contact
1089 private function birthday_event($contact, $birthday) {
1091 logger("updating birthday: ".$birthday." for contact ".$contact["id"]);
1093 $bdtext = sprintf(t("%s\'s birthday"), $contact["name"]);
1094 $bdtext2 = sprintf(t("Happy Birthday %s"), " [url=".$contact["url"]."]".$contact["name"]."[/url]") ;
1097 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1098 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1099 intval($contact["uid"]),
1100 intval($contact["id"]),
1101 dbesc(datetime_convert()),
1102 dbesc(datetime_convert()),
1103 dbesc(datetime_convert("UTC","UTC", $birthday)),
1104 dbesc(datetime_convert("UTC","UTC", $birthday." + 1 day ")),
1112 * @brief Fetch the author data from head or entry items
1114 * @param object $xpath XPath object
1115 * @param object $context In which context should the data be searched
1116 * @param array $importer Record of the importer user mixed with contact of the content
1117 * @param string $element Element name from which the data is fetched
1118 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1120 * @return Returns an array with relevant data of the author
1122 private function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "") {
1125 $author["name"] = $xpath->evaluate($element."/atom:name/text()", $context)->item(0)->nodeValue;
1126 $author["link"] = $xpath->evaluate($element."/atom:uri/text()", $context)->item(0)->nodeValue;
1128 $r = q("SELECT `id`, `uid`, `url`, `network`, `avatar-date`, `name-date`, `uri-date`, `addr`,
1129 `name`, `nick`, `about`, `location`, `keywords`, `bdyear`, `bd`
1130 FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
1131 intval($importer["uid"]), dbesc(normalise_link($author["link"])), dbesc(NETWORK_STATUSNET));
1134 $author["contact-id"] = $r[0]["id"];
1135 $author["network"] = $r[0]["network"];
1138 logger("Contact ".$author["link"]." wasn't found for user ".$importer["uid"]." XML: ".$xml, LOGGER_DEBUG);
1140 $author["contact-id"] = $importer["id"];
1141 $author["network"] = $importer["network"];
1145 // Until now we aren't serving different sizes - but maybe later
1146 $avatarlist = array();
1147 // @todo check if "avatar" or "photo" would be the best field in the specification
1148 $avatars = $xpath->query($element."/atom:link[@rel='avatar']", $context);
1149 foreach($avatars AS $avatar) {
1152 foreach($avatar->attributes AS $attributes) {
1153 if ($attributes->name == "href")
1154 $href = $attributes->textContent;
1155 if ($attributes->name == "width")
1156 $width = $attributes->textContent;
1157 if ($attributes->name == "updated")
1158 $contact["avatar-date"] = $attributes->textContent;
1160 if (($width > 0) AND ($href != ""))
1161 $avatarlist[$width] = $href;
1163 if (count($avatarlist) > 0) {
1164 krsort($avatarlist);
1165 $author["avatar"] = current($avatarlist);
1168 if ($r AND !$onlyfetch) {
1169 logger("Check if contact details for contact ".$r[0]["id"]." (".$r[0]["nick"].") have to be updated.", LOGGER_DEBUG);
1171 $poco = array("url" => $contact["url"]);
1173 // When was the last change to name or uri?
1174 $name_element = $xpath->query($element."/atom:name", $context)->item(0);
1175 foreach($name_element->attributes AS $attributes)
1176 if ($attributes->name == "updated")
1177 $poco["name-date"] = $attributes->textContent;
1179 $link_element = $xpath->query($element."/atom:link", $context)->item(0);
1180 foreach($link_element->attributes AS $attributes)
1181 if ($attributes->name == "updated")
1182 $poco["uri-date"] = $attributes->textContent;
1184 // Update contact data
1185 $value = $xpath->evaluate($element."/dfrn:handle/text()", $context)->item(0)->nodeValue;
1187 $poco["addr"] = $value;
1189 $value = $xpath->evaluate($element."/poco:displayName/text()", $context)->item(0)->nodeValue;
1191 $poco["name"] = $value;
1193 $value = $xpath->evaluate($element."/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
1195 $poco["nick"] = $value;
1197 $value = $xpath->evaluate($element."/poco:note/text()", $context)->item(0)->nodeValue;
1199 $poco["about"] = $value;
1201 $value = $xpath->evaluate($element."/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
1203 $poco["location"] = $value;
1205 /// @todo Add support for the following fields that we don't support by now in the contact table:
1206 /// - poco:utcOffset
1213 // Save the keywords into the contact table
1215 $tagelements = $xpath->evaluate($element."/poco:tags/text()", $context);
1216 foreach($tagelements AS $tag)
1217 $tags[$tag->nodeValue] = $tag->nodeValue;
1220 $poco["keywords"] = implode(", ", $tags);
1222 // "dfrn:birthday" contains the birthday converted to UTC
1223 $old_bdyear = $contact["bdyear"];
1225 $birthday = $xpath->evaluate($element."/dfrn:birthday/text()", $context)->item(0)->nodeValue;
1227 if (strtotime($birthday) > time()) {
1228 $bd_timestamp = strtotime($birthday);
1230 $poco["bdyear"] = date("Y", $bd_timestamp);
1233 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1234 $value = $xpath->evaluate($element."/poco:birthday/text()", $context)->item(0)->nodeValue;
1236 if (!in_array($value, array("", "0000-00-00"))) {
1237 $bdyear = date("Y");
1238 $value = str_replace("0000", $bdyear, $value);
1240 if (strtotime($value) < time()) {
1241 $value = str_replace($bdyear, $bdyear + 1, $value);
1242 $bdyear = $bdyear + 1;
1245 $poco["bd"] = $value;
1248 $contact = array_merge($contact, $poco);
1250 if ($old_bdyear != $contact["bdyear"])
1251 self::birthday_event($contact, $birthday);
1253 // Get all field names
1255 foreach ($r[0] AS $field => $data)
1256 $fields[$field] = $data;
1258 unset($fields["id"]);
1259 unset($fields["uid"]);
1260 unset($fields["url"]);
1261 unset($fields["avatar-date"]);
1262 unset($fields["name-date"]);
1263 unset($fields["uri-date"]);
1265 // Update check for this field has to be done differently
1266 $datefields = array("name-date", "uri-date");
1267 foreach ($datefields AS $field)
1268 if (strtotime($contact[$field]) > strtotime($r[0][$field])) {
1269 logger("Difference for contact ".$contact["id"]." in field '".$field."'. Old value: '".$contact[$field]."', new value '".$r[0][$field]."'", LOGGER_DEBUG);
1273 foreach ($fields AS $field => $data)
1274 if ($contact[$field] != $r[0][$field]) {
1275 logger("Difference for contact ".$contact["id"]." in field '".$field."'. Old value: '".$contact[$field]."', new value '".$r[0][$field]."'", LOGGER_DEBUG);
1280 logger("Update contact data for contact ".$contact["id"]." (".$contact["nick"].")", LOGGER_DEBUG);
1282 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1283 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s',
1284 `name-date` = '%s', `uri-date` = '%s'
1285 WHERE `id` = %d AND `network` = '%s'",
1286 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
1287 dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1288 dbesc($contact["bd"]), dbesc($contact["name-date"]), dbesc($contact["uri-date"]),
1289 intval($contact["id"]), dbesc($contact["network"]));
1292 update_contact_avatar($author["avatar"], $importer["uid"], $contact["id"],
1293 (strtotime($contact["avatar-date"]) > strtotime($r[0]["avatar-date"])));
1295 // The generation is a sign for the reliability of the provided data.
1296 // It is used in the socgraph.php to prevent that old contact data
1297 // that was relayed over several servers can overwrite contact
1298 // data that we received directly.
1300 $poco["generation"] = 2;
1301 $poco["photo"] = $author["avatar"];
1302 update_gcontact($poco);
1309 * @brief Transforms activity objects into an XML string
1311 * @param object $xpath XPath object
1312 * @param object $activity Activity object
1313 * @param text $element element name
1315 * @return string XML string
1317 private function transform_activity($xpath, $activity, $element) {
1318 if (!is_object($activity))
1321 $obj_doc = new DOMDocument("1.0", "utf-8");
1322 $obj_doc->formatOutput = true;
1324 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1326 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1327 xml::add_element($obj_doc, $obj_element, "type", $activity_type);
1329 $id = $xpath->query("atom:id", $activity)->item(0);
1331 $obj_element->appendChild($obj_doc->importNode($id, true));
1333 $title = $xpath->query("atom:title", $activity)->item(0);
1334 if (is_object($title))
1335 $obj_element->appendChild($obj_doc->importNode($title, true));
1337 $links = $xpath->query("atom:link", $activity);
1338 if (is_object($links))
1339 foreach ($links AS $link)
1340 $obj_element->appendChild($obj_doc->importNode($link, true));
1342 $content = $xpath->query("atom:content", $activity)->item(0);
1343 if (is_object($content))
1344 $obj_element->appendChild($obj_doc->importNode($content, true));
1346 $obj_doc->appendChild($obj_element);
1348 $objxml = $obj_doc->saveXML($obj_element);
1350 // @todo This isn't totally clean. We should find a way to transform the namespaces
1351 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1356 * @brief Processes the mail elements
1358 * @param object $xpath XPath object
1359 * @param object $mail mail elements
1360 * @param array $importer Record of the importer user mixed with contact of the content
1362 private function process_mail($xpath, $mail, $importer) {
1364 logger("Processing mails");
1367 $msg["uid"] = $importer["importer_uid"];
1368 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1369 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1370 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1371 $msg["contact-id"] = $importer["id"];
1372 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1373 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1374 $msg["created"] = $xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue;
1375 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1376 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1378 $msg["replied"] = 0;
1382 $r = dbq("INSERT INTO `mail` (`".implode("`, `", array_keys($msg))."`) VALUES ('".implode("', '", array_values($msg))."')");
1384 // send notifications.
1386 $notif_params = array(
1387 "type" => NOTIFY_MAIL,
1388 "notify_flags" => $importer["notify-flags"],
1389 "language" => $importer["language"],
1390 "to_name" => $importer["username"],
1391 "to_email" => $importer["email"],
1392 "uid" => $importer["importer_uid"],
1394 "source_name" => $msg["from-name"],
1395 "source_link" => $importer["url"],
1396 "source_photo" => $importer["thumb"],
1397 "verb" => ACTIVITY_POST,
1401 notification($notif_params);
1403 logger("Mail is processed, notification was sent.");
1407 * @brief Processes the suggestion elements
1409 * @param object $xpath XPath object
1410 * @param object $suggestion suggestion elements
1411 * @param array $importer Record of the importer user mixed with contact of the content
1413 private function process_suggestion($xpath, $suggestion, $importer) {
1415 logger("Processing suggestions");
1418 $suggest["uid"] = $importer["importer_uid"];
1419 $suggest["cid"] = $importer["id"];
1420 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1421 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1422 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1423 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1424 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1426 // Does our member already have a friend matching this description?
1428 $r = q("SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1429 dbesc($suggest["name"]),
1430 dbesc(normalise_link($suggest["url"])),
1431 intval($suggest["uid"])
1436 // Do we already have an fcontact record for this person?
1439 $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1440 dbesc($suggest["url"]),
1441 dbesc($suggest["name"]),
1442 dbesc($suggest["request"])
1447 // OK, we do. Do we already have an introduction for this person ?
1448 $r = q("SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1449 intval($suggest["uid"]),
1456 $r = q("INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1457 dbesc($suggest["name"]),
1458 dbesc($suggest["url"]),
1459 dbesc($suggest["photo"]),
1460 dbesc($suggest["request"])
1462 $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1463 dbesc($suggest["url"]),
1464 dbesc($suggest["name"]),
1465 dbesc($suggest["request"])
1470 // database record did not get created. Quietly give up.
1474 $hash = random_string();
1476 $r = q("INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1477 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1478 intval($suggest["uid"]),
1480 intval($suggest["cid"]),
1481 dbesc($suggest["body"]),
1483 dbesc(datetime_convert()),
1488 "type" => NOTIFY_SUGGEST,
1489 "notify_flags" => $importer["notify-flags"],
1490 "language" => $importer["language"],
1491 "to_name" => $importer["username"],
1492 "to_email" => $importer["email"],
1493 "uid" => $importer["importer_uid"],
1495 "link" => App::get_baseurl()."/notifications/intros",
1496 "source_name" => $importer["name"],
1497 "source_link" => $importer["url"],
1498 "source_photo" => $importer["photo"],
1499 "verb" => ACTIVITY_REQ_FRIEND,
1508 * @brief Processes the relocation elements
1510 * @param object $xpath XPath object
1511 * @param object $relocation relocation elements
1512 * @param array $importer Record of the importer user mixed with contact of the content
1514 private function process_relocation($xpath, $relocation, $importer) {
1516 logger("Processing relocations");
1518 $relocate = array();
1519 $relocate["uid"] = $importer["importer_uid"];
1520 $relocate["cid"] = $importer["id"];
1521 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1522 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1523 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1524 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1525 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1526 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1527 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1528 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1529 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1530 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1533 $r = q("SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
1534 intval($importer["id"]),
1535 intval($importer["importer_uid"]));
1541 $x = q("UPDATE `contact` SET
1552 `site-pubkey` = '%s'
1553 WHERE `id` = %d AND `uid` = %d;",
1554 dbesc($relocate["name"]),
1555 dbesc($relocate["photo"]),
1556 dbesc($relocate["thumb"]),
1557 dbesc($relocate["micro"]),
1558 dbesc($relocate["url"]),
1559 dbesc(normalise_link($relocate["url"])),
1560 dbesc($relocate["request"]),
1561 dbesc($relocate["confirm"]),
1562 dbesc($relocate["notify"]),
1563 dbesc($relocate["poll"]),
1564 dbesc($relocate["sitepubkey"]),
1565 intval($importer["id"]),
1566 intval($importer["importer_uid"]));
1573 'owner-link' => array($old["url"], $relocate["url"]),
1574 'author-link' => array($old["url"], $relocate["url"]),
1575 'owner-avatar' => array($old["photo"], $relocate["photo"]),
1576 'author-avatar' => array($old["photo"], $relocate["photo"]),
1578 foreach ($fields as $n=>$f){
1579 $x = q("UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1582 intval($importer["importer_uid"]));
1588 /// merge with current record, current contents have priority
1589 /// update record, set url-updated
1590 /// update profile photos
1591 /// schedule a scan?
1596 * @brief Updates an item
1598 * @param array $current the current item record
1599 * @param array $item the new item record
1600 * @param array $importer Record of the importer user mixed with contact of the content
1601 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
1603 private function update_content($current, $item, $importer, $entrytype) {
1606 if (edited_timestamp_is_newer($current, $item)) {
1608 // do not accept (ignore) an earlier edit than one we currently have.
1609 if(datetime_convert("UTC","UTC",$item["edited"]) < $current["edited"])
1612 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s', `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
1613 dbesc($item["title"]),
1614 dbesc($item["body"]),
1615 dbesc($item["tag"]),
1616 dbesc(datetime_convert("UTC","UTC",$item["edited"])),
1617 dbesc(datetime_convert()),
1618 dbesc($item["uri"]),
1619 intval($importer["importer_uid"])
1621 create_tags_from_itemuri($item["uri"], $importer["importer_uid"]);
1622 update_thread_uri($item["uri"], $importer["importer_uid"]);
1626 if ($entrytype == DFRN_REPLY_RC)
1627 proc_run("php", "include/notifier.php","comment-import", $current["id"]);
1630 // update last-child if it changes
1631 if($item["last-child"] AND ($item["last-child"] != $current["last-child"])) {
1632 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1633 dbesc(datetime_convert()),
1634 dbesc($item["parent-uri"]),
1635 intval($importer["importer_uid"])
1637 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
1638 intval($item["last-child"]),
1639 dbesc(datetime_convert()),
1640 dbesc($item["uri"]),
1641 intval($importer["importer_uid"])
1648 * @brief Detects the entry type of the item
1650 * @param array $importer Record of the importer user mixed with contact of the content
1651 * @param array $item the new item record
1653 * @return int Is it a toplevel entry, a comment or a relayed comment?
1655 private function get_entry_type($importer, $item) {
1656 if ($item["parent-uri"] != $item["uri"]) {
1659 if($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
1662 logger("possible community action");
1664 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
1666 // was the top-level post for this action written by somebody on this site?
1667 // Specifically, the recipient?
1669 $is_a_remote_action = false;
1671 $r = q("SELECT `item`.`parent-uri` FROM `item`
1672 WHERE `item`.`uri` = '%s'
1674 dbesc($item["parent-uri"])
1676 if($r && count($r)) {
1677 $r = q("SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
1678 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1679 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
1680 AND `item`.`uid` = %d
1683 dbesc($r[0]["parent-uri"]),
1684 dbesc($r[0]["parent-uri"]),
1685 dbesc($r[0]["parent-uri"]),
1686 intval($importer["importer_uid"])
1689 $is_a_remote_action = true;
1692 // Does this have the characteristics of a community or private group action?
1693 // If it's an action to a wall post on a community/prvgroup page it's a
1694 // valid community action. Also forum_mode makes it valid for sure.
1695 // If neither, it's not.
1697 if($is_a_remote_action && $community) {
1698 if((!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
1699 $is_a_remote_action = false;
1700 logger("not a community action");
1704 if ($is_a_remote_action)
1705 return DFRN_REPLY_RC;
1710 return DFRN_TOP_LEVEL;
1715 * @brief Send a "poke"
1717 * @param array $item the new item record
1718 * @param array $importer Record of the importer user mixed with contact of the content
1719 * @param int $posted_id The record number of item record that was just posted
1721 private function do_poke($item, $importer, $posted_id) {
1722 $verb = urldecode(substr($item["verb"],strpos($item["verb"], "#")+1));
1725 $xo = parse_xml_string($item["object"],false);
1727 if(($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
1729 // somebody was poked/prodded. Was it me?
1730 foreach($xo->link as $l) {
1731 $atts = $l->attributes();
1732 switch($atts["rel"]) {
1734 $Blink = $atts["href"];
1741 if($Blink && link_compare($Blink,App::get_baseurl()."/profile/".$importer["nickname"])) {
1743 // send a notification
1745 "type" => NOTIFY_POKE,
1746 "notify_flags" => $importer["notify-flags"],
1747 "language" => $importer["language"],
1748 "to_name" => $importer["username"],
1749 "to_email" => $importer["email"],
1750 "uid" => $importer["importer_uid"],
1752 "link" => App::get_baseurl()."/display/".urlencode(get_item_guid($posted_id)),
1753 "source_name" => stripslashes($item["author-name"]),
1754 "source_link" => $item["author-link"],
1755 "source_photo" => ((link_compare($item["author-link"],$importer["url"]))
1756 ? $importer["thumb"] : $item["author-avatar"]),
1757 "verb" => $item["verb"],
1758 "otype" => "person",
1759 "activity" => $verb,
1760 "parent" => $item["parent"]
1767 * @brief Processes several actions, depending on the verb
1769 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
1770 * @param array $importer Record of the importer user mixed with contact of the content
1771 * @param array $item the new item record
1772 * @param bool $is_like Is the verb a "like"?
1774 * @return bool Should the processing of the entries be continued?
1776 private function process_verbs($entrytype, $importer, &$item, &$is_like) {
1778 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
1780 if (($entrytype == DFRN_TOP_LEVEL)) {
1781 // The filling of the the "contact" variable is done for legcy reasons
1782 // The functions below are partly used by ostatus.php as well - where we have this variable
1783 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
1785 $nickname = $contact["nick"];
1787 // Big question: Do we need these functions? They were part of the "consume_feed" function.
1788 // This function once was responsible for DFRN and OStatus.
1789 if(activity_match($item["verb"],ACTIVITY_FOLLOW)) {
1790 logger("New follower");
1791 new_follower($importer, $contact, $item, $nickname);
1794 if(activity_match($item["verb"],ACTIVITY_UNFOLLOW)) {
1795 logger("Lost follower");
1796 lose_follower($importer, $contact, $item);
1799 if(activity_match($item["verb"],ACTIVITY_REQ_FRIEND)) {
1800 logger("New friend request");
1801 new_follower($importer, $contact, $item, $nickname, true);
1804 if(activity_match($item["verb"],ACTIVITY_UNFRIEND)) {
1805 logger("Lost sharer");
1806 lose_sharer($importer, $contact, $item);
1810 if(($item["verb"] == ACTIVITY_LIKE)
1811 || ($item["verb"] == ACTIVITY_DISLIKE)
1812 || ($item["verb"] == ACTIVITY_ATTEND)
1813 || ($item["verb"] == ACTIVITY_ATTENDNO)
1814 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)) {
1816 $item["type"] = "activity";
1817 $item["gravity"] = GRAVITY_LIKE;
1818 // only one like or dislike per person
1819 // splitted into two queries for performance issues
1820 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `parent-uri` = '%s' AND NOT `deleted` LIMIT 1",
1821 intval($item["uid"]),
1822 dbesc($item["author-link"]),
1823 dbesc($item["verb"]),
1824 dbesc($item["parent-uri"])
1829 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `thr-parent` = '%s' AND NOT `deleted` LIMIT 1",
1830 intval($item["uid"]),
1831 dbesc($item["author-link"]),
1832 dbesc($item["verb"]),
1833 dbesc($item["parent-uri"])
1840 if(($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
1842 $xo = parse_xml_string($item["object"],false);
1843 $xt = parse_xml_string($item["target"],false);
1845 if($xt->type == ACTIVITY_OBJ_NOTE) {
1846 $r = q("SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1848 intval($importer["importer_uid"])
1854 // extract tag, if not duplicate, add to parent item
1856 if(!(stristr($r[0]["tag"],trim($xo->content)))) {
1857 q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
1858 dbesc($r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
1861 create_tags_from_item($r[0]["id"]);
1871 * @brief Processes the link elements
1873 * @param object $links link elements
1874 * @param array $item the item record
1876 private function parse_links($links, &$item) {
1882 foreach ($links AS $link) {
1883 foreach($link->attributes AS $attributes) {
1884 if ($attributes->name == "href")
1885 $href = $attributes->textContent;
1886 if ($attributes->name == "rel")
1887 $rel = $attributes->textContent;
1888 if ($attributes->name == "type")
1889 $type = $attributes->textContent;
1890 if ($attributes->name == "length")
1891 $length = $attributes->textContent;
1892 if ($attributes->name == "title")
1893 $title = $attributes->textContent;
1895 if (($rel != "") AND ($href != ""))
1898 $item["plink"] = $href;
1902 if(strlen($item["attach"]))
1903 $item["attach"] .= ",";
1905 $item["attach"] .= '[attach]href="'.$href.'" length="'.$length.'" type="'.$type.'" title="'.$title.'"[/attach]';
1912 * @brief Processes the entry elements which contain the items and comments
1914 * @param array $header Array of the header elements that always stay the same
1915 * @param object $xpath XPath object
1916 * @param object $entry entry elements
1917 * @param array $importer Record of the importer user mixed with contact of the content
1919 private function process_entry($header, $xpath, $entry, $importer) {
1921 logger("Processing entries");
1926 $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
1929 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
1931 $item["owner-name"] = $owner["name"];
1932 $item["owner-link"] = $owner["link"];
1933 $item["owner-avatar"] = $owner["avatar"];
1936 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
1938 $item["author-name"] = $author["name"];
1939 $item["author-link"] = $author["link"];
1940 $item["author-avatar"] = $author["avatar"];
1942 $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
1944 $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
1945 $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
1947 $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
1948 $item["body"] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$item["body"]);
1949 // make sure nobody is trying to sneak some html tags by us
1950 $item["body"] = notags(base64url_decode($item["body"]));
1952 $item["body"] = limit_body_size($item["body"]);
1954 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
1955 if((strpos($item['body'],'<') !== false) && (strpos($item['body'],'>') !== false)) {
1957 $item['body'] = reltoabs($item['body'],$base_url);
1959 $item['body'] = html2bb_video($item['body']);
1961 $item['body'] = oembed_html2bbcode($item['body']);
1963 $config = HTMLPurifier_Config::createDefault();
1964 $config->set('Cache.DefinitionImpl', null);
1966 // we shouldn't need a whitelist, because the bbcode converter
1967 // will strip out any unsupported tags.
1969 $purifier = new HTMLPurifier($config);
1970 $item['body'] = $purifier->purify($item['body']);
1972 $item['body'] = @html2bbcode($item['body']);
1975 /// @todo We should check for a repeated post and if we know the repeated author.
1977 // We don't need the content element since "dfrn:env" is always present
1978 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
1980 $item["last-child"] = $xpath->query("dfrn:comment-allow/text()", $entry)->item(0)->nodeValue;
1981 $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
1983 $georsspoint = $xpath->query("georss:point", $entry);
1985 $item["coord"] = $georsspoint->item(0)->nodeValue;
1987 $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
1989 $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
1991 if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true")
1992 $item["bookmark"] = true;
1994 $notice_info = $xpath->query("statusnet:notice_info", $entry);
1995 if ($notice_info AND ($notice_info->length > 0)) {
1996 foreach($notice_info->item(0)->attributes AS $attributes) {
1997 if ($attributes->name == "source")
1998 $item["app"] = strip_tags($attributes->textContent);
2002 $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
2004 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "item_store"
2005 $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
2007 $item["dsprsig"] = $dsprsig;
2009 $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
2011 if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "")
2012 $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
2014 $object = $xpath->query("activity:object", $entry)->item(0);
2015 $item["object"] = self::transform_activity($xpath, $object, "object");
2017 if (trim($item["object"]) != "") {
2018 $r = parse_xml_string($item["object"], false);
2019 if (isset($r->type))
2020 $item["object-type"] = $r->type;
2023 $target = $xpath->query("activity:target", $entry)->item(0);
2024 $item["target"] = self::transform_activity($xpath, $target, "target");
2026 $categories = $xpath->query("atom:category", $entry);
2028 foreach ($categories AS $category) {
2031 foreach($category->attributes AS $attributes) {
2032 if ($attributes->name == "term")
2033 $term = $attributes->textContent;
2035 if ($attributes->name == "scheme")
2036 $scheme = $attributes->textContent;
2039 if (($term != "") AND ($scheme != "")) {
2040 $parts = explode(":", $scheme);
2041 if ((count($parts) >= 4) AND (array_shift($parts) == "X-DFRN")) {
2042 $termhash = array_shift($parts);
2043 $termurl = implode(":", $parts);
2045 if(strlen($item["tag"]))
2046 $item["tag"] .= ",";
2048 $item["tag"] .= $termhash."[url=".$termurl."]".$term."[/url]";
2056 $links = $xpath->query("atom:link", $entry);
2058 self::parse_links($links, $item);
2060 // Is it a reply or a top level posting?
2061 $item["parent-uri"] = $item["uri"];
2063 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2064 if (is_object($inreplyto->item(0)))
2065 foreach($inreplyto->item(0)->attributes AS $attributes)
2066 if ($attributes->name == "ref")
2067 $item["parent-uri"] = $attributes->textContent;
2069 // Get the type of the item (Top level post, reply or remote reply)
2070 $entrytype = self::get_entry_type($importer, $item);
2072 // Now assign the rest of the values that depend on the type of the message
2073 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2074 if (!isset($item["object-type"]))
2075 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2077 if ($item["contact-id"] != $owner["contact-id"])
2078 $item["contact-id"] = $owner["contact-id"];
2080 if (($item["network"] != $owner["network"]) AND ($owner["network"] != ""))
2081 $item["network"] = $owner["network"];
2083 if ($item["contact-id"] != $author["contact-id"])
2084 $item["contact-id"] = $author["contact-id"];
2086 if (($item["network"] != $author["network"]) AND ($author["network"] != ""))
2087 $item["network"] = $author["network"];
2089 // This code was taken from the old DFRN code
2090 // When activated, forums don't work.
2091 // And: Why should we disallow commenting by followers?
2092 // the behaviour is now similar to the Diaspora part.
2093 //if($importer["rel"] == CONTACT_IS_FOLLOWER) {
2094 // logger("Contact ".$importer["id"]." is only follower. Quitting", LOGGER_DEBUG);
2099 if ($entrytype == DFRN_REPLY_RC) {
2100 $item["type"] = "remote-comment";
2102 } elseif ($entrytype == DFRN_TOP_LEVEL) {
2103 if (!isset($item["object-type"]))
2104 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2107 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2108 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2109 $ev = bbtoevent($item["body"]);
2110 if((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2111 logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2112 $ev["cid"] = $importer["id"];
2113 $ev["uid"] = $importer["uid"];
2114 $ev["uri"] = $item["uri"];
2115 $ev["edited"] = $item["edited"];
2116 $ev['private'] = $item['private'];
2117 $ev["guid"] = $item["guid"];
2119 $r = q("SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2120 dbesc($item["uri"]),
2121 intval($importer["uid"])
2124 $ev["id"] = $r[0]["id"];
2126 $event_id = event_store($ev);
2127 logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2133 $r = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2134 dbesc($item["uri"]),
2135 intval($importer["importer_uid"])
2138 if (!self::process_verbs($entrytype, $importer, $item, $is_like)) {
2139 logger("Exiting because 'process_verbs' told us so", LOGGER_DEBUG);
2143 // Update content if 'updated' changes
2145 if (self::update_content($r[0], $item, $importer, $entrytype))
2146 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2148 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2152 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2153 $posted_id = item_store($item);
2158 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2160 $item["id"] = $posted_id;
2162 $r = q("SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2164 intval($importer["importer_uid"])
2167 $parent = $r[0]["parent"];
2168 $parent_uri = $r[0]["parent-uri"];
2172 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2173 dbesc(datetime_convert()),
2174 intval($importer["importer_uid"]),
2175 intval($r[0]["parent"])
2178 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d",
2179 dbesc(datetime_convert()),
2180 intval($importer["importer_uid"]),
2185 if($posted_id AND $parent AND ($entrytype == DFRN_REPLY_RC)) {
2186 logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
2187 proc_run("php", "include/notifier.php", "comment-import", $posted_id);
2192 } else { // $entrytype == DFRN_TOP_LEVEL
2193 if(!link_compare($item["owner-link"],$importer["url"])) {
2194 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2195 // but otherwise there's a possible data mixup on the sender's system.
2196 // the tgroup delivery code called from item_store will correct it if it's a forum,
2197 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2198 logger('Correcting item owner.', LOGGER_DEBUG);
2199 $item["owner-name"] = $importer["senderName"];
2200 $item["owner-link"] = $importer["url"];
2201 $item["owner-avatar"] = $importer["thumb"];
2204 if(($importer["rel"] == CONTACT_IS_FOLLOWER) && (!tgroup_check($importer["importer_uid"], $item))) {
2205 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2209 // This is my contact on another system, but it's really me.
2210 // Turn this into a wall post.
2211 $notify = item_is_remote_self($importer, $item);
2213 $posted_id = item_store($item, false, $notify);
2215 logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2217 if(stristr($item["verb"],ACTIVITY_POKE))
2218 self::do_poke($item, $importer, $posted_id);
2223 * @brief Deletes items
2225 * @param object $xpath XPath object
2226 * @param object $deletion deletion elements
2227 * @param array $importer Record of the importer user mixed with contact of the content
2229 private function process_deletion($xpath, $deletion, $importer) {
2231 logger("Processing deletions");
2233 foreach($deletion->attributes AS $attributes) {
2234 if ($attributes->name == "ref")
2235 $uri = $attributes->textContent;
2236 if ($attributes->name == "when")
2237 $when = $attributes->textContent;
2240 $when = datetime_convert("UTC", "UTC", $when, "Y-m-d H:i:s");
2242 $when = datetime_convert("UTC", "UTC", "now", "Y-m-d H:i:s");
2244 if (!$uri OR !$importer["id"])
2247 /// @todo Only select the used fields
2248 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` INNER JOIN `contact` on `item`.`contact-id` = `contact`.`id`
2249 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2251 intval($importer["uid"]),
2252 intval($importer["id"])
2255 logger("Item with uri ".$uri." from contact ".$importer["id"]." for user ".$importer["uid"]." wasn't found.", LOGGER_DEBUG);
2261 $entrytype = self::get_entry_type($importer, $item);
2263 if(!$item["deleted"])
2264 logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG);
2268 if($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2269 logger("Deleting event ".$item["event-id"], LOGGER_DEBUG);
2270 event_delete($item["event-id"]);
2273 if(($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2275 $xo = parse_xml_string($item["object"],false);
2276 $xt = parse_xml_string($item["target"],false);
2278 if($xt->type == ACTIVITY_OBJ_NOTE) {
2279 $i = q("SELECT `id`, `contact-id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2281 intval($importer["importer_uid"])
2285 // For tags, the owner cannot remove the tag on the author's copy of the post.
2287 $owner_remove = (($item["contact-id"] == $i[0]["contact-id"]) ? true: false);
2288 $author_remove = (($item["origin"] && $item["self"]) ? true : false);
2289 $author_copy = (($item["origin"]) ? true : false);
2291 if($owner_remove && $author_copy)
2293 if($author_remove || $owner_remove) {
2294 $tags = explode(',',$i[0]["tag"]);
2297 foreach($tags as $tag)
2298 if(trim($tag) !== trim($xo->body))
2299 $newtags[] = trim($tag);
2301 q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2302 dbesc(implode(',',$newtags)),
2305 create_tags_from_item($i[0]["id"]);
2311 if($entrytype == DFRN_TOP_LEVEL) {
2312 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2313 `body` = '', `title` = ''
2314 WHERE `parent-uri` = '%s' AND `uid` = %d",
2316 dbesc(datetime_convert()),
2318 intval($importer["uid"])
2320 create_tags_from_itemuri($uri, $importer["uid"]);
2321 create_files_from_itemuri($uri, $importer["uid"]);
2322 update_thread_uri($uri, $importer["uid"]);
2324 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2325 `body` = '', `title` = ''
2326 WHERE `uri` = '%s' AND `uid` = %d",
2328 dbesc(datetime_convert()),
2330 intval($importer["uid"])
2332 create_tags_from_itemuri($uri, $importer["uid"]);
2333 create_files_from_itemuri($uri, $importer["uid"]);
2334 update_thread_uri($uri, $importer["importer_uid"]);
2335 if($item["last-child"]) {
2336 // ensure that last-child is set in case the comment that had it just got wiped.
2337 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2338 dbesc(datetime_convert()),
2339 dbesc($item["parent-uri"]),
2340 intval($item["uid"])
2342 // who is the last child now?
2343 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
2344 ORDER BY `created` DESC LIMIT 1",
2345 dbesc($item["parent-uri"]),
2346 intval($importer["uid"])
2349 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
2354 // if this is a relayed delete, propagate it to other recipients
2356 if($entrytype == DFRN_REPLY_RC) {
2357 logger("Notifying followers about deletion of post ".$item["id"], LOGGER_DEBUG);
2358 proc_run("php", "include/notifier.php","drop", $item["id"]);
2365 * @brief Imports a DFRN message
2367 * @param text $xml The DFRN message
2368 * @param array $importer Record of the importer user mixed with contact of the content
2369 * @param bool $sort_by_date Is used when feeds are polled
2371 public static function import($xml,$importer, $sort_by_date = false) {
2376 if($importer["readonly"]) {
2377 // We aren't receiving stuff from this person. But we will quietly ignore them
2378 // rather than a blatant "go away" message.
2379 logger('ignoring contact '.$importer["id"]);
2383 $doc = new DOMDocument();
2384 @$doc->loadXML($xml);
2386 $xpath = new DomXPath($doc);
2387 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2388 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2389 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2390 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2391 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2392 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2393 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2394 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2395 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2396 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2399 $header["uid"] = $importer["uid"];
2400 $header["network"] = NETWORK_DFRN;
2401 $header["type"] = "remote";
2402 $header["wall"] = 0;
2403 $header["origin"] = 0;
2404 $header["contact-id"] = $importer["id"];
2406 // Update the contact table if the data has changed
2408 // The "atom:author" is only present in feeds
2409 if ($xpath->query("/atom:feed/atom:author")->length > 0)
2410 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2412 // Only the "dfrn:owner" in the head section contains all data
2413 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0)
2414 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2416 logger("Import DFRN message for user ".$importer["uid"]." from contact ".$importer["id"], LOGGER_DEBUG);
2418 // is it a public forum? Private forums aren't supported by now with this method
2419 $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()", $context)->item(0)->nodeValue);
2421 if ($forum != $importer["forum"])
2422 q("UPDATE `contact` SET `forum` = %d WHERE `forum` != %d AND `id` = %d",
2423 intval($forum), intval($forum),
2424 intval($importer["id"])
2427 $mails = $xpath->query("/atom:feed/dfrn:mail");
2428 foreach ($mails AS $mail)
2429 self::process_mail($xpath, $mail, $importer);
2431 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2432 foreach ($suggestions AS $suggestion)
2433 self::process_suggestion($xpath, $suggestion, $importer);
2435 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2436 foreach ($relocations AS $relocation)
2437 self::process_relocation($xpath, $relocation, $importer);
2439 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2440 foreach ($deletions AS $deletion)
2441 self::process_deletion($xpath, $deletion, $importer);
2443 if (!$sort_by_date) {
2444 $entries = $xpath->query("/atom:feed/atom:entry");
2445 foreach ($entries AS $entry)
2446 self::process_entry($header, $xpath, $entry, $importer);
2448 $newentries = array();
2449 $entries = $xpath->query("/atom:feed/atom:entry");
2450 foreach ($entries AS $entry) {
2451 $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2452 $newentries[strtotime($created)] = $entry;
2455 // Now sort after the publishing date
2458 foreach ($newentries AS $entry)
2459 self::process_entry($header, $xpath, $entry, $importer);
2461 logger("Import done for user ".$importer["uid"]." from contact ".$importer["id"], LOGGER_DEBUG);