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
9 namespace Friendica\Protocol;
12 use Friendica\Content\OEmbed;
13 use Friendica\Core\Config;
14 use Friendica\Core\System;
15 use Friendica\Core\Worker;
16 use Friendica\Database\DBM;
17 use Friendica\Model\Contact;
18 use Friendica\Model\GContact;
19 use Friendica\Model\Group;
20 use Friendica\Model\Profile;
21 use Friendica\Model\Term;
22 use Friendica\Model\User;
23 use Friendica\Object\Image;
24 use Friendica\Protocol\OStatus;
25 use Friendica\Util\Crypto;
26 use Friendica\Util\XML;
32 use HTMLPurifier_Config;
34 require_once 'boot.php';
35 require_once 'include/dba.php';
36 require_once "include/enotify.php";
37 require_once "include/threads.php";
38 require_once "include/items.php";
39 require_once "include/tags.php";
40 require_once "include/event.php";
41 require_once "include/text.php";
42 require_once "include/html2bbcode.php";
43 require_once "include/bbcode.php";
46 * @brief This class contain functions to create and send DFRN XML files
51 const DFRN_TOP_LEVEL = 0; // Top level posting
52 const DFRN_REPLY = 1; // Regular reply that is stored locally
53 const DFRN_REPLY_RC = 2; // Reply that will be relayed
56 * @brief Generates the atom entries for delivery.php
58 * This function is used whenever content is transmitted via DFRN.
60 * @param array $items Item elements
61 * @param array $owner Owner record
63 * @return string DFRN entries
64 * @todo Add type-hints
66 public static function entries($items, $owner)
68 $doc = new DOMDocument('1.0', 'utf-8');
69 $doc->formatOutput = true;
71 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
73 if (! count($items)) {
74 return trim($doc->saveXML());
77 foreach ($items as $item) {
78 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
79 $root->appendChild($entry);
82 return(trim($doc->saveXML()));
86 * @brief Generate an atom feed for the given user
88 * This function is called when another server is pulling data from the user feed.
90 * @param string $dfrn_id DFRN ID from the requesting party
91 * @param string $owner_nick Owner nick name
92 * @param string $last_update Date of the last update
93 * @param int $direction Can be -1, 0 or 1.
94 * @param boolean $onlyheader Output only the header without content? (Default is "no")
96 * @return string DFRN feed entries
98 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false)
102 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
103 $public_feed = (($dfrn_id) ? false : true);
104 $starred = false; // not yet implemented, possible security issues
107 if ($public_feed && $a->argc > 2) {
108 for ($x = 2; $x < $a->argc; $x++) {
109 if ($a->argv[$x] == 'converse') {
112 if ($a->argv[$x] == 'starred') {
115 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
116 $category = $a->argv[$x+1];
123 // default permissions - anonymous user
125 $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = '' ";
128 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
129 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
130 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
134 if (! DBM::is_result($r)) {
139 $owner_id = $owner['uid'];
140 $owner_nick = $owner['nickname'];
142 $sql_post_table = "";
144 if (! $public_feed) {
146 switch ($direction) {
148 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
152 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
153 $my_id = '1:' . $dfrn_id;
156 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
157 $my_id = '0:' . $dfrn_id;
165 "SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
169 if (! DBM::is_result($r)) {
174 include_once 'include/security.php';
175 $groups = Group::getIdsByContactId($contact['id']);
177 if (count($groups)) {
178 for ($x = 0; $x < count($groups); $x ++)
179 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
180 $gs = implode('|', $groups);
182 $gs = '<<>>' ; // Impossible to match
185 $sql_extra = sprintf(
187 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
188 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
189 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
190 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
192 intval($contact['id']),
193 intval($contact['id']),
205 if (! strlen($last_update)) {
206 $last_update = 'now -30 days';
209 if (isset($category)) {
210 $sql_post_table = sprintf(
211 "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` ",
212 dbesc(protect_sprintf($category)),
213 intval(TERM_OBJ_POST),
214 intval(TERM_CATEGORY),
217 //$sql_extra .= file_tag_file_query('item',$category,'category');
222 $sql_extra .= " AND `contact`.`self` = 1 ";
226 $check_date = datetime_convert('UTC', 'UTC', $last_update, 'Y-m-d H:i:s');
229 "SELECT `item`.*, `item`.`id` AS `item_id`,
230 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
231 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
232 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
233 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
234 FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
235 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
236 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
237 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
238 WHERE `item`.`uid` = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
239 AND `item`.`wall` AND `item`.`changed` > '%s'
241 ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
248 * Will check further below if this actually returned results.
249 * We will provide an empty feed if that is the case.
254 $doc = new DOMDocument('1.0', 'utf-8');
255 $doc->formatOutput = true;
257 $alternatelink = $owner['url'];
259 if (isset($category)) {
260 $alternatelink .= "/category/".$category;
264 $author = "dfrn:owner";
269 $root = self::addHeader($doc, $owner, $author, $alternatelink, true);
271 /// @TODO This hook can't work anymore
272 // call_hooks('atom_feed', $atom);
274 if (!DBM::is_result($items) || $onlyheader) {
275 $atom = trim($doc->saveXML());
277 call_hooks('atom_feed_end', $atom);
282 foreach ($items as $item) {
283 // prevent private email from leaking.
284 if ($item['network'] == NETWORK_MAIL) {
288 // public feeds get html, our own nodes use bbcode
292 // catch any email that's in a public conversation and make sure it doesn't leak
293 if ($item['private']) {
300 $entry = self::entry($doc, $type, $item, $owner, true);
301 $root->appendChild($entry);
304 $atom = trim($doc->saveXML());
306 call_hooks('atom_feed_end', $atom);
312 * @brief Generate an atom entry for a given item id
314 * @param int $item_id The item id
315 * @param boolean $conversation Show the conversation. If false show the single post.
317 * @return string DFRN feed entry
319 public static function itemFeed($item_id, $conversation = false)
322 $condition = '`item`.`parent`';
324 $condition = '`item`.`id`';
328 "SELECT `item`.*, `item`.`id` AS `item_id`,
329 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
330 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
331 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
332 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
334 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
335 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
336 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
337 WHERE %s = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
338 AND NOT `item`.`private`",
343 if (!DBM::is_result($r)) {
350 if ($item['uid'] != 0) {
351 $owner = User::getOwnerDataById($item['uid']);
356 $owner = ['uid' => 0, 'nick' => 'feed-item'];
359 $doc = new DOMDocument('1.0', 'utf-8');
360 $doc->formatOutput = true;
364 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
365 $doc->appendChild($root);
367 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
368 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
369 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
370 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
371 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
372 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
373 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
374 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
375 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
377 //$root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
379 foreach ($items as $item) {
380 $entry = self::entry($doc, $type, $item, $owner, true, 0);
381 $root->appendChild($entry);
384 $root = self::entry($doc, $type, $item, $owner, true, 0, true);
387 $atom = trim($doc->saveXML());
392 * @brief Create XML text for DFRN mails
394 * @param array $item message elements
395 * @param array $owner Owner record
397 * @return string DFRN mail
398 * @todo Add type-hints
400 public static function mail($item, $owner)
402 $doc = new DOMDocument('1.0', 'utf-8');
403 $doc->formatOutput = true;
405 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
407 $mail = $doc->createElement("dfrn:mail");
408 $sender = $doc->createElement("dfrn:sender");
410 XML::addElement($doc, $sender, "dfrn:name", $owner['name']);
411 XML::addElement($doc, $sender, "dfrn:uri", $owner['url']);
412 XML::addElement($doc, $sender, "dfrn:avatar", $owner['thumb']);
414 $mail->appendChild($sender);
416 XML::addElement($doc, $mail, "dfrn:id", $item['uri']);
417 XML::addElement($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
418 XML::addElement($doc, $mail, "dfrn:sentdate", datetime_convert('UTC', 'UTC', $item['created'] . '+00:00', ATOM_TIME));
419 XML::addElement($doc, $mail, "dfrn:subject", $item['title']);
420 XML::addElement($doc, $mail, "dfrn:content", $item['body']);
422 $root->appendChild($mail);
424 return(trim($doc->saveXML()));
428 * @brief Create XML text for DFRN friend suggestions
430 * @param array $item suggestion elements
431 * @param array $owner Owner record
433 * @return string DFRN suggestions
434 * @todo Add type-hints
436 public static function fsuggest($item, $owner)
438 $doc = new DOMDocument('1.0', 'utf-8');
439 $doc->formatOutput = true;
441 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
443 $suggest = $doc->createElement("dfrn:suggest");
445 XML::addElement($doc, $suggest, "dfrn:url", $item['url']);
446 XML::addElement($doc, $suggest, "dfrn:name", $item['name']);
447 XML::addElement($doc, $suggest, "dfrn:photo", $item['photo']);
448 XML::addElement($doc, $suggest, "dfrn:request", $item['request']);
449 XML::addElement($doc, $suggest, "dfrn:note", $item['note']);
451 $root->appendChild($suggest);
453 return(trim($doc->saveXML()));
457 * @brief Create XML text for DFRN relocations
459 * @param array $owner Owner record
460 * @param int $uid User ID
462 * @return string DFRN relocations
463 * @todo Add type-hints
465 public static function relocate($owner, $uid)
468 /* get site pubkey. this could be a new installation with no site keys*/
469 $pubkey = Config::get('system', 'site_pubkey');
471 $res = Crypto::newKeypair(1024);
472 Config::set('system', 'site_prvkey', $res['prvkey']);
473 Config::set('system', 'site_pubkey', $res['pubkey']);
477 "SELECT `resource-id` , `scale`, type FROM `photo`
478 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;",
482 $ext = Image::supportedTypes();
484 foreach ($rp as $p) {
485 $photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
490 $doc = new DOMDocument('1.0', 'utf-8');
491 $doc->formatOutput = true;
493 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
495 $relocate = $doc->createElement("dfrn:relocate");
497 XML::addElement($doc, $relocate, "dfrn:url", $owner['url']);
498 XML::addElement($doc, $relocate, "dfrn:name", $owner['name']);
499 XML::addElement($doc, $relocate, "dfrn:addr", $owner['addr']);
500 XML::addElement($doc, $relocate, "dfrn:avatar", $owner['avatar']);
501 XML::addElement($doc, $relocate, "dfrn:photo", $photos[4]);
502 XML::addElement($doc, $relocate, "dfrn:thumb", $photos[5]);
503 XML::addElement($doc, $relocate, "dfrn:micro", $photos[6]);
504 XML::addElement($doc, $relocate, "dfrn:request", $owner['request']);
505 XML::addElement($doc, $relocate, "dfrn:confirm", $owner['confirm']);
506 XML::addElement($doc, $relocate, "dfrn:notify", $owner['notify']);
507 XML::addElement($doc, $relocate, "dfrn:poll", $owner['poll']);
508 XML::addElement($doc, $relocate, "dfrn:sitepubkey", Config::get('system', 'site_pubkey'));
510 $root->appendChild($relocate);
512 return(trim($doc->saveXML()));
516 * @brief Adds the header elements for the DFRN protocol
518 * @param object $doc XML document
519 * @param array $owner Owner record
520 * @param string $authorelement Element name for the author
521 * @param string $alternatelink link to profile or category
522 * @param bool $public Is it a header for public posts?
524 * @return object XML root object
525 * @todo Add type-hints
527 private static function addHeader($doc, $owner, $authorelement, $alternatelink = "", $public = false)
530 if ($alternatelink == "") {
531 $alternatelink = $owner['url'];
534 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
535 $doc->appendChild($root);
537 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
538 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
539 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
540 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
541 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
542 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
543 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
544 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
545 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
547 XML::addElement($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
548 XML::addElement($doc, $root, "title", $owner["name"]);
550 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION];
551 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
553 $attributes = ["rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/"];
554 XML::addElement($doc, $root, "link", "", $attributes);
556 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $alternatelink];
557 XML::addElement($doc, $root, "link", "", $attributes);
561 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
562 OStatus::hublinks($doc, $root, $owner["nick"]);
564 $attributes = ["rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
565 XML::addElement($doc, $root, "link", "", $attributes);
567 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
568 XML::addElement($doc, $root, "link", "", $attributes);
570 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
571 XML::addElement($doc, $root, "link", "", $attributes);
574 // For backward compatibility we keep this element
575 if ($owner['page-flags'] == PAGE_COMMUNITY) {
576 XML::addElement($doc, $root, "dfrn:community", 1);
579 // The former element is replaced by this one
580 XML::addElement($doc, $root, "dfrn:account_type", $owner["account-type"]);
582 /// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
584 XML::addElement($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
586 $author = self::addAuthor($doc, $owner, $authorelement, $public);
587 $root->appendChild($author);
593 * @brief Adds the author element in the header for the DFRN protocol
595 * @param object $doc XML document
596 * @param array $owner Owner record
597 * @param string $authorelement Element name for the author
598 * @param boolean $public boolean
600 * @return object XML author object
601 * @todo Add type-hints
603 private static function addAuthor($doc, $owner, $authorelement, $public)
605 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
607 "SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
608 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
609 intval($owner['uid'])
611 if (DBM::is_result($r)) {
617 $author = $doc->createElement($authorelement);
619 $namdate = datetime_convert('UTC', 'UTC', $owner['name-date'].'+00:00', ATOM_TIME);
620 $uridate = datetime_convert('UTC', 'UTC', $owner['uri-date'].'+00:00', ATOM_TIME);
621 $picdate = datetime_convert('UTC', 'UTC', $owner['avatar-date'].'+00:00', ATOM_TIME);
625 if (!$public || !$hidewall) {
626 $attributes = ["dfrn:updated" => $namdate];
629 XML::addElement($doc, $author, "name", $owner["name"], $attributes);
630 XML::addElement($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
631 XML::addElement($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
633 $attributes = ["rel" => "photo", "type" => "image/jpeg",
634 "media:width" => 175, "media:height" => 175, "href" => $owner['photo']];
636 if (!$public || !$hidewall) {
637 $attributes["dfrn:updated"] = $picdate;
640 XML::addElement($doc, $author, "link", "", $attributes);
642 $attributes["rel"] = "avatar";
643 XML::addElement($doc, $author, "link", "", $attributes);
646 XML::addElement($doc, $author, "dfrn:hide", "true");
649 // The following fields will only be generated if the data isn't meant for a public feed
654 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
657 XML::addElement($doc, $author, "dfrn:birthday", $birthday);
660 // Only show contact details when we are allowed to
662 "SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
663 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
664 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
666 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
667 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
668 intval($owner['uid'])
670 if (DBM::is_result($r)) {
673 XML::addElement($doc, $author, "poco:displayName", $profile["name"]);
674 XML::addElement($doc, $author, "poco:updated", $namdate);
676 if (trim($profile["dob"]) > '0001-01-01') {
677 XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
680 XML::addElement($doc, $author, "poco:note", $profile["about"]);
681 XML::addElement($doc, $author, "poco:preferredUsername", $profile["nickname"]);
683 $savetz = date_default_timezone_get();
684 date_default_timezone_set($profile["timezone"]);
685 XML::addElement($doc, $author, "poco:utcOffset", date("P"));
686 date_default_timezone_set($savetz);
688 if (trim($profile["homepage"]) != "") {
689 $urls = $doc->createElement("poco:urls");
690 XML::addElement($doc, $urls, "poco:type", "homepage");
691 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
692 XML::addElement($doc, $urls, "poco:primary", "true");
693 $author->appendChild($urls);
696 if (trim($profile["pub_keywords"]) != "") {
697 $keywords = explode(",", $profile["pub_keywords"]);
699 foreach ($keywords as $keyword) {
700 XML::addElement($doc, $author, "poco:tags", trim($keyword));
704 if (trim($profile["xmpp"]) != "") {
705 $ims = $doc->createElement("poco:ims");
706 XML::addElement($doc, $ims, "poco:type", "xmpp");
707 XML::addElement($doc, $ims, "poco:value", $profile["xmpp"]);
708 XML::addElement($doc, $ims, "poco:primary", "true");
709 $author->appendChild($ims);
712 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
713 $element = $doc->createElement("poco:address");
715 XML::addElement($doc, $element, "poco:formatted", Profile::formatLocation($profile));
717 if (trim($profile["locality"]) != "") {
718 XML::addElement($doc, $element, "poco:locality", $profile["locality"]);
721 if (trim($profile["region"]) != "") {
722 XML::addElement($doc, $element, "poco:region", $profile["region"]);
725 if (trim($profile["country-name"]) != "") {
726 XML::addElement($doc, $element, "poco:country", $profile["country-name"]);
729 $author->appendChild($element);
737 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
739 * @param object $doc XML document
740 * @param string $element Element name for the author
741 * @param string $contact_url Link of the contact
742 * @param array $item Item elements
744 * @return object XML author object
745 * @todo Add type-hints
747 private static function addEntryAuthor($doc, $element, $contact_url, $item)
749 $contact = Contact::getDetailsByURL($contact_url, $item["uid"]);
751 $author = $doc->createElement($element);
752 XML::addElement($doc, $author, "name", $contact["name"]);
753 XML::addElement($doc, $author, "uri", $contact["url"]);
754 XML::addElement($doc, $author, "dfrn:handle", $contact["addr"]);
757 /// - Check real image type and image size
758 /// - Check which of these boths elements we should use
761 "type" => "image/jpeg",
763 "media:height" => 80,
764 "href" => $contact["photo"]];
765 XML::addElement($doc, $author, "link", "", $attributes);
769 "type" => "image/jpeg",
771 "media:height" => 80,
772 "href" => $contact["photo"]];
773 XML::addElement($doc, $author, "link", "", $attributes);
779 * @brief Adds the activity elements
781 * @param object $doc XML document
782 * @param string $element Element name for the activity
783 * @param string $activity activity value
785 * @return object XML activity object
786 * @todo Add type-hints
788 private static function createActivity($doc, $element, $activity)
791 $entry = $doc->createElement($element);
793 $r = parse_xml_string($activity, false);
798 XML::addElement($doc, $entry, "activity:object-type", $r->type);
801 XML::addElement($doc, $entry, "id", $r->id);
804 XML::addElement($doc, $entry, "title", $r->title);
808 if (substr($r->link, 0, 1) == '<') {
809 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
810 $r->link = str_replace('&', '&', $r->link);
813 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
815 // XML does need a single element as root element so we add a dummy element here
816 $data = parse_xml_string("<dummy>" . $r->link . "</dummy>", false);
817 if (is_object($data)) {
818 foreach ($data->link as $link) {
820 foreach ($link->attributes() as $parameter => $value) {
821 $attributes[$parameter] = $value;
823 XML::addElement($doc, $entry, "link", "", $attributes);
827 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
828 XML::addElement($doc, $entry, "link", "", $attributes);
832 XML::addElement($doc, $entry, "content", bbcode($r->content), ["type" => "html"]);
842 * @brief Adds the elements for attachments
844 * @param object $doc XML document
845 * @param object $root XML root
846 * @param array $item Item element
848 * @return object XML attachment object
849 * @todo Add type-hints
851 private static function getAttachment($doc, $root, $item)
853 $arr = explode('[/attach],', $item['attach']);
855 foreach ($arr as $r) {
857 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
859 $attributes = ["rel" => "enclosure",
860 "href" => $matches[1],
861 "type" => $matches[3]];
863 if (intval($matches[2])) {
864 $attributes["length"] = intval($matches[2]);
867 if (trim($matches[4]) != "") {
868 $attributes["title"] = trim($matches[4]);
871 XML::addElement($doc, $root, "link", "", $attributes);
878 * @brief Adds the "entry" elements for the DFRN protocol
880 * @param object $doc XML document
881 * @param string $type "text" or "html"
882 * @param array $item Item element
883 * @param array $owner Owner record
884 * @param bool $comment Trigger the sending of the "comment" element
885 * @param int $cid Contact ID of the recipient
886 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
888 * @return object XML entry object
889 * @todo Add type-hints
891 private static function entry($doc, $type, $item, $owner, $comment = false, $cid = 0, $single = false)
895 if (!$item['parent']) {
899 if ($item['deleted']) {
900 $attributes = ["ref" => $item['uri'], "when" => datetime_convert('UTC', 'UTC', $item['edited'] . '+00:00', ATOM_TIME)];
901 return XML::createElement($doc, "at:deleted-entry", "", $attributes);
905 $entry = $doc->createElement("entry");
907 $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry');
908 $doc->appendChild($entry);
910 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
911 $entry->setAttribute("xmlns:at", NAMESPACE_TOMB);
912 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
913 $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
914 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
915 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
916 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
917 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
918 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
921 if ($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid']) {
922 $body = fix_private_photos($item['body'], $owner['uid'], $item, $cid);
924 $body = $item['body'];
927 // Remove the abstract element. It is only locally important.
928 $body = remove_abstract($body);
930 if ($type == 'html') {
933 if ($item['title'] != "") {
934 $htmlbody = "[b]".$item['title']."[/b]\n\n".$htmlbody;
937 $htmlbody = bbcode($htmlbody, false, false, 7);
940 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
941 $entry->appendChild($author);
943 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
944 $entry->appendChild($dfrnowner);
946 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
947 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
948 $parent = q("SELECT `guid`,`plink` FROM `item` WHERE `uri` = '%s' AND `uid` = %d", dbesc($parent_item), intval($item['uid']));
949 $attributes = ["ref" => $parent_item, "type" => "text/html",
950 "href" => $parent[0]['plink'],
951 "dfrn:diaspora_guid" => $parent[0]['guid']];
952 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
955 // Add conversation data. This is used for OStatus
956 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
957 $conversation_uri = $conversation_href;
959 if (isset($parent_item)) {
960 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $item['parent-uri']);
961 if (DBM::is_result($r)) {
962 if ($r['conversation-uri'] != '') {
963 $conversation_uri = $r['conversation-uri'];
965 if ($r['conversation-href'] != '') {
966 $conversation_href = $r['conversation-href'];
972 "href" => $conversation_href,
973 "ref" => $conversation_uri];
975 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
977 XML::addElement($doc, $entry, "id", $item["uri"]);
978 XML::addElement($doc, $entry, "title", $item["title"]);
980 XML::addElement($doc, $entry, "published", datetime_convert("UTC", "UTC", $item["created"] . "+00:00", ATOM_TIME));
981 XML::addElement($doc, $entry, "updated", datetime_convert("UTC", "UTC", $item["edited"] . "+00:00", ATOM_TIME));
983 // "dfrn:env" is used to read the content
984 XML::addElement($doc, $entry, "dfrn:env", base64url_encode($body, true));
986 // The "content" field is not read by the receiver. We could remove it when the type is "text"
987 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
988 XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
990 // We save this value in "plink". Maybe we should read it from there as well?
996 ["rel" => "alternate", "type" => "text/html",
997 "href" => System::baseUrl() . "/display/" . $item["guid"]]
1000 // "comment-allow" is some old fashioned stuff for old Friendica versions.
1001 // It is included in the rewritten code for completeness
1003 XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
1006 if ($item['location']) {
1007 XML::addElement($doc, $entry, "dfrn:location", $item['location']);
1010 if ($item['coord']) {
1011 XML::addElement($doc, $entry, "georss:point", $item['coord']);
1014 if (($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])) {
1015 XML::addElement($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
1018 if ($item['extid']) {
1019 XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
1022 if ($item['bookmark']) {
1023 XML::addElement($doc, $entry, "dfrn:bookmark", "true");
1027 XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
1030 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
1032 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
1033 // It is needed for relayed comments to Diaspora.
1034 if ($item['signed_text']) {
1035 $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer']]));
1036 XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
1039 XML::addElement($doc, $entry, "activity:verb", construct_verb($item));
1041 if ($item['object-type'] != "") {
1042 XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
1043 } elseif ($item['id'] == $item['parent']) {
1044 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1046 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
1049 $actobj = self::createActivity($doc, "activity:object", $item['object']);
1051 $entry->appendChild($actobj);
1054 $actarg = self::createActivity($doc, "activity:target", $item['target']);
1056 $entry->appendChild($actarg);
1059 $tags = item_getfeedtags($item);
1062 foreach ($tags as $t) {
1063 if (($type != 'html') || ($t[0] != "@")) {
1064 XML::addElement($doc, $entry, "category", "", ["scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]]);
1070 foreach ($tags as $t) {
1072 $mentioned[$t[1]] = $t[1];
1077 foreach ($mentioned as $mention) {
1079 "SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1080 intval($owner["uid"]),
1081 dbesc(normalise_link($mention))
1084 if (DBM::is_result($r) && ($r[0]["forum"] || $r[0]["prv"])) {
1090 ["rel" => "mentioned",
1091 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1100 ["rel" => "mentioned",
1101 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1107 self::getAttachment($doc, $entry, $item);
1113 * @brief encrypts data via AES
1115 * @param string $data The data that is to be encrypted
1116 * @param string $key The AES key
1118 * @return string encrypted data
1120 private static function aesEncrypt($data, $key)
1122 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1126 * @brief decrypts data via AES
1128 * @param string $encrypted The encrypted data
1129 * @param string $key The AES key
1131 * @return string decrypted data
1133 public static function aesDecrypt($encrypted, $key)
1135 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1139 * @brief Delivers the atom content to the contacts
1141 * @param array $owner Owner record
1142 * @param array $contact Contact record of the receiver
1143 * @param string $atom Content that will be transmitted
1144 * @param bool $dissolve (to be documented)
1146 * @return int Deliver status. -1 means an error.
1147 * @todo Add array type-hint for $owner, $contact
1149 public static function deliver($owner, $contact, $atom, $dissolve = false)
1153 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1155 if ($contact['duplex'] && $contact['dfrn-id']) {
1156 $idtosend = '0:' . $orig_id;
1158 if ($contact['duplex'] && $contact['issued-id']) {
1159 $idtosend = '1:' . $orig_id;
1162 $rino = Config::get('system', 'rino_encrypt');
1163 $rino = intval($rino);
1165 logger("Local rino version: ". $rino, LOGGER_DEBUG);
1167 $ssl_val = intval(Config::get('system', 'ssl_policy'));
1171 case SSL_POLICY_FULL:
1172 $ssl_policy = 'full';
1174 case SSL_POLICY_SELFSIGN:
1175 $ssl_policy = 'self';
1177 case SSL_POLICY_NONE:
1179 $ssl_policy = 'none';
1183 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1185 logger('dfrn_deliver: ' . $url);
1187 $ret = z_fetch_url($url);
1189 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1190 return -2; // timed out
1193 $xml = $ret['body'];
1195 $curl_stat = $a->get_curl_code();
1197 return -3; // timed out
1200 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1206 if (strpos($xml, '<?xml') === false) {
1207 logger('dfrn_deliver: no valid XML returned');
1208 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1212 $res = parse_xml_string($xml);
1214 if ((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id))) {
1215 return (($res->status) ? $res->status : 3);
1219 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1220 $challenge = hex2bin((string) $res->challenge);
1221 $perm = (($res->perm) ? $res->perm : null);
1222 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1223 $rino_remote_version = intval($res->rino);
1224 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1226 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
1228 if ($owner['page-flags'] == PAGE_PRVGROUP) {
1232 $final_dfrn_id = '';
1235 if ((($perm == 'rw') && (! intval($contact['writable'])))
1236 || (($perm == 'r') && (intval($contact['writable'])))
1239 "update contact set writable = %d where id = %d",
1240 intval(($perm == 'rw') ? 1 : 0),
1241 intval($contact['id'])
1243 $contact['writable'] = (string) 1 - intval($contact['writable']);
1247 if (($contact['duplex'] && strlen($contact['pubkey']))
1248 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1249 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
1251 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
1252 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
1254 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
1255 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
1258 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1260 if (strpos($final_dfrn_id, ':') == 1) {
1261 $final_dfrn_id = substr($final_dfrn_id, 2);
1264 if ($final_dfrn_id != $orig_id) {
1265 logger('dfrn_deliver: wrong dfrn_id.');
1266 // did not decode properly - cannot trust this site
1270 $postvars['dfrn_id'] = $idtosend;
1271 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1273 $postvars['dissolve'] = '1';
1277 if ((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1278 $postvars['data'] = $atom;
1279 $postvars['perm'] = 'rw';
1281 $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
1282 $postvars['perm'] = 'r';
1285 $postvars['ssl_policy'] = $ssl_policy;
1288 $postvars['page'] = $page;
1292 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1293 logger('rino version: '. $rino_remote_version);
1295 switch ($rino_remote_version) {
1297 $key = openssl_random_pseudo_bytes(16);
1298 $data = self::aesEncrypt($postvars['data'], $key);
1301 logger("rino: invalid requested version '$rino_remote_version'");
1305 $postvars['rino'] = $rino_remote_version;
1306 $postvars['data'] = bin2hex($data);
1308 if ($dfrn_version >= 2.1) {
1309 if (($contact['duplex'] && strlen($contact['pubkey']))
1310 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1311 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
1313 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1315 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1318 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1319 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1321 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1325 logger('md5 rawkey ' . md5($postvars['key']));
1327 $postvars['key'] = bin2hex($postvars['key']);
1331 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), LOGGER_DATA);
1333 $xml = post_url($contact['notify'], $postvars);
1335 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1337 $curl_stat = $a->get_curl_code();
1338 if ((!$curl_stat) || (!strlen($xml))) {
1339 return -9; // timed out
1342 if (($curl_stat == 503) && (stristr($a->get_curl_headers(), 'retry-after'))) {
1346 if (strpos($xml, '<?xml') === false) {
1347 logger('dfrn_deliver: phase 2: no valid XML returned');
1348 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1352 if ($contact['term-date'] > NULL_DATE) {
1353 logger("dfrn_deliver: $url back from the dead - removing mark for death");
1354 Contact::unmarkForArchival($contact);
1357 $res = parse_xml_string($xml);
1359 if (!isset($res->status)) {
1363 if (!empty($res->message)) {
1364 logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1367 return intval($res->status);
1371 * @brief Add new birthday event for this person
1373 * @param array $contact Contact record
1374 * @param string $birthday Birthday of the contact
1376 * @todo Add array type-hint for $contact
1378 private static function birthdayEvent($contact, $birthday)
1380 // Check for duplicates
1382 "SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1383 intval($contact["uid"]),
1384 intval($contact["id"]),
1385 dbesc(datetime_convert("UTC", "UTC", $birthday)),
1389 if (DBM::is_result($r)) {
1393 logger("updating birthday: ".$birthday." for contact ".$contact["id"]);
1395 $bdtext = sprintf(t("%s\'s birthday"), $contact["name"]);
1396 $bdtext2 = sprintf(t("Happy Birthday %s"), " [url=".$contact["url"]."]".$contact["name"]."[/url]");
1399 "INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1400 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1401 intval($contact["uid"]),
1402 intval($contact["id"]),
1403 dbesc(datetime_convert()),
1404 dbesc(datetime_convert()),
1405 dbesc(datetime_convert("UTC", "UTC", $birthday)),
1406 dbesc(datetime_convert("UTC", "UTC", $birthday . " + 1 day ")),
1414 * @brief Fetch the author data from head or entry items
1416 * @param object $xpath XPath object
1417 * @param object $context In which context should the data be searched
1418 * @param array $importer Record of the importer user mixed with contact of the content
1419 * @param string $element Element name from which the data is fetched
1420 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1421 * @param string $xml optional, default empty
1423 * @return array Relevant data of the author
1424 * @todo Find good type-hints for all parameter
1426 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
1429 $author["name"] = $xpath->evaluate($element."/atom:name/text()", $context)->item(0)->nodeValue;
1430 $author["link"] = $xpath->evaluate($element."/atom:uri/text()", $context)->item(0)->nodeValue;
1433 "SELECT `id`, `uid`, `url`, `network`, `avatar-date`, `name-date`, `uri-date`, `addr`,
1434 `name`, `nick`, `about`, `location`, `keywords`, `xmpp`, `bdyear`, `bd`, `hidden`, `contact-type`
1435 FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
1436 intval($importer["uid"]),
1437 dbesc(normalise_link($author["link"])),
1438 dbesc(NETWORK_STATUSNET)
1441 if (DBM::is_result($r)) {
1443 $author["contact-id"] = $r[0]["id"];
1444 $author["network"] = $r[0]["network"];
1447 logger("Contact ".$author["link"]." wasn't found for user ".$importer["uid"]." XML: ".$xml, LOGGER_DEBUG);
1450 $author["contact-id"] = $importer["id"];
1451 $author["network"] = $importer["network"];
1455 // Until now we aren't serving different sizes - but maybe later
1457 /// @todo check if "avatar" or "photo" would be the best field in the specification
1458 $avatars = $xpath->query($element."/atom:link[@rel='avatar']", $context);
1459 foreach ($avatars as $avatar) {
1462 foreach ($avatar->attributes as $attributes) {
1463 /// @TODO Rewrite these similar if () to one switch
1464 if ($attributes->name == "href") {
1465 $href = $attributes->textContent;
1467 if ($attributes->name == "width") {
1468 $width = $attributes->textContent;
1470 if ($attributes->name == "updated") {
1471 $contact["avatar-date"] = $attributes->textContent;
1474 if (($width > 0) && ($href != "")) {
1475 $avatarlist[$width] = $href;
1478 if (count($avatarlist) > 0) {
1479 krsort($avatarlist);
1480 $author["avatar"] = current($avatarlist);
1483 if (DBM::is_result($r) && !$onlyfetch) {
1484 logger("Check if contact details for contact " . $r[0]["id"] . " (" . $r[0]["nick"] . ") have to be updated.", LOGGER_DEBUG);
1486 $poco = ["url" => $contact["url"]];
1488 // When was the last change to name or uri?
1489 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1490 foreach ($name_element->attributes as $attributes) {
1491 if ($attributes->name == "updated") {
1492 $poco["name-date"] = $attributes->textContent;
1496 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1497 foreach ($link_element->attributes as $attributes) {
1498 if ($attributes->name == "updated") {
1499 $poco["uri-date"] = $attributes->textContent;
1503 // Update contact data
1504 $value = $xpath->evaluate($element . "/dfrn:handle/text()", $context)->item(0)->nodeValue;
1506 $poco["addr"] = $value;
1509 $value = $xpath->evaluate($element . "/poco:displayName/text()", $context)->item(0)->nodeValue;
1511 $poco["name"] = $value;
1514 $value = $xpath->evaluate($element . "/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
1516 $poco["nick"] = $value;
1519 $value = $xpath->evaluate($element . "/poco:note/text()", $context)->item(0)->nodeValue;
1521 $poco["about"] = $value;
1524 $value = $xpath->evaluate($element . "/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
1526 $poco["location"] = $value;
1529 /// @todo Only search for elements with "poco:type" = "xmpp"
1530 $value = $xpath->evaluate($element . "/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
1532 $poco["xmpp"] = $value;
1535 /// @todo Add support for the following fields that we don't support by now in the contact table:
1536 /// - poco:utcOffset
1542 // If the "hide" element is present then the profile isn't searchable.
1543 $hide = intval($xpath->evaluate($element . "/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
1545 logger("Hidden status for contact " . $contact["url"] . ": " . $hide, LOGGER_DEBUG);
1547 // If the contact isn't searchable then set the contact to "hidden".
1548 // Problem: This can be manually overridden by the user.
1550 $contact["hidden"] = true;
1553 // Save the keywords into the contact table
1555 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1556 foreach ($tagelements as $tag) {
1557 $tags[$tag->nodeValue] = $tag->nodeValue;
1561 $poco["keywords"] = implode(", ", $tags);
1564 // "dfrn:birthday" contains the birthday converted to UTC
1565 $old_bdyear = $contact["bdyear"];
1567 $birthday = $xpath->evaluate($element . "/dfrn:birthday/text()", $context)->item(0)->nodeValue;
1569 if (strtotime($birthday) > time()) {
1570 $bd_timestamp = strtotime($birthday);
1572 $poco["bdyear"] = date("Y", $bd_timestamp);
1575 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1576 $value = $xpath->evaluate($element . "/poco:birthday/text()", $context)->item(0)->nodeValue;
1578 if (!in_array($value, ["", "0000-00-00", "0001-01-01"])) {
1579 $bdyear = date("Y");
1580 $value = str_replace("0000", $bdyear, $value);
1582 if (strtotime($value) < time()) {
1583 $value = str_replace($bdyear, $bdyear + 1, $value);
1584 $bdyear = $bdyear + 1;
1587 $poco["bd"] = $value;
1590 $contact = array_merge($contact, $poco);
1592 if ($old_bdyear != $contact["bdyear"]) {
1593 self::birthdayEvent($contact, $birthday);
1596 // Get all field names
1598 foreach ($r[0] as $field => $data) {
1599 $fields[$field] = $data;
1602 unset($fields["id"]);
1603 unset($fields["uid"]);
1604 unset($fields["url"]);
1605 unset($fields["avatar-date"]);
1606 unset($fields["name-date"]);
1607 unset($fields["uri-date"]);
1609 // Update check for this field has to be done differently
1610 $datefields = ["name-date", "uri-date"];
1611 foreach ($datefields as $field) {
1612 if (strtotime($contact[$field]) > strtotime($r[0][$field])) {
1613 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $r[0][$field] . "'", LOGGER_DEBUG);
1618 foreach ($fields as $field => $data) {
1619 if ($contact[$field] != $r[0][$field]) {
1620 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $r[0][$field] . "'", LOGGER_DEBUG);
1626 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1629 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1630 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1631 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1632 WHERE `id` = %d AND `network` = '%s'",
1633 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
1634 dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1635 dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
1636 dbesc(DBM::date($contact["name-date"])), dbesc(DBM::date($contact["uri-date"])),
1637 intval($contact["id"]), dbesc($contact["network"])
1641 Contact::updateAvatar(
1645 (strtotime($contact["avatar-date"]) > strtotime($r[0]["avatar-date"]))
1649 * The generation is a sign for the reliability of the provided data.
1650 * It is used in the socgraph.php to prevent that old contact data
1651 * that was relayed over several servers can overwrite contact
1652 * data that we received directly.
1655 $poco["generation"] = 2;
1656 $poco["photo"] = $author["avatar"];
1657 $poco["hide"] = $hide;
1658 $poco["contact-type"] = $contact["contact-type"];
1659 $gcid = GContact::update($poco);
1661 GContact::link($gcid, $importer["uid"], $contact["id"]);
1668 * @brief Transforms activity objects into an XML string
1670 * @param object $xpath XPath object
1671 * @param object $activity Activity object
1672 * @param string $element element name
1674 * @return string XML string
1675 * @todo Find good type-hints for all parameter
1677 private static function transformActivity($xpath, $activity, $element)
1679 if (!is_object($activity)) {
1683 $obj_doc = new DOMDocument("1.0", "utf-8");
1684 $obj_doc->formatOutput = true;
1686 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1688 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1689 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1691 $id = $xpath->query("atom:id", $activity)->item(0);
1692 if (is_object($id)) {
1693 $obj_element->appendChild($obj_doc->importNode($id, true));
1696 $title = $xpath->query("atom:title", $activity)->item(0);
1697 if (is_object($title)) {
1698 $obj_element->appendChild($obj_doc->importNode($title, true));
1701 $links = $xpath->query("atom:link", $activity);
1702 if (is_object($links)) {
1703 foreach ($links as $link) {
1704 $obj_element->appendChild($obj_doc->importNode($link, true));
1708 $content = $xpath->query("atom:content", $activity)->item(0);
1709 if (is_object($content)) {
1710 $obj_element->appendChild($obj_doc->importNode($content, true));
1713 $obj_doc->appendChild($obj_element);
1715 $objxml = $obj_doc->saveXML($obj_element);
1717 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1718 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1723 * @brief Processes the mail elements
1725 * @param object $xpath XPath object
1726 * @param object $mail mail elements
1727 * @param array $importer Record of the importer user mixed with contact of the content
1729 * @todo Find good type-hints for all parameter
1731 private static function processMail($xpath, $mail, $importer)
1733 logger("Processing mails");
1735 /// @TODO Rewrite this to one statement
1737 $msg["uid"] = $importer["importer_uid"];
1738 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1739 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1740 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1741 $msg["contact-id"] = $importer["id"];
1742 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1743 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1744 $msg["created"] = $xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue;
1745 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1746 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1748 $msg["replied"] = 0;
1750 dba::insert('mail', $msg);
1752 // send notifications.
1753 /// @TODO Arange this mess
1755 "type" => NOTIFY_MAIL,
1756 "notify_flags" => $importer["notify-flags"],
1757 "language" => $importer["language"],
1758 "to_name" => $importer["username"],
1759 "to_email" => $importer["email"],
1760 "uid" => $importer["importer_uid"],
1762 "source_name" => $msg["from-name"],
1763 "source_link" => $importer["url"],
1764 "source_photo" => $importer["thumb"],
1765 "verb" => ACTIVITY_POST,
1769 notification($notif_params);
1771 logger("Mail is processed, notification was sent.");
1775 * @brief Processes the suggestion elements
1777 * @param object $xpath XPath object
1778 * @param object $suggestion suggestion elements
1779 * @param array $importer Record of the importer user mixed with contact of the content
1781 * @todo Find good type-hints for all parameter
1783 private static function processSuggestion($xpath, $suggestion, $importer)
1787 logger("Processing suggestions");
1789 /// @TODO Rewrite this to one statement
1791 $suggest["uid"] = $importer["importer_uid"];
1792 $suggest["cid"] = $importer["id"];
1793 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1794 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1795 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1796 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1797 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1799 // Does our member already have a friend matching this description?
1802 "SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1803 dbesc($suggest["name"]),
1804 dbesc(normalise_link($suggest["url"])),
1805 intval($suggest["uid"])
1809 * The valid result means the friend we're about to send a friend
1810 * suggestion already has them in their contact, which means no further
1811 * action is required.
1813 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1815 if (DBM::is_result($r)) {
1819 // Do we already have an fcontact record for this person?
1823 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1824 dbesc($suggest["url"]),
1825 dbesc($suggest["name"]),
1826 dbesc($suggest["request"])
1828 if (DBM::is_result($r)) {
1831 // OK, we do. Do we already have an introduction for this person ?
1833 "SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1834 intval($suggest["uid"]),
1839 * The valid result means the friend we're about to send a friend
1840 * suggestion already has them in their contact, which means no further
1841 * action is required.
1843 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1845 if (DBM::is_result($r)) {
1851 "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1852 dbesc($suggest["name"]),
1853 dbesc($suggest["url"]),
1854 dbesc($suggest["photo"]),
1855 dbesc($suggest["request"])
1859 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1860 dbesc($suggest["url"]),
1861 dbesc($suggest["name"]),
1862 dbesc($suggest["request"])
1866 * If no record in fcontact is found, below INSERT statement will not
1867 * link an introduction to it.
1869 if (!DBM::is_result($r)) {
1870 // database record did not get created. Quietly give up.
1876 $hash = random_string();
1879 "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1880 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1881 intval($suggest["uid"]),
1883 intval($suggest["cid"]),
1884 dbesc($suggest["body"]),
1886 dbesc(datetime_convert()),
1892 "type" => NOTIFY_SUGGEST,
1893 "notify_flags" => $importer["notify-flags"],
1894 "language" => $importer["language"],
1895 "to_name" => $importer["username"],
1896 "to_email" => $importer["email"],
1897 "uid" => $importer["importer_uid"],
1899 "link" => System::baseUrl()."/notifications/intros",
1900 "source_name" => $importer["name"],
1901 "source_link" => $importer["url"],
1902 "source_photo" => $importer["photo"],
1903 "verb" => ACTIVITY_REQ_FRIEND,
1911 * @brief Processes the relocation elements
1913 * @param object $xpath XPath object
1914 * @param object $relocation relocation elements
1915 * @param array $importer Record of the importer user mixed with contact of the content
1917 * @todo Find good type-hints for all parameter
1919 private static function processRelocation($xpath, $relocation, $importer)
1921 logger("Processing relocations");
1923 /// @TODO Rewrite this to one statement
1925 $relocate["uid"] = $importer["importer_uid"];
1926 $relocate["cid"] = $importer["id"];
1927 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1928 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
1929 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1930 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
1931 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1932 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1933 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1934 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1935 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1936 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1937 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1938 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1940 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
1941 $relocate["avatar"] = $relocate["photo"];
1944 if ($relocate["addr"] == "") {
1945 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
1950 "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
1951 intval($importer["id"]),
1952 intval($importer["importer_uid"])
1955 if (!DBM::is_result($r)) {
1956 logger("Query failed to execute, no result returned in " . __FUNCTION__);
1962 // Update the gcontact entry
1963 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
1966 "UPDATE `gcontact` SET
1975 WHERE `nurl` = '%s';",
1976 dbesc($relocate["name"]),
1977 dbesc($relocate["avatar"]),
1978 dbesc($relocate["url"]),
1979 dbesc(normalise_link($relocate["url"])),
1980 dbesc($relocate["addr"]),
1981 dbesc($relocate["addr"]),
1982 dbesc($relocate["notify"]),
1983 dbesc($relocate["server_url"]),
1984 dbesc(normalise_link($old["url"]))
1987 // Update the contact table. We try to find every entry.
1989 "UPDATE `contact` SET
1999 `site-pubkey` = '%s'
2000 WHERE (`id` = %d AND `uid` = %d) OR (`nurl` = '%s');",
2001 dbesc($relocate["name"]),
2002 dbesc($relocate["avatar"]),
2003 dbesc($relocate["url"]),
2004 dbesc(normalise_link($relocate["url"])),
2005 dbesc($relocate["addr"]),
2006 dbesc($relocate["request"]),
2007 dbesc($relocate["confirm"]),
2008 dbesc($relocate["notify"]),
2009 dbesc($relocate["poll"]),
2010 dbesc($relocate["sitepubkey"]),
2011 intval($importer["id"]),
2012 intval($importer["importer_uid"]),
2013 dbesc(normalise_link($old["url"]))
2016 Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
2023 /// @todo This is an extreme performance killer
2025 'owner-link' => [$old["url"], $relocate["url"]],
2026 'author-link' => [$old["url"], $relocate["url"]],
2027 //'owner-avatar' => array($old["photo"], $relocate["photo"]),
2028 //'author-avatar' => array($old["photo"], $relocate["photo"]),
2030 foreach ($fields as $n => $f) {
2032 "SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
2035 intval($importer["importer_uid"])
2038 if (DBM::is_result($r)) {
2040 "UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
2045 intval($importer["importer_uid"])
2055 /// merge with current record, current contents have priority
2056 /// update record, set url-updated
2057 /// update profile photos
2058 /// schedule a scan?
2063 * @brief Updates an item
2065 * @param array $current the current item record
2066 * @param array $item the new item record
2067 * @param array $importer Record of the importer user mixed with contact of the content
2068 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2070 * @todo set proper type-hints (array?)
2072 private static function updateContent($current, $item, $importer, $entrytype)
2076 if (edited_timestamp_is_newer($current, $item)) {
2077 // do not accept (ignore) an earlier edit than one we currently have.
2078 if (datetime_convert("UTC", "UTC", $item["edited"]) < $current["edited"]) {
2082 $fields = ['title' => $item["title"], 'body' => $item["body"],
2083 'tag' => $item["tag"], 'changed' => datetime_convert(),
2084 'edited' => datetime_convert("UTC", "UTC", $item["edited"])];
2086 $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
2087 dba::update('item', $fields, $condition);
2089 create_tags_from_itemuri($item["uri"], $importer["importer_uid"]);
2090 update_thread_uri($item["uri"], $importer["importer_uid"]);
2094 if ($entrytype == DFRN_REPLY_RC) {
2095 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $current["id"]);
2102 * @brief Detects the entry type of the item
2104 * @param array $importer Record of the importer user mixed with contact of the content
2105 * @param array $item the new item record
2107 * @return int Is it a toplevel entry, a comment or a relayed comment?
2108 * @todo set proper type-hints (array?)
2110 private static function getEntryType($importer, $item)
2112 if ($item["parent-uri"] != $item["uri"]) {
2115 if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
2118 logger("possible community action");
2120 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2123 // was the top-level post for this action written by somebody on this site?
2124 // Specifically, the recipient?
2126 $is_a_remote_action = false;
2129 "SELECT `item`.`parent-uri` FROM `item`
2130 WHERE `item`.`uri` = '%s'
2132 dbesc($item["parent-uri"])
2134 if (DBM::is_result($r)) {
2136 "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2137 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2138 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2139 AND `item`.`uid` = %d
2142 dbesc($r[0]["parent-uri"]),
2143 dbesc($r[0]["parent-uri"]),
2144 dbesc($r[0]["parent-uri"]),
2145 intval($importer["importer_uid"])
2147 if (DBM::is_result($r)) {
2148 $is_a_remote_action = true;
2153 * Does this have the characteristics of a community or private group action?
2154 * If it's an action to a wall post on a community/prvgroup page it's a
2155 * valid community action. Also forum_mode makes it valid for sure.
2156 * If neither, it's not.
2158 if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2159 $is_a_remote_action = false;
2160 logger("not a community action");
2163 if ($is_a_remote_action) {
2164 return DFRN_REPLY_RC;
2169 return DFRN_TOP_LEVEL;
2174 * @brief Send a "poke"
2176 * @param array $item the new item record
2177 * @param array $importer Record of the importer user mixed with contact of the content
2178 * @param int $posted_id The record number of item record that was just posted
2180 * @todo set proper type-hints (array?)
2182 private static function doPoke($item, $importer, $posted_id)
2184 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2188 $xo = parse_xml_string($item["object"], false);
2190 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2191 // somebody was poked/prodded. Was it me?
2192 foreach ($xo->link as $l) {
2193 $atts = $l->attributes();
2194 switch ($atts["rel"]) {
2196 $Blink = $atts["href"];
2203 if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2204 // send a notification
2207 "type" => NOTIFY_POKE,
2208 "notify_flags" => $importer["notify-flags"],
2209 "language" => $importer["language"],
2210 "to_name" => $importer["username"],
2211 "to_email" => $importer["email"],
2212 "uid" => $importer["importer_uid"],
2214 "link" => System::baseUrl()."/display/".urlencode(get_item_guid($posted_id)),
2215 "source_name" => stripslashes($item["author-name"]),
2216 "source_link" => $item["author-link"],
2217 "source_photo" => ((link_compare($item["author-link"], $importer["url"]))
2218 ? $importer["thumb"] : $item["author-avatar"]),
2219 "verb" => $item["verb"],
2220 "otype" => "person",
2221 "activity" => $verb,
2222 "parent" => $item["parent"]]
2229 * @brief Processes several actions, depending on the verb
2231 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2232 * @param array $importer Record of the importer user mixed with contact of the content
2233 * @param array $item the new item record
2234 * @param bool $is_like Is the verb a "like"?
2236 * @return bool Should the processing of the entries be continued?
2237 * @todo set proper type-hints (array?)
2239 private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2241 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2243 if (($entrytype == DFRN_TOP_LEVEL)) {
2244 // The filling of the the "contact" variable is done for legcy reasons
2245 // The functions below are partly used by ostatus.php as well - where we have this variable
2246 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2248 $nickname = $contact["nick"];
2250 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2251 // This function once was responsible for DFRN and OStatus.
2252 if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2253 logger("New follower");
2254 new_follower($importer, $contact, $item, $nickname);
2257 if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2258 logger("Lost follower");
2259 lose_follower($importer, $contact, $item);
2262 if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2263 logger("New friend request");
2264 new_follower($importer, $contact, $item, $nickname, true);
2267 if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2268 logger("Lost sharer");
2269 lose_sharer($importer, $contact, $item);
2273 if (($item["verb"] == ACTIVITY_LIKE)
2274 || ($item["verb"] == ACTIVITY_DISLIKE)
2275 || ($item["verb"] == ACTIVITY_ATTEND)
2276 || ($item["verb"] == ACTIVITY_ATTENDNO)
2277 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
2280 $item["type"] = "activity";
2281 $item["gravity"] = GRAVITY_LIKE;
2282 // only one like or dislike per person
2283 // splitted into two queries for performance issues
2285 "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `parent-uri` = '%s' AND NOT `deleted` LIMIT 1",
2286 intval($item["uid"]),
2287 dbesc($item["author-link"]),
2288 dbesc($item["verb"]),
2289 dbesc($item["parent-uri"])
2291 if (DBM::is_result($r)) {
2296 "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `thr-parent` = '%s' AND NOT `deleted` LIMIT 1",
2297 intval($item["uid"]),
2298 dbesc($item["author-link"]),
2299 dbesc($item["verb"]),
2300 dbesc($item["parent-uri"])
2302 if (DBM::is_result($r)) {
2309 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2310 $xo = parse_xml_string($item["object"], false);
2311 $xt = parse_xml_string($item["target"], false);
2313 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2315 "SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2317 intval($importer["importer_uid"])
2320 if (!DBM::is_result($r)) {
2321 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2325 // extract tag, if not duplicate, add to parent item
2327 if (!(stristr($r[0]["tag"], trim($xo->content)))) {
2329 "UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2330 dbesc($r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2333 create_tags_from_item($r[0]["id"]);
2343 * @brief Processes the link elements
2345 * @param object $links link elements
2346 * @param array $item the item record
2348 * @todo set proper type-hints
2350 private static function parseLinks($links, &$item)
2357 foreach ($links as $link) {
2358 foreach ($link->attributes as $attributes) {
2359 switch ($attributes->name) {
2360 case "href" : $href = $attributes->textContent; break;
2361 case "rel" : $rel = $attributes->textContent; break;
2362 case "type" : $type = $attributes->textContent; break;
2363 case "length": $length = $attributes->textContent; break;
2364 case "title" : $title = $attributes->textContent; break;
2367 if (($rel != "") && ($href != "")) {
2370 $item["plink"] = $href;
2374 if (strlen($item["attach"])) {
2375 $item["attach"] .= ",";
2378 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2386 * @brief Processes the entry elements which contain the items and comments
2388 * @param array $header Array of the header elements that always stay the same
2389 * @param object $xpath XPath object
2390 * @param object $entry entry elements
2391 * @param array $importer Record of the importer user mixed with contact of the content
2392 * @param object $xml xml
2394 * @todo Add type-hints
2396 private static function processEntry($header, $xpath, $entry, $importer, $xml)
2398 logger("Processing entries");
2402 $item["protocol"] = PROTOCOL_DFRN;
2404 $item["source"] = $xml;
2407 $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
2409 $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
2412 "SELECT `id`, `uid`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2413 dbesc($item["uri"]),
2414 intval($importer["importer_uid"])
2417 // Is there an existing item?
2418 if (DBM::is_result($current) && edited_timestamp_is_newer($current[0], $item)
2419 && (datetime_convert("UTC", "UTC", $item["edited"]) < $current[0]["edited"])
2421 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2426 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2428 $item["owner-name"] = $owner["name"];
2429 $item["owner-link"] = $owner["link"];
2430 $item["owner-avatar"] = $owner["avatar"];
2433 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2435 $item["author-name"] = $author["name"];
2436 $item["author-link"] = $author["link"];
2437 $item["author-avatar"] = $author["avatar"];
2439 $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
2441 $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2443 $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
2444 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2445 // make sure nobody is trying to sneak some html tags by us
2446 $item["body"] = notags(base64url_decode($item["body"]));
2448 $item["body"] = limit_body_size($item["body"]);
2450 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2451 if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
2452 $base_url = get_app()->get_baseurl();
2453 $item['body'] = reltoabs($item['body'], $base_url);
2455 $item['body'] = html2bb_video($item['body']);
2457 $item['body'] = OEmbed::HTML2BBCode($item['body']);
2459 $config = HTMLPurifier_Config::createDefault();
2460 $config->set('Cache.DefinitionImpl', null);
2462 // we shouldn't need a whitelist, because the bbcode converter
2463 // will strip out any unsupported tags.
2465 $purifier = new HTMLPurifier($config);
2466 $item['body'] = $purifier->purify($item['body']);
2468 $item['body'] = @html2bbcode($item['body']);
2471 /// @todo We should check for a repeated post and if we know the repeated author.
2473 // We don't need the content element since "dfrn:env" is always present
2474 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2476 $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
2478 $georsspoint = $xpath->query("georss:point", $entry);
2480 $item["coord"] = $georsspoint->item(0)->nodeValue;
2483 $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
2485 $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
2487 if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true") {
2488 $item["bookmark"] = true;
2491 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2492 if ($notice_info && ($notice_info->length > 0)) {
2493 foreach ($notice_info->item(0)->attributes as $attributes) {
2494 if ($attributes->name == "source") {
2495 $item["app"] = strip_tags($attributes->textContent);
2500 $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
2502 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "item_store"
2503 $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
2504 if ($dsprsig != "") {
2505 $item["dsprsig"] = $dsprsig;
2508 $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
2510 if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "") {
2511 $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
2514 $object = $xpath->query("activity:object", $entry)->item(0);
2515 $item["object"] = self::transformActivity($xpath, $object, "object");
2517 if (trim($item["object"]) != "") {
2518 $r = parse_xml_string($item["object"], false);
2519 if (isset($r->type)) {
2520 $item["object-type"] = $r->type;
2524 $target = $xpath->query("activity:target", $entry)->item(0);
2525 $item["target"] = self::transformActivity($xpath, $target, "target");
2527 $categories = $xpath->query("atom:category", $entry);
2529 foreach ($categories as $category) {
2532 foreach ($category->attributes as $attributes) {
2533 if ($attributes->name == "term") {
2534 $term = $attributes->textContent;
2537 if ($attributes->name == "scheme") {
2538 $scheme = $attributes->textContent;
2542 if (($term != "") && ($scheme != "")) {
2543 $parts = explode(":", $scheme);
2544 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2545 $termhash = array_shift($parts);
2546 $termurl = implode(":", $parts);
2548 if (strlen($item["tag"])) {
2549 $item["tag"] .= ",";
2552 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2560 $links = $xpath->query("atom:link", $entry);
2562 self::parseLinks($links, $item);
2565 $item['conversation-uri'] = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
2567 $conv = $xpath->query('ostatus:conversation', $entry);
2568 if (is_object($conv->item(0))) {
2569 foreach ($conv->item(0)->attributes as $attributes) {
2570 if ($attributes->name == "ref") {
2571 $item['conversation-uri'] = $attributes->textContent;
2573 if ($attributes->name == "href") {
2574 $item['conversation-href'] = $attributes->textContent;
2579 // Is it a reply or a top level posting?
2580 $item["parent-uri"] = $item["uri"];
2582 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2583 if (is_object($inreplyto->item(0))) {
2584 foreach ($inreplyto->item(0)->attributes as $attributes) {
2585 if ($attributes->name == "ref") {
2586 $item["parent-uri"] = $attributes->textContent;
2591 // Get the type of the item (Top level post, reply or remote reply)
2592 $entrytype = self::getEntryType($importer, $item);
2594 // Now assign the rest of the values that depend on the type of the message
2595 if (in_array($entrytype, [DFRN_REPLY, DFRN_REPLY_RC])) {
2596 if (!isset($item["object-type"])) {
2597 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2600 if ($item["contact-id"] != $owner["contact-id"]) {
2601 $item["contact-id"] = $owner["contact-id"];
2604 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2605 $item["network"] = $owner["network"];
2608 if ($item["contact-id"] != $author["contact-id"]) {
2609 $item["contact-id"] = $author["contact-id"];
2612 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2613 $item["network"] = $author["network"];
2617 if ($entrytype == DFRN_REPLY_RC) {
2618 $item["type"] = "remote-comment";
2620 } elseif ($entrytype == DFRN_TOP_LEVEL) {
2621 if (!isset($item["object-type"])) {
2622 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2626 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2627 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2628 $ev = bbtoevent($item["body"]);
2629 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2630 logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2631 $ev["cid"] = $importer["id"];
2632 $ev["uid"] = $importer["uid"];
2633 $ev["uri"] = $item["uri"];
2634 $ev["edited"] = $item["edited"];
2635 $ev["private"] = $item["private"];
2636 $ev["guid"] = $item["guid"];
2639 "SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2640 dbesc($item["uri"]),
2641 intval($importer["uid"])
2643 if (DBM::is_result($r)) {
2644 $ev["id"] = $r[0]["id"];
2647 $event_id = event_store($ev);
2648 logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2654 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2655 logger("Exiting because 'processVerbs' told us so", LOGGER_DEBUG);
2659 // Update content if 'updated' changes
2660 if (DBM::is_result($current)) {
2661 if (self::updateContent($r[0], $item, $importer, $entrytype)) {
2662 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2664 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2669 if (in_array($entrytype, [DFRN_REPLY, DFRN_REPLY_RC])) {
2670 $posted_id = item_store($item);
2674 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2676 $item["id"] = $posted_id;
2679 "SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2681 intval($importer["importer_uid"])
2683 if (DBM::is_result($r)) {
2684 $parent = $r[0]["parent"];
2685 $parent_uri = $r[0]["parent-uri"];
2688 if ($posted_id && $parent && ($entrytype == DFRN_REPLY_RC)) {
2689 logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
2690 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $posted_id);
2695 } else { // $entrytype == DFRN_TOP_LEVEL
2696 if (!link_compare($item["owner-link"], $importer["url"])) {
2698 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2699 * but otherwise there's a possible data mixup on the sender's system.
2700 * the tgroup delivery code called from item_store will correct it if it's a forum,
2701 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2703 logger('Correcting item owner.', LOGGER_DEBUG);
2704 $item["owner-name"] = $importer["senderName"];
2705 $item["owner-link"] = $importer["url"];
2706 $item["owner-avatar"] = $importer["thumb"];
2709 if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!tgroup_check($importer["importer_uid"], $item))) {
2710 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2714 // This is my contact on another system, but it's really me.
2715 // Turn this into a wall post.
2716 $notify = item_is_remote_self($importer, $item);
2718 $posted_id = item_store($item, false, $notify);
2720 logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2722 if (stristr($item["verb"], ACTIVITY_POKE)) {
2723 self::doPoke($item, $importer, $posted_id);
2729 * @brief Deletes items
2731 * @param object $xpath XPath object
2732 * @param object $deletion deletion elements
2733 * @param array $importer Record of the importer user mixed with contact of the content
2735 * @todo set proper type-hints
2737 private static function processDeletion($xpath, $deletion, $importer)
2739 logger("Processing deletions");
2741 foreach ($deletion->attributes as $attributes) {
2742 if ($attributes->name == "ref") {
2743 $uri = $attributes->textContent;
2745 if ($attributes->name == "when") {
2746 $when = $attributes->textContent;
2750 $when = datetime_convert("UTC", "UTC", $when, "Y-m-d H:i:s");
2752 $when = datetime_convert("UTC", "UTC", "now", "Y-m-d H:i:s");
2755 if (!$uri || !$importer["id"]) {
2759 /// @todo Only select the used fields
2761 "SELECT `item`.*, `contact`.`self` FROM `item` INNER JOIN `contact` on `item`.`contact-id` = `contact`.`id`
2762 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2764 intval($importer["uid"]),
2765 intval($importer["id"])
2767 if (!DBM::is_result($r)) {
2768 logger("Item with uri " . $uri . " from contact " . $importer["id"] . " for user " . $importer["uid"] . " wasn't found.", LOGGER_DEBUG);
2773 $entrytype = self::getEntryType($importer, $item);
2775 if (!$item["deleted"]) {
2776 logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG);
2781 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2782 logger("Deleting event ".$item["event-id"], LOGGER_DEBUG);
2783 event_delete($item["event-id"]);
2786 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2787 $xo = parse_xml_string($item["object"], false);
2788 $xt = parse_xml_string($item["target"], false);
2790 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2792 "SELECT `id`, `contact-id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2794 intval($importer["importer_uid"])
2796 if (DBM::is_result($i)) {
2797 // For tags, the owner cannot remove the tag on the author's copy of the post.
2799 $owner_remove = (($item["contact-id"] == $i[0]["contact-id"]) ? true: false);
2800 $author_remove = (($item["origin"] && $item["self"]) ? true : false);
2801 $author_copy = (($item["origin"]) ? true : false);
2803 if ($owner_remove && $author_copy) {
2806 if ($author_remove || $owner_remove) {
2807 $tags = explode(',', $i[0]["tag"]);
2810 foreach ($tags as $tag) {
2811 if (trim($tag) !== trim($xo->body)) {
2812 $newtags[] = trim($tag);
2817 "UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2818 dbesc(implode(',', $newtags)),
2821 create_tags_from_item($i[0]["id"]);
2827 if ($entrytype == DFRN_TOP_LEVEL) {
2829 "UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2830 `body` = '', `title` = ''
2831 WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2833 dbesc(datetime_convert()),
2835 intval($importer["uid"])
2837 create_tags_from_itemuri($uri, $importer["uid"]);
2838 Term::createFromItemURI($uri, $importer["uid"]);
2839 update_thread_uri($uri, $importer["uid"]);
2842 "UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2843 `body` = '', `title` = ''
2844 WHERE `uri` = '%s' AND `uid` IN (0, %d)",
2846 dbesc(datetime_convert()),
2848 intval($importer["uid"])
2850 create_tags_from_itemuri($uri, $importer["uid"]);
2851 Term::createFromItemURI($uri, $importer["uid"]);
2852 update_thread_uri($uri, $importer["importer_uid"]);
2854 // if this is a relayed delete, propagate it to other recipients
2856 if ($entrytype == DFRN_REPLY_RC) {
2857 logger("Notifying followers about deletion of post " . $item["id"], LOGGER_DEBUG);
2858 Worker::add(PRIORITY_HIGH, "Notifier", "drop", $item["id"]);
2865 * @brief Imports a DFRN message
2867 * @param string $xml The DFRN message
2868 * @param array $importer Record of the importer user mixed with contact of the content
2869 * @param bool $sort_by_date Is used when feeds are polled
2870 * @return integer Import status
2871 * @todo set proper type-hints
2873 public static function import($xml, $importer, $sort_by_date = false)
2879 $doc = new DOMDocument();
2880 @$doc->loadXML($xml);
2882 $xpath = new DOMXPath($doc);
2883 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2884 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2885 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2886 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2887 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2888 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2889 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2890 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2891 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2892 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2895 $header["uid"] = $importer["uid"];
2896 $header["network"] = NETWORK_DFRN;
2897 $header["type"] = "remote";
2898 $header["wall"] = 0;
2899 $header["origin"] = 0;
2900 $header["contact-id"] = $importer["id"];
2902 // Update the contact table if the data has changed
2904 // The "atom:author" is only present in feeds
2905 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2906 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2909 // Only the "dfrn:owner" in the head section contains all data
2910 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2911 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2914 logger("Import DFRN message for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2916 // The account type is new since 3.5.1
2917 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2918 $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()")->item(0)->nodeValue);
2920 if ($accounttype != $importer["contact-type"]) {
2921 dba::update('contact', ['contact-type' => $accounttype], ['id' => $importer["id"]]);
2925 // is it a public forum? Private forums aren't supported with this method
2926 // This is deprecated since 3.5.1
2927 $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()")->item(0)->nodeValue);
2929 if ($forum != $importer["forum"]) {
2930 $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2931 dba::update('contact', ['forum' => $forum], $condition);
2934 // We are processing relocations even if we are ignoring a contact
2935 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2936 foreach ($relocations as $relocation) {
2937 self::processRelocation($xpath, $relocation, $importer);
2940 if ($importer["readonly"]) {
2941 // We aren't receiving stuff from this person. But we will quietly ignore them
2942 // rather than a blatant "go away" message.
2943 logger('ignoring contact '.$importer["id"]);
2947 $mails = $xpath->query("/atom:feed/dfrn:mail");
2948 foreach ($mails as $mail) {
2949 self::processMail($xpath, $mail, $importer);
2952 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2953 foreach ($suggestions as $suggestion) {
2954 self::processSuggestion($xpath, $suggestion, $importer);
2957 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2958 foreach ($deletions as $deletion) {
2959 self::processDeletion($xpath, $deletion, $importer);
2962 if (!$sort_by_date) {
2963 $entries = $xpath->query("/atom:feed/atom:entry");
2964 foreach ($entries as $entry) {
2965 self::processEntry($header, $xpath, $entry, $importer, $xml);
2969 $entries = $xpath->query("/atom:feed/atom:entry");
2970 foreach ($entries as $entry) {
2971 $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2972 $newentries[strtotime($created)] = $entry;
2975 // Now sort after the publishing date
2978 foreach ($newentries as $entry) {
2979 self::processEntry($header, $xpath, $entry, $importer, $xml);
2982 logger("Import done for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2988 * @param string $contact_nick contact nickname
2990 public static function autoRedir(App $a, $contact_nick)
2993 if (x($_REQUEST, 'redir') && intval($_REQUEST['redir'])) {
2997 if ((! $contact_nick) || ($contact_nick === $a->user['nickname'])) {
3002 // We need to find out if $contact_nick is a user on this hub, and if so, if I
3003 // am a contact of that user. However, that user may have other contacts with the
3004 // same nickname as me on other hubs or other networks. Exclude these by requiring
3005 // that the contact have a local URL. I will be the only person with my nickname at
3006 // this URL, so if a result is found, then I am a contact of the $contact_nick user.
3008 // We also have to make sure that I'm a legitimate contact--I'm not blocked or pending.
3010 $baseurl = System::baseUrl();
3011 $domain_st = strpos($baseurl, "://");
3012 if ($domain_st === false) {
3015 $baseurl = substr($baseurl, $domain_st + 3);
3016 $nurl = normalise_link($baseurl);
3018 /// @todo Why is there a query for "url" *and* "nurl"? Especially this normalising is strange.
3019 $r = q("SELECT `id` FROM `contact` WHERE `uid` = (SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1)
3020 AND `nick` = '%s' AND NOT `self` AND (`url` LIKE '%%%s%%' OR `nurl` LIKE '%%%s%%') AND NOT `blocked` AND NOT `pending` LIMIT 1",
3021 dbesc($contact_nick),
3022 dbesc($a->user['nickname']),
3026 if ((! DBM::is_result($r)) || $r[0]['id'] == remote_user()) {
3030 $r = q("SELECT * FROM contact WHERE nick = '%s'
3031 AND network = '%s' AND uid = %d AND url LIKE '%%%s%%' LIMIT 1",
3032 dbesc($contact_nick),
3033 dbesc(NETWORK_DFRN),
3034 intval(local_user()),
3037 if (! DBM::is_result($r)) {
3043 $dfrn_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
3045 if ($r[0]['duplex'] && $r[0]['issued-id']) {
3046 $orig_id = $r[0]['issued-id'];
3047 $dfrn_id = '1:' . $orig_id;
3049 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
3050 $orig_id = $r[0]['dfrn-id'];
3051 $dfrn_id = '0:' . $orig_id;
3054 // ensure that we've got a valid ID. There may be some edge cases with forums and non-duplex mode
3055 // that may have triggered some of the "went to {profile/intro} and got an RSS feed" issues
3057 if (strlen($dfrn_id) < 3) {
3061 $sec = random_string();
3063 dba::insert('profile_check', ['uid' => local_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id, 'sec' => $sec, 'expire' => time() + 45]);
3065 $url = curPageURL();
3067 logger('auto_redir: ' . $r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
3068 $dest = (($url) ? '&destination_url=' . $url : '');
3069 goaway($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
3070 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest);