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.
71 * @param boolean $onlyheader Output only the header without content? (Default is "no")
73 * @return string DFRN feed entries
75 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false) {
79 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
80 $public_feed = (($dfrn_id) ? false : true);
81 $starred = false; // not yet implemented, possible security issues
84 if($public_feed && $a->argc > 2) {
85 for($x = 2; $x < $a->argc; $x++) {
86 if($a->argv[$x] == 'converse')
88 if($a->argv[$x] == 'starred')
90 if($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1]))
91 $category = $a->argv[$x+1];
97 // default permissions - anonymous user
99 $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = '' ";
101 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
102 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
103 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
111 $owner_id = $owner['uid'];
112 $owner_nick = $owner['nickname'];
114 $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 NOT `blocked` 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 if(! strlen($last_update))
174 $last_update = 'now -30 days';
176 if(isset($category)) {
177 $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` ",
178 dbesc(protect_sprintf($category)), intval(TERM_OBJ_POST), intval(TERM_CATEGORY), intval($owner_id));
179 //$sql_extra .= file_tag_file_query('item',$category,'category');
184 $sql_extra .= " AND `contact`.`self` = 1 ";
187 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
189 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
190 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
191 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
192 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
193 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
194 FROM `item` USE INDEX (`uid_wall_changed`, `uid_type_changed`) $sql_post_table
195 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
196 AND NOT `contact`.`blocked`
197 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
198 WHERE `item`.`uid` = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
199 AND `item`.`wall` AND `item`.`changed` > '%s'
201 ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
207 // Will check further below if this actually returned results.
208 // We will provide an empty feed if that is the case.
212 $doc = new DOMDocument('1.0', 'utf-8');
213 $doc->formatOutput = true;
215 $alternatelink = $owner['url'];
218 $alternatelink .= "/category/".$category;
221 $author = "dfrn:owner";
225 $root = self::add_header($doc, $owner, $author, $alternatelink, true);
227 // This hook can't work anymore
228 // call_hooks('atom_feed', $atom);
230 if (!count($items) OR $onlyheader) {
231 $atom = trim($doc->saveXML());
233 call_hooks('atom_feed_end', $atom);
238 foreach($items as $item) {
240 // prevent private email from leaking.
241 if($item['network'] == NETWORK_MAIL)
244 // public feeds get html, our own nodes use bbcode
248 // catch any email that's in a public conversation and make sure it doesn't leak
254 $entry = self::entry($doc, $type, $item, $owner, true);
255 $root->appendChild($entry);
259 $atom = trim($doc->saveXML());
261 call_hooks('atom_feed_end', $atom);
267 * @brief Create XML text for DFRN mails
269 * @param array $item message elements
270 * @param array $owner Owner record
272 * @return string DFRN mail
274 public static function mail($item, $owner) {
275 $doc = new DOMDocument('1.0', 'utf-8');
276 $doc->formatOutput = true;
278 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
280 $mail = $doc->createElement("dfrn:mail");
281 $sender = $doc->createElement("dfrn:sender");
283 xml::add_element($doc, $sender, "dfrn:name", $owner['name']);
284 xml::add_element($doc, $sender, "dfrn:uri", $owner['url']);
285 xml::add_element($doc, $sender, "dfrn:avatar", $owner['thumb']);
287 $mail->appendChild($sender);
289 xml::add_element($doc, $mail, "dfrn:id", $item['uri']);
290 xml::add_element($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
291 xml::add_element($doc, $mail, "dfrn:sentdate", datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME));
292 xml::add_element($doc, $mail, "dfrn:subject", $item['title']);
293 xml::add_element($doc, $mail, "dfrn:content", $item['body']);
295 $root->appendChild($mail);
297 return(trim($doc->saveXML()));
301 * @brief Create XML text for DFRN friend suggestions
303 * @param array $item suggestion elements
304 * @param array $owner Owner record
306 * @return string DFRN suggestions
308 public static function fsuggest($item, $owner) {
309 $doc = new DOMDocument('1.0', 'utf-8');
310 $doc->formatOutput = true;
312 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
314 $suggest = $doc->createElement("dfrn:suggest");
316 xml::add_element($doc, $suggest, "dfrn:url", $item['url']);
317 xml::add_element($doc, $suggest, "dfrn:name", $item['name']);
318 xml::add_element($doc, $suggest, "dfrn:photo", $item['photo']);
319 xml::add_element($doc, $suggest, "dfrn:request", $item['request']);
320 xml::add_element($doc, $suggest, "dfrn:note", $item['note']);
322 $root->appendChild($suggest);
324 return(trim($doc->saveXML()));
328 * @brief Create XML text for DFRN relocations
330 * @param array $owner Owner record
331 * @param int $uid User ID
333 * @return string DFRN relocations
335 public static function relocate($owner, $uid) {
337 /* get site pubkey. this could be a new installation with no site keys*/
338 $pubkey = get_config('system','site_pubkey');
340 $res = new_keypair(1024);
341 set_config('system','site_prvkey', $res['prvkey']);
342 set_config('system','site_pubkey', $res['pubkey']);
345 $rp = q("SELECT `resource-id` , `scale`, type FROM `photo`
346 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;", $uid);
348 $ext = Photo::supportedTypes();
351 $photos[$p['scale']] = app::get_baseurl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
355 $doc = new DOMDocument('1.0', 'utf-8');
356 $doc->formatOutput = true;
358 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
360 $relocate = $doc->createElement("dfrn:relocate");
362 xml::add_element($doc, $relocate, "dfrn:url", $owner['url']);
363 xml::add_element($doc, $relocate, "dfrn:name", $owner['name']);
364 xml::add_element($doc, $relocate, "dfrn:addr", $owner['addr']);
365 xml::add_element($doc, $relocate, "dfrn:avatar", $owner['avatar']);
366 xml::add_element($doc, $relocate, "dfrn:photo", $photos[4]);
367 xml::add_element($doc, $relocate, "dfrn:thumb", $photos[5]);
368 xml::add_element($doc, $relocate, "dfrn:micro", $photos[6]);
369 xml::add_element($doc, $relocate, "dfrn:request", $owner['request']);
370 xml::add_element($doc, $relocate, "dfrn:confirm", $owner['confirm']);
371 xml::add_element($doc, $relocate, "dfrn:notify", $owner['notify']);
372 xml::add_element($doc, $relocate, "dfrn:poll", $owner['poll']);
373 xml::add_element($doc, $relocate, "dfrn:sitepubkey", get_config('system','site_pubkey'));
375 $root->appendChild($relocate);
377 return(trim($doc->saveXML()));
381 * @brief Adds the header elements for the DFRN protocol
383 * @param object $doc XML document
384 * @param array $owner Owner record
385 * @param string $authorelement Element name for the author
386 * @param string $alternatelink link to profile or category
387 * @param bool $public Is it a header for public posts?
389 * @return object XML root object
391 private function add_header($doc, $owner, $authorelement, $alternatelink = "", $public = false) {
393 if ($alternatelink == "")
394 $alternatelink = $owner['url'];
396 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
397 $doc->appendChild($root);
399 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
400 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
401 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
402 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
403 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
404 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
405 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
406 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
407 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
409 xml::add_element($doc, $root, "id", app::get_baseurl()."/profile/".$owner["nick"]);
410 xml::add_element($doc, $root, "title", $owner["name"]);
412 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
413 xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
415 $attributes = array("rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/");
416 xml::add_element($doc, $root, "link", "", $attributes);
418 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $alternatelink);
419 xml::add_element($doc, $root, "link", "", $attributes);
423 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
424 ostatus::hublinks($doc, $root);
426 $attributes = array("rel" => "salmon", "href" => app::get_baseurl()."/salmon/".$owner["nick"]);
427 xml::add_element($doc, $root, "link", "", $attributes);
429 $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => app::get_baseurl()."/salmon/".$owner["nick"]);
430 xml::add_element($doc, $root, "link", "", $attributes);
432 $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => app::get_baseurl()."/salmon/".$owner["nick"]);
433 xml::add_element($doc, $root, "link", "", $attributes);
436 // For backward compatibility we keep this element
437 if ($owner['page-flags'] == PAGE_COMMUNITY)
438 xml::add_element($doc, $root, "dfrn:community", 1);
440 // The former element is replaced by this one
441 xml::add_element($doc, $root, "dfrn:account_type", $owner["account-type"]);
443 /// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
445 xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
447 $author = self::add_author($doc, $owner, $authorelement, $public);
448 $root->appendChild($author);
454 * @brief Adds the author element in the header for the DFRN protocol
456 * @param object $doc XML document
457 * @param array $owner Owner record
458 * @param string $authorelement Element name for the author
460 * @return object XML author object
462 private function add_author($doc, $owner, $authorelement, $public) {
464 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
465 $r = q("SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
466 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
467 intval($owner['uid']));
473 $author = $doc->createElement($authorelement);
475 $namdate = datetime_convert('UTC', 'UTC', $owner['name-date'].'+00:00', ATOM_TIME);
476 $uridate = datetime_convert('UTC', 'UTC', $owner['uri-date'].'+00:00', ATOM_TIME);
477 $picdate = datetime_convert('UTC', 'UTC', $owner['avatar-date'].'+00:00', ATOM_TIME);
479 if (!$public OR !$hidewall)
480 $attributes = array("dfrn:updated" => $namdate);
482 $attributes = array();
484 xml::add_element($doc, $author, "name", $owner["name"], $attributes);
485 xml::add_element($doc, $author, "uri", app::get_baseurl().'/profile/'.$owner["nickname"], $attributes);
486 xml::add_element($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
488 $attributes = array("rel" => "photo", "type" => "image/jpeg",
489 "media:width" => 175, "media:height" => 175, "href" => $owner['photo']);
491 if (!$public OR !$hidewall)
492 $attributes["dfrn:updated"] = $picdate;
494 xml::add_element($doc, $author, "link", "", $attributes);
496 $attributes["rel"] = "avatar";
497 xml::add_element($doc, $author, "link", "", $attributes);
500 xml::add_element($doc, $author, "dfrn:hide", "true");
502 // The following fields will only be generated if the data isn't meant for a public feed
506 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
509 xml::add_element($doc, $author, "dfrn:birthday", $birthday);
511 // Only show contact details when we are allowed to
512 $r = q("SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
513 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
514 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
516 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
517 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
518 intval($owner['uid']));
522 xml::add_element($doc, $author, "poco:displayName", $profile["name"]);
523 xml::add_element($doc, $author, "poco:updated", $namdate);
525 if (trim($profile["dob"]) != "0000-00-00")
526 xml::add_element($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
528 xml::add_element($doc, $author, "poco:note", $profile["about"]);
529 xml::add_element($doc, $author, "poco:preferredUsername", $profile["nickname"]);
531 $savetz = date_default_timezone_get();
532 date_default_timezone_set($profile["timezone"]);
533 xml::add_element($doc, $author, "poco:utcOffset", date("P"));
534 date_default_timezone_set($savetz);
536 if (trim($profile["homepage"]) != "") {
537 $urls = $doc->createElement("poco:urls");
538 xml::add_element($doc, $urls, "poco:type", "homepage");
539 xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
540 xml::add_element($doc, $urls, "poco:primary", "true");
541 $author->appendChild($urls);
544 if (trim($profile["pub_keywords"]) != "") {
545 $keywords = explode(",", $profile["pub_keywords"]);
547 foreach ($keywords AS $keyword)
548 xml::add_element($doc, $author, "poco:tags", trim($keyword));
552 if (trim($profile["xmpp"]) != "") {
553 $ims = $doc->createElement("poco:ims");
554 xml::add_element($doc, $ims, "poco:type", "xmpp");
555 xml::add_element($doc, $ims, "poco:value", $profile["xmpp"]);
556 xml::add_element($doc, $ims, "poco:primary", "true");
557 $author->appendChild($ims);
560 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
561 $element = $doc->createElement("poco:address");
563 xml::add_element($doc, $element, "poco:formatted", formatted_location($profile));
565 if (trim($profile["locality"]) != "")
566 xml::add_element($doc, $element, "poco:locality", $profile["locality"]);
568 if (trim($profile["region"]) != "")
569 xml::add_element($doc, $element, "poco:region", $profile["region"]);
571 if (trim($profile["country-name"]) != "")
572 xml::add_element($doc, $element, "poco:country", $profile["country-name"]);
574 $author->appendChild($element);
582 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
584 * @param object $doc XML document
585 * @param string $element Element name for the author
586 * @param string $contact_url Link of the contact
587 * @param array $items Item elements
589 * @return object XML author object
591 private function add_entry_author($doc, $element, $contact_url, $item) {
593 $contact = get_contact_details_by_url($contact_url, $item["uid"]);
595 $author = $doc->createElement($element);
596 xml::add_element($doc, $author, "name", $contact["name"]);
597 xml::add_element($doc, $author, "uri", $contact["url"]);
598 xml::add_element($doc, $author, "dfrn:handle", $contact["addr"]);
601 /// - Check real image type and image size
602 /// - Check which of these boths elements we should use
605 "type" => "image/jpeg",
607 "media:height" => 80,
608 "href" => $contact["photo"]);
609 xml::add_element($doc, $author, "link", "", $attributes);
613 "type" => "image/jpeg",
615 "media:height" => 80,
616 "href" => $contact["photo"]);
617 xml::add_element($doc, $author, "link", "", $attributes);
623 * @brief Adds the activity elements
625 * @param object $doc XML document
626 * @param string $element Element name for the activity
627 * @param string $activity activity value
629 * @return object XML activity object
631 private function create_activity($doc, $element, $activity) {
634 $entry = $doc->createElement($element);
636 $r = parse_xml_string($activity, false);
640 xml::add_element($doc, $entry, "activity:object-type", $r->type);
642 xml::add_element($doc, $entry, "id", $r->id);
644 xml::add_element($doc, $entry, "title", $r->title);
646 if(substr($r->link,0,1) == '<') {
647 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
648 $r->link = str_replace('&','&', $r->link);
650 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
652 // XML does need a single element as root element so we add a dummy element here
653 $data = parse_xml_string("<dummy>".$r->link."</dummy>", false);
654 if (is_object($data)) {
655 foreach ($data->link AS $link) {
656 $attributes = array();
657 foreach ($link->attributes() AS $parameter => $value)
658 $attributes[$parameter] = $value;
659 xml::add_element($doc, $entry, "link", "", $attributes);
663 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $r->link);
664 xml::add_element($doc, $entry, "link", "", $attributes);
668 xml::add_element($doc, $entry, "content", bbcode($r->content), array("type" => "html"));
677 * @brief Adds the elements for attachments
679 * @param object $doc XML document
680 * @param object $root XML root
681 * @param array $item Item element
683 * @return object XML attachment object
685 private function get_attachment($doc, $root, $item) {
686 $arr = explode('[/attach],',$item['attach']);
688 foreach($arr as $r) {
690 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches);
692 $attributes = array("rel" => "enclosure",
693 "href" => $matches[1],
694 "type" => $matches[3]);
696 if(intval($matches[2]))
697 $attributes["length"] = intval($matches[2]);
699 if(trim($matches[4]) != "")
700 $attributes["title"] = trim($matches[4]);
702 xml::add_element($doc, $root, "link", "", $attributes);
709 * @brief Adds the "entry" elements for the DFRN protocol
711 * @param object $doc XML document
712 * @param string $type "text" or "html"
713 * @param array $item Item element
714 * @param array $owner Owner record
715 * @param bool $comment Trigger the sending of the "comment" element
716 * @param int $cid Contact ID of the recipient
718 * @return object XML entry object
720 private function entry($doc, $type, $item, $owner, $comment = false, $cid = 0) {
722 $mentioned = array();
727 if($item['deleted']) {
728 $attributes = array("ref" => $item['uri'], "when" => datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME));
729 return xml::create_element($doc, "at:deleted-entry", "", $attributes);
732 $entry = $doc->createElement("entry");
734 if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
735 $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
737 $body = $item['body'];
739 // Remove the abstract element. It is only locally important.
740 $body = remove_abstract($body);
742 if ($type == 'html') {
745 if ($item['title'] != "")
746 $htmlbody = "[b]".$item['title']."[/b]\n\n".$htmlbody;
748 $htmlbody = bbcode($htmlbody, false, false, 7);
751 $author = self::add_entry_author($doc, "author", $item["author-link"], $item);
752 $entry->appendChild($author);
754 $dfrnowner = self::add_entry_author($doc, "dfrn:owner", $item["owner-link"], $item);
755 $entry->appendChild($dfrnowner);
757 if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
758 $parent = q("SELECT `guid` FROM `item` WHERE `id` = %d", intval($item["parent"]));
759 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
760 $attributes = array("ref" => $parent_item, "type" => "text/html",
761 "href" => app::get_baseurl().'/display/'.$parent[0]['guid'],
762 "dfrn:diaspora_guid" => $parent[0]['guid']);
763 xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
766 xml::add_element($doc, $entry, "id", $item["uri"]);
767 xml::add_element($doc, $entry, "title", $item["title"]);
769 xml::add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
770 xml::add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
772 // "dfrn:env" is used to read the content
773 xml::add_element($doc, $entry, "dfrn:env", base64url_encode($body, true));
775 // The "content" field is not read by the receiver. We could remove it when the type is "text"
776 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
777 xml::add_element($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), array("type" => $type));
779 // We save this value in "plink". Maybe we should read it from there as well?
780 xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
781 "href" => app::get_baseurl()."/display/".$item["guid"]));
783 // "comment-allow" is some old fashioned stuff for old Friendica versions.
784 // It is included in the rewritten code for completeness
786 xml::add_element($doc, $entry, "dfrn:comment-allow", intval($item['last-child']));
788 if($item['location'])
789 xml::add_element($doc, $entry, "dfrn:location", $item['location']);
792 xml::add_element($doc, $entry, "georss:point", $item['coord']);
794 if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
795 xml::add_element($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
798 xml::add_element($doc, $entry, "dfrn:extid", $item['extid']);
800 if($item['bookmark'])
801 xml::add_element($doc, $entry, "dfrn:bookmark", "true");
804 xml::add_element($doc, $entry, "statusnet:notice_info", "", array("local_id" => $item['id'], "source" => $item['app']));
806 xml::add_element($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
808 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
809 // It is needed for relayed comments to Diaspora.
810 if($item['signed_text']) {
811 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
812 xml::add_element($doc, $entry, "dfrn:diaspora_signature", $sign);
815 xml::add_element($doc, $entry, "activity:verb", construct_verb($item));
817 if ($item['object-type'] != "")
818 xml::add_element($doc, $entry, "activity:object-type", $item['object-type']);
819 elseif ($item['id'] == $item['parent'])
820 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
822 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
824 $actobj = self::create_activity($doc, "activity:object", $item['object']);
826 $entry->appendChild($actobj);
828 $actarg = self::create_activity($doc, "activity:target", $item['target']);
830 $entry->appendChild($actarg);
832 $tags = item_getfeedtags($item);
836 if (($type != 'html') OR ($t[0] != "@"))
837 xml::add_element($doc, $entry, "category", "", array("scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]));
843 $mentioned[$t[1]] = $t[1];
845 foreach ($mentioned AS $mention) {
846 $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
847 intval($owner["uid"]),
848 dbesc(normalise_link($mention)));
849 if ($r[0]["forum"] OR $r[0]["prv"])
850 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
851 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
852 "href" => $mention));
854 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
855 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
856 "href" => $mention));
859 self::get_attachment($doc, $entry, $item);
865 * @brief Delivers the atom content to the contacts
867 * @param array $owner Owner record
868 * @param array $contactr Contact record of the receiver
869 * @param string $atom Content that will be transmitted
870 * @param bool $dissolve (to be documented)
872 * @return int Deliver status. -1 means an error.
874 public static function deliver($owner,$contact,$atom, $dissolve = false) {
878 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
880 if($contact['duplex'] && $contact['dfrn-id'])
881 $idtosend = '0:' . $orig_id;
882 if($contact['duplex'] && $contact['issued-id'])
883 $idtosend = '1:' . $orig_id;
886 $rino = get_config('system','rino_encrypt');
887 $rino = intval($rino);
888 // use RINO1 if mcrypt isn't installed and RINO2 was selected
889 if ($rino==2 and !function_exists('mcrypt_create_iv')) $rino=1;
891 logger("Local rino version: ". $rino, LOGGER_DEBUG);
893 $ssl_val = intval(get_config('system','ssl_policy'));
897 case SSL_POLICY_FULL:
898 $ssl_policy = 'full';
900 case SSL_POLICY_SELFSIGN:
901 $ssl_policy = 'self';
903 case SSL_POLICY_NONE:
905 $ssl_policy = 'none';
909 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
911 logger('dfrn_deliver: ' . $url);
913 $xml = fetch_url($url);
915 $curl_stat = $a->get_curl_code();
917 return(-1); // timed out
919 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
924 if(strpos($xml,'<?xml') === false) {
925 logger('dfrn_deliver: no valid XML returned');
926 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
930 $res = parse_xml_string($xml);
932 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
933 return (($res->status) ? $res->status : 3);
936 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
937 $challenge = hex2bin((string) $res->challenge);
938 $perm = (($res->perm) ? $res->perm : null);
939 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
940 $rino_remote_version = intval($res->rino);
941 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
943 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
945 if($owner['page-flags'] == PAGE_PRVGROUP)
951 if((($perm == 'rw') && (! intval($contact['writable'])))
952 || (($perm == 'r') && (intval($contact['writable'])))) {
953 q("update contact set writable = %d where id = %d",
954 intval(($perm == 'rw') ? 1 : 0),
955 intval($contact['id'])
957 $contact['writable'] = (string) 1 - intval($contact['writable']);
961 if(($contact['duplex'] && strlen($contact['pubkey']))
962 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
963 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
964 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
965 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
967 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
968 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
971 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
973 if(strpos($final_dfrn_id,':') == 1)
974 $final_dfrn_id = substr($final_dfrn_id,2);
976 if($final_dfrn_id != $orig_id) {
977 logger('dfrn_deliver: wrong dfrn_id.');
978 // did not decode properly - cannot trust this site
982 $postvars['dfrn_id'] = $idtosend;
983 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
985 $postvars['dissolve'] = '1';
988 if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
989 $postvars['data'] = $atom;
990 $postvars['perm'] = 'rw';
992 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
993 $postvars['perm'] = 'r';
996 $postvars['ssl_policy'] = $ssl_policy;
999 $postvars['page'] = $page;
1002 if($rino>0 && $rino_remote_version>0 && (! $dissolve)) {
1003 logger('rino version: '. $rino_remote_version);
1005 switch($rino_remote_version) {
1007 // Deprecated rino version!
1008 $key = substr(random_string(),0,16);
1009 $data = aes_encrypt($postvars['data'],$key);
1012 // RINO 2 based on php-encryption
1014 $key = Crypto::createNewRandomKey();
1015 } catch (CryptoTestFailed $ex) {
1016 logger('Cannot safely create a key');
1018 } catch (CannotPerformOperation $ex) {
1019 logger('Cannot safely create a key');
1023 $data = Crypto::encrypt($postvars['data'], $key);
1024 } catch (CryptoTestFailed $ex) {
1025 logger('Cannot safely perform encryption');
1027 } catch (CannotPerformOperation $ex) {
1028 logger('Cannot safely perform encryption');
1033 logger("rino: invalid requested verision '$rino_remote_version'");
1037 $postvars['rino'] = $rino_remote_version;
1038 $postvars['data'] = bin2hex($data);
1040 #logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1043 if($dfrn_version >= 2.1) {
1044 if(($contact['duplex'] && strlen($contact['pubkey']))
1045 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1046 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey'])))
1048 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1050 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1053 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY))
1054 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1056 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1060 logger('md5 rawkey ' . md5($postvars['key']));
1062 $postvars['key'] = bin2hex($postvars['key']);
1066 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1068 $xml = post_url($contact['notify'],$postvars);
1070 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1072 $curl_stat = $a->get_curl_code();
1073 if((! $curl_stat) || (! strlen($xml)))
1074 return(-1); // timed out
1076 if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
1079 if(strpos($xml,'<?xml') === false) {
1080 logger('dfrn_deliver: phase 2: no valid XML returned');
1081 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1085 if($contact['term-date'] != '0000-00-00 00:00:00') {
1086 logger("dfrn_deliver: $url back from the dead - removing mark for death");
1087 require_once('include/Contact.php');
1088 unmark_for_death($contact);
1091 $res = parse_xml_string($xml);
1093 return $res->status;
1097 * @brief Add new birthday event for this person
1099 * @param array $contact Contact record
1100 * @param string $birthday Birthday of the contact
1103 private function birthday_event($contact, $birthday) {
1105 logger("updating birthday: ".$birthday." for contact ".$contact["id"]);
1107 $bdtext = sprintf(t("%s\'s birthday"), $contact["name"]);
1108 $bdtext2 = sprintf(t("Happy Birthday %s"), " [url=".$contact["url"]."]".$contact["name"]."[/url]") ;
1111 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1112 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1113 intval($contact["uid"]),
1114 intval($contact["id"]),
1115 dbesc(datetime_convert()),
1116 dbesc(datetime_convert()),
1117 dbesc(datetime_convert("UTC","UTC", $birthday)),
1118 dbesc(datetime_convert("UTC","UTC", $birthday." + 1 day ")),
1126 * @brief Fetch the author data from head or entry items
1128 * @param object $xpath XPath object
1129 * @param object $context In which context should the data be searched
1130 * @param array $importer Record of the importer user mixed with contact of the content
1131 * @param string $element Element name from which the data is fetched
1132 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1134 * @return Returns an array with relevant data of the author
1136 private function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "") {
1139 $author["name"] = $xpath->evaluate($element."/atom:name/text()", $context)->item(0)->nodeValue;
1140 $author["link"] = $xpath->evaluate($element."/atom:uri/text()", $context)->item(0)->nodeValue;
1142 $r = q("SELECT `id`, `uid`, `url`, `network`, `avatar-date`, `name-date`, `uri-date`, `addr`,
1143 `name`, `nick`, `about`, `location`, `keywords`, `xmpp`, `bdyear`, `bd`, `hidden`, `contact-type`
1144 FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
1145 intval($importer["uid"]), dbesc(normalise_link($author["link"])), dbesc(NETWORK_STATUSNET));
1148 $author["contact-id"] = $r[0]["id"];
1149 $author["network"] = $r[0]["network"];
1152 logger("Contact ".$author["link"]." wasn't found for user ".$importer["uid"]." XML: ".$xml, LOGGER_DEBUG);
1154 $author["contact-id"] = $importer["id"];
1155 $author["network"] = $importer["network"];
1159 // Until now we aren't serving different sizes - but maybe later
1160 $avatarlist = array();
1161 // @todo check if "avatar" or "photo" would be the best field in the specification
1162 $avatars = $xpath->query($element."/atom:link[@rel='avatar']", $context);
1163 foreach($avatars AS $avatar) {
1166 foreach($avatar->attributes AS $attributes) {
1167 if ($attributes->name == "href")
1168 $href = $attributes->textContent;
1169 if ($attributes->name == "width")
1170 $width = $attributes->textContent;
1171 if ($attributes->name == "updated")
1172 $contact["avatar-date"] = $attributes->textContent;
1174 if (($width > 0) AND ($href != ""))
1175 $avatarlist[$width] = $href;
1177 if (count($avatarlist) > 0) {
1178 krsort($avatarlist);
1179 $author["avatar"] = current($avatarlist);
1182 if ($r AND !$onlyfetch) {
1183 logger("Check if contact details for contact ".$r[0]["id"]." (".$r[0]["nick"].") have to be updated.", LOGGER_DEBUG);
1185 $poco = array("url" => $contact["url"]);
1187 // When was the last change to name or uri?
1188 $name_element = $xpath->query($element."/atom:name", $context)->item(0);
1189 foreach($name_element->attributes AS $attributes)
1190 if ($attributes->name == "updated")
1191 $poco["name-date"] = $attributes->textContent;
1193 $link_element = $xpath->query($element."/atom:link", $context)->item(0);
1194 foreach($link_element->attributes AS $attributes)
1195 if ($attributes->name == "updated")
1196 $poco["uri-date"] = $attributes->textContent;
1198 // Update contact data
1199 $value = $xpath->evaluate($element."/dfrn:handle/text()", $context)->item(0)->nodeValue;
1201 $poco["addr"] = $value;
1203 $value = $xpath->evaluate($element."/poco:displayName/text()", $context)->item(0)->nodeValue;
1205 $poco["name"] = $value;
1207 $value = $xpath->evaluate($element."/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
1209 $poco["nick"] = $value;
1211 $value = $xpath->evaluate($element."/poco:note/text()", $context)->item(0)->nodeValue;
1213 $poco["about"] = $value;
1215 $value = $xpath->evaluate($element."/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
1217 $poco["location"] = $value;
1219 /// @todo Only search for elements with "poco:type" = "xmpp"
1220 $value = $xpath->evaluate($element."/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
1222 $poco["xmpp"] = $value;
1224 /// @todo Add support for the following fields that we don't support by now in the contact table:
1225 /// - poco:utcOffset
1231 // If the "hide" element is present then the profile isn't searchable.
1232 $hide = intval($xpath->evaluate($element."/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
1234 logger("Hidden status for contact ".$contact["url"].": ".$hide, LOGGER_DEBUG);
1236 // If the contact isn't searchable then set the contact to "hidden".
1237 // Problem: This can be manually overridden by the user.
1239 $contact["hidden"] = true;
1241 // Save the keywords into the contact table
1243 $tagelements = $xpath->evaluate($element."/poco:tags/text()", $context);
1244 foreach($tagelements AS $tag)
1245 $tags[$tag->nodeValue] = $tag->nodeValue;
1248 $poco["keywords"] = implode(", ", $tags);
1250 // "dfrn:birthday" contains the birthday converted to UTC
1251 $old_bdyear = $contact["bdyear"];
1253 $birthday = $xpath->evaluate($element."/dfrn:birthday/text()", $context)->item(0)->nodeValue;
1255 if (strtotime($birthday) > time()) {
1256 $bd_timestamp = strtotime($birthday);
1258 $poco["bdyear"] = date("Y", $bd_timestamp);
1261 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1262 $value = $xpath->evaluate($element."/poco:birthday/text()", $context)->item(0)->nodeValue;
1264 if (!in_array($value, array("", "0000-00-00"))) {
1265 $bdyear = date("Y");
1266 $value = str_replace("0000", $bdyear, $value);
1268 if (strtotime($value) < time()) {
1269 $value = str_replace($bdyear, $bdyear + 1, $value);
1270 $bdyear = $bdyear + 1;
1273 $poco["bd"] = $value;
1276 $contact = array_merge($contact, $poco);
1278 if ($old_bdyear != $contact["bdyear"])
1279 self::birthday_event($contact, $birthday);
1281 // Get all field names
1283 foreach ($r[0] AS $field => $data)
1284 $fields[$field] = $data;
1286 unset($fields["id"]);
1287 unset($fields["uid"]);
1288 unset($fields["url"]);
1289 unset($fields["avatar-date"]);
1290 unset($fields["name-date"]);
1291 unset($fields["uri-date"]);
1293 // Update check for this field has to be done differently
1294 $datefields = array("name-date", "uri-date");
1295 foreach ($datefields AS $field)
1296 if (strtotime($contact[$field]) > strtotime($r[0][$field])) {
1297 logger("Difference for contact ".$contact["id"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
1301 foreach ($fields AS $field => $data)
1302 if ($contact[$field] != $r[0][$field]) {
1303 logger("Difference for contact ".$contact["id"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
1308 logger("Update contact data for contact ".$contact["id"]." (".$contact["nick"].")", LOGGER_DEBUG);
1310 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1311 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1312 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1313 WHERE `id` = %d AND `network` = '%s'",
1314 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
1315 dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1316 dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
1317 dbesc($contact["name-date"]), dbesc($contact["uri-date"]),
1318 intval($contact["id"]), dbesc($contact["network"]));
1321 update_contact_avatar($author["avatar"], $importer["uid"], $contact["id"],
1322 (strtotime($contact["avatar-date"]) > strtotime($r[0]["avatar-date"])));
1324 // The generation is a sign for the reliability of the provided data.
1325 // It is used in the socgraph.php to prevent that old contact data
1326 // that was relayed over several servers can overwrite contact
1327 // data that we received directly.
1329 $poco["generation"] = 2;
1330 $poco["photo"] = $author["avatar"];
1331 $poco["hide"] = $hide;
1332 $poco["contact-type"] = $contact["contact-type"];
1333 update_gcontact($poco);
1340 * @brief Transforms activity objects into an XML string
1342 * @param object $xpath XPath object
1343 * @param object $activity Activity object
1344 * @param text $element element name
1346 * @return string XML string
1348 private function transform_activity($xpath, $activity, $element) {
1349 if (!is_object($activity))
1352 $obj_doc = new DOMDocument("1.0", "utf-8");
1353 $obj_doc->formatOutput = true;
1355 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1357 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1358 xml::add_element($obj_doc, $obj_element, "type", $activity_type);
1360 $id = $xpath->query("atom:id", $activity)->item(0);
1362 $obj_element->appendChild($obj_doc->importNode($id, true));
1364 $title = $xpath->query("atom:title", $activity)->item(0);
1365 if (is_object($title))
1366 $obj_element->appendChild($obj_doc->importNode($title, true));
1368 $links = $xpath->query("atom:link", $activity);
1369 if (is_object($links))
1370 foreach ($links AS $link)
1371 $obj_element->appendChild($obj_doc->importNode($link, true));
1373 $content = $xpath->query("atom:content", $activity)->item(0);
1374 if (is_object($content))
1375 $obj_element->appendChild($obj_doc->importNode($content, true));
1377 $obj_doc->appendChild($obj_element);
1379 $objxml = $obj_doc->saveXML($obj_element);
1381 // @todo This isn't totally clean. We should find a way to transform the namespaces
1382 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1387 * @brief Processes the mail elements
1389 * @param object $xpath XPath object
1390 * @param object $mail mail elements
1391 * @param array $importer Record of the importer user mixed with contact of the content
1393 private function process_mail($xpath, $mail, $importer) {
1395 logger("Processing mails");
1398 $msg["uid"] = $importer["importer_uid"];
1399 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1400 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1401 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1402 $msg["contact-id"] = $importer["id"];
1403 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1404 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1405 $msg["created"] = $xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue;
1406 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1407 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1409 $msg["replied"] = 0;
1413 $r = dbq("INSERT INTO `mail` (`".implode("`, `", array_keys($msg))."`) VALUES ('".implode("', '", array_values($msg))."')");
1415 // send notifications.
1417 $notif_params = array(
1418 "type" => NOTIFY_MAIL,
1419 "notify_flags" => $importer["notify-flags"],
1420 "language" => $importer["language"],
1421 "to_name" => $importer["username"],
1422 "to_email" => $importer["email"],
1423 "uid" => $importer["importer_uid"],
1425 "source_name" => $msg["from-name"],
1426 "source_link" => $importer["url"],
1427 "source_photo" => $importer["thumb"],
1428 "verb" => ACTIVITY_POST,
1432 notification($notif_params);
1434 logger("Mail is processed, notification was sent.");
1438 * @brief Processes the suggestion elements
1440 * @param object $xpath XPath object
1441 * @param object $suggestion suggestion elements
1442 * @param array $importer Record of the importer user mixed with contact of the content
1444 private function process_suggestion($xpath, $suggestion, $importer) {
1446 logger("Processing suggestions");
1449 $suggest["uid"] = $importer["importer_uid"];
1450 $suggest["cid"] = $importer["id"];
1451 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1452 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1453 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1454 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1455 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1457 // Does our member already have a friend matching this description?
1459 $r = q("SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1460 dbesc($suggest["name"]),
1461 dbesc(normalise_link($suggest["url"])),
1462 intval($suggest["uid"])
1467 // Do we already have an fcontact record for this person?
1470 $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1471 dbesc($suggest["url"]),
1472 dbesc($suggest["name"]),
1473 dbesc($suggest["request"])
1478 // OK, we do. Do we already have an introduction for this person ?
1479 $r = q("SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1480 intval($suggest["uid"]),
1487 $r = q("INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1488 dbesc($suggest["name"]),
1489 dbesc($suggest["url"]),
1490 dbesc($suggest["photo"]),
1491 dbesc($suggest["request"])
1493 $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1494 dbesc($suggest["url"]),
1495 dbesc($suggest["name"]),
1496 dbesc($suggest["request"])
1501 // database record did not get created. Quietly give up.
1505 $hash = random_string();
1507 $r = q("INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1508 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1509 intval($suggest["uid"]),
1511 intval($suggest["cid"]),
1512 dbesc($suggest["body"]),
1514 dbesc(datetime_convert()),
1519 "type" => NOTIFY_SUGGEST,
1520 "notify_flags" => $importer["notify-flags"],
1521 "language" => $importer["language"],
1522 "to_name" => $importer["username"],
1523 "to_email" => $importer["email"],
1524 "uid" => $importer["importer_uid"],
1526 "link" => App::get_baseurl()."/notifications/intros",
1527 "source_name" => $importer["name"],
1528 "source_link" => $importer["url"],
1529 "source_photo" => $importer["photo"],
1530 "verb" => ACTIVITY_REQ_FRIEND,
1539 * @brief Processes the relocation elements
1541 * @param object $xpath XPath object
1542 * @param object $relocation relocation elements
1543 * @param array $importer Record of the importer user mixed with contact of the content
1545 private function process_relocation($xpath, $relocation, $importer) {
1547 logger("Processing relocations");
1549 $relocate = array();
1550 $relocate["uid"] = $importer["importer_uid"];
1551 $relocate["cid"] = $importer["id"];
1552 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1553 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
1554 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1555 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
1556 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1557 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1558 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1559 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1560 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1561 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1562 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1563 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1565 if (($relocate["avatar"] == "") AND ($relocate["photo"] != ""))
1566 $relocate["avatar"] = $relocate["photo"];
1568 if ($relocate["addr"] == "")
1569 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
1572 $r = q("SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
1573 intval($importer["id"]),
1574 intval($importer["importer_uid"]));
1580 // Update the gcontact entry
1581 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
1583 $x = q("UPDATE `gcontact` SET
1592 WHERE `nurl` = '%s';",
1593 dbesc($relocate["name"]),
1594 dbesc($relocate["avatar"]),
1595 dbesc($relocate["url"]),
1596 dbesc(normalise_link($relocate["url"])),
1597 dbesc($relocate["addr"]),
1598 dbesc($relocate["addr"]),
1599 dbesc($relocate["notify"]),
1600 dbesc($relocate["server_url"]),
1601 dbesc(normalise_link($old["url"])));
1603 // Update the contact table. We try to find every entry.
1604 $x = q("UPDATE `contact` SET
1614 `site-pubkey` = '%s'
1615 WHERE (`id` = %d AND `uid` = %d) OR (`nurl` = '%s');",
1616 dbesc($relocate["name"]),
1617 dbesc($relocate["avatar"]),
1618 dbesc($relocate["url"]),
1619 dbesc(normalise_link($relocate["url"])),
1620 dbesc($relocate["addr"]),
1621 dbesc($relocate["request"]),
1622 dbesc($relocate["confirm"]),
1623 dbesc($relocate["notify"]),
1624 dbesc($relocate["poll"]),
1625 dbesc($relocate["sitepubkey"]),
1626 intval($importer["id"]),
1627 intval($importer["importer_uid"]),
1628 dbesc(normalise_link($old["url"])));
1630 update_contact_avatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
1636 /// @todo This is an extreme performance killer
1638 'owner-link' => array($old["url"], $relocate["url"]),
1639 'author-link' => array($old["url"], $relocate["url"]),
1640 //'owner-avatar' => array($old["photo"], $relocate["photo"]),
1641 //'author-avatar' => array($old["photo"], $relocate["photo"]),
1643 foreach ($fields as $n=>$f) {
1644 $r = q("SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
1646 intval($importer["importer_uid"]));
1649 $x = q("UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1652 intval($importer["importer_uid"]));
1659 /// merge with current record, current contents have priority
1660 /// update record, set url-updated
1661 /// update profile photos
1662 /// schedule a scan?
1667 * @brief Updates an item
1669 * @param array $current the current item record
1670 * @param array $item the new item record
1671 * @param array $importer Record of the importer user mixed with contact of the content
1672 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
1674 private function update_content($current, $item, $importer, $entrytype) {
1677 if (edited_timestamp_is_newer($current, $item)) {
1679 // do not accept (ignore) an earlier edit than one we currently have.
1680 if(datetime_convert("UTC","UTC",$item["edited"]) < $current["edited"])
1683 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s', `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
1684 dbesc($item["title"]),
1685 dbesc($item["body"]),
1686 dbesc($item["tag"]),
1687 dbesc(datetime_convert("UTC","UTC",$item["edited"])),
1688 dbesc(datetime_convert()),
1689 dbesc($item["uri"]),
1690 intval($importer["importer_uid"])
1692 create_tags_from_itemuri($item["uri"], $importer["importer_uid"]);
1693 update_thread_uri($item["uri"], $importer["importer_uid"]);
1697 if ($entrytype == DFRN_REPLY_RC)
1698 proc_run(PRIORITY_HIGH, "include/notifier.php","comment-import", $current["id"]);
1701 // update last-child if it changes
1702 if($item["last-child"] AND ($item["last-child"] != $current["last-child"])) {
1703 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1704 dbesc(datetime_convert()),
1705 dbesc($item["parent-uri"]),
1706 intval($importer["importer_uid"])
1708 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
1709 intval($item["last-child"]),
1710 dbesc(datetime_convert()),
1711 dbesc($item["uri"]),
1712 intval($importer["importer_uid"])
1719 * @brief Detects the entry type of the item
1721 * @param array $importer Record of the importer user mixed with contact of the content
1722 * @param array $item the new item record
1724 * @return int Is it a toplevel entry, a comment or a relayed comment?
1726 private function get_entry_type($importer, $item) {
1727 if ($item["parent-uri"] != $item["uri"]) {
1730 if($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
1733 logger("possible community action");
1735 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
1737 // was the top-level post for this action written by somebody on this site?
1738 // Specifically, the recipient?
1740 $is_a_remote_action = false;
1742 $r = q("SELECT `item`.`parent-uri` FROM `item`
1743 WHERE `item`.`uri` = '%s'
1745 dbesc($item["parent-uri"])
1747 if($r && count($r)) {
1748 $r = q("SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
1749 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1750 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
1751 AND `item`.`uid` = %d
1754 dbesc($r[0]["parent-uri"]),
1755 dbesc($r[0]["parent-uri"]),
1756 dbesc($r[0]["parent-uri"]),
1757 intval($importer["importer_uid"])
1760 $is_a_remote_action = true;
1763 // Does this have the characteristics of a community or private group action?
1764 // If it's an action to a wall post on a community/prvgroup page it's a
1765 // valid community action. Also forum_mode makes it valid for sure.
1766 // If neither, it's not.
1768 if($is_a_remote_action && $community) {
1769 if((!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
1770 $is_a_remote_action = false;
1771 logger("not a community action");
1775 if ($is_a_remote_action)
1776 return DFRN_REPLY_RC;
1781 return DFRN_TOP_LEVEL;
1786 * @brief Send a "poke"
1788 * @param array $item the new item record
1789 * @param array $importer Record of the importer user mixed with contact of the content
1790 * @param int $posted_id The record number of item record that was just posted
1792 private function do_poke($item, $importer, $posted_id) {
1793 $verb = urldecode(substr($item["verb"],strpos($item["verb"], "#")+1));
1796 $xo = parse_xml_string($item["object"],false);
1798 if(($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
1800 // somebody was poked/prodded. Was it me?
1801 foreach($xo->link as $l) {
1802 $atts = $l->attributes();
1803 switch($atts["rel"]) {
1805 $Blink = $atts["href"];
1812 if($Blink && link_compare($Blink,App::get_baseurl()."/profile/".$importer["nickname"])) {
1814 // send a notification
1816 "type" => NOTIFY_POKE,
1817 "notify_flags" => $importer["notify-flags"],
1818 "language" => $importer["language"],
1819 "to_name" => $importer["username"],
1820 "to_email" => $importer["email"],
1821 "uid" => $importer["importer_uid"],
1823 "link" => App::get_baseurl()."/display/".urlencode(get_item_guid($posted_id)),
1824 "source_name" => stripslashes($item["author-name"]),
1825 "source_link" => $item["author-link"],
1826 "source_photo" => ((link_compare($item["author-link"],$importer["url"]))
1827 ? $importer["thumb"] : $item["author-avatar"]),
1828 "verb" => $item["verb"],
1829 "otype" => "person",
1830 "activity" => $verb,
1831 "parent" => $item["parent"]
1838 * @brief Processes several actions, depending on the verb
1840 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
1841 * @param array $importer Record of the importer user mixed with contact of the content
1842 * @param array $item the new item record
1843 * @param bool $is_like Is the verb a "like"?
1845 * @return bool Should the processing of the entries be continued?
1847 private function process_verbs($entrytype, $importer, &$item, &$is_like) {
1849 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
1851 if (($entrytype == DFRN_TOP_LEVEL)) {
1852 // The filling of the the "contact" variable is done for legcy reasons
1853 // The functions below are partly used by ostatus.php as well - where we have this variable
1854 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
1856 $nickname = $contact["nick"];
1858 // Big question: Do we need these functions? They were part of the "consume_feed" function.
1859 // This function once was responsible for DFRN and OStatus.
1860 if(activity_match($item["verb"],ACTIVITY_FOLLOW)) {
1861 logger("New follower");
1862 new_follower($importer, $contact, $item, $nickname);
1865 if(activity_match($item["verb"],ACTIVITY_UNFOLLOW)) {
1866 logger("Lost follower");
1867 lose_follower($importer, $contact, $item);
1870 if(activity_match($item["verb"],ACTIVITY_REQ_FRIEND)) {
1871 logger("New friend request");
1872 new_follower($importer, $contact, $item, $nickname, true);
1875 if(activity_match($item["verb"],ACTIVITY_UNFRIEND)) {
1876 logger("Lost sharer");
1877 lose_sharer($importer, $contact, $item);
1881 if(($item["verb"] == ACTIVITY_LIKE)
1882 || ($item["verb"] == ACTIVITY_DISLIKE)
1883 || ($item["verb"] == ACTIVITY_ATTEND)
1884 || ($item["verb"] == ACTIVITY_ATTENDNO)
1885 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)) {
1887 $item["type"] = "activity";
1888 $item["gravity"] = GRAVITY_LIKE;
1889 // only one like or dislike per person
1890 // splitted into two queries for performance issues
1891 $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",
1892 intval($item["uid"]),
1893 dbesc($item["author-link"]),
1894 dbesc($item["verb"]),
1895 dbesc($item["parent-uri"])
1900 $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",
1901 intval($item["uid"]),
1902 dbesc($item["author-link"]),
1903 dbesc($item["verb"]),
1904 dbesc($item["parent-uri"])
1911 if(($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
1913 $xo = parse_xml_string($item["object"],false);
1914 $xt = parse_xml_string($item["target"],false);
1916 if($xt->type == ACTIVITY_OBJ_NOTE) {
1917 $r = q("SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1919 intval($importer["importer_uid"])
1925 // extract tag, if not duplicate, add to parent item
1927 if(!(stristr($r[0]["tag"],trim($xo->content)))) {
1928 q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
1929 dbesc($r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
1932 create_tags_from_item($r[0]["id"]);
1942 * @brief Processes the link elements
1944 * @param object $links link elements
1945 * @param array $item the item record
1947 private function parse_links($links, &$item) {
1953 foreach ($links AS $link) {
1954 foreach($link->attributes AS $attributes) {
1955 if ($attributes->name == "href")
1956 $href = $attributes->textContent;
1957 if ($attributes->name == "rel")
1958 $rel = $attributes->textContent;
1959 if ($attributes->name == "type")
1960 $type = $attributes->textContent;
1961 if ($attributes->name == "length")
1962 $length = $attributes->textContent;
1963 if ($attributes->name == "title")
1964 $title = $attributes->textContent;
1966 if (($rel != "") AND ($href != ""))
1969 $item["plink"] = $href;
1973 if(strlen($item["attach"]))
1974 $item["attach"] .= ",";
1976 $item["attach"] .= '[attach]href="'.$href.'" length="'.$length.'" type="'.$type.'" title="'.$title.'"[/attach]';
1983 * @brief Processes the entry elements which contain the items and comments
1985 * @param array $header Array of the header elements that always stay the same
1986 * @param object $xpath XPath object
1987 * @param object $entry entry elements
1988 * @param array $importer Record of the importer user mixed with contact of the content
1990 private function process_entry($header, $xpath, $entry, $importer) {
1992 logger("Processing entries");
1997 $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
2000 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2002 $item["owner-name"] = $owner["name"];
2003 $item["owner-link"] = $owner["link"];
2004 $item["owner-avatar"] = $owner["avatar"];
2007 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2009 $item["author-name"] = $author["name"];
2010 $item["author-link"] = $author["link"];
2011 $item["author-avatar"] = $author["avatar"];
2013 $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
2015 $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2016 $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
2018 $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
2019 $item["body"] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$item["body"]);
2020 // make sure nobody is trying to sneak some html tags by us
2021 $item["body"] = notags(base64url_decode($item["body"]));
2023 $item["body"] = limit_body_size($item["body"]);
2025 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2026 if((strpos($item['body'],'<') !== false) && (strpos($item['body'],'>') !== false)) {
2028 $item['body'] = reltoabs($item['body'],$base_url);
2030 $item['body'] = html2bb_video($item['body']);
2032 $item['body'] = oembed_html2bbcode($item['body']);
2034 $config = HTMLPurifier_Config::createDefault();
2035 $config->set('Cache.DefinitionImpl', null);
2037 // we shouldn't need a whitelist, because the bbcode converter
2038 // will strip out any unsupported tags.
2040 $purifier = new HTMLPurifier($config);
2041 $item['body'] = $purifier->purify($item['body']);
2043 $item['body'] = @html2bbcode($item['body']);
2046 /// @todo We should check for a repeated post and if we know the repeated author.
2048 // We don't need the content element since "dfrn:env" is always present
2049 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2051 $item["last-child"] = $xpath->query("dfrn:comment-allow/text()", $entry)->item(0)->nodeValue;
2052 $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
2054 $georsspoint = $xpath->query("georss:point", $entry);
2056 $item["coord"] = $georsspoint->item(0)->nodeValue;
2058 $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
2060 $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
2062 if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true")
2063 $item["bookmark"] = true;
2065 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2066 if ($notice_info AND ($notice_info->length > 0)) {
2067 foreach($notice_info->item(0)->attributes AS $attributes) {
2068 if ($attributes->name == "source")
2069 $item["app"] = strip_tags($attributes->textContent);
2073 $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
2075 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "item_store"
2076 $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
2078 $item["dsprsig"] = $dsprsig;
2080 $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
2082 if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "")
2083 $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
2085 $object = $xpath->query("activity:object", $entry)->item(0);
2086 $item["object"] = self::transform_activity($xpath, $object, "object");
2088 if (trim($item["object"]) != "") {
2089 $r = parse_xml_string($item["object"], false);
2090 if (isset($r->type))
2091 $item["object-type"] = $r->type;
2094 $target = $xpath->query("activity:target", $entry)->item(0);
2095 $item["target"] = self::transform_activity($xpath, $target, "target");
2097 $categories = $xpath->query("atom:category", $entry);
2099 foreach ($categories AS $category) {
2102 foreach($category->attributes AS $attributes) {
2103 if ($attributes->name == "term")
2104 $term = $attributes->textContent;
2106 if ($attributes->name == "scheme")
2107 $scheme = $attributes->textContent;
2110 if (($term != "") AND ($scheme != "")) {
2111 $parts = explode(":", $scheme);
2112 if ((count($parts) >= 4) AND (array_shift($parts) == "X-DFRN")) {
2113 $termhash = array_shift($parts);
2114 $termurl = implode(":", $parts);
2116 if(strlen($item["tag"]))
2117 $item["tag"] .= ",";
2119 $item["tag"] .= $termhash."[url=".$termurl."]".$term."[/url]";
2127 $links = $xpath->query("atom:link", $entry);
2129 self::parse_links($links, $item);
2131 // Is it a reply or a top level posting?
2132 $item["parent-uri"] = $item["uri"];
2134 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2135 if (is_object($inreplyto->item(0)))
2136 foreach($inreplyto->item(0)->attributes AS $attributes)
2137 if ($attributes->name == "ref")
2138 $item["parent-uri"] = $attributes->textContent;
2140 // Get the type of the item (Top level post, reply or remote reply)
2141 $entrytype = self::get_entry_type($importer, $item);
2143 // Now assign the rest of the values that depend on the type of the message
2144 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2145 if (!isset($item["object-type"]))
2146 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2148 if ($item["contact-id"] != $owner["contact-id"])
2149 $item["contact-id"] = $owner["contact-id"];
2151 if (($item["network"] != $owner["network"]) AND ($owner["network"] != ""))
2152 $item["network"] = $owner["network"];
2154 if ($item["contact-id"] != $author["contact-id"])
2155 $item["contact-id"] = $author["contact-id"];
2157 if (($item["network"] != $author["network"]) AND ($author["network"] != ""))
2158 $item["network"] = $author["network"];
2160 // This code was taken from the old DFRN code
2161 // When activated, forums don't work.
2162 // And: Why should we disallow commenting by followers?
2163 // the behaviour is now similar to the Diaspora part.
2164 //if($importer["rel"] == CONTACT_IS_FOLLOWER) {
2165 // logger("Contact ".$importer["id"]." is only follower. Quitting", LOGGER_DEBUG);
2170 if ($entrytype == DFRN_REPLY_RC) {
2171 $item["type"] = "remote-comment";
2173 } elseif ($entrytype == DFRN_TOP_LEVEL) {
2174 if (!isset($item["object-type"]))
2175 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2178 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2179 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2180 $ev = bbtoevent($item["body"]);
2181 if((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2182 logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2183 $ev["cid"] = $importer["id"];
2184 $ev["uid"] = $importer["uid"];
2185 $ev["uri"] = $item["uri"];
2186 $ev["edited"] = $item["edited"];
2187 $ev['private'] = $item['private'];
2188 $ev["guid"] = $item["guid"];
2190 $r = q("SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2191 dbesc($item["uri"]),
2192 intval($importer["uid"])
2195 $ev["id"] = $r[0]["id"];
2197 $event_id = event_store($ev);
2198 logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2204 $r = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2205 dbesc($item["uri"]),
2206 intval($importer["importer_uid"])
2209 if (!self::process_verbs($entrytype, $importer, $item, $is_like)) {
2210 logger("Exiting because 'process_verbs' told us so", LOGGER_DEBUG);
2214 // Update content if 'updated' changes
2216 if (self::update_content($r[0], $item, $importer, $entrytype))
2217 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2219 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2223 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2224 $posted_id = item_store($item);
2229 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2231 $item["id"] = $posted_id;
2233 $r = q("SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2235 intval($importer["importer_uid"])
2238 $parent = $r[0]["parent"];
2239 $parent_uri = $r[0]["parent-uri"];
2243 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2244 dbesc(datetime_convert()),
2245 intval($importer["importer_uid"]),
2246 intval($r[0]["parent"])
2249 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d",
2250 dbesc(datetime_convert()),
2251 intval($importer["importer_uid"]),
2256 if($posted_id AND $parent AND ($entrytype == DFRN_REPLY_RC)) {
2257 logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
2258 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $posted_id);
2263 } else { // $entrytype == DFRN_TOP_LEVEL
2264 if(!link_compare($item["owner-link"],$importer["url"])) {
2265 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2266 // but otherwise there's a possible data mixup on the sender's system.
2267 // the tgroup delivery code called from item_store will correct it if it's a forum,
2268 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2269 logger('Correcting item owner.', LOGGER_DEBUG);
2270 $item["owner-name"] = $importer["senderName"];
2271 $item["owner-link"] = $importer["url"];
2272 $item["owner-avatar"] = $importer["thumb"];
2275 if(($importer["rel"] == CONTACT_IS_FOLLOWER) && (!tgroup_check($importer["importer_uid"], $item))) {
2276 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2280 // This is my contact on another system, but it's really me.
2281 // Turn this into a wall post.
2282 $notify = item_is_remote_self($importer, $item);
2284 $posted_id = item_store($item, false, $notify);
2286 logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2288 if(stristr($item["verb"],ACTIVITY_POKE))
2289 self::do_poke($item, $importer, $posted_id);
2294 * @brief Deletes items
2296 * @param object $xpath XPath object
2297 * @param object $deletion deletion elements
2298 * @param array $importer Record of the importer user mixed with contact of the content
2300 private function process_deletion($xpath, $deletion, $importer) {
2302 logger("Processing deletions");
2304 foreach($deletion->attributes AS $attributes) {
2305 if ($attributes->name == "ref")
2306 $uri = $attributes->textContent;
2307 if ($attributes->name == "when")
2308 $when = $attributes->textContent;
2311 $when = datetime_convert("UTC", "UTC", $when, "Y-m-d H:i:s");
2313 $when = datetime_convert("UTC", "UTC", "now", "Y-m-d H:i:s");
2315 if (!$uri OR !$importer["id"])
2318 /// @todo Only select the used fields
2319 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` INNER JOIN `contact` on `item`.`contact-id` = `contact`.`id`
2320 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2322 intval($importer["uid"]),
2323 intval($importer["id"])
2326 logger("Item with uri ".$uri." from contact ".$importer["id"]." for user ".$importer["uid"]." wasn't found.", LOGGER_DEBUG);
2332 $entrytype = self::get_entry_type($importer, $item);
2334 if(!$item["deleted"])
2335 logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG);
2339 if($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2340 logger("Deleting event ".$item["event-id"], LOGGER_DEBUG);
2341 event_delete($item["event-id"]);
2344 if(($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2346 $xo = parse_xml_string($item["object"],false);
2347 $xt = parse_xml_string($item["target"],false);
2349 if($xt->type == ACTIVITY_OBJ_NOTE) {
2350 $i = q("SELECT `id`, `contact-id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2352 intval($importer["importer_uid"])
2356 // For tags, the owner cannot remove the tag on the author's copy of the post.
2358 $owner_remove = (($item["contact-id"] == $i[0]["contact-id"]) ? true: false);
2359 $author_remove = (($item["origin"] && $item["self"]) ? true : false);
2360 $author_copy = (($item["origin"]) ? true : false);
2362 if($owner_remove && $author_copy)
2364 if($author_remove || $owner_remove) {
2365 $tags = explode(',',$i[0]["tag"]);
2368 foreach($tags as $tag)
2369 if(trim($tag) !== trim($xo->body))
2370 $newtags[] = trim($tag);
2372 q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2373 dbesc(implode(',',$newtags)),
2376 create_tags_from_item($i[0]["id"]);
2382 if($entrytype == DFRN_TOP_LEVEL) {
2383 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2384 `body` = '', `title` = ''
2385 WHERE `parent-uri` = '%s' AND `uid` = %d",
2387 dbesc(datetime_convert()),
2389 intval($importer["uid"])
2391 create_tags_from_itemuri($uri, $importer["uid"]);
2392 create_files_from_itemuri($uri, $importer["uid"]);
2393 update_thread_uri($uri, $importer["uid"]);
2395 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2396 `body` = '', `title` = ''
2397 WHERE `uri` = '%s' AND `uid` = %d",
2399 dbesc(datetime_convert()),
2401 intval($importer["uid"])
2403 create_tags_from_itemuri($uri, $importer["uid"]);
2404 create_files_from_itemuri($uri, $importer["uid"]);
2405 update_thread_uri($uri, $importer["importer_uid"]);
2406 if($item["last-child"]) {
2407 // ensure that last-child is set in case the comment that had it just got wiped.
2408 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2409 dbesc(datetime_convert()),
2410 dbesc($item["parent-uri"]),
2411 intval($item["uid"])
2413 // who is the last child now?
2414 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
2415 ORDER BY `created` DESC LIMIT 1",
2416 dbesc($item["parent-uri"]),
2417 intval($importer["uid"])
2420 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
2425 // if this is a relayed delete, propagate it to other recipients
2427 if($entrytype == DFRN_REPLY_RC) {
2428 logger("Notifying followers about deletion of post ".$item["id"], LOGGER_DEBUG);
2429 proc_run(PRIORITY_HIGH, "include/notifier.php","drop", $item["id"]);
2436 * @brief Imports a DFRN message
2438 * @param text $xml The DFRN message
2439 * @param array $importer Record of the importer user mixed with contact of the content
2440 * @param bool $sort_by_date Is used when feeds are polled
2442 public static function import($xml,$importer, $sort_by_date = false) {
2447 if($importer["readonly"]) {
2448 // We aren't receiving stuff from this person. But we will quietly ignore them
2449 // rather than a blatant "go away" message.
2450 logger('ignoring contact '.$importer["id"]);
2454 $doc = new DOMDocument();
2455 @$doc->loadXML($xml);
2457 $xpath = new DomXPath($doc);
2458 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2459 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2460 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2461 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2462 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2463 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2464 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2465 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2466 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2467 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2470 $header["uid"] = $importer["uid"];
2471 $header["network"] = NETWORK_DFRN;
2472 $header["type"] = "remote";
2473 $header["wall"] = 0;
2474 $header["origin"] = 0;
2475 $header["contact-id"] = $importer["id"];
2477 // Update the contact table if the data has changed
2479 // The "atom:author" is only present in feeds
2480 if ($xpath->query("/atom:feed/atom:author")->length > 0)
2481 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2483 // Only the "dfrn:owner" in the head section contains all data
2484 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0)
2485 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2487 logger("Import DFRN message for user ".$importer["uid"]." from contact ".$importer["id"], LOGGER_DEBUG);
2489 // The account type is new since 3.5.1
2490 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2491 $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()", $context)->item(0)->nodeValue);
2493 if ($accounttype != $importer["contact-type"])
2494 q("UPDATE `contact` SET `contact-type` = %d WHERE `id` = %d",
2495 intval($accounttype),
2496 intval($importer["id"])
2500 // is it a public forum? Private forums aren't supported with this method
2501 // This is deprecated since 3.5.1
2502 $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()", $context)->item(0)->nodeValue);
2504 if ($forum != $importer["forum"])
2505 q("UPDATE `contact` SET `forum` = %d WHERE `forum` != %d AND `id` = %d",
2506 intval($forum), intval($forum),
2507 intval($importer["id"])
2510 $mails = $xpath->query("/atom:feed/dfrn:mail");
2511 foreach ($mails AS $mail)
2512 self::process_mail($xpath, $mail, $importer);
2514 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2515 foreach ($suggestions AS $suggestion)
2516 self::process_suggestion($xpath, $suggestion, $importer);
2518 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2519 foreach ($relocations AS $relocation)
2520 self::process_relocation($xpath, $relocation, $importer);
2522 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2523 foreach ($deletions AS $deletion)
2524 self::process_deletion($xpath, $deletion, $importer);
2526 if (!$sort_by_date) {
2527 $entries = $xpath->query("/atom:feed/atom:entry");
2528 foreach ($entries AS $entry)
2529 self::process_entry($header, $xpath, $entry, $importer);
2531 $newentries = array();
2532 $entries = $xpath->query("/atom:feed/atom:entry");
2533 foreach ($entries AS $entry) {
2534 $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2535 $newentries[strtotime($created)] = $entry;
2538 // Now sort after the publishing date
2541 foreach ($newentries AS $entry)
2542 self::process_entry($header, $xpath, $entry, $importer);
2544 logger("Import done for user ".$importer["uid"]." from contact ".$importer["id"], LOGGER_DEBUG);