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
12 require_once("include/Contact.php");
13 require_once("include/ostatus.php");
14 require_once("include/enotify.php");
15 require_once("include/threads.php");
16 require_once("include/socgraph.php");
17 require_once("include/items.php");
18 require_once("include/tags.php");
19 require_once("include/files.php");
20 require_once("include/event.php");
21 require_once("include/text.php");
22 require_once("include/oembed.php");
23 require_once("include/html2bbcode.php");
24 require_once("include/bbcode.php");
25 require_once("include/xml.php");
28 * @brief This class contain functions to create and send DFRN XML files
33 const DFRN_TOP_LEVEL = 0; // Top level posting
34 const DFRN_REPLY = 1; // Regular reply that is stored locally
35 const DFRN_REPLY_RC = 2; // Reply that will be relayed
38 * @brief Generates the atom entries for delivery.php
40 * This function is used whenever content is transmitted via DFRN.
42 * @param array $items Item elements
43 * @param array $owner Owner record
45 * @return string DFRN entries
46 * @todo Add type-hints
48 public static function entries($items,$owner) {
50 $doc = new DOMDocument('1.0', 'utf-8');
51 $doc->formatOutput = true;
53 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
55 if (! count($items)) {
56 return trim($doc->saveXML());
59 foreach ($items as $item) {
60 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
61 $root->appendChild($entry);
64 return(trim($doc->saveXML()));
68 * @brief Generate an atom feed for the given user
70 * This function is called when another server is pulling data from the user feed.
72 * @param string $dfrn_id DFRN ID from the requesting party
73 * @param string $owner_nick Owner nick name
74 * @param string $last_update Date of the last update
75 * @param int $direction Can be -1, 0 or 1.
76 * @param boolean $onlyheader Output only the header without content? (Default is "no")
78 * @return string DFRN feed entries
80 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false) {
84 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
85 $public_feed = (($dfrn_id) ? false : true);
86 $starred = false; // not yet implemented, possible security issues
89 if ($public_feed && $a->argc > 2) {
90 for ($x = 2; $x < $a->argc; $x++) {
91 if ($a->argv[$x] == 'converse') {
94 if ($a->argv[$x] == 'starred') {
97 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
98 $category = $a->argv[$x+1];
105 // default permissions - anonymous user
107 $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = '' ";
109 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
110 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
111 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
115 if (! dbm::is_result($r)) {
120 $owner_id = $owner['uid'];
121 $owner_nick = $owner['nickname'];
123 $sql_post_table = "";
125 if (! $public_feed) {
130 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
134 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
135 $my_id = '1:' . $dfrn_id;
138 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
139 $my_id = '0:' . $dfrn_id;
146 $r = q("SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
150 if (! dbm::is_result($r)) {
155 require_once('include/security.php');
156 $groups = init_groups_visitor($contact['id']);
158 if (count($groups)) {
159 for ($x = 0; $x < count($groups); $x ++)
160 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
161 $gs = implode('|', $groups);
163 $gs = '<<>>' ; // Impossible to match
166 $sql_extra = sprintf("
167 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
168 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
169 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
170 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
172 intval($contact['id']),
173 intval($contact['id']),
185 if (! strlen($last_update)) {
186 $last_update = 'now -30 days';
189 if (isset($category)) {
190 $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` ",
191 dbesc(protect_sprintf($category)), intval(TERM_OBJ_POST), intval(TERM_CATEGORY), intval($owner_id));
192 //$sql_extra .= file_tag_file_query('item',$category,'category');
197 $sql_extra .= " AND `contact`.`self` = 1 ";
201 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
203 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
204 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
205 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
206 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
207 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
208 FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
209 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
210 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
211 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
212 WHERE `item`.`uid` = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
213 AND `item`.`wall` AND `item`.`changed` > '%s'
215 ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
222 * Will check further below if this actually returned results.
223 * We will provide an empty feed if that is the case.
228 $doc = new DOMDocument('1.0', 'utf-8');
229 $doc->formatOutput = true;
231 $alternatelink = $owner['url'];
233 if (isset($category)) {
234 $alternatelink .= "/category/".$category;
238 $author = "dfrn:owner";
243 $root = self::add_header($doc, $owner, $author, $alternatelink, true);
245 /// @TODO This hook can't work anymore
246 // call_hooks('atom_feed', $atom);
248 if (!dbm::is_result($items) || $onlyheader) {
249 $atom = trim($doc->saveXML());
251 call_hooks('atom_feed_end', $atom);
256 foreach ($items as $item) {
258 // prevent private email from leaking.
259 if ($item['network'] == NETWORK_MAIL) {
263 // public feeds get html, our own nodes use bbcode
267 // catch any email that's in a public conversation and make sure it doesn't leak
268 if ($item['private']) {
275 $entry = self::entry($doc, $type, $item, $owner, true);
276 $root->appendChild($entry);
280 $atom = trim($doc->saveXML());
282 call_hooks('atom_feed_end', $atom);
288 * @brief Generate an atom entry for a given item id
290 * @param int $item_id The item id
292 * @return string DFRN feed entry
294 public static function itemFeed($item_id) {
295 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
296 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
297 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
298 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
299 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
301 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
302 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
303 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
304 WHERE `item`.`id` = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
305 AND `item`.`wall` AND NOT `item`.`private`",
309 if (!dbm::is_result($r)) {
315 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
316 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
317 WHERE `contact`.`self` AND `user`.`uid` = %d LIMIT 1",
321 if (!dbm::is_result($r)) {
327 $doc = new DOMDocument('1.0', 'utf-8');
328 $doc->formatOutput = true;
330 $alternatelink = $owner['url'];
332 $root = self::add_header($doc, $owner, 'dfrn:owner', $alternatelink, true);
336 $entry = self::entry($doc, $type, $item, $owner, true);
337 $root->appendChild($entry);
339 $atom = trim($doc->saveXML());
344 * @brief Create XML text for DFRN mails
346 * @param array $item message elements
347 * @param array $owner Owner record
349 * @return string DFRN mail
350 * @todo Add type-hints
352 public static function mail($item, $owner) {
353 $doc = new DOMDocument('1.0', 'utf-8');
354 $doc->formatOutput = true;
356 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
358 $mail = $doc->createElement("dfrn:mail");
359 $sender = $doc->createElement("dfrn:sender");
361 xml::add_element($doc, $sender, "dfrn:name", $owner['name']);
362 xml::add_element($doc, $sender, "dfrn:uri", $owner['url']);
363 xml::add_element($doc, $sender, "dfrn:avatar", $owner['thumb']);
365 $mail->appendChild($sender);
367 xml::add_element($doc, $mail, "dfrn:id", $item['uri']);
368 xml::add_element($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
369 xml::add_element($doc, $mail, "dfrn:sentdate", datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME));
370 xml::add_element($doc, $mail, "dfrn:subject", $item['title']);
371 xml::add_element($doc, $mail, "dfrn:content", $item['body']);
373 $root->appendChild($mail);
375 return(trim($doc->saveXML()));
379 * @brief Create XML text for DFRN friend suggestions
381 * @param array $item suggestion elements
382 * @param array $owner Owner record
384 * @return string DFRN suggestions
385 * @todo Add type-hints
387 public static function fsuggest($item, $owner) {
388 $doc = new DOMDocument('1.0', 'utf-8');
389 $doc->formatOutput = true;
391 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
393 $suggest = $doc->createElement("dfrn:suggest");
395 xml::add_element($doc, $suggest, "dfrn:url", $item['url']);
396 xml::add_element($doc, $suggest, "dfrn:name", $item['name']);
397 xml::add_element($doc, $suggest, "dfrn:photo", $item['photo']);
398 xml::add_element($doc, $suggest, "dfrn:request", $item['request']);
399 xml::add_element($doc, $suggest, "dfrn:note", $item['note']);
401 $root->appendChild($suggest);
403 return(trim($doc->saveXML()));
407 * @brief Create XML text for DFRN relocations
409 * @param array $owner Owner record
410 * @param int $uid User ID
412 * @return string DFRN relocations
413 * @todo Add type-hints
415 public static function relocate($owner, $uid) {
417 /* get site pubkey. this could be a new installation with no site keys*/
418 $pubkey = get_config('system','site_pubkey');
420 $res = new_keypair(1024);
421 set_config('system','site_prvkey', $res['prvkey']);
422 set_config('system','site_pubkey', $res['pubkey']);
425 $rp = q("SELECT `resource-id` , `scale`, type FROM `photo`
426 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;", $uid);
428 $ext = Photo::supportedTypes();
430 foreach ($rp as $p) {
431 $photos[$p['scale']] = App::get_baseurl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
436 $doc = new DOMDocument('1.0', 'utf-8');
437 $doc->formatOutput = true;
439 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
441 $relocate = $doc->createElement("dfrn:relocate");
443 xml::add_element($doc, $relocate, "dfrn:url", $owner['url']);
444 xml::add_element($doc, $relocate, "dfrn:name", $owner['name']);
445 xml::add_element($doc, $relocate, "dfrn:addr", $owner['addr']);
446 xml::add_element($doc, $relocate, "dfrn:avatar", $owner['avatar']);
447 xml::add_element($doc, $relocate, "dfrn:photo", $photos[4]);
448 xml::add_element($doc, $relocate, "dfrn:thumb", $photos[5]);
449 xml::add_element($doc, $relocate, "dfrn:micro", $photos[6]);
450 xml::add_element($doc, $relocate, "dfrn:request", $owner['request']);
451 xml::add_element($doc, $relocate, "dfrn:confirm", $owner['confirm']);
452 xml::add_element($doc, $relocate, "dfrn:notify", $owner['notify']);
453 xml::add_element($doc, $relocate, "dfrn:poll", $owner['poll']);
454 xml::add_element($doc, $relocate, "dfrn:sitepubkey", get_config('system','site_pubkey'));
456 $root->appendChild($relocate);
458 return(trim($doc->saveXML()));
462 * @brief Adds the header elements for the DFRN protocol
464 * @param object $doc XML document
465 * @param array $owner Owner record
466 * @param string $authorelement Element name for the author
467 * @param string $alternatelink link to profile or category
468 * @param bool $public Is it a header for public posts?
470 * @return object XML root object
471 * @todo Add type-hints
473 private static function add_header($doc, $owner, $authorelement, $alternatelink = "", $public = false) {
475 if ($alternatelink == "") {
476 $alternatelink = $owner['url'];
479 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
480 $doc->appendChild($root);
482 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
483 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
484 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
485 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
486 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
487 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
488 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
489 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
490 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
492 xml::add_element($doc, $root, "id", App::get_baseurl()."/profile/".$owner["nick"]);
493 xml::add_element($doc, $root, "title", $owner["name"]);
495 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
496 xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
498 $attributes = array("rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/");
499 xml::add_element($doc, $root, "link", "", $attributes);
501 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $alternatelink);
502 xml::add_element($doc, $root, "link", "", $attributes);
506 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
507 ostatus::hublinks($doc, $root, $owner["nick"]);
509 $attributes = array("rel" => "salmon", "href" => App::get_baseurl()."/salmon/".$owner["nick"]);
510 xml::add_element($doc, $root, "link", "", $attributes);
512 $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => App::get_baseurl()."/salmon/".$owner["nick"]);
513 xml::add_element($doc, $root, "link", "", $attributes);
515 $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => App::get_baseurl()."/salmon/".$owner["nick"]);
516 xml::add_element($doc, $root, "link", "", $attributes);
519 // For backward compatibility we keep this element
520 if ($owner['page-flags'] == PAGE_COMMUNITY) {
521 xml::add_element($doc, $root, "dfrn:community", 1);
524 // The former element is replaced by this one
525 xml::add_element($doc, $root, "dfrn:account_type", $owner["account-type"]);
527 /// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
529 xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
531 $author = self::add_author($doc, $owner, $authorelement, $public);
532 $root->appendChild($author);
538 * @brief Adds the author element in the header for the DFRN protocol
540 * @param object $doc XML document
541 * @param array $owner Owner record
542 * @param string $authorelement Element name for the author
544 * @return object XML author object
545 * @todo Add type-hints
547 private static function add_author($doc, $owner, $authorelement, $public) {
549 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
550 $r = q("SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
551 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
552 intval($owner['uid']));
553 if (dbm::is_result($r)) {
559 $author = $doc->createElement($authorelement);
561 $namdate = datetime_convert('UTC', 'UTC', $owner['name-date'].'+00:00', ATOM_TIME);
562 $uridate = datetime_convert('UTC', 'UTC', $owner['uri-date'].'+00:00', ATOM_TIME);
563 $picdate = datetime_convert('UTC', 'UTC', $owner['avatar-date'].'+00:00', ATOM_TIME);
565 $attributes = array();
567 if (!$public || !$hidewall) {
568 $attributes = array("dfrn:updated" => $namdate);
571 xml::add_element($doc, $author, "name", $owner["name"], $attributes);
572 xml::add_element($doc, $author, "uri", App::get_baseurl().'/profile/'.$owner["nickname"], $attributes);
573 xml::add_element($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
575 $attributes = array("rel" => "photo", "type" => "image/jpeg",
576 "media:width" => 175, "media:height" => 175, "href" => $owner['photo']);
578 if (!$public || !$hidewall) {
579 $attributes["dfrn:updated"] = $picdate;
582 xml::add_element($doc, $author, "link", "", $attributes);
584 $attributes["rel"] = "avatar";
585 xml::add_element($doc, $author, "link", "", $attributes);
588 xml::add_element($doc, $author, "dfrn:hide", "true");
591 // The following fields will only be generated if the data isn't meant for a public feed
596 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
599 xml::add_element($doc, $author, "dfrn:birthday", $birthday);
601 // Only show contact details when we are allowed to
602 $r = q("SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
603 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
604 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
606 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
607 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
608 intval($owner['uid']));
609 if (dbm::is_result($r)) {
612 xml::add_element($doc, $author, "poco:displayName", $profile["name"]);
613 xml::add_element($doc, $author, "poco:updated", $namdate);
615 if (trim($profile["dob"]) > '0001-01-01') {
616 xml::add_element($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
619 xml::add_element($doc, $author, "poco:note", $profile["about"]);
620 xml::add_element($doc, $author, "poco:preferredUsername", $profile["nickname"]);
622 $savetz = date_default_timezone_get();
623 date_default_timezone_set($profile["timezone"]);
624 xml::add_element($doc, $author, "poco:utcOffset", date("P"));
625 date_default_timezone_set($savetz);
627 if (trim($profile["homepage"]) != "") {
628 $urls = $doc->createElement("poco:urls");
629 xml::add_element($doc, $urls, "poco:type", "homepage");
630 xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
631 xml::add_element($doc, $urls, "poco:primary", "true");
632 $author->appendChild($urls);
635 if (trim($profile["pub_keywords"]) != "") {
636 $keywords = explode(",", $profile["pub_keywords"]);
638 foreach ($keywords AS $keyword) {
639 xml::add_element($doc, $author, "poco:tags", trim($keyword));
644 if (trim($profile["xmpp"]) != "") {
645 $ims = $doc->createElement("poco:ims");
646 xml::add_element($doc, $ims, "poco:type", "xmpp");
647 xml::add_element($doc, $ims, "poco:value", $profile["xmpp"]);
648 xml::add_element($doc, $ims, "poco:primary", "true");
649 $author->appendChild($ims);
652 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
653 $element = $doc->createElement("poco:address");
655 xml::add_element($doc, $element, "poco:formatted", formatted_location($profile));
657 if (trim($profile["locality"]) != "") {
658 xml::add_element($doc, $element, "poco:locality", $profile["locality"]);
661 if (trim($profile["region"]) != "") {
662 xml::add_element($doc, $element, "poco:region", $profile["region"]);
665 if (trim($profile["country-name"]) != "") {
666 xml::add_element($doc, $element, "poco:country", $profile["country-name"]);
669 $author->appendChild($element);
677 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
679 * @param object $doc XML document
680 * @param string $element Element name for the author
681 * @param string $contact_url Link of the contact
682 * @param array $items Item elements
684 * @return object XML author object
685 * @todo Add type-hints
687 private static function add_entry_author($doc, $element, $contact_url, $item) {
689 $contact = get_contact_details_by_url($contact_url, $item["uid"]);
691 $author = $doc->createElement($element);
692 xml::add_element($doc, $author, "name", $contact["name"]);
693 xml::add_element($doc, $author, "uri", $contact["url"]);
694 xml::add_element($doc, $author, "dfrn:handle", $contact["addr"]);
697 /// - Check real image type and image size
698 /// - Check which of these boths elements we should use
701 "type" => "image/jpeg",
703 "media:height" => 80,
704 "href" => $contact["photo"]);
705 xml::add_element($doc, $author, "link", "", $attributes);
709 "type" => "image/jpeg",
711 "media:height" => 80,
712 "href" => $contact["photo"]);
713 xml::add_element($doc, $author, "link", "", $attributes);
719 * @brief Adds the activity elements
721 * @param object $doc XML document
722 * @param string $element Element name for the activity
723 * @param string $activity activity value
725 * @return object XML activity object
726 * @todo Add type-hints
728 private static function create_activity($doc, $element, $activity) {
731 $entry = $doc->createElement($element);
733 $r = parse_xml_string($activity, false);
738 xml::add_element($doc, $entry, "activity:object-type", $r->type);
741 xml::add_element($doc, $entry, "id", $r->id);
744 xml::add_element($doc, $entry, "title", $r->title);
748 if (substr($r->link, 0, 1) == '<') {
749 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
750 $r->link = str_replace('&', '&', $r->link);
753 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
755 // XML does need a single element as root element so we add a dummy element here
756 $data = parse_xml_string("<dummy>" . $r->link . "</dummy>", false);
757 if (is_object($data)) {
758 foreach ($data->link AS $link) {
759 $attributes = array();
760 foreach ($link->attributes() AS $parameter => $value) {
761 $attributes[$parameter] = $value;
763 xml::add_element($doc, $entry, "link", "", $attributes);
767 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $r->link);
768 xml::add_element($doc, $entry, "link", "", $attributes);
772 xml::add_element($doc, $entry, "content", bbcode($r->content), array("type" => "html"));
782 * @brief Adds the elements for attachments
784 * @param object $doc XML document
785 * @param object $root XML root
786 * @param array $item Item element
788 * @return object XML attachment object
789 * @todo Add type-hints
791 private static function get_attachment($doc, $root, $item) {
792 $arr = explode('[/attach],',$item['attach']);
794 foreach ($arr as $r) {
796 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches);
798 $attributes = array("rel" => "enclosure",
799 "href" => $matches[1],
800 "type" => $matches[3]);
802 if (intval($matches[2])) {
803 $attributes["length"] = intval($matches[2]);
806 if (trim($matches[4]) != "") {
807 $attributes["title"] = trim($matches[4]);
810 xml::add_element($doc, $root, "link", "", $attributes);
817 * @brief Adds the "entry" elements for the DFRN protocol
819 * @param object $doc XML document
820 * @param string $type "text" or "html"
821 * @param array $item Item element
822 * @param array $owner Owner record
823 * @param bool $comment Trigger the sending of the "comment" element
824 * @param int $cid Contact ID of the recipient
826 * @return object XML entry object
827 * @todo Add type-hints
829 private static function entry($doc, $type, $item, $owner, $comment = false, $cid = 0) {
831 $mentioned = array();
833 if (!$item['parent']) {
837 if ($item['deleted']) {
838 $attributes = array("ref" => $item['uri'], "when" => datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME));
839 return xml::create_element($doc, "at:deleted-entry", "", $attributes);
842 $entry = $doc->createElement("entry");
844 if ($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid']) {
845 $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
847 $body = $item['body'];
850 // Remove the abstract element. It is only locally important.
851 $body = remove_abstract($body);
853 if ($type == 'html') {
856 if ($item['title'] != "") {
857 $htmlbody = "[b]".$item['title']."[/b]\n\n".$htmlbody;
860 $htmlbody = bbcode($htmlbody, false, false, 7);
863 $author = self::add_entry_author($doc, "author", $item["author-link"], $item);
864 $entry->appendChild($author);
866 $dfrnowner = self::add_entry_author($doc, "dfrn:owner", $item["owner-link"], $item);
867 $entry->appendChild($dfrnowner);
869 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
870 $parent = q("SELECT `guid` FROM `item` WHERE `id` = %d", intval($item["parent"]));
871 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
872 $attributes = array("ref" => $parent_item, "type" => "text/html",
873 "href" => App::get_baseurl().'/display/'.$parent[0]['guid'],
874 "dfrn:diaspora_guid" => $parent[0]['guid']);
875 xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
878 // Add conversation data. This is used for OStatus
879 $conversation_href = App::get_baseurl()."/display/".$owner["nick"]."/".$item["parent"];
880 $conversation_uri = $conversation_href;
882 if (isset($parent_item)) {
883 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $item['parent-uri']);
884 if (dbm::is_result($r)) {
885 if ($r['conversation-uri'] != '') {
886 $conversation_uri = $r['conversation-uri'];
888 if ($r['conversation-href'] != '') {
889 $conversation_href = $r['conversation-href'];
895 "href" => $conversation_href,
896 "ref" => $conversation_uri);
898 xml::add_element($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
900 xml::add_element($doc, $entry, "id", $item["uri"]);
901 xml::add_element($doc, $entry, "title", $item["title"]);
903 xml::add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
904 xml::add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
906 // "dfrn:env" is used to read the content
907 xml::add_element($doc, $entry, "dfrn:env", base64url_encode($body, true));
909 // The "content" field is not read by the receiver. We could remove it when the type is "text"
910 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
911 xml::add_element($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), array("type" => $type));
913 // We save this value in "plink". Maybe we should read it from there as well?
914 xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
915 "href" => App::get_baseurl()."/display/".$item["guid"]));
917 // "comment-allow" is some old fashioned stuff for old Friendica versions.
918 // It is included in the rewritten code for completeness
920 xml::add_element($doc, $entry, "dfrn:comment-allow", intval($item['last-child']));
923 if ($item['location']) {
924 xml::add_element($doc, $entry, "dfrn:location", $item['location']);
927 if ($item['coord']) {
928 xml::add_element($doc, $entry, "georss:point", $item['coord']);
931 if (($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])) {
932 xml::add_element($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
935 if ($item['extid']) {
936 xml::add_element($doc, $entry, "dfrn:extid", $item['extid']);
939 if ($item['bookmark']) {
940 xml::add_element($doc, $entry, "dfrn:bookmark", "true");
944 xml::add_element($doc, $entry, "statusnet:notice_info", "", array("local_id" => $item['id'], "source" => $item['app']));
947 xml::add_element($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
949 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
950 // It is needed for relayed comments to Diaspora.
951 if ($item['signed_text']) {
952 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
953 xml::add_element($doc, $entry, "dfrn:diaspora_signature", $sign);
956 xml::add_element($doc, $entry, "activity:verb", construct_verb($item));
958 if ($item['object-type'] != "") {
959 xml::add_element($doc, $entry, "activity:object-type", $item['object-type']);
960 } elseif ($item['id'] == $item['parent']) {
961 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
963 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
966 $actobj = self::create_activity($doc, "activity:object", $item['object']);
968 $entry->appendChild($actobj);
971 $actarg = self::create_activity($doc, "activity:target", $item['target']);
973 $entry->appendChild($actarg);
976 $tags = item_getfeedtags($item);
979 foreach ($tags as $t) {
980 if (($type != 'html') || ($t[0] != "@")) {
981 xml::add_element($doc, $entry, "category", "", array("scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]));
987 foreach ($tags as $t) {
989 $mentioned[$t[1]] = $t[1];
994 foreach ($mentioned AS $mention) {
995 $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
996 intval($owner["uid"]),
997 dbesc(normalise_link($mention)));
999 if (dbm::is_result($r) && ($r[0]["forum"] || $r[0]["prv"])) {
1000 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1001 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1002 "href" => $mention));
1004 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1005 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1006 "href" => $mention));
1010 self::get_attachment($doc, $entry, $item);
1016 * @brief encrypts data via AES
1018 * @param string $data The data that is to be encrypted
1019 * @param string $key The AES key
1021 * @return string encrypted data
1023 private static function aes_encrypt($data, $key) {
1024 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1028 * @brief decrypts data via AES
1030 * @param string $encrypted The encrypted data
1031 * @param string $key The AES key
1033 * @return string decrypted data
1035 public static function aes_decrypt($encrypted, $key) {
1036 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1040 * @brief Delivers the atom content to the contacts
1042 * @param array $owner Owner record
1043 * @param array $contactr Contact record of the receiver
1044 * @param string $atom Content that will be transmitted
1045 * @param bool $dissolve (to be documented)
1047 * @return int Deliver status. -1 means an error.
1048 * @todo Add array type-hint for $owner, $contact
1050 public static function deliver($owner,$contact,$atom, $dissolve = false) {
1054 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1056 if ($contact['duplex'] && $contact['dfrn-id']) {
1057 $idtosend = '0:' . $orig_id;
1059 if ($contact['duplex'] && $contact['issued-id']) {
1060 $idtosend = '1:' . $orig_id;
1063 $rino = get_config('system', 'rino_encrypt');
1064 $rino = intval($rino);
1066 logger("Local rino version: ". $rino, LOGGER_DEBUG);
1068 $ssl_val = intval(get_config('system','ssl_policy'));
1072 case SSL_POLICY_FULL:
1073 $ssl_policy = 'full';
1075 case SSL_POLICY_SELFSIGN:
1076 $ssl_policy = 'self';
1078 case SSL_POLICY_NONE:
1080 $ssl_policy = 'none';
1084 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1086 logger('dfrn_deliver: ' . $url);
1088 $ret = z_fetch_url($url);
1090 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1091 return -2; // timed out
1094 $xml = $ret['body'];
1096 $curl_stat = $a->get_curl_code();
1098 return -3; // timed out
1101 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1107 if (strpos($xml,'<?xml') === false) {
1108 logger('dfrn_deliver: no valid XML returned');
1109 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1113 $res = parse_xml_string($xml);
1115 if ((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id))) {
1116 return (($res->status) ? $res->status : 3);
1119 $postvars = array();
1120 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1121 $challenge = hex2bin((string) $res->challenge);
1122 $perm = (($res->perm) ? $res->perm : null);
1123 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1124 $rino_remote_version = intval($res->rino);
1125 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1127 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
1129 if ($owner['page-flags'] == PAGE_PRVGROUP) {
1133 $final_dfrn_id = '';
1136 if ((($perm == 'rw') && (! intval($contact['writable'])))
1137 || (($perm == 'r') && (intval($contact['writable'])))) {
1138 q("update contact set writable = %d where id = %d",
1139 intval(($perm == 'rw') ? 1 : 0),
1140 intval($contact['id'])
1142 $contact['writable'] = (string) 1 - intval($contact['writable']);
1146 if (($contact['duplex'] && strlen($contact['pubkey']))
1147 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1148 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1149 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
1150 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
1152 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
1153 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
1156 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1158 if (strpos($final_dfrn_id,':') == 1) {
1159 $final_dfrn_id = substr($final_dfrn_id,2);
1162 if ($final_dfrn_id != $orig_id) {
1163 logger('dfrn_deliver: wrong dfrn_id.');
1164 // did not decode properly - cannot trust this site
1168 $postvars['dfrn_id'] = $idtosend;
1169 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1171 $postvars['dissolve'] = '1';
1175 if ((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1176 $postvars['data'] = $atom;
1177 $postvars['perm'] = 'rw';
1179 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1180 $postvars['perm'] = 'r';
1183 $postvars['ssl_policy'] = $ssl_policy;
1186 $postvars['page'] = $page;
1190 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1191 logger('rino version: '. $rino_remote_version);
1193 switch ($rino_remote_version) {
1195 // Deprecated rino version!
1196 $key = openssl_random_pseudo_bytes(16);
1197 $data = self::aes_encrypt($postvars['data'], $key);
1200 // RINO 2 based on php-encryption
1202 $key = Crypto::createNewRandomKey();
1203 } catch (CryptoTestFailed $ex) {
1204 logger('Cannot safely create a key');
1206 } catch (CannotPerformOperation $ex) {
1207 logger('Cannot safely create a key');
1211 $data = Crypto::encrypt($postvars['data'], $key);
1212 } catch (CryptoTestFailed $ex) {
1213 logger('Cannot safely perform encryption');
1215 } catch (CannotPerformOperation $ex) {
1216 logger('Cannot safely perform encryption');
1221 logger("rino: invalid requested verision '$rino_remote_version'");
1225 $postvars['rino'] = $rino_remote_version;
1226 $postvars['data'] = bin2hex($data);
1228 //logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1231 if ($dfrn_version >= 2.1) {
1232 if (($contact['duplex'] && strlen($contact['pubkey']))
1233 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1234 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1235 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1237 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1241 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1242 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1244 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1249 logger('md5 rawkey ' . md5($postvars['key']));
1251 $postvars['key'] = bin2hex($postvars['key']);
1255 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1257 $xml = post_url($contact['notify'], $postvars);
1259 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1261 $curl_stat = $a->get_curl_code();
1262 if ((!$curl_stat) || (!strlen($xml))) {
1263 return -9; // timed out
1266 if (($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after'))) {
1270 if (strpos($xml,'<?xml') === false) {
1271 logger('dfrn_deliver: phase 2: no valid XML returned');
1272 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1276 if ($contact['term-date'] > NULL_DATE) {
1277 logger("dfrn_deliver: $url back from the dead - removing mark for death");
1278 require_once('include/Contact.php');
1279 unmark_for_death($contact);
1282 $res = parse_xml_string($xml);
1284 if (!isset($res->status)) {
1288 if (!empty($res->message)) {
1289 logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1292 return intval($res->status);
1296 * @brief Add new birthday event for this person
1298 * @param array $contact Contact record
1299 * @param string $birthday Birthday of the contact
1300 * @todo Add array type-hint for $contact
1302 private static function birthday_event($contact, $birthday) {
1304 // Check for duplicates
1305 $r = q("SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1306 intval($contact["uid"]),
1307 intval($contact["id"]),
1308 dbesc(datetime_convert("UTC","UTC", $birthday)),
1311 if (dbm::is_result($r)) {
1315 logger("updating birthday: ".$birthday." for contact ".$contact["id"]);
1317 $bdtext = sprintf(t("%s\'s birthday"), $contact["name"]);
1318 $bdtext2 = sprintf(t("Happy Birthday %s"), " [url=".$contact["url"]."]".$contact["name"]."[/url]") ;
1320 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1321 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1322 intval($contact["uid"]),
1323 intval($contact["id"]),
1324 dbesc(datetime_convert()),
1325 dbesc(datetime_convert()),
1326 dbesc(datetime_convert("UTC","UTC", $birthday)),
1327 dbesc(datetime_convert("UTC","UTC", $birthday." + 1 day ")),
1335 * @brief Fetch the author data from head or entry items
1337 * @param object $xpath XPath object
1338 * @param object $context In which context should the data be searched
1339 * @param array $importer Record of the importer user mixed with contact of the content
1340 * @param string $element Element name from which the data is fetched
1341 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1343 * @return Returns an array with relevant data of the author
1344 * @todo Find good type-hints for all parameter
1346 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "") {
1349 $author["name"] = $xpath->evaluate($element."/atom:name/text()", $context)->item(0)->nodeValue;
1350 $author["link"] = $xpath->evaluate($element."/atom:uri/text()", $context)->item(0)->nodeValue;
1352 $r = q("SELECT `id`, `uid`, `url`, `network`, `avatar-date`, `name-date`, `uri-date`, `addr`,
1353 `name`, `nick`, `about`, `location`, `keywords`, `xmpp`, `bdyear`, `bd`, `hidden`, `contact-type`
1354 FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
1355 intval($importer["uid"]), dbesc(normalise_link($author["link"])), dbesc(NETWORK_STATUSNET));
1357 if (dbm::is_result($r)) {
1359 $author["contact-id"] = $r[0]["id"];
1360 $author["network"] = $r[0]["network"];
1363 logger("Contact ".$author["link"]." wasn't found for user ".$importer["uid"]." XML: ".$xml, LOGGER_DEBUG);
1366 $author["contact-id"] = $importer["id"];
1367 $author["network"] = $importer["network"];
1371 // Until now we aren't serving different sizes - but maybe later
1372 $avatarlist = array();
1373 /// @todo check if "avatar" or "photo" would be the best field in the specification
1374 $avatars = $xpath->query($element."/atom:link[@rel='avatar']", $context);
1375 foreach ($avatars AS $avatar) {
1378 foreach ($avatar->attributes AS $attributes) {
1379 /// @TODO Rewrite these similar if () to one switch
1380 if ($attributes->name == "href") {
1381 $href = $attributes->textContent;
1383 if ($attributes->name == "width") {
1384 $width = $attributes->textContent;
1386 if ($attributes->name == "updated") {
1387 $contact["avatar-date"] = $attributes->textContent;
1390 if (($width > 0) && ($href != "")) {
1391 $avatarlist[$width] = $href;
1394 if (count($avatarlist) > 0) {
1395 krsort($avatarlist);
1396 $author["avatar"] = current($avatarlist);
1399 if (dbm::is_result($r) && !$onlyfetch) {
1400 logger("Check if contact details for contact " . $r[0]["id"] . " (" . $r[0]["nick"] . ") have to be updated.", LOGGER_DEBUG);
1402 $poco = array("url" => $contact["url"]);
1404 // When was the last change to name or uri?
1405 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1406 foreach ($name_element->attributes AS $attributes) {
1407 if ($attributes->name == "updated") {
1408 $poco["name-date"] = $attributes->textContent;
1412 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1413 foreach ($link_element->attributes AS $attributes) {
1414 if ($attributes->name == "updated") {
1415 $poco["uri-date"] = $attributes->textContent;
1419 // Update contact data
1420 $value = $xpath->evaluate($element . "/dfrn:handle/text()", $context)->item(0)->nodeValue;
1422 $poco["addr"] = $value;
1425 $value = $xpath->evaluate($element . "/poco:displayName/text()", $context)->item(0)->nodeValue;
1427 $poco["name"] = $value;
1430 $value = $xpath->evaluate($element . "/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
1432 $poco["nick"] = $value;
1435 $value = $xpath->evaluate($element . "/poco:note/text()", $context)->item(0)->nodeValue;
1437 $poco["about"] = $value;
1440 $value = $xpath->evaluate($element . "/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
1442 $poco["location"] = $value;
1445 /// @todo Only search for elements with "poco:type" = "xmpp"
1446 $value = $xpath->evaluate($element . "/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
1448 $poco["xmpp"] = $value;
1451 /// @todo Add support for the following fields that we don't support by now in the contact table:
1452 /// - poco:utcOffset
1458 // If the "hide" element is present then the profile isn't searchable.
1459 $hide = intval($xpath->evaluate($element . "/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
1461 logger("Hidden status for contact " . $contact["url"] . ": " . $hide, LOGGER_DEBUG);
1463 // If the contact isn't searchable then set the contact to "hidden".
1464 // Problem: This can be manually overridden by the user.
1466 $contact["hidden"] = true;
1469 // Save the keywords into the contact table
1471 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1472 foreach ($tagelements AS $tag) {
1473 $tags[$tag->nodeValue] = $tag->nodeValue;
1477 $poco["keywords"] = implode(", ", $tags);
1480 // "dfrn:birthday" contains the birthday converted to UTC
1481 $old_bdyear = $contact["bdyear"];
1483 $birthday = $xpath->evaluate($element . "/dfrn:birthday/text()", $context)->item(0)->nodeValue;
1485 if (strtotime($birthday) > time()) {
1486 $bd_timestamp = strtotime($birthday);
1488 $poco["bdyear"] = date("Y", $bd_timestamp);
1491 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1492 $value = $xpath->evaluate($element . "/poco:birthday/text()", $context)->item(0)->nodeValue;
1494 if (!in_array($value, array("", "0000-00-00", "0001-01-01"))) {
1495 $bdyear = date("Y");
1496 $value = str_replace("0000", $bdyear, $value);
1498 if (strtotime($value) < time()) {
1499 $value = str_replace($bdyear, $bdyear + 1, $value);
1500 $bdyear = $bdyear + 1;
1503 $poco["bd"] = $value;
1506 $contact = array_merge($contact, $poco);
1508 if ($old_bdyear != $contact["bdyear"]) {
1509 self::birthday_event($contact, $birthday);
1512 // Get all field names
1514 foreach ($r[0] AS $field => $data) {
1515 $fields[$field] = $data;
1518 unset($fields["id"]);
1519 unset($fields["uid"]);
1520 unset($fields["url"]);
1521 unset($fields["avatar-date"]);
1522 unset($fields["name-date"]);
1523 unset($fields["uri-date"]);
1525 // Update check for this field has to be done differently
1526 $datefields = array("name-date", "uri-date");
1527 foreach ($datefields AS $field) {
1528 if (strtotime($contact[$field]) > strtotime($r[0][$field])) {
1529 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $r[0][$field] . "'", LOGGER_DEBUG);
1534 foreach ($fields AS $field => $data) {
1535 if ($contact[$field] != $r[0][$field]) {
1536 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $r[0][$field] . "'", LOGGER_DEBUG);
1542 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1544 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1545 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1546 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1547 WHERE `id` = %d AND `network` = '%s'",
1548 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
1549 dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1550 dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
1551 dbesc(dbm::date($contact["name-date"])), dbesc(dbm::date($contact["uri-date"])),
1552 intval($contact["id"]), dbesc($contact["network"]));
1555 update_contact_avatar($author["avatar"], $importer["uid"], $contact["id"],
1556 (strtotime($contact["avatar-date"]) > strtotime($r[0]["avatar-date"])));
1559 * The generation is a sign for the reliability of the provided data.
1560 * It is used in the socgraph.php to prevent that old contact data
1561 * that was relayed over several servers can overwrite contact
1562 * data that we received directly.
1565 $poco["generation"] = 2;
1566 $poco["photo"] = $author["avatar"];
1567 $poco["hide"] = $hide;
1568 $poco["contact-type"] = $contact["contact-type"];
1569 $gcid = update_gcontact($poco);
1571 link_gcontact($gcid, $importer["uid"], $contact["id"]);
1578 * @brief Transforms activity objects into an XML string
1580 * @param object $xpath XPath object
1581 * @param object $activity Activity object
1582 * @param text $element element name
1584 * @return string XML string
1585 * @todo Find good type-hints for all parameter
1587 private static function transform_activity($xpath, $activity, $element) {
1588 if (!is_object($activity)) {
1592 $obj_doc = new DOMDocument("1.0", "utf-8");
1593 $obj_doc->formatOutput = true;
1595 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1597 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1598 xml::add_element($obj_doc, $obj_element, "type", $activity_type);
1600 $id = $xpath->query("atom:id", $activity)->item(0);
1601 if (is_object($id)) {
1602 $obj_element->appendChild($obj_doc->importNode($id, true));
1605 $title = $xpath->query("atom:title", $activity)->item(0);
1606 if (is_object($title)) {
1607 $obj_element->appendChild($obj_doc->importNode($title, true));
1610 $links = $xpath->query("atom:link", $activity);
1611 if (is_object($links)) {
1612 foreach ($links AS $link) {
1613 $obj_element->appendChild($obj_doc->importNode($link, true));
1617 $content = $xpath->query("atom:content", $activity)->item(0);
1618 if (is_object($content)) {
1619 $obj_element->appendChild($obj_doc->importNode($content, true));
1622 $obj_doc->appendChild($obj_element);
1624 $objxml = $obj_doc->saveXML($obj_element);
1626 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1627 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1632 * @brief Processes the mail elements
1634 * @param object $xpath XPath object
1635 * @param object $mail mail elements
1636 * @param array $importer Record of the importer user mixed with contact of the content
1637 * @todo Find good type-hints for all parameter
1639 private static function process_mail($xpath, $mail, $importer) {
1641 logger("Processing mails");
1643 /// @TODO Rewrite this to one statement
1645 $msg["uid"] = $importer["importer_uid"];
1646 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1647 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1648 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1649 $msg["contact-id"] = $importer["id"];
1650 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1651 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1652 $msg["created"] = $xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue;
1653 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1654 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1656 $msg["replied"] = 0;
1658 dbm::esc_array($msg, true);
1660 $r = dbq("INSERT INTO `mail` (`".implode("`, `", array_keys($msg))."`) VALUES (".implode(", ", array_values($msg)).")");
1662 // send notifications.
1663 /// @TODO Arange this mess
1664 $notif_params = array(
1665 "type" => NOTIFY_MAIL,
1666 "notify_flags" => $importer["notify-flags"],
1667 "language" => $importer["language"],
1668 "to_name" => $importer["username"],
1669 "to_email" => $importer["email"],
1670 "uid" => $importer["importer_uid"],
1672 "source_name" => $msg["from-name"],
1673 "source_link" => $importer["url"],
1674 "source_photo" => $importer["thumb"],
1675 "verb" => ACTIVITY_POST,
1679 notification($notif_params);
1681 logger("Mail is processed, notification was sent.");
1685 * @brief Processes the suggestion elements
1687 * @param object $xpath XPath object
1688 * @param object $suggestion suggestion elements
1689 * @param array $importer Record of the importer user mixed with contact of the content
1690 * @todo Find good type-hints for all parameter
1692 private static function process_suggestion($xpath, $suggestion, $importer) {
1695 logger("Processing suggestions");
1697 /// @TODO Rewrite this to one statement
1699 $suggest["uid"] = $importer["importer_uid"];
1700 $suggest["cid"] = $importer["id"];
1701 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1702 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1703 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1704 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1705 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1707 // Does our member already have a friend matching this description?
1709 $r = q("SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1710 dbesc($suggest["name"]),
1711 dbesc(normalise_link($suggest["url"])),
1712 intval($suggest["uid"])
1716 * The valid result means the friend we're about to send a friend
1717 * suggestion already has them in their contact, which means no further
1718 * action is required.
1720 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1722 if (dbm::is_result($r)) {
1726 // Do we already have an fcontact record for this person?
1729 $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1730 dbesc($suggest["url"]),
1731 dbesc($suggest["name"]),
1732 dbesc($suggest["request"])
1734 if (dbm::is_result($r)) {
1737 // OK, we do. Do we already have an introduction for this person ?
1738 $r = q("SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1739 intval($suggest["uid"]),
1744 * The valid result means the friend we're about to send a friend
1745 * suggestion already has them in their contact, which means no further
1746 * action is required.
1748 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1750 if (dbm::is_result($r)) {
1755 $r = q("INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1756 dbesc($suggest["name"]),
1757 dbesc($suggest["url"]),
1758 dbesc($suggest["photo"]),
1759 dbesc($suggest["request"])
1762 $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1763 dbesc($suggest["url"]),
1764 dbesc($suggest["name"]),
1765 dbesc($suggest["request"])
1769 * If no record in fcontact is found, below INSERT statement will not
1770 * link an introduction to it.
1772 if (!dbm::is_result($r)) {
1773 // database record did not get created. Quietly give up.
1779 $hash = random_string();
1781 $r = q("INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1782 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1783 intval($suggest["uid"]),
1785 intval($suggest["cid"]),
1786 dbesc($suggest["body"]),
1788 dbesc(datetime_convert()),
1793 "type" => NOTIFY_SUGGEST,
1794 "notify_flags" => $importer["notify-flags"],
1795 "language" => $importer["language"],
1796 "to_name" => $importer["username"],
1797 "to_email" => $importer["email"],
1798 "uid" => $importer["importer_uid"],
1800 "link" => App::get_baseurl()."/notifications/intros",
1801 "source_name" => $importer["name"],
1802 "source_link" => $importer["url"],
1803 "source_photo" => $importer["photo"],
1804 "verb" => ACTIVITY_REQ_FRIEND,
1813 * @brief Processes the relocation elements
1815 * @param object $xpath XPath object
1816 * @param object $relocation relocation elements
1817 * @param array $importer Record of the importer user mixed with contact of the content
1818 * @todo Find good type-hints for all parameter
1820 private static function process_relocation($xpath, $relocation, $importer) {
1822 logger("Processing relocations");
1824 /// @TODO Rewrite this to one statement
1825 $relocate = array();
1826 $relocate["uid"] = $importer["importer_uid"];
1827 $relocate["cid"] = $importer["id"];
1828 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1829 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
1830 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1831 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
1832 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1833 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1834 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1835 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1836 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1837 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1838 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1839 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1841 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
1842 $relocate["avatar"] = $relocate["photo"];
1845 if ($relocate["addr"] == "") {
1846 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
1850 $r = q("SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
1851 intval($importer["id"]),
1852 intval($importer["importer_uid"]));
1854 if (!dbm::is_result($r)) {
1855 logger("Query failed to execute, no result returned in " . __FUNCTION__);
1861 // Update the gcontact entry
1862 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
1864 $x = q("UPDATE `gcontact` SET
1873 WHERE `nurl` = '%s';",
1874 dbesc($relocate["name"]),
1875 dbesc($relocate["avatar"]),
1876 dbesc($relocate["url"]),
1877 dbesc(normalise_link($relocate["url"])),
1878 dbesc($relocate["addr"]),
1879 dbesc($relocate["addr"]),
1880 dbesc($relocate["notify"]),
1881 dbesc($relocate["server_url"]),
1882 dbesc(normalise_link($old["url"])));
1884 // Update the contact table. We try to find every entry.
1885 $x = q("UPDATE `contact` SET
1895 `site-pubkey` = '%s'
1896 WHERE (`id` = %d AND `uid` = %d) OR (`nurl` = '%s');",
1897 dbesc($relocate["name"]),
1898 dbesc($relocate["avatar"]),
1899 dbesc($relocate["url"]),
1900 dbesc(normalise_link($relocate["url"])),
1901 dbesc($relocate["addr"]),
1902 dbesc($relocate["request"]),
1903 dbesc($relocate["confirm"]),
1904 dbesc($relocate["notify"]),
1905 dbesc($relocate["poll"]),
1906 dbesc($relocate["sitepubkey"]),
1907 intval($importer["id"]),
1908 intval($importer["importer_uid"]),
1909 dbesc(normalise_link($old["url"])));
1911 update_contact_avatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
1918 /// @todo This is an extreme performance killer
1920 'owner-link' => array($old["url"], $relocate["url"]),
1921 'author-link' => array($old["url"], $relocate["url"]),
1922 //'owner-avatar' => array($old["photo"], $relocate["photo"]),
1923 //'author-avatar' => array($old["photo"], $relocate["photo"]),
1925 foreach ($fields as $n=>$f) {
1926 $r = q("SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
1928 intval($importer["importer_uid"]));
1930 if (dbm::is_result($r)) {
1931 $x = q("UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1934 intval($importer["importer_uid"]));
1943 /// merge with current record, current contents have priority
1944 /// update record, set url-updated
1945 /// update profile photos
1946 /// schedule a scan?
1951 * @brief Updates an item
1953 * @param array $current the current item record
1954 * @param array $item the new item record
1955 * @param array $importer Record of the importer user mixed with contact of the content
1956 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
1957 * @todo set proper type-hints (array?)
1959 private static function update_content($current, $item, $importer, $entrytype) {
1962 if (edited_timestamp_is_newer($current, $item)) {
1964 // do not accept (ignore) an earlier edit than one we currently have.
1965 if (datetime_convert("UTC","UTC",$item["edited"]) < $current["edited"]) {
1969 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s', `changed` = '%s' WHERE `uri` = '%s' AND `uid` IN (0, %d)",
1970 dbesc($item["title"]),
1971 dbesc($item["body"]),
1972 dbesc($item["tag"]),
1973 dbesc(datetime_convert("UTC","UTC",$item["edited"])),
1974 dbesc(datetime_convert()),
1975 dbesc($item["uri"]),
1976 intval($importer["importer_uid"])
1978 create_tags_from_itemuri($item["uri"], $importer["importer_uid"]);
1979 update_thread_uri($item["uri"], $importer["importer_uid"]);
1983 if ($entrytype == DFRN_REPLY_RC) {
1984 proc_run(PRIORITY_HIGH, "include/notifier.php","comment-import", $current["id"]);
1988 // update last-child if it changes
1989 if ($item["last-child"] && ($item["last-child"] != $current["last-child"])) {
1990 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
1991 dbesc(datetime_convert()),
1992 dbesc($item["parent-uri"]),
1993 intval($importer["importer_uid"])
1995 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` IN (0, %d)",
1996 intval($item["last-child"]),
1997 dbesc(datetime_convert()),
1998 dbesc($item["uri"]),
1999 intval($importer["importer_uid"])
2006 * @brief Detects the entry type of the item
2008 * @param array $importer Record of the importer user mixed with contact of the content
2009 * @param array $item the new item record
2011 * @return int Is it a toplevel entry, a comment or a relayed comment?
2012 * @todo set proper type-hints (array?)
2014 private static function get_entry_type($importer, $item) {
2015 if ($item["parent-uri"] != $item["uri"]) {
2018 if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
2021 logger("possible community action");
2023 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2026 // was the top-level post for this action written by somebody on this site?
2027 // Specifically, the recipient?
2029 $is_a_remote_action = false;
2031 $r = q("SELECT `item`.`parent-uri` FROM `item`
2032 WHERE `item`.`uri` = '%s'
2034 dbesc($item["parent-uri"])
2036 if (dbm::is_result($r)) {
2037 $r = q("SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2038 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2039 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2040 AND `item`.`uid` = %d
2043 dbesc($r[0]["parent-uri"]),
2044 dbesc($r[0]["parent-uri"]),
2045 dbesc($r[0]["parent-uri"]),
2046 intval($importer["importer_uid"])
2048 if (dbm::is_result($r)) {
2049 $is_a_remote_action = true;
2054 * Does this have the characteristics of a community or private group action?
2055 * If it's an action to a wall post on a community/prvgroup page it's a
2056 * valid community action. Also forum_mode makes it valid for sure.
2057 * If neither, it's not.
2060 /// @TODO Maybe merge these if() blocks into one?
2061 if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2062 $is_a_remote_action = false;
2063 logger("not a community action");
2066 if ($is_a_remote_action) {
2067 return DFRN_REPLY_RC;
2072 return DFRN_TOP_LEVEL;
2078 * @brief Send a "poke"
2080 * @param array $item the new item record
2081 * @param array $importer Record of the importer user mixed with contact of the content
2082 * @param int $posted_id The record number of item record that was just posted
2083 * @todo set proper type-hints (array?)
2085 private static function do_poke($item, $importer, $posted_id) {
2086 $verb = urldecode(substr($item["verb"],strpos($item["verb"], "#")+1));
2090 $xo = parse_xml_string($item["object"],false);
2092 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2094 // somebody was poked/prodded. Was it me?
2095 foreach ($xo->link as $l) {
2096 $atts = $l->attributes();
2097 switch ($atts["rel"]) {
2099 $Blink = $atts["href"];
2106 if ($Blink && link_compare($Blink, App::get_baseurl() . "/profile/" . $importer["nickname"])) {
2108 // send a notification
2110 "type" => NOTIFY_POKE,
2111 "notify_flags" => $importer["notify-flags"],
2112 "language" => $importer["language"],
2113 "to_name" => $importer["username"],
2114 "to_email" => $importer["email"],
2115 "uid" => $importer["importer_uid"],
2117 "link" => App::get_baseurl()."/display/".urlencode(get_item_guid($posted_id)),
2118 "source_name" => stripslashes($item["author-name"]),
2119 "source_link" => $item["author-link"],
2120 "source_photo" => ((link_compare($item["author-link"],$importer["url"]))
2121 ? $importer["thumb"] : $item["author-avatar"]),
2122 "verb" => $item["verb"],
2123 "otype" => "person",
2124 "activity" => $verb,
2125 "parent" => $item["parent"]
2132 * @brief Processes several actions, depending on the verb
2134 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2135 * @param array $importer Record of the importer user mixed with contact of the content
2136 * @param array $item the new item record
2137 * @param bool $is_like Is the verb a "like"?
2139 * @return bool Should the processing of the entries be continued?
2140 * @todo set proper type-hints (array?)
2142 private static function process_verbs($entrytype, $importer, &$item, &$is_like) {
2144 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2146 if (($entrytype == DFRN_TOP_LEVEL)) {
2147 // The filling of the the "contact" variable is done for legcy reasons
2148 // The functions below are partly used by ostatus.php as well - where we have this variable
2149 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2151 $nickname = $contact["nick"];
2153 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2154 // This function once was responsible for DFRN and OStatus.
2155 if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2156 logger("New follower");
2157 new_follower($importer, $contact, $item, $nickname);
2160 if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2161 logger("Lost follower");
2162 lose_follower($importer, $contact, $item);
2165 if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2166 logger("New friend request");
2167 new_follower($importer, $contact, $item, $nickname, true);
2170 if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2171 logger("Lost sharer");
2172 lose_sharer($importer, $contact, $item);
2176 if (($item["verb"] == ACTIVITY_LIKE)
2177 || ($item["verb"] == ACTIVITY_DISLIKE)
2178 || ($item["verb"] == ACTIVITY_ATTEND)
2179 || ($item["verb"] == ACTIVITY_ATTENDNO)
2180 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)) {
2182 $item["type"] = "activity";
2183 $item["gravity"] = GRAVITY_LIKE;
2184 // only one like or dislike per person
2185 // splitted into two queries for performance issues
2186 $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",
2187 intval($item["uid"]),
2188 dbesc($item["author-link"]),
2189 dbesc($item["verb"]),
2190 dbesc($item["parent-uri"])
2192 if (dbm::is_result($r)) {
2196 $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",
2197 intval($item["uid"]),
2198 dbesc($item["author-link"]),
2199 dbesc($item["verb"]),
2200 dbesc($item["parent-uri"])
2202 if (dbm::is_result($r)) {
2209 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2211 $xo = parse_xml_string($item["object"],false);
2212 $xt = parse_xml_string($item["target"],false);
2214 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2215 $r = q("SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2217 intval($importer["importer_uid"])
2220 if (!dbm::is_result($r)) {
2221 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2225 // extract tag, if not duplicate, add to parent item
2227 if (!(stristr($r[0]["tag"],trim($xo->content)))) {
2228 q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2229 dbesc($r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2232 create_tags_from_item($r[0]["id"]);
2242 * @brief Processes the link elements
2244 * @param object $links link elements
2245 * @param array $item the item record
2246 * @todo set proper type-hints
2248 private static function parse_links($links, &$item) {
2254 foreach ($links AS $link) {
2255 foreach ($link->attributes AS $attributes) {
2256 /// @TODO Rewrite these repeated (same) if () statements to a switch()
2257 if ($attributes->name == "href") {
2258 $href = $attributes->textContent;
2260 if ($attributes->name == "rel") {
2261 $rel = $attributes->textContent;
2263 if ($attributes->name == "type") {
2264 $type = $attributes->textContent;
2266 if ($attributes->name == "length") {
2267 $length = $attributes->textContent;
2269 if ($attributes->name == "title") {
2270 $title = $attributes->textContent;
2273 if (($rel != "") && ($href != "")) {
2276 $item["plink"] = $href;
2280 if (strlen($item["attach"])) {
2281 $item["attach"] .= ",";
2284 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2292 * @brief Processes the entry elements which contain the items and comments
2294 * @param array $header Array of the header elements that always stay the same
2295 * @param object $xpath XPath object
2296 * @param object $entry entry elements
2297 * @param array $importer Record of the importer user mixed with contact of the content
2298 * @todo Add type-hints
2300 private static function process_entry($header, $xpath, $entry, $importer, $xml) {
2302 logger("Processing entries");
2306 $item["protocol"] = PROTOCOL_DFRN;
2308 $item["source"] = $xml;
2311 $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
2313 $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
2315 $current = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2316 dbesc($item["uri"]),
2317 intval($importer["importer_uid"])
2320 // Is there an existing item?
2321 if (dbm::is_result($current) && edited_timestamp_is_newer($current[0], $item) &&
2322 (datetime_convert("UTC","UTC",$item["edited"]) < $current[0]["edited"])) {
2323 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2328 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2330 $item["owner-name"] = $owner["name"];
2331 $item["owner-link"] = $owner["link"];
2332 $item["owner-avatar"] = $owner["avatar"];
2335 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2337 $item["author-name"] = $author["name"];
2338 $item["author-link"] = $author["link"];
2339 $item["author-avatar"] = $author["avatar"];
2341 $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
2343 $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2345 $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
2346 $item["body"] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$item["body"]);
2347 // make sure nobody is trying to sneak some html tags by us
2348 $item["body"] = notags(base64url_decode($item["body"]));
2350 $item["body"] = limit_body_size($item["body"]);
2352 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2353 if ((strpos($item['body'],'<') !== false) && (strpos($item['body'],'>') !== false)) {
2355 $item['body'] = reltoabs($item['body'],$base_url);
2357 $item['body'] = html2bb_video($item['body']);
2359 $item['body'] = oembed_html2bbcode($item['body']);
2361 $config = HTMLPurifier_Config::createDefault();
2362 $config->set('Cache.DefinitionImpl', null);
2364 // we shouldn't need a whitelist, because the bbcode converter
2365 // will strip out any unsupported tags.
2367 $purifier = new HTMLPurifier($config);
2368 $item['body'] = $purifier->purify($item['body']);
2370 $item['body'] = @html2bbcode($item['body']);
2373 /// @todo We should check for a repeated post and if we know the repeated author.
2375 // We don't need the content element since "dfrn:env" is always present
2376 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2378 $item["last-child"] = $xpath->query("dfrn:comment-allow/text()", $entry)->item(0)->nodeValue;
2379 $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
2381 $georsspoint = $xpath->query("georss:point", $entry);
2383 $item["coord"] = $georsspoint->item(0)->nodeValue;
2386 $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
2388 $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
2390 if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true") {
2391 $item["bookmark"] = true;
2394 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2395 if ($notice_info && ($notice_info->length > 0)) {
2396 foreach ($notice_info->item(0)->attributes AS $attributes) {
2397 if ($attributes->name == "source") {
2398 $item["app"] = strip_tags($attributes->textContent);
2403 $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
2405 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "item_store"
2406 $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
2407 if ($dsprsig != "") {
2408 $item["dsprsig"] = $dsprsig;
2411 $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
2413 if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "") {
2414 $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
2417 $object = $xpath->query("activity:object", $entry)->item(0);
2418 $item["object"] = self::transform_activity($xpath, $object, "object");
2420 if (trim($item["object"]) != "") {
2421 $r = parse_xml_string($item["object"], false);
2422 if (isset($r->type)) {
2423 $item["object-type"] = $r->type;
2427 $target = $xpath->query("activity:target", $entry)->item(0);
2428 $item["target"] = self::transform_activity($xpath, $target, "target");
2430 $categories = $xpath->query("atom:category", $entry);
2432 foreach ($categories AS $category) {
2435 foreach ($category->attributes AS $attributes) {
2436 if ($attributes->name == "term") {
2437 $term = $attributes->textContent;
2440 if ($attributes->name == "scheme") {
2441 $scheme = $attributes->textContent;
2445 if (($term != "") && ($scheme != "")) {
2446 $parts = explode(":", $scheme);
2447 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2448 $termhash = array_shift($parts);
2449 $termurl = implode(":", $parts);
2451 if (strlen($item["tag"])) {
2452 $item["tag"] .= ",";
2455 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2463 $links = $xpath->query("atom:link", $entry);
2465 self::parse_links($links, $item);
2468 $item['conversation-uri'] = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
2470 $conv = $xpath->query('ostatus:conversation', $entry);
2471 if (is_object($conv->item(0))) {
2472 foreach ($conv->item(0)->attributes AS $attributes) {
2473 if ($attributes->name == "ref") {
2474 $item['conversation-uri'] = $attributes->textContent;
2476 if ($attributes->name == "href") {
2477 $item['conversation-href'] = $attributes->textContent;
2482 // Is it a reply or a top level posting?
2483 $item["parent-uri"] = $item["uri"];
2485 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2486 if (is_object($inreplyto->item(0))) {
2487 foreach ($inreplyto->item(0)->attributes AS $attributes) {
2488 if ($attributes->name == "ref") {
2489 $item["parent-uri"] = $attributes->textContent;
2494 // Get the type of the item (Top level post, reply or remote reply)
2495 $entrytype = self::get_entry_type($importer, $item);
2497 // Now assign the rest of the values that depend on the type of the message
2498 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2499 if (!isset($item["object-type"])) {
2500 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2503 if ($item["contact-id"] != $owner["contact-id"]) {
2504 $item["contact-id"] = $owner["contact-id"];
2507 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2508 $item["network"] = $owner["network"];
2511 if ($item["contact-id"] != $author["contact-id"]) {
2512 $item["contact-id"] = $author["contact-id"];
2515 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2516 $item["network"] = $author["network"];
2519 /// @TODO maybe remove this old-lost code then?
2520 // This code was taken from the old DFRN code
2521 // When activated, forums don't work.
2522 // And: Why should we disallow commenting by followers?
2523 // the behaviour is now similar to the Diaspora part.
2524 //if ($importer["rel"] == CONTACT_IS_FOLLOWER) {
2525 // logger("Contact ".$importer["id"]." is only follower. Quitting", LOGGER_DEBUG);
2530 if ($entrytype == DFRN_REPLY_RC) {
2531 $item["type"] = "remote-comment";
2533 } elseif ($entrytype == DFRN_TOP_LEVEL) {
2534 if (!isset($item["object-type"])) {
2535 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2539 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2540 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2541 $ev = bbtoevent($item["body"]);
2542 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2543 logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2544 /// @TODO Mixure of "/' ahead ...
2545 $ev["cid"] = $importer["id"];
2546 $ev["uid"] = $importer["uid"];
2547 $ev["uri"] = $item["uri"];
2548 $ev["edited"] = $item["edited"];
2549 $ev['private'] = $item['private'];
2550 $ev["guid"] = $item["guid"];
2552 $r = q("SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2553 dbesc($item["uri"]),
2554 intval($importer["uid"])
2556 if (dbm::is_result($r)) {
2557 $ev["id"] = $r[0]["id"];
2560 $event_id = event_store($ev);
2561 logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2567 if (!self::process_verbs($entrytype, $importer, $item, $is_like)) {
2568 logger("Exiting because 'process_verbs' told us so", LOGGER_DEBUG);
2572 // Update content if 'updated' changes
2573 if (dbm::is_result($current)) {
2574 if (self::update_content($r[0], $item, $importer, $entrytype)) {
2575 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2577 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2582 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2583 $posted_id = item_store($item);
2588 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2590 $item["id"] = $posted_id;
2592 $r = q("SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2594 intval($importer["importer_uid"])
2596 if (dbm::is_result($r)) {
2597 $parent = $r[0]["parent"];
2598 $parent_uri = $r[0]["parent-uri"];
2602 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2603 dbesc(datetime_convert()),
2604 intval($importer["importer_uid"]),
2605 intval($r[0]["parent"])
2608 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d",
2609 dbesc(datetime_convert()),
2610 intval($importer["importer_uid"]),
2615 if ($posted_id && $parent && ($entrytype == DFRN_REPLY_RC)) {
2616 logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
2617 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $posted_id);
2622 } else { // $entrytype == DFRN_TOP_LEVEL
2623 if (!link_compare($item["owner-link"],$importer["url"])) {
2625 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2626 * but otherwise there's a possible data mixup on the sender's system.
2627 * the tgroup delivery code called from item_store will correct it if it's a forum,
2628 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2630 logger('Correcting item owner.', LOGGER_DEBUG);
2631 $item["owner-name"] = $importer["senderName"];
2632 $item["owner-link"] = $importer["url"];
2633 $item["owner-avatar"] = $importer["thumb"];
2636 if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!tgroup_check($importer["importer_uid"], $item))) {
2637 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2641 // This is my contact on another system, but it's really me.
2642 // Turn this into a wall post.
2643 $notify = item_is_remote_self($importer, $item);
2645 $posted_id = item_store($item, false, $notify);
2647 logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2649 if (stristr($item["verb"],ACTIVITY_POKE))
2650 self::do_poke($item, $importer, $posted_id);
2655 * @brief Deletes items
2657 * @param object $xpath XPath object
2658 * @param object $deletion deletion elements
2659 * @param array $importer Record of the importer user mixed with contact of the content
2660 * @todo set proper type-hints
2662 private static function process_deletion($xpath, $deletion, $importer) {
2664 logger("Processing deletions");
2666 foreach ($deletion->attributes AS $attributes) {
2667 if ($attributes->name == "ref") {
2668 $uri = $attributes->textContent;
2670 if ($attributes->name == "when") {
2671 $when = $attributes->textContent;
2675 $when = datetime_convert("UTC", "UTC", $when, "Y-m-d H:i:s");
2677 $when = datetime_convert("UTC", "UTC", "now", "Y-m-d H:i:s");
2680 if (!$uri || !$importer["id"]) {
2684 /// @todo Only select the used fields
2685 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` INNER JOIN `contact` on `item`.`contact-id` = `contact`.`id`
2686 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2688 intval($importer["uid"]),
2689 intval($importer["id"])
2691 if (!dbm::is_result($r)) {
2692 logger("Item with uri " . $uri . " from contact " . $importer["id"] . " for user " . $importer["uid"] . " wasn't found.", LOGGER_DEBUG);
2698 $entrytype = self::get_entry_type($importer, $item);
2700 if (!$item["deleted"]) {
2701 logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG);
2706 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2707 logger("Deleting event ".$item["event-id"], LOGGER_DEBUG);
2708 event_delete($item["event-id"]);
2711 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2713 $xo = parse_xml_string($item["object"],false);
2714 $xt = parse_xml_string($item["target"],false);
2716 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2717 $i = q("SELECT `id`, `contact-id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2719 intval($importer["importer_uid"])
2721 if (dbm::is_result($i)) {
2723 // For tags, the owner cannot remove the tag on the author's copy of the post.
2725 $owner_remove = (($item["contact-id"] == $i[0]["contact-id"]) ? true: false);
2726 $author_remove = (($item["origin"] && $item["self"]) ? true : false);
2727 $author_copy = (($item["origin"]) ? true : false);
2729 if ($owner_remove && $author_copy) {
2732 if ($author_remove || $owner_remove) {
2733 $tags = explode(',',$i[0]["tag"]);
2736 foreach ($tags as $tag) {
2737 if (trim($tag) !== trim($xo->body)) {
2738 $newtags[] = trim($tag);
2742 q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2743 dbesc(implode(',', $newtags)),
2746 create_tags_from_item($i[0]["id"]);
2752 if ($entrytype == DFRN_TOP_LEVEL) {
2753 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2754 `body` = '', `title` = ''
2755 WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2757 dbesc(datetime_convert()),
2759 intval($importer["uid"])
2761 create_tags_from_itemuri($uri, $importer["uid"]);
2762 create_files_from_itemuri($uri, $importer["uid"]);
2763 update_thread_uri($uri, $importer["uid"]);
2765 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2766 `body` = '', `title` = ''
2767 WHERE `uri` = '%s' AND `uid` IN (0, %d)",
2769 dbesc(datetime_convert()),
2771 intval($importer["uid"])
2773 create_tags_from_itemuri($uri, $importer["uid"]);
2774 create_files_from_itemuri($uri, $importer["uid"]);
2775 update_thread_uri($uri, $importer["importer_uid"]);
2776 if ($item["last-child"]) {
2777 // ensure that last-child is set in case the comment that had it just got wiped.
2778 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2779 dbesc(datetime_convert()),
2780 dbesc($item["parent-uri"]),
2781 intval($item["uid"])
2783 // who is the last child now?
2784 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
2785 ORDER BY `created` DESC LIMIT 1",
2786 dbesc($item["parent-uri"]),
2787 intval($importer["uid"])
2789 if (dbm::is_result($r)) {
2790 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
2795 // if this is a relayed delete, propagate it to other recipients
2797 if ($entrytype == DFRN_REPLY_RC) {
2798 logger("Notifying followers about deletion of post " . $item["id"], LOGGER_DEBUG);
2799 proc_run(PRIORITY_HIGH, "include/notifier.php","drop", $item["id"]);
2806 * @brief Imports a DFRN message
2808 * @param text $xml The DFRN message
2809 * @param array $importer Record of the importer user mixed with contact of the content
2810 * @param bool $sort_by_date Is used when feeds are polled
2811 * @return integer Import status
2812 * @todo set proper type-hints
2814 public static function import($xml, $importer, $sort_by_date = false) {
2820 if ($importer["readonly"]) {
2821 // We aren't receiving stuff from this person. But we will quietly ignore them
2822 // rather than a blatant "go away" message.
2823 logger('ignoring contact '.$importer["id"]);
2827 $doc = new DOMDocument();
2828 @$doc->loadXML($xml);
2830 $xpath = new DomXPath($doc);
2831 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2832 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2833 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2834 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2835 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2836 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2837 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2838 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2839 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2840 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2843 $header["uid"] = $importer["uid"];
2844 $header["network"] = NETWORK_DFRN;
2845 $header["type"] = "remote";
2846 $header["wall"] = 0;
2847 $header["origin"] = 0;
2848 $header["contact-id"] = $importer["id"];
2850 // Update the contact table if the data has changed
2852 // The "atom:author" is only present in feeds
2853 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2854 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2857 // Only the "dfrn:owner" in the head section contains all data
2858 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2859 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2862 logger("Import DFRN message for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2864 // The account type is new since 3.5.1
2865 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2866 $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()", $context)->item(0)->nodeValue);
2868 if ($accounttype != $importer["contact-type"]) {
2869 /// @TODO this way is the norm or putting ); at the end of the line?
2870 q("UPDATE `contact` SET `contact-type` = %d WHERE `id` = %d",
2871 intval($accounttype),
2872 intval($importer["id"])
2877 // is it a public forum? Private forums aren't supported with this method
2878 // This is deprecated since 3.5.1
2879 $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()", $context)->item(0)->nodeValue);
2881 if ($forum != $importer["forum"]) {
2882 q("UPDATE `contact` SET `forum` = %d WHERE `forum` != %d AND `id` = %d",
2883 intval($forum), intval($forum),
2884 intval($importer["id"])
2888 $mails = $xpath->query("/atom:feed/dfrn:mail");
2889 foreach ($mails AS $mail) {
2890 self::process_mail($xpath, $mail, $importer);
2893 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2894 foreach ($suggestions AS $suggestion) {
2895 self::process_suggestion($xpath, $suggestion, $importer);
2898 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2899 foreach ($relocations AS $relocation) {
2900 self::process_relocation($xpath, $relocation, $importer);
2903 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2904 foreach ($deletions AS $deletion) {
2905 self::process_deletion($xpath, $deletion, $importer);
2908 if (!$sort_by_date) {
2909 $entries = $xpath->query("/atom:feed/atom:entry");
2910 foreach ($entries AS $entry) {
2911 self::process_entry($header, $xpath, $entry, $importer, $xml);
2914 $newentries = array();
2915 $entries = $xpath->query("/atom:feed/atom:entry");
2916 foreach ($entries AS $entry) {
2917 $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2918 $newentries[strtotime($created)] = $entry;
2921 // Now sort after the publishing date
2924 foreach ($newentries AS $entry) {
2925 self::process_entry($header, $xpath, $entry, $importer, $xml);
2928 logger("Import done for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);