3 * @file include/dfrn.php
4 * @brief The implementation of the dfrn protocol
6 * @see https://github.com/friendica/friendica/wiki/Protocol and
7 * https://github.com/friendica/friendica/blob/master/spec/dfrn2.pdf
11 use Friendica\Core\Config;
12 use Friendica\Core\System;
13 use Friendica\Core\Worker;
15 require_once("include/Contact.php");
16 require_once("include/ostatus.php");
17 require_once("include/enotify.php");
18 require_once("include/threads.php");
19 require_once("include/socgraph.php");
20 require_once("include/items.php");
21 require_once("include/tags.php");
22 require_once("include/files.php");
23 require_once("include/event.php");
24 require_once("include/text.php");
25 require_once("include/oembed.php");
26 require_once("include/html2bbcode.php");
27 require_once("include/bbcode.php");
28 require_once("include/xml.php");
31 * @brief This class contain functions to create and send DFRN XML files
36 const DFRN_TOP_LEVEL = 0; // Top level posting
37 const DFRN_REPLY = 1; // Regular reply that is stored locally
38 const DFRN_REPLY_RC = 2; // Reply that will be relayed
41 * @brief Generates the atom entries for delivery.php
43 * This function is used whenever content is transmitted via DFRN.
45 * @param array $items Item elements
46 * @param array $owner Owner record
48 * @return string DFRN entries
49 * @todo Add type-hints
51 public static function entries($items,$owner) {
53 $doc = new DOMDocument('1.0', 'utf-8');
54 $doc->formatOutput = true;
56 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
58 if (! count($items)) {
59 return trim($doc->saveXML());
62 foreach ($items as $item) {
63 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
64 $root->appendChild($entry);
67 return(trim($doc->saveXML()));
71 * @brief Generate an atom feed for the given user
73 * This function is called when another server is pulling data from the user feed.
75 * @param string $dfrn_id DFRN ID from the requesting party
76 * @param string $owner_nick Owner nick name
77 * @param string $last_update Date of the last update
78 * @param int $direction Can be -1, 0 or 1.
79 * @param boolean $onlyheader Output only the header without content? (Default is "no")
81 * @return string DFRN feed entries
83 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false) {
87 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
88 $public_feed = (($dfrn_id) ? false : true);
89 $starred = false; // not yet implemented, possible security issues
92 if ($public_feed && $a->argc > 2) {
93 for ($x = 2; $x < $a->argc; $x++) {
94 if ($a->argv[$x] == 'converse') {
97 if ($a->argv[$x] == 'starred') {
100 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
101 $category = $a->argv[$x+1];
108 // default permissions - anonymous user
110 $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = '' ";
112 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
113 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
114 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
118 if (! dbm::is_result($r)) {
123 $owner_id = $owner['uid'];
124 $owner_nick = $owner['nickname'];
126 $sql_post_table = "";
128 if (! $public_feed) {
133 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
137 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
138 $my_id = '1:' . $dfrn_id;
141 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
142 $my_id = '0:' . $dfrn_id;
149 $r = q("SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
153 if (! dbm::is_result($r)) {
158 require_once('include/security.php');
159 $groups = init_groups_visitor($contact['id']);
161 if (count($groups)) {
162 for ($x = 0; $x < count($groups); $x ++)
163 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
164 $gs = implode('|', $groups);
166 $gs = '<<>>' ; // Impossible to match
169 $sql_extra = sprintf("
170 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
171 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
172 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
173 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
175 intval($contact['id']),
176 intval($contact['id']),
188 if (! strlen($last_update)) {
189 $last_update = 'now -30 days';
192 if (isset($category)) {
193 $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` ",
194 dbesc(protect_sprintf($category)), intval(TERM_OBJ_POST), intval(TERM_CATEGORY), intval($owner_id));
195 //$sql_extra .= file_tag_file_query('item',$category,'category');
200 $sql_extra .= " AND `contact`.`self` = 1 ";
204 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
206 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
207 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
208 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
209 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
210 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
211 FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
212 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
213 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
214 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
215 WHERE `item`.`uid` = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
216 AND `item`.`wall` AND `item`.`changed` > '%s'
218 ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
225 * Will check further below if this actually returned results.
226 * We will provide an empty feed if that is the case.
231 $doc = new DOMDocument('1.0', 'utf-8');
232 $doc->formatOutput = true;
234 $alternatelink = $owner['url'];
236 if (isset($category)) {
237 $alternatelink .= "/category/".$category;
241 $author = "dfrn:owner";
246 $root = self::add_header($doc, $owner, $author, $alternatelink, true);
248 /// @TODO This hook can't work anymore
249 // call_hooks('atom_feed', $atom);
251 if (!dbm::is_result($items) || $onlyheader) {
252 $atom = trim($doc->saveXML());
254 call_hooks('atom_feed_end', $atom);
259 foreach ($items as $item) {
261 // prevent private email from leaking.
262 if ($item['network'] == NETWORK_MAIL) {
266 // public feeds get html, our own nodes use bbcode
270 // catch any email that's in a public conversation and make sure it doesn't leak
271 if ($item['private']) {
278 $entry = self::entry($doc, $type, $item, $owner, true);
279 $root->appendChild($entry);
283 $atom = trim($doc->saveXML());
285 call_hooks('atom_feed_end', $atom);
291 * @brief Generate an atom entry for a given item id
293 * @param int $item_id The item id
294 * @param boolean $conversation Show the conversation. If false show the single post.
296 * @return string DFRN feed entry
298 public static function itemFeed($item_id, $conversation = false) {
300 $condition = '`item`.`parent`';
302 $condition = '`item`.`id`';
305 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
306 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
307 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
308 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
309 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
311 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
312 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
313 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
314 WHERE %s = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
315 AND NOT `item`.`private`",
320 if (!dbm::is_result($r)) {
327 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
328 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
329 WHERE `contact`.`self` AND `user`.`uid` = %d LIMIT 1",
333 if (!dbm::is_result($r)) {
339 $doc = new DOMDocument('1.0', 'utf-8');
340 $doc->formatOutput = true;
344 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
345 $doc->appendChild($root);
347 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
348 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
349 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
350 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
351 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
352 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
353 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
354 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
355 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
357 //$root = self::add_header($doc, $owner, "dfrn:owner", "", false);
359 foreach ($items as $item) {
360 $entry = self::entry($doc, $type, $item, $owner, true, 0);
361 $root->appendChild($entry);
364 $root = self::entry($doc, $type, $item, $owner, true, 0, true);
367 $atom = trim($doc->saveXML());
372 * @brief Create XML text for DFRN mails
374 * @param array $item message elements
375 * @param array $owner Owner record
377 * @return string DFRN mail
378 * @todo Add type-hints
380 public static function mail($item, $owner) {
381 $doc = new DOMDocument('1.0', 'utf-8');
382 $doc->formatOutput = true;
384 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
386 $mail = $doc->createElement("dfrn:mail");
387 $sender = $doc->createElement("dfrn:sender");
389 xml::add_element($doc, $sender, "dfrn:name", $owner['name']);
390 xml::add_element($doc, $sender, "dfrn:uri", $owner['url']);
391 xml::add_element($doc, $sender, "dfrn:avatar", $owner['thumb']);
393 $mail->appendChild($sender);
395 xml::add_element($doc, $mail, "dfrn:id", $item['uri']);
396 xml::add_element($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
397 xml::add_element($doc, $mail, "dfrn:sentdate", datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME));
398 xml::add_element($doc, $mail, "dfrn:subject", $item['title']);
399 xml::add_element($doc, $mail, "dfrn:content", $item['body']);
401 $root->appendChild($mail);
403 return(trim($doc->saveXML()));
407 * @brief Create XML text for DFRN friend suggestions
409 * @param array $item suggestion elements
410 * @param array $owner Owner record
412 * @return string DFRN suggestions
413 * @todo Add type-hints
415 public static function fsuggest($item, $owner) {
416 $doc = new DOMDocument('1.0', 'utf-8');
417 $doc->formatOutput = true;
419 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
421 $suggest = $doc->createElement("dfrn:suggest");
423 xml::add_element($doc, $suggest, "dfrn:url", $item['url']);
424 xml::add_element($doc, $suggest, "dfrn:name", $item['name']);
425 xml::add_element($doc, $suggest, "dfrn:photo", $item['photo']);
426 xml::add_element($doc, $suggest, "dfrn:request", $item['request']);
427 xml::add_element($doc, $suggest, "dfrn:note", $item['note']);
429 $root->appendChild($suggest);
431 return(trim($doc->saveXML()));
435 * @brief Create XML text for DFRN relocations
437 * @param array $owner Owner record
438 * @param int $uid User ID
440 * @return string DFRN relocations
441 * @todo Add type-hints
443 public static function relocate($owner, $uid) {
445 /* get site pubkey. this could be a new installation with no site keys*/
446 $pubkey = Config::get('system','site_pubkey');
448 $res = new_keypair(1024);
449 Config::set('system','site_prvkey', $res['prvkey']);
450 Config::set('system','site_pubkey', $res['pubkey']);
453 $rp = q("SELECT `resource-id` , `scale`, type FROM `photo`
454 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;", $uid);
456 $ext = Photo::supportedTypes();
458 foreach ($rp as $p) {
459 $photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
464 $doc = new DOMDocument('1.0', 'utf-8');
465 $doc->formatOutput = true;
467 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
469 $relocate = $doc->createElement("dfrn:relocate");
471 xml::add_element($doc, $relocate, "dfrn:url", $owner['url']);
472 xml::add_element($doc, $relocate, "dfrn:name", $owner['name']);
473 xml::add_element($doc, $relocate, "dfrn:addr", $owner['addr']);
474 xml::add_element($doc, $relocate, "dfrn:avatar", $owner['avatar']);
475 xml::add_element($doc, $relocate, "dfrn:photo", $photos[4]);
476 xml::add_element($doc, $relocate, "dfrn:thumb", $photos[5]);
477 xml::add_element($doc, $relocate, "dfrn:micro", $photos[6]);
478 xml::add_element($doc, $relocate, "dfrn:request", $owner['request']);
479 xml::add_element($doc, $relocate, "dfrn:confirm", $owner['confirm']);
480 xml::add_element($doc, $relocate, "dfrn:notify", $owner['notify']);
481 xml::add_element($doc, $relocate, "dfrn:poll", $owner['poll']);
482 xml::add_element($doc, $relocate, "dfrn:sitepubkey", Config::get('system','site_pubkey'));
484 $root->appendChild($relocate);
486 return(trim($doc->saveXML()));
490 * @brief Adds the header elements for the DFRN protocol
492 * @param object $doc XML document
493 * @param array $owner Owner record
494 * @param string $authorelement Element name for the author
495 * @param string $alternatelink link to profile or category
496 * @param bool $public Is it a header for public posts?
498 * @return object XML root object
499 * @todo Add type-hints
501 private static function add_header($doc, $owner, $authorelement, $alternatelink = "", $public = false) {
503 if ($alternatelink == "") {
504 $alternatelink = $owner['url'];
507 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
508 $doc->appendChild($root);
510 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
511 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
512 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
513 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
514 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
515 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
516 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
517 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
518 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
520 xml::add_element($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
521 xml::add_element($doc, $root, "title", $owner["name"]);
523 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
524 xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
526 $attributes = array("rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/");
527 xml::add_element($doc, $root, "link", "", $attributes);
529 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $alternatelink);
530 xml::add_element($doc, $root, "link", "", $attributes);
534 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
535 ostatus::hublinks($doc, $root, $owner["nick"]);
537 $attributes = array("rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
538 xml::add_element($doc, $root, "link", "", $attributes);
540 $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
541 xml::add_element($doc, $root, "link", "", $attributes);
543 $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
544 xml::add_element($doc, $root, "link", "", $attributes);
547 // For backward compatibility we keep this element
548 if ($owner['page-flags'] == PAGE_COMMUNITY) {
549 xml::add_element($doc, $root, "dfrn:community", 1);
552 // The former element is replaced by this one
553 xml::add_element($doc, $root, "dfrn:account_type", $owner["account-type"]);
555 /// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
557 xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
559 $author = self::add_author($doc, $owner, $authorelement, $public);
560 $root->appendChild($author);
566 * @brief Adds the author element in the header for the DFRN protocol
568 * @param object $doc XML document
569 * @param array $owner Owner record
570 * @param string $authorelement Element name for the author
572 * @return object XML author object
573 * @todo Add type-hints
575 private static function add_author($doc, $owner, $authorelement, $public) {
577 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
578 $r = q("SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
579 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
580 intval($owner['uid']));
581 if (dbm::is_result($r)) {
587 $author = $doc->createElement($authorelement);
589 $namdate = datetime_convert('UTC', 'UTC', $owner['name-date'].'+00:00', ATOM_TIME);
590 $uridate = datetime_convert('UTC', 'UTC', $owner['uri-date'].'+00:00', ATOM_TIME);
591 $picdate = datetime_convert('UTC', 'UTC', $owner['avatar-date'].'+00:00', ATOM_TIME);
593 $attributes = array();
595 if (!$public || !$hidewall) {
596 $attributes = array("dfrn:updated" => $namdate);
599 xml::add_element($doc, $author, "name", $owner["name"], $attributes);
600 xml::add_element($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
601 xml::add_element($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
603 $attributes = array("rel" => "photo", "type" => "image/jpeg",
604 "media:width" => 175, "media:height" => 175, "href" => $owner['photo']);
606 if (!$public || !$hidewall) {
607 $attributes["dfrn:updated"] = $picdate;
610 xml::add_element($doc, $author, "link", "", $attributes);
612 $attributes["rel"] = "avatar";
613 xml::add_element($doc, $author, "link", "", $attributes);
616 xml::add_element($doc, $author, "dfrn:hide", "true");
619 // The following fields will only be generated if the data isn't meant for a public feed
624 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
627 xml::add_element($doc, $author, "dfrn:birthday", $birthday);
629 // Only show contact details when we are allowed to
630 $r = q("SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
631 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
632 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
634 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
635 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
636 intval($owner['uid']));
637 if (dbm::is_result($r)) {
640 xml::add_element($doc, $author, "poco:displayName", $profile["name"]);
641 xml::add_element($doc, $author, "poco:updated", $namdate);
643 if (trim($profile["dob"]) > '0001-01-01') {
644 xml::add_element($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
647 xml::add_element($doc, $author, "poco:note", $profile["about"]);
648 xml::add_element($doc, $author, "poco:preferredUsername", $profile["nickname"]);
650 $savetz = date_default_timezone_get();
651 date_default_timezone_set($profile["timezone"]);
652 xml::add_element($doc, $author, "poco:utcOffset", date("P"));
653 date_default_timezone_set($savetz);
655 if (trim($profile["homepage"]) != "") {
656 $urls = $doc->createElement("poco:urls");
657 xml::add_element($doc, $urls, "poco:type", "homepage");
658 xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
659 xml::add_element($doc, $urls, "poco:primary", "true");
660 $author->appendChild($urls);
663 if (trim($profile["pub_keywords"]) != "") {
664 $keywords = explode(",", $profile["pub_keywords"]);
666 foreach ($keywords AS $keyword) {
667 xml::add_element($doc, $author, "poco:tags", trim($keyword));
672 if (trim($profile["xmpp"]) != "") {
673 $ims = $doc->createElement("poco:ims");
674 xml::add_element($doc, $ims, "poco:type", "xmpp");
675 xml::add_element($doc, $ims, "poco:value", $profile["xmpp"]);
676 xml::add_element($doc, $ims, "poco:primary", "true");
677 $author->appendChild($ims);
680 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
681 $element = $doc->createElement("poco:address");
683 xml::add_element($doc, $element, "poco:formatted", formatted_location($profile));
685 if (trim($profile["locality"]) != "") {
686 xml::add_element($doc, $element, "poco:locality", $profile["locality"]);
689 if (trim($profile["region"]) != "") {
690 xml::add_element($doc, $element, "poco:region", $profile["region"]);
693 if (trim($profile["country-name"]) != "") {
694 xml::add_element($doc, $element, "poco:country", $profile["country-name"]);
697 $author->appendChild($element);
705 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
707 * @param object $doc XML document
708 * @param string $element Element name for the author
709 * @param string $contact_url Link of the contact
710 * @param array $items Item elements
712 * @return object XML author object
713 * @todo Add type-hints
715 private static function add_entry_author($doc, $element, $contact_url, $item) {
717 $contact = get_contact_details_by_url($contact_url, $item["uid"]);
719 $author = $doc->createElement($element);
720 xml::add_element($doc, $author, "name", $contact["name"]);
721 xml::add_element($doc, $author, "uri", $contact["url"]);
722 xml::add_element($doc, $author, "dfrn:handle", $contact["addr"]);
725 /// - Check real image type and image size
726 /// - Check which of these boths elements we should use
729 "type" => "image/jpeg",
731 "media:height" => 80,
732 "href" => $contact["photo"]);
733 xml::add_element($doc, $author, "link", "", $attributes);
737 "type" => "image/jpeg",
739 "media:height" => 80,
740 "href" => $contact["photo"]);
741 xml::add_element($doc, $author, "link", "", $attributes);
747 * @brief Adds the activity elements
749 * @param object $doc XML document
750 * @param string $element Element name for the activity
751 * @param string $activity activity value
753 * @return object XML activity object
754 * @todo Add type-hints
756 private static function create_activity($doc, $element, $activity) {
759 $entry = $doc->createElement($element);
761 $r = parse_xml_string($activity, false);
766 xml::add_element($doc, $entry, "activity:object-type", $r->type);
769 xml::add_element($doc, $entry, "id", $r->id);
772 xml::add_element($doc, $entry, "title", $r->title);
776 if (substr($r->link, 0, 1) == '<') {
777 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
778 $r->link = str_replace('&', '&', $r->link);
781 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
783 // XML does need a single element as root element so we add a dummy element here
784 $data = parse_xml_string("<dummy>" . $r->link . "</dummy>", false);
785 if (is_object($data)) {
786 foreach ($data->link AS $link) {
787 $attributes = array();
788 foreach ($link->attributes() AS $parameter => $value) {
789 $attributes[$parameter] = $value;
791 xml::add_element($doc, $entry, "link", "", $attributes);
795 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $r->link);
796 xml::add_element($doc, $entry, "link", "", $attributes);
800 xml::add_element($doc, $entry, "content", bbcode($r->content), array("type" => "html"));
810 * @brief Adds the elements for attachments
812 * @param object $doc XML document
813 * @param object $root XML root
814 * @param array $item Item element
816 * @return object XML attachment object
817 * @todo Add type-hints
819 private static function get_attachment($doc, $root, $item) {
820 $arr = explode('[/attach],',$item['attach']);
822 foreach ($arr as $r) {
824 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches);
826 $attributes = array("rel" => "enclosure",
827 "href" => $matches[1],
828 "type" => $matches[3]);
830 if (intval($matches[2])) {
831 $attributes["length"] = intval($matches[2]);
834 if (trim($matches[4]) != "") {
835 $attributes["title"] = trim($matches[4]);
838 xml::add_element($doc, $root, "link", "", $attributes);
845 * @brief Adds the "entry" elements for the DFRN protocol
847 * @param object $doc XML document
848 * @param string $type "text" or "html"
849 * @param array $item Item element
850 * @param array $owner Owner record
851 * @param bool $comment Trigger the sending of the "comment" element
852 * @param int $cid Contact ID of the recipient
853 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
855 * @return object XML entry object
856 * @todo Add type-hints
858 private static function entry($doc, $type, $item, $owner, $comment = false, $cid = 0, $single = false) {
860 $mentioned = array();
862 if (!$item['parent']) {
866 if ($item['deleted']) {
867 $attributes = array("ref" => $item['uri'], "when" => datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME));
868 return xml::create_element($doc, "at:deleted-entry", "", $attributes);
872 $entry = $doc->createElement("entry");
874 $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry');
875 $doc->appendChild($entry);
877 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
878 $entry->setAttribute("xmlns:at", NAMESPACE_TOMB);
879 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
880 $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
881 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
882 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
883 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
884 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
885 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
888 if ($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid']) {
889 $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
891 $body = $item['body'];
894 // Remove the abstract element. It is only locally important.
895 $body = remove_abstract($body);
897 if ($type == 'html') {
900 if ($item['title'] != "") {
901 $htmlbody = "[b]".$item['title']."[/b]\n\n".$htmlbody;
904 $htmlbody = bbcode($htmlbody, false, false, 7);
907 $author = self::add_entry_author($doc, "author", $item["author-link"], $item);
908 $entry->appendChild($author);
910 $dfrnowner = self::add_entry_author($doc, "dfrn:owner", $item["owner-link"], $item);
911 $entry->appendChild($dfrnowner);
913 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
914 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
915 $parent = q("SELECT `guid`,`plink` FROM `item` WHERE `uri` = '%s' AND `uid` = %d", dbesc($parent_item), intval($item['uid']));
916 $attributes = array("ref" => $parent_item, "type" => "text/html",
917 "href" => $parent[0]['plink'],
918 "dfrn:diaspora_guid" => $parent[0]['guid']);
919 xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
922 // Add conversation data. This is used for OStatus
923 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
924 $conversation_uri = $conversation_href;
926 if (isset($parent_item)) {
927 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $item['parent-uri']);
928 if (dbm::is_result($r)) {
929 if ($r['conversation-uri'] != '') {
930 $conversation_uri = $r['conversation-uri'];
932 if ($r['conversation-href'] != '') {
933 $conversation_href = $r['conversation-href'];
939 "href" => $conversation_href,
940 "ref" => $conversation_uri);
942 xml::add_element($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
944 xml::add_element($doc, $entry, "id", $item["uri"]);
945 xml::add_element($doc, $entry, "title", $item["title"]);
947 xml::add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
948 xml::add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
950 // "dfrn:env" is used to read the content
951 xml::add_element($doc, $entry, "dfrn:env", base64url_encode($body, true));
953 // The "content" field is not read by the receiver. We could remove it when the type is "text"
954 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
955 xml::add_element($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), array("type" => $type));
957 // We save this value in "plink". Maybe we should read it from there as well?
958 xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
959 "href" => System::baseUrl()."/display/".$item["guid"]));
961 // "comment-allow" is some old fashioned stuff for old Friendica versions.
962 // It is included in the rewritten code for completeness
964 xml::add_element($doc, $entry, "dfrn:comment-allow", intval($item['last-child']));
967 if ($item['location']) {
968 xml::add_element($doc, $entry, "dfrn:location", $item['location']);
971 if ($item['coord']) {
972 xml::add_element($doc, $entry, "georss:point", $item['coord']);
975 if (($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])) {
976 xml::add_element($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
979 if ($item['extid']) {
980 xml::add_element($doc, $entry, "dfrn:extid", $item['extid']);
983 if ($item['bookmark']) {
984 xml::add_element($doc, $entry, "dfrn:bookmark", "true");
988 xml::add_element($doc, $entry, "statusnet:notice_info", "", array("local_id" => $item['id'], "source" => $item['app']));
991 xml::add_element($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
993 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
994 // It is needed for relayed comments to Diaspora.
995 if ($item['signed_text']) {
996 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
997 xml::add_element($doc, $entry, "dfrn:diaspora_signature", $sign);
1000 xml::add_element($doc, $entry, "activity:verb", construct_verb($item));
1002 if ($item['object-type'] != "") {
1003 xml::add_element($doc, $entry, "activity:object-type", $item['object-type']);
1004 } elseif ($item['id'] == $item['parent']) {
1005 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1007 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
1010 $actobj = self::create_activity($doc, "activity:object", $item['object']);
1012 $entry->appendChild($actobj);
1015 $actarg = self::create_activity($doc, "activity:target", $item['target']);
1017 $entry->appendChild($actarg);
1020 $tags = item_getfeedtags($item);
1023 foreach ($tags as $t) {
1024 if (($type != 'html') || ($t[0] != "@")) {
1025 xml::add_element($doc, $entry, "category", "", array("scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]));
1031 foreach ($tags as $t) {
1033 $mentioned[$t[1]] = $t[1];
1038 foreach ($mentioned AS $mention) {
1039 $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1040 intval($owner["uid"]),
1041 dbesc(normalise_link($mention)));
1043 if (dbm::is_result($r) && ($r[0]["forum"] || $r[0]["prv"])) {
1044 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1045 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1046 "href" => $mention));
1048 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1049 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1050 "href" => $mention));
1054 self::get_attachment($doc, $entry, $item);
1060 * @brief encrypts data via AES
1062 * @param string $data The data that is to be encrypted
1063 * @param string $key The AES key
1065 * @return string encrypted data
1067 private static function aes_encrypt($data, $key) {
1068 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1072 * @brief decrypts data via AES
1074 * @param string $encrypted The encrypted data
1075 * @param string $key The AES key
1077 * @return string decrypted data
1079 public static function aes_decrypt($encrypted, $key) {
1080 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1084 * @brief Delivers the atom content to the contacts
1086 * @param array $owner Owner record
1087 * @param array $contactr Contact record of the receiver
1088 * @param string $atom Content that will be transmitted
1089 * @param bool $dissolve (to be documented)
1091 * @return int Deliver status. -1 means an error.
1092 * @todo Add array type-hint for $owner, $contact
1094 public static function deliver($owner,$contact,$atom, $dissolve = false) {
1098 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1100 if ($contact['duplex'] && $contact['dfrn-id']) {
1101 $idtosend = '0:' . $orig_id;
1103 if ($contact['duplex'] && $contact['issued-id']) {
1104 $idtosend = '1:' . $orig_id;
1107 $rino = Config::get('system', 'rino_encrypt');
1108 $rino = intval($rino);
1110 logger("Local rino version: ". $rino, LOGGER_DEBUG);
1112 $ssl_val = intval(Config::get('system','ssl_policy'));
1116 case SSL_POLICY_FULL:
1117 $ssl_policy = 'full';
1119 case SSL_POLICY_SELFSIGN:
1120 $ssl_policy = 'self';
1122 case SSL_POLICY_NONE:
1124 $ssl_policy = 'none';
1128 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1130 logger('dfrn_deliver: ' . $url);
1132 $ret = z_fetch_url($url);
1134 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1135 return -2; // timed out
1138 $xml = $ret['body'];
1140 $curl_stat = $a->get_curl_code();
1142 return -3; // timed out
1145 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1151 if (strpos($xml,'<?xml') === false) {
1152 logger('dfrn_deliver: no valid XML returned');
1153 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1157 $res = parse_xml_string($xml);
1159 if ((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id))) {
1160 return (($res->status) ? $res->status : 3);
1163 $postvars = array();
1164 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1165 $challenge = hex2bin((string) $res->challenge);
1166 $perm = (($res->perm) ? $res->perm : null);
1167 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1168 $rino_remote_version = intval($res->rino);
1169 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1171 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
1173 if ($owner['page-flags'] == PAGE_PRVGROUP) {
1177 $final_dfrn_id = '';
1180 if ((($perm == 'rw') && (! intval($contact['writable'])))
1181 || (($perm == 'r') && (intval($contact['writable'])))) {
1182 q("update contact set writable = %d where id = %d",
1183 intval(($perm == 'rw') ? 1 : 0),
1184 intval($contact['id'])
1186 $contact['writable'] = (string) 1 - intval($contact['writable']);
1190 if (($contact['duplex'] && strlen($contact['pubkey']))
1191 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1192 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1193 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
1194 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
1196 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
1197 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
1200 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1202 if (strpos($final_dfrn_id,':') == 1) {
1203 $final_dfrn_id = substr($final_dfrn_id,2);
1206 if ($final_dfrn_id != $orig_id) {
1207 logger('dfrn_deliver: wrong dfrn_id.');
1208 // did not decode properly - cannot trust this site
1212 $postvars['dfrn_id'] = $idtosend;
1213 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1215 $postvars['dissolve'] = '1';
1219 if ((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1220 $postvars['data'] = $atom;
1221 $postvars['perm'] = 'rw';
1223 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1224 $postvars['perm'] = 'r';
1227 $postvars['ssl_policy'] = $ssl_policy;
1230 $postvars['page'] = $page;
1234 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1235 logger('rino version: '. $rino_remote_version);
1237 switch ($rino_remote_version) {
1239 // Deprecated rino version!
1240 $key = openssl_random_pseudo_bytes(16);
1241 $data = self::aes_encrypt($postvars['data'], $key);
1244 // RINO 2 based on php-encryption
1246 $key = Crypto::createNewRandomKey();
1247 } catch (CryptoTestFailed $ex) {
1248 logger('Cannot safely create a key');
1250 } catch (CannotPerformOperation $ex) {
1251 logger('Cannot safely create a key');
1255 $data = Crypto::encrypt($postvars['data'], $key);
1256 } catch (CryptoTestFailed $ex) {
1257 logger('Cannot safely perform encryption');
1259 } catch (CannotPerformOperation $ex) {
1260 logger('Cannot safely perform encryption');
1265 logger("rino: invalid requested verision '$rino_remote_version'");
1269 $postvars['rino'] = $rino_remote_version;
1270 $postvars['data'] = bin2hex($data);
1272 //logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1275 if ($dfrn_version >= 2.1) {
1276 if (($contact['duplex'] && strlen($contact['pubkey']))
1277 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1278 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1279 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1281 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1285 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1286 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1288 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1293 logger('md5 rawkey ' . md5($postvars['key']));
1295 $postvars['key'] = bin2hex($postvars['key']);
1299 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1301 $xml = post_url($contact['notify'], $postvars);
1303 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1305 $curl_stat = $a->get_curl_code();
1306 if ((!$curl_stat) || (!strlen($xml))) {
1307 return -9; // timed out
1310 if (($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after'))) {
1314 if (strpos($xml,'<?xml') === false) {
1315 logger('dfrn_deliver: phase 2: no valid XML returned');
1316 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1320 if ($contact['term-date'] > NULL_DATE) {
1321 logger("dfrn_deliver: $url back from the dead - removing mark for death");
1322 require_once('include/Contact.php');
1323 unmark_for_death($contact);
1326 $res = parse_xml_string($xml);
1328 if (!isset($res->status)) {
1332 if (!empty($res->message)) {
1333 logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1336 return intval($res->status);
1340 * @brief Add new birthday event for this person
1342 * @param array $contact Contact record
1343 * @param string $birthday Birthday of the contact
1344 * @todo Add array type-hint for $contact
1346 private static function birthday_event($contact, $birthday) {
1348 // Check for duplicates
1349 $r = q("SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1350 intval($contact["uid"]),
1351 intval($contact["id"]),
1352 dbesc(datetime_convert("UTC","UTC", $birthday)),
1355 if (dbm::is_result($r)) {
1359 logger("updating birthday: ".$birthday." for contact ".$contact["id"]);
1361 $bdtext = sprintf(t("%s\'s birthday"), $contact["name"]);
1362 $bdtext2 = sprintf(t("Happy Birthday %s"), " [url=".$contact["url"]."]".$contact["name"]."[/url]") ;
1364 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1365 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1366 intval($contact["uid"]),
1367 intval($contact["id"]),
1368 dbesc(datetime_convert()),
1369 dbesc(datetime_convert()),
1370 dbesc(datetime_convert("UTC","UTC", $birthday)),
1371 dbesc(datetime_convert("UTC","UTC", $birthday." + 1 day ")),
1379 * @brief Fetch the author data from head or entry items
1381 * @param object $xpath XPath object
1382 * @param object $context In which context should the data be searched
1383 * @param array $importer Record of the importer user mixed with contact of the content
1384 * @param string $element Element name from which the data is fetched
1385 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1387 * @return Returns an array with relevant data of the author
1388 * @todo Find good type-hints for all parameter
1390 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "") {
1393 $author["name"] = $xpath->evaluate($element."/atom:name/text()", $context)->item(0)->nodeValue;
1394 $author["link"] = $xpath->evaluate($element."/atom:uri/text()", $context)->item(0)->nodeValue;
1396 $r = q("SELECT `id`, `uid`, `url`, `network`, `avatar-date`, `name-date`, `uri-date`, `addr`,
1397 `name`, `nick`, `about`, `location`, `keywords`, `xmpp`, `bdyear`, `bd`, `hidden`, `contact-type`
1398 FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
1399 intval($importer["uid"]), dbesc(normalise_link($author["link"])), dbesc(NETWORK_STATUSNET));
1401 if (dbm::is_result($r)) {
1403 $author["contact-id"] = $r[0]["id"];
1404 $author["network"] = $r[0]["network"];
1407 logger("Contact ".$author["link"]." wasn't found for user ".$importer["uid"]." XML: ".$xml, LOGGER_DEBUG);
1410 $author["contact-id"] = $importer["id"];
1411 $author["network"] = $importer["network"];
1415 // Until now we aren't serving different sizes - but maybe later
1416 $avatarlist = array();
1417 /// @todo check if "avatar" or "photo" would be the best field in the specification
1418 $avatars = $xpath->query($element."/atom:link[@rel='avatar']", $context);
1419 foreach ($avatars AS $avatar) {
1422 foreach ($avatar->attributes AS $attributes) {
1423 /// @TODO Rewrite these similar if () to one switch
1424 if ($attributes->name == "href") {
1425 $href = $attributes->textContent;
1427 if ($attributes->name == "width") {
1428 $width = $attributes->textContent;
1430 if ($attributes->name == "updated") {
1431 $contact["avatar-date"] = $attributes->textContent;
1434 if (($width > 0) && ($href != "")) {
1435 $avatarlist[$width] = $href;
1438 if (count($avatarlist) > 0) {
1439 krsort($avatarlist);
1440 $author["avatar"] = current($avatarlist);
1443 if (dbm::is_result($r) && !$onlyfetch) {
1444 logger("Check if contact details for contact " . $r[0]["id"] . " (" . $r[0]["nick"] . ") have to be updated.", LOGGER_DEBUG);
1446 $poco = array("url" => $contact["url"]);
1448 // When was the last change to name or uri?
1449 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1450 foreach ($name_element->attributes AS $attributes) {
1451 if ($attributes->name == "updated") {
1452 $poco["name-date"] = $attributes->textContent;
1456 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1457 foreach ($link_element->attributes AS $attributes) {
1458 if ($attributes->name == "updated") {
1459 $poco["uri-date"] = $attributes->textContent;
1463 // Update contact data
1464 $value = $xpath->evaluate($element . "/dfrn:handle/text()", $context)->item(0)->nodeValue;
1466 $poco["addr"] = $value;
1469 $value = $xpath->evaluate($element . "/poco:displayName/text()", $context)->item(0)->nodeValue;
1471 $poco["name"] = $value;
1474 $value = $xpath->evaluate($element . "/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
1476 $poco["nick"] = $value;
1479 $value = $xpath->evaluate($element . "/poco:note/text()", $context)->item(0)->nodeValue;
1481 $poco["about"] = $value;
1484 $value = $xpath->evaluate($element . "/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
1486 $poco["location"] = $value;
1489 /// @todo Only search for elements with "poco:type" = "xmpp"
1490 $value = $xpath->evaluate($element . "/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
1492 $poco["xmpp"] = $value;
1495 /// @todo Add support for the following fields that we don't support by now in the contact table:
1496 /// - poco:utcOffset
1502 // If the "hide" element is present then the profile isn't searchable.
1503 $hide = intval($xpath->evaluate($element . "/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
1505 logger("Hidden status for contact " . $contact["url"] . ": " . $hide, LOGGER_DEBUG);
1507 // If the contact isn't searchable then set the contact to "hidden".
1508 // Problem: This can be manually overridden by the user.
1510 $contact["hidden"] = true;
1513 // Save the keywords into the contact table
1515 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1516 foreach ($tagelements AS $tag) {
1517 $tags[$tag->nodeValue] = $tag->nodeValue;
1521 $poco["keywords"] = implode(", ", $tags);
1524 // "dfrn:birthday" contains the birthday converted to UTC
1525 $old_bdyear = $contact["bdyear"];
1527 $birthday = $xpath->evaluate($element . "/dfrn:birthday/text()", $context)->item(0)->nodeValue;
1529 if (strtotime($birthday) > time()) {
1530 $bd_timestamp = strtotime($birthday);
1532 $poco["bdyear"] = date("Y", $bd_timestamp);
1535 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1536 $value = $xpath->evaluate($element . "/poco:birthday/text()", $context)->item(0)->nodeValue;
1538 if (!in_array($value, array("", "0000-00-00", "0001-01-01"))) {
1539 $bdyear = date("Y");
1540 $value = str_replace("0000", $bdyear, $value);
1542 if (strtotime($value) < time()) {
1543 $value = str_replace($bdyear, $bdyear + 1, $value);
1544 $bdyear = $bdyear + 1;
1547 $poco["bd"] = $value;
1550 $contact = array_merge($contact, $poco);
1552 if ($old_bdyear != $contact["bdyear"]) {
1553 self::birthday_event($contact, $birthday);
1556 // Get all field names
1558 foreach ($r[0] AS $field => $data) {
1559 $fields[$field] = $data;
1562 unset($fields["id"]);
1563 unset($fields["uid"]);
1564 unset($fields["url"]);
1565 unset($fields["avatar-date"]);
1566 unset($fields["name-date"]);
1567 unset($fields["uri-date"]);
1569 // Update check for this field has to be done differently
1570 $datefields = array("name-date", "uri-date");
1571 foreach ($datefields AS $field) {
1572 if (strtotime($contact[$field]) > strtotime($r[0][$field])) {
1573 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $r[0][$field] . "'", LOGGER_DEBUG);
1578 foreach ($fields AS $field => $data) {
1579 if ($contact[$field] != $r[0][$field]) {
1580 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $r[0][$field] . "'", LOGGER_DEBUG);
1586 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1588 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1589 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1590 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1591 WHERE `id` = %d AND `network` = '%s'",
1592 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
1593 dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1594 dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
1595 dbesc(dbm::date($contact["name-date"])), dbesc(dbm::date($contact["uri-date"])),
1596 intval($contact["id"]), dbesc($contact["network"]));
1599 update_contact_avatar($author["avatar"], $importer["uid"], $contact["id"],
1600 (strtotime($contact["avatar-date"]) > strtotime($r[0]["avatar-date"])));
1603 * The generation is a sign for the reliability of the provided data.
1604 * It is used in the socgraph.php to prevent that old contact data
1605 * that was relayed over several servers can overwrite contact
1606 * data that we received directly.
1609 $poco["generation"] = 2;
1610 $poco["photo"] = $author["avatar"];
1611 $poco["hide"] = $hide;
1612 $poco["contact-type"] = $contact["contact-type"];
1613 $gcid = update_gcontact($poco);
1615 link_gcontact($gcid, $importer["uid"], $contact["id"]);
1622 * @brief Transforms activity objects into an XML string
1624 * @param object $xpath XPath object
1625 * @param object $activity Activity object
1626 * @param text $element element name
1628 * @return string XML string
1629 * @todo Find good type-hints for all parameter
1631 private static function transform_activity($xpath, $activity, $element) {
1632 if (!is_object($activity)) {
1636 $obj_doc = new DOMDocument("1.0", "utf-8");
1637 $obj_doc->formatOutput = true;
1639 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1641 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1642 xml::add_element($obj_doc, $obj_element, "type", $activity_type);
1644 $id = $xpath->query("atom:id", $activity)->item(0);
1645 if (is_object($id)) {
1646 $obj_element->appendChild($obj_doc->importNode($id, true));
1649 $title = $xpath->query("atom:title", $activity)->item(0);
1650 if (is_object($title)) {
1651 $obj_element->appendChild($obj_doc->importNode($title, true));
1654 $links = $xpath->query("atom:link", $activity);
1655 if (is_object($links)) {
1656 foreach ($links AS $link) {
1657 $obj_element->appendChild($obj_doc->importNode($link, true));
1661 $content = $xpath->query("atom:content", $activity)->item(0);
1662 if (is_object($content)) {
1663 $obj_element->appendChild($obj_doc->importNode($content, true));
1666 $obj_doc->appendChild($obj_element);
1668 $objxml = $obj_doc->saveXML($obj_element);
1670 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1671 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1676 * @brief Processes the mail elements
1678 * @param object $xpath XPath object
1679 * @param object $mail mail elements
1680 * @param array $importer Record of the importer user mixed with contact of the content
1681 * @todo Find good type-hints for all parameter
1683 private static function process_mail($xpath, $mail, $importer) {
1685 logger("Processing mails");
1687 /// @TODO Rewrite this to one statement
1689 $msg["uid"] = $importer["importer_uid"];
1690 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1691 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1692 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1693 $msg["contact-id"] = $importer["id"];
1694 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1695 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1696 $msg["created"] = $xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue;
1697 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1698 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1700 $msg["replied"] = 0;
1702 dba::insert('mail', $msg);
1704 // send notifications.
1705 /// @TODO Arange this mess
1706 $notif_params = array(
1707 "type" => NOTIFY_MAIL,
1708 "notify_flags" => $importer["notify-flags"],
1709 "language" => $importer["language"],
1710 "to_name" => $importer["username"],
1711 "to_email" => $importer["email"],
1712 "uid" => $importer["importer_uid"],
1714 "source_name" => $msg["from-name"],
1715 "source_link" => $importer["url"],
1716 "source_photo" => $importer["thumb"],
1717 "verb" => ACTIVITY_POST,
1721 notification($notif_params);
1723 logger("Mail is processed, notification was sent.");
1727 * @brief Processes the suggestion elements
1729 * @param object $xpath XPath object
1730 * @param object $suggestion suggestion elements
1731 * @param array $importer Record of the importer user mixed with contact of the content
1732 * @todo Find good type-hints for all parameter
1734 private static function process_suggestion($xpath, $suggestion, $importer) {
1737 logger("Processing suggestions");
1739 /// @TODO Rewrite this to one statement
1741 $suggest["uid"] = $importer["importer_uid"];
1742 $suggest["cid"] = $importer["id"];
1743 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1744 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1745 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1746 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1747 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1749 // Does our member already have a friend matching this description?
1751 $r = q("SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1752 dbesc($suggest["name"]),
1753 dbesc(normalise_link($suggest["url"])),
1754 intval($suggest["uid"])
1758 * The valid result means the friend we're about to send a friend
1759 * suggestion already has them in their contact, which means no further
1760 * action is required.
1762 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1764 if (dbm::is_result($r)) {
1768 // Do we already have an fcontact record for this person?
1771 $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1772 dbesc($suggest["url"]),
1773 dbesc($suggest["name"]),
1774 dbesc($suggest["request"])
1776 if (dbm::is_result($r)) {
1779 // OK, we do. Do we already have an introduction for this person ?
1780 $r = q("SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1781 intval($suggest["uid"]),
1786 * The valid result means the friend we're about to send a friend
1787 * suggestion already has them in their contact, which means no further
1788 * action is required.
1790 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1792 if (dbm::is_result($r)) {
1797 $r = q("INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1798 dbesc($suggest["name"]),
1799 dbesc($suggest["url"]),
1800 dbesc($suggest["photo"]),
1801 dbesc($suggest["request"])
1804 $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1805 dbesc($suggest["url"]),
1806 dbesc($suggest["name"]),
1807 dbesc($suggest["request"])
1811 * If no record in fcontact is found, below INSERT statement will not
1812 * link an introduction to it.
1814 if (!dbm::is_result($r)) {
1815 // database record did not get created. Quietly give up.
1821 $hash = random_string();
1823 $r = q("INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1824 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1825 intval($suggest["uid"]),
1827 intval($suggest["cid"]),
1828 dbesc($suggest["body"]),
1830 dbesc(datetime_convert()),
1835 "type" => NOTIFY_SUGGEST,
1836 "notify_flags" => $importer["notify-flags"],
1837 "language" => $importer["language"],
1838 "to_name" => $importer["username"],
1839 "to_email" => $importer["email"],
1840 "uid" => $importer["importer_uid"],
1842 "link" => System::baseUrl()."/notifications/intros",
1843 "source_name" => $importer["name"],
1844 "source_link" => $importer["url"],
1845 "source_photo" => $importer["photo"],
1846 "verb" => ACTIVITY_REQ_FRIEND,
1855 * @brief Processes the relocation elements
1857 * @param object $xpath XPath object
1858 * @param object $relocation relocation elements
1859 * @param array $importer Record of the importer user mixed with contact of the content
1860 * @todo Find good type-hints for all parameter
1862 private static function process_relocation($xpath, $relocation, $importer) {
1864 logger("Processing relocations");
1866 /// @TODO Rewrite this to one statement
1867 $relocate = array();
1868 $relocate["uid"] = $importer["importer_uid"];
1869 $relocate["cid"] = $importer["id"];
1870 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1871 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
1872 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1873 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
1874 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1875 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1876 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1877 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1878 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1879 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1880 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1881 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1883 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
1884 $relocate["avatar"] = $relocate["photo"];
1887 if ($relocate["addr"] == "") {
1888 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
1892 $r = q("SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
1893 intval($importer["id"]),
1894 intval($importer["importer_uid"]));
1896 if (!dbm::is_result($r)) {
1897 logger("Query failed to execute, no result returned in " . __FUNCTION__);
1903 // Update the gcontact entry
1904 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
1906 $x = q("UPDATE `gcontact` SET
1915 WHERE `nurl` = '%s';",
1916 dbesc($relocate["name"]),
1917 dbesc($relocate["avatar"]),
1918 dbesc($relocate["url"]),
1919 dbesc(normalise_link($relocate["url"])),
1920 dbesc($relocate["addr"]),
1921 dbesc($relocate["addr"]),
1922 dbesc($relocate["notify"]),
1923 dbesc($relocate["server_url"]),
1924 dbesc(normalise_link($old["url"])));
1926 // Update the contact table. We try to find every entry.
1927 $x = q("UPDATE `contact` SET
1937 `site-pubkey` = '%s'
1938 WHERE (`id` = %d AND `uid` = %d) OR (`nurl` = '%s');",
1939 dbesc($relocate["name"]),
1940 dbesc($relocate["avatar"]),
1941 dbesc($relocate["url"]),
1942 dbesc(normalise_link($relocate["url"])),
1943 dbesc($relocate["addr"]),
1944 dbesc($relocate["request"]),
1945 dbesc($relocate["confirm"]),
1946 dbesc($relocate["notify"]),
1947 dbesc($relocate["poll"]),
1948 dbesc($relocate["sitepubkey"]),
1949 intval($importer["id"]),
1950 intval($importer["importer_uid"]),
1951 dbesc(normalise_link($old["url"])));
1953 update_contact_avatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
1960 /// @todo This is an extreme performance killer
1962 'owner-link' => array($old["url"], $relocate["url"]),
1963 'author-link' => array($old["url"], $relocate["url"]),
1964 //'owner-avatar' => array($old["photo"], $relocate["photo"]),
1965 //'author-avatar' => array($old["photo"], $relocate["photo"]),
1967 foreach ($fields as $n=>$f) {
1968 $r = q("SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
1970 intval($importer["importer_uid"]));
1972 if (dbm::is_result($r)) {
1973 $x = q("UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1976 intval($importer["importer_uid"]));
1985 /// merge with current record, current contents have priority
1986 /// update record, set url-updated
1987 /// update profile photos
1988 /// schedule a scan?
1993 * @brief Updates an item
1995 * @param array $current the current item record
1996 * @param array $item the new item record
1997 * @param array $importer Record of the importer user mixed with contact of the content
1998 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
1999 * @todo set proper type-hints (array?)
2001 private static function update_content($current, $item, $importer, $entrytype) {
2004 if (edited_timestamp_is_newer($current, $item)) {
2006 // do not accept (ignore) an earlier edit than one we currently have.
2007 if (datetime_convert("UTC","UTC",$item["edited"]) < $current["edited"]) {
2011 $fields = array('title' => $item["title"], 'body' => $item["body"],
2012 'tag' => $item["tag"], 'changed' => datetime_convert(),
2013 'edited' => datetime_convert("UTC", "UTC", $item["edited"]));
2015 $condition = array("`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]);
2016 dba::update('item', $fields, $condition);
2018 create_tags_from_itemuri($item["uri"], $importer["importer_uid"]);
2019 update_thread_uri($item["uri"], $importer["importer_uid"]);
2023 if ($entrytype == DFRN_REPLY_RC) {
2024 Worker::add(PRIORITY_HIGH, "notifier","comment-import", $current["id"]);
2028 // update last-child if it changes
2029 if ($item["last-child"] && ($item["last-child"] != $current["last-child"])) {
2030 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2031 dbesc(datetime_convert()),
2032 dbesc($item["parent-uri"]),
2033 intval($importer["importer_uid"])
2035 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` IN (0, %d)",
2036 intval($item["last-child"]),
2037 dbesc(datetime_convert()),
2038 dbesc($item["uri"]),
2039 intval($importer["importer_uid"])
2046 * @brief Detects the entry type of the item
2048 * @param array $importer Record of the importer user mixed with contact of the content
2049 * @param array $item the new item record
2051 * @return int Is it a toplevel entry, a comment or a relayed comment?
2052 * @todo set proper type-hints (array?)
2054 private static function get_entry_type($importer, $item) {
2055 if ($item["parent-uri"] != $item["uri"]) {
2058 if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
2061 logger("possible community action");
2063 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2066 // was the top-level post for this action written by somebody on this site?
2067 // Specifically, the recipient?
2069 $is_a_remote_action = false;
2071 $r = q("SELECT `item`.`parent-uri` FROM `item`
2072 WHERE `item`.`uri` = '%s'
2074 dbesc($item["parent-uri"])
2076 if (dbm::is_result($r)) {
2077 $r = q("SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2078 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2079 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2080 AND `item`.`uid` = %d
2083 dbesc($r[0]["parent-uri"]),
2084 dbesc($r[0]["parent-uri"]),
2085 dbesc($r[0]["parent-uri"]),
2086 intval($importer["importer_uid"])
2088 if (dbm::is_result($r)) {
2089 $is_a_remote_action = true;
2094 * Does this have the characteristics of a community or private group action?
2095 * If it's an action to a wall post on a community/prvgroup page it's a
2096 * valid community action. Also forum_mode makes it valid for sure.
2097 * If neither, it's not.
2100 /// @TODO Maybe merge these if() blocks into one?
2101 if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2102 $is_a_remote_action = false;
2103 logger("not a community action");
2106 if ($is_a_remote_action) {
2107 return DFRN_REPLY_RC;
2112 return DFRN_TOP_LEVEL;
2118 * @brief Send a "poke"
2120 * @param array $item the new item record
2121 * @param array $importer Record of the importer user mixed with contact of the content
2122 * @param int $posted_id The record number of item record that was just posted
2123 * @todo set proper type-hints (array?)
2125 private static function do_poke($item, $importer, $posted_id) {
2126 $verb = urldecode(substr($item["verb"],strpos($item["verb"], "#")+1));
2130 $xo = parse_xml_string($item["object"],false);
2132 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2134 // somebody was poked/prodded. Was it me?
2135 foreach ($xo->link as $l) {
2136 $atts = $l->attributes();
2137 switch ($atts["rel"]) {
2139 $Blink = $atts["href"];
2146 if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2148 // send a notification
2150 "type" => NOTIFY_POKE,
2151 "notify_flags" => $importer["notify-flags"],
2152 "language" => $importer["language"],
2153 "to_name" => $importer["username"],
2154 "to_email" => $importer["email"],
2155 "uid" => $importer["importer_uid"],
2157 "link" => System::baseUrl()."/display/".urlencode(get_item_guid($posted_id)),
2158 "source_name" => stripslashes($item["author-name"]),
2159 "source_link" => $item["author-link"],
2160 "source_photo" => ((link_compare($item["author-link"],$importer["url"]))
2161 ? $importer["thumb"] : $item["author-avatar"]),
2162 "verb" => $item["verb"],
2163 "otype" => "person",
2164 "activity" => $verb,
2165 "parent" => $item["parent"]
2172 * @brief Processes several actions, depending on the verb
2174 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2175 * @param array $importer Record of the importer user mixed with contact of the content
2176 * @param array $item the new item record
2177 * @param bool $is_like Is the verb a "like"?
2179 * @return bool Should the processing of the entries be continued?
2180 * @todo set proper type-hints (array?)
2182 private static function process_verbs($entrytype, $importer, &$item, &$is_like) {
2184 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2186 if (($entrytype == DFRN_TOP_LEVEL)) {
2187 // The filling of the the "contact" variable is done for legcy reasons
2188 // The functions below are partly used by ostatus.php as well - where we have this variable
2189 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2191 $nickname = $contact["nick"];
2193 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2194 // This function once was responsible for DFRN and OStatus.
2195 if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2196 logger("New follower");
2197 new_follower($importer, $contact, $item, $nickname);
2200 if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2201 logger("Lost follower");
2202 lose_follower($importer, $contact, $item);
2205 if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2206 logger("New friend request");
2207 new_follower($importer, $contact, $item, $nickname, true);
2210 if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2211 logger("Lost sharer");
2212 lose_sharer($importer, $contact, $item);
2216 if (($item["verb"] == ACTIVITY_LIKE)
2217 || ($item["verb"] == ACTIVITY_DISLIKE)
2218 || ($item["verb"] == ACTIVITY_ATTEND)
2219 || ($item["verb"] == ACTIVITY_ATTENDNO)
2220 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)) {
2222 $item["type"] = "activity";
2223 $item["gravity"] = GRAVITY_LIKE;
2224 // only one like or dislike per person
2225 // splitted into two queries for performance issues
2226 $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",
2227 intval($item["uid"]),
2228 dbesc($item["author-link"]),
2229 dbesc($item["verb"]),
2230 dbesc($item["parent-uri"])
2232 if (dbm::is_result($r)) {
2236 $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",
2237 intval($item["uid"]),
2238 dbesc($item["author-link"]),
2239 dbesc($item["verb"]),
2240 dbesc($item["parent-uri"])
2242 if (dbm::is_result($r)) {
2249 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2251 $xo = parse_xml_string($item["object"],false);
2252 $xt = parse_xml_string($item["target"],false);
2254 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2255 $r = q("SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2257 intval($importer["importer_uid"])
2260 if (!dbm::is_result($r)) {
2261 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2265 // extract tag, if not duplicate, add to parent item
2267 if (!(stristr($r[0]["tag"],trim($xo->content)))) {
2268 q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2269 dbesc($r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2272 create_tags_from_item($r[0]["id"]);
2282 * @brief Processes the link elements
2284 * @param object $links link elements
2285 * @param array $item the item record
2286 * @todo set proper type-hints
2288 private static function parse_links($links, &$item) {
2294 foreach ($links AS $link) {
2295 foreach ($link->attributes AS $attributes) {
2296 /// @TODO Rewrite these repeated (same) if () statements to a switch()
2297 if ($attributes->name == "href") {
2298 $href = $attributes->textContent;
2300 if ($attributes->name == "rel") {
2301 $rel = $attributes->textContent;
2303 if ($attributes->name == "type") {
2304 $type = $attributes->textContent;
2306 if ($attributes->name == "length") {
2307 $length = $attributes->textContent;
2309 if ($attributes->name == "title") {
2310 $title = $attributes->textContent;
2313 if (($rel != "") && ($href != "")) {
2316 $item["plink"] = $href;
2320 if (strlen($item["attach"])) {
2321 $item["attach"] .= ",";
2324 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2332 * @brief Processes the entry elements which contain the items and comments
2334 * @param array $header Array of the header elements that always stay the same
2335 * @param object $xpath XPath object
2336 * @param object $entry entry elements
2337 * @param array $importer Record of the importer user mixed with contact of the content
2338 * @todo Add type-hints
2340 private static function process_entry($header, $xpath, $entry, $importer, $xml) {
2342 logger("Processing entries");
2346 $item["protocol"] = PROTOCOL_DFRN;
2348 $item["source"] = $xml;
2351 $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
2353 $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
2355 $current = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2356 dbesc($item["uri"]),
2357 intval($importer["importer_uid"])
2360 // Is there an existing item?
2361 if (dbm::is_result($current) && edited_timestamp_is_newer($current[0], $item) &&
2362 (datetime_convert("UTC","UTC",$item["edited"]) < $current[0]["edited"])) {
2363 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2368 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2370 $item["owner-name"] = $owner["name"];
2371 $item["owner-link"] = $owner["link"];
2372 $item["owner-avatar"] = $owner["avatar"];
2375 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2377 $item["author-name"] = $author["name"];
2378 $item["author-link"] = $author["link"];
2379 $item["author-avatar"] = $author["avatar"];
2381 $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
2383 $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2385 $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
2386 $item["body"] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$item["body"]);
2387 // make sure nobody is trying to sneak some html tags by us
2388 $item["body"] = notags(base64url_decode($item["body"]));
2390 $item["body"] = limit_body_size($item["body"]);
2392 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2393 if ((strpos($item['body'],'<') !== false) && (strpos($item['body'],'>') !== false)) {
2395 $item['body'] = reltoabs($item['body'],$base_url);
2397 $item['body'] = html2bb_video($item['body']);
2399 $item['body'] = oembed_html2bbcode($item['body']);
2401 $config = HTMLPurifier_Config::createDefault();
2402 $config->set('Cache.DefinitionImpl', null);
2404 // we shouldn't need a whitelist, because the bbcode converter
2405 // will strip out any unsupported tags.
2407 $purifier = new HTMLPurifier($config);
2408 $item['body'] = $purifier->purify($item['body']);
2410 $item['body'] = @html2bbcode($item['body']);
2413 /// @todo We should check for a repeated post and if we know the repeated author.
2415 // We don't need the content element since "dfrn:env" is always present
2416 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2418 $item["last-child"] = $xpath->query("dfrn:comment-allow/text()", $entry)->item(0)->nodeValue;
2419 $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
2421 $georsspoint = $xpath->query("georss:point", $entry);
2423 $item["coord"] = $georsspoint->item(0)->nodeValue;
2426 $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
2428 $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
2430 if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true") {
2431 $item["bookmark"] = true;
2434 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2435 if ($notice_info && ($notice_info->length > 0)) {
2436 foreach ($notice_info->item(0)->attributes AS $attributes) {
2437 if ($attributes->name == "source") {
2438 $item["app"] = strip_tags($attributes->textContent);
2443 $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
2445 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "item_store"
2446 $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
2447 if ($dsprsig != "") {
2448 $item["dsprsig"] = $dsprsig;
2451 $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
2453 if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "") {
2454 $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
2457 $object = $xpath->query("activity:object", $entry)->item(0);
2458 $item["object"] = self::transform_activity($xpath, $object, "object");
2460 if (trim($item["object"]) != "") {
2461 $r = parse_xml_string($item["object"], false);
2462 if (isset($r->type)) {
2463 $item["object-type"] = $r->type;
2467 $target = $xpath->query("activity:target", $entry)->item(0);
2468 $item["target"] = self::transform_activity($xpath, $target, "target");
2470 $categories = $xpath->query("atom:category", $entry);
2472 foreach ($categories AS $category) {
2475 foreach ($category->attributes AS $attributes) {
2476 if ($attributes->name == "term") {
2477 $term = $attributes->textContent;
2480 if ($attributes->name == "scheme") {
2481 $scheme = $attributes->textContent;
2485 if (($term != "") && ($scheme != "")) {
2486 $parts = explode(":", $scheme);
2487 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2488 $termhash = array_shift($parts);
2489 $termurl = implode(":", $parts);
2491 if (strlen($item["tag"])) {
2492 $item["tag"] .= ",";
2495 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2503 $links = $xpath->query("atom:link", $entry);
2505 self::parse_links($links, $item);
2508 $item['conversation-uri'] = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
2510 $conv = $xpath->query('ostatus:conversation', $entry);
2511 if (is_object($conv->item(0))) {
2512 foreach ($conv->item(0)->attributes AS $attributes) {
2513 if ($attributes->name == "ref") {
2514 $item['conversation-uri'] = $attributes->textContent;
2516 if ($attributes->name == "href") {
2517 $item['conversation-href'] = $attributes->textContent;
2522 // Is it a reply or a top level posting?
2523 $item["parent-uri"] = $item["uri"];
2525 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2526 if (is_object($inreplyto->item(0))) {
2527 foreach ($inreplyto->item(0)->attributes AS $attributes) {
2528 if ($attributes->name == "ref") {
2529 $item["parent-uri"] = $attributes->textContent;
2534 // Get the type of the item (Top level post, reply or remote reply)
2535 $entrytype = self::get_entry_type($importer, $item);
2537 // Now assign the rest of the values that depend on the type of the message
2538 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2539 if (!isset($item["object-type"])) {
2540 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2543 if ($item["contact-id"] != $owner["contact-id"]) {
2544 $item["contact-id"] = $owner["contact-id"];
2547 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2548 $item["network"] = $owner["network"];
2551 if ($item["contact-id"] != $author["contact-id"]) {
2552 $item["contact-id"] = $author["contact-id"];
2555 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2556 $item["network"] = $author["network"];
2559 /// @TODO maybe remove this old-lost code then?
2560 // This code was taken from the old DFRN code
2561 // When activated, forums don't work.
2562 // And: Why should we disallow commenting by followers?
2563 // the behaviour is now similar to the Diaspora part.
2564 //if ($importer["rel"] == CONTACT_IS_FOLLOWER) {
2565 // logger("Contact ".$importer["id"]." is only follower. Quitting", LOGGER_DEBUG);
2570 if ($entrytype == DFRN_REPLY_RC) {
2571 $item["type"] = "remote-comment";
2573 } elseif ($entrytype == DFRN_TOP_LEVEL) {
2574 if (!isset($item["object-type"])) {
2575 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2579 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2580 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2581 $ev = bbtoevent($item["body"]);
2582 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2583 logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2584 /// @TODO Mixure of "/' ahead ...
2585 $ev["cid"] = $importer["id"];
2586 $ev["uid"] = $importer["uid"];
2587 $ev["uri"] = $item["uri"];
2588 $ev["edited"] = $item["edited"];
2589 $ev['private'] = $item['private'];
2590 $ev["guid"] = $item["guid"];
2592 $r = q("SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2593 dbesc($item["uri"]),
2594 intval($importer["uid"])
2596 if (dbm::is_result($r)) {
2597 $ev["id"] = $r[0]["id"];
2600 $event_id = event_store($ev);
2601 logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2607 if (!self::process_verbs($entrytype, $importer, $item, $is_like)) {
2608 logger("Exiting because 'process_verbs' told us so", LOGGER_DEBUG);
2612 // Update content if 'updated' changes
2613 if (dbm::is_result($current)) {
2614 if (self::update_content($r[0], $item, $importer, $entrytype)) {
2615 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2617 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2622 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2623 $posted_id = item_store($item);
2628 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2630 $item["id"] = $posted_id;
2632 $r = q("SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2634 intval($importer["importer_uid"])
2636 if (dbm::is_result($r)) {
2637 $parent = $r[0]["parent"];
2638 $parent_uri = $r[0]["parent-uri"];
2642 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2643 dbesc(datetime_convert()),
2644 intval($importer["importer_uid"]),
2645 intval($r[0]["parent"])
2648 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d",
2649 dbesc(datetime_convert()),
2650 intval($importer["importer_uid"]),
2655 if ($posted_id && $parent && ($entrytype == DFRN_REPLY_RC)) {
2656 logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
2657 Worker::add(PRIORITY_HIGH, "notifier", "comment-import", $posted_id);
2662 } else { // $entrytype == DFRN_TOP_LEVEL
2663 if (!link_compare($item["owner-link"],$importer["url"])) {
2665 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2666 * but otherwise there's a possible data mixup on the sender's system.
2667 * the tgroup delivery code called from item_store will correct it if it's a forum,
2668 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2670 logger('Correcting item owner.', LOGGER_DEBUG);
2671 $item["owner-name"] = $importer["senderName"];
2672 $item["owner-link"] = $importer["url"];
2673 $item["owner-avatar"] = $importer["thumb"];
2676 if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!tgroup_check($importer["importer_uid"], $item))) {
2677 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2681 // This is my contact on another system, but it's really me.
2682 // Turn this into a wall post.
2683 $notify = item_is_remote_self($importer, $item);
2685 $posted_id = item_store($item, false, $notify);
2687 logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2689 if (stristr($item["verb"],ACTIVITY_POKE))
2690 self::do_poke($item, $importer, $posted_id);
2695 * @brief Deletes items
2697 * @param object $xpath XPath object
2698 * @param object $deletion deletion elements
2699 * @param array $importer Record of the importer user mixed with contact of the content
2700 * @todo set proper type-hints
2702 private static function process_deletion($xpath, $deletion, $importer) {
2704 logger("Processing deletions");
2706 foreach ($deletion->attributes AS $attributes) {
2707 if ($attributes->name == "ref") {
2708 $uri = $attributes->textContent;
2710 if ($attributes->name == "when") {
2711 $when = $attributes->textContent;
2715 $when = datetime_convert("UTC", "UTC", $when, "Y-m-d H:i:s");
2717 $when = datetime_convert("UTC", "UTC", "now", "Y-m-d H:i:s");
2720 if (!$uri || !$importer["id"]) {
2724 /// @todo Only select the used fields
2725 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` INNER JOIN `contact` on `item`.`contact-id` = `contact`.`id`
2726 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2728 intval($importer["uid"]),
2729 intval($importer["id"])
2731 if (!dbm::is_result($r)) {
2732 logger("Item with uri " . $uri . " from contact " . $importer["id"] . " for user " . $importer["uid"] . " wasn't found.", LOGGER_DEBUG);
2738 $entrytype = self::get_entry_type($importer, $item);
2740 if (!$item["deleted"]) {
2741 logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG);
2746 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2747 logger("Deleting event ".$item["event-id"], LOGGER_DEBUG);
2748 event_delete($item["event-id"]);
2751 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2753 $xo = parse_xml_string($item["object"],false);
2754 $xt = parse_xml_string($item["target"],false);
2756 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2757 $i = q("SELECT `id`, `contact-id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2759 intval($importer["importer_uid"])
2761 if (dbm::is_result($i)) {
2763 // For tags, the owner cannot remove the tag on the author's copy of the post.
2765 $owner_remove = (($item["contact-id"] == $i[0]["contact-id"]) ? true: false);
2766 $author_remove = (($item["origin"] && $item["self"]) ? true : false);
2767 $author_copy = (($item["origin"]) ? true : false);
2769 if ($owner_remove && $author_copy) {
2772 if ($author_remove || $owner_remove) {
2773 $tags = explode(',',$i[0]["tag"]);
2776 foreach ($tags as $tag) {
2777 if (trim($tag) !== trim($xo->body)) {
2778 $newtags[] = trim($tag);
2782 q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2783 dbesc(implode(',', $newtags)),
2786 create_tags_from_item($i[0]["id"]);
2792 if ($entrytype == DFRN_TOP_LEVEL) {
2793 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2794 `body` = '', `title` = ''
2795 WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2797 dbesc(datetime_convert()),
2799 intval($importer["uid"])
2801 create_tags_from_itemuri($uri, $importer["uid"]);
2802 create_files_from_itemuri($uri, $importer["uid"]);
2803 update_thread_uri($uri, $importer["uid"]);
2805 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2806 `body` = '', `title` = ''
2807 WHERE `uri` = '%s' AND `uid` IN (0, %d)",
2809 dbesc(datetime_convert()),
2811 intval($importer["uid"])
2813 create_tags_from_itemuri($uri, $importer["uid"]);
2814 create_files_from_itemuri($uri, $importer["uid"]);
2815 update_thread_uri($uri, $importer["importer_uid"]);
2816 if ($item["last-child"]) {
2817 // ensure that last-child is set in case the comment that had it just got wiped.
2818 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2819 dbesc(datetime_convert()),
2820 dbesc($item["parent-uri"]),
2821 intval($item["uid"])
2823 // who is the last child now?
2824 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
2825 ORDER BY `created` DESC LIMIT 1",
2826 dbesc($item["parent-uri"]),
2827 intval($importer["uid"])
2829 if (dbm::is_result($r)) {
2830 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
2835 // if this is a relayed delete, propagate it to other recipients
2837 if ($entrytype == DFRN_REPLY_RC) {
2838 logger("Notifying followers about deletion of post " . $item["id"], LOGGER_DEBUG);
2839 Worker::add(PRIORITY_HIGH, "notifier","drop", $item["id"]);
2846 * @brief Imports a DFRN message
2848 * @param text $xml The DFRN message
2849 * @param array $importer Record of the importer user mixed with contact of the content
2850 * @param bool $sort_by_date Is used when feeds are polled
2851 * @return integer Import status
2852 * @todo set proper type-hints
2854 public static function import($xml, $importer, $sort_by_date = false) {
2860 $doc = new DOMDocument();
2861 @$doc->loadXML($xml);
2863 $xpath = new DomXPath($doc);
2864 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2865 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2866 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2867 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2868 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2869 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2870 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2871 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2872 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2873 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2876 $header["uid"] = $importer["uid"];
2877 $header["network"] = NETWORK_DFRN;
2878 $header["type"] = "remote";
2879 $header["wall"] = 0;
2880 $header["origin"] = 0;
2881 $header["contact-id"] = $importer["id"];
2883 // Update the contact table if the data has changed
2885 // The "atom:author" is only present in feeds
2886 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2887 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2890 // Only the "dfrn:owner" in the head section contains all data
2891 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2892 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2895 logger("Import DFRN message for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2897 // The account type is new since 3.5.1
2898 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2899 $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()", $context)->item(0)->nodeValue);
2901 if ($accounttype != $importer["contact-type"]) {
2902 dba::update('contact', array('contact-type' => $accounttype), array('id' => $importer["id"]));
2906 // is it a public forum? Private forums aren't supported with this method
2907 // This is deprecated since 3.5.1
2908 $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()", $context)->item(0)->nodeValue);
2910 if ($forum != $importer["forum"]) {
2911 $condition = array('`forum` != ? AND `id` = ?', $forum, $importer["id"]);
2912 dba::update('contact', array('forum' => $forum), $condition);
2915 // We are processing relocations even if we are ignoring a contact
2916 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2917 foreach ($relocations AS $relocation) {
2918 self::process_relocation($xpath, $relocation, $importer);
2921 if ($importer["readonly"]) {
2922 // We aren't receiving stuff from this person. But we will quietly ignore them
2923 // rather than a blatant "go away" message.
2924 logger('ignoring contact '.$importer["id"]);
2928 $mails = $xpath->query("/atom:feed/dfrn:mail");
2929 foreach ($mails AS $mail) {
2930 self::process_mail($xpath, $mail, $importer);
2933 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2934 foreach ($suggestions AS $suggestion) {
2935 self::process_suggestion($xpath, $suggestion, $importer);
2938 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2939 foreach ($deletions AS $deletion) {
2940 self::process_deletion($xpath, $deletion, $importer);
2943 if (!$sort_by_date) {
2944 $entries = $xpath->query("/atom:feed/atom:entry");
2945 foreach ($entries AS $entry) {
2946 self::process_entry($header, $xpath, $entry, $importer, $xml);
2949 $newentries = array();
2950 $entries = $xpath->query("/atom:feed/atom:entry");
2951 foreach ($entries AS $entry) {
2952 $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2953 $newentries[strtotime($created)] = $entry;
2956 // Now sort after the publishing date
2959 foreach ($newentries AS $entry) {
2960 self::process_entry($header, $xpath, $entry, $importer, $xml);
2963 logger("Import done for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);