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;
11 use Defuse\Crypto\Crypto;
12 use Defuse\Crypto\Exception\EnvironmentIsBrokenException;
13 use Defuse\Crypto\Key;
15 use Friendica\Content\OEmbed;
16 use Friendica\Core\Config;
17 use Friendica\Core\System;
18 use Friendica\Core\Worker;
19 use Friendica\Database\DBM;
20 use Friendica\Model\Contact;
21 use Friendica\Model\GContact;
22 use Friendica\Model\Group;
23 use Friendica\Model\Profile;
24 use Friendica\Model\Term;
25 use Friendica\Model\User;
26 use Friendica\Object\Image;
27 use Friendica\Protocol\OStatus;
28 use Friendica\Util\Crypto as FriendicaCrypto;
29 use Friendica\Util\XML;
35 use HTMLPurifier_Config;
37 require_once 'boot.php';
38 require_once 'include/dba.php';
39 require_once "include/enotify.php";
40 require_once "include/threads.php";
41 require_once "include/items.php";
42 require_once "include/tags.php";
43 require_once "include/event.php";
44 require_once "include/text.php";
45 require_once "include/html2bbcode.php";
46 require_once "include/bbcode.php";
49 * @brief This class contain functions to create and send DFRN XML files
54 const DFRN_TOP_LEVEL = 0; // Top level posting
55 const DFRN_REPLY = 1; // Regular reply that is stored locally
56 const DFRN_REPLY_RC = 2; // Reply that will be relayed
59 * @brief Generates the atom entries for delivery.php
61 * This function is used whenever content is transmitted via DFRN.
63 * @param array $items Item elements
64 * @param array $owner Owner record
66 * @return string DFRN entries
67 * @todo Add type-hints
69 public static function entries($items, $owner)
71 $doc = new DOMDocument('1.0', 'utf-8');
72 $doc->formatOutput = true;
74 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
76 if (! count($items)) {
77 return trim($doc->saveXML());
80 foreach ($items as $item) {
81 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
82 $root->appendChild($entry);
85 return(trim($doc->saveXML()));
89 * @brief Generate an atom feed for the given user
91 * This function is called when another server is pulling data from the user feed.
93 * @param string $dfrn_id DFRN ID from the requesting party
94 * @param string $owner_nick Owner nick name
95 * @param string $last_update Date of the last update
96 * @param int $direction Can be -1, 0 or 1.
97 * @param boolean $onlyheader Output only the header without content? (Default is "no")
99 * @return string DFRN feed entries
101 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false)
105 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
106 $public_feed = (($dfrn_id) ? false : true);
107 $starred = false; // not yet implemented, possible security issues
110 if ($public_feed && $a->argc > 2) {
111 for ($x = 2; $x < $a->argc; $x++) {
112 if ($a->argv[$x] == 'converse') {
115 if ($a->argv[$x] == 'starred') {
118 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
119 $category = $a->argv[$x+1];
126 // default permissions - anonymous user
128 $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = '' ";
131 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
132 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
133 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
137 if (! DBM::is_result($r)) {
142 $owner_id = $owner['uid'];
143 $owner_nick = $owner['nickname'];
145 $sql_post_table = "";
147 if (! $public_feed) {
149 switch ($direction) {
151 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
155 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
156 $my_id = '1:' . $dfrn_id;
159 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
160 $my_id = '0:' . $dfrn_id;
168 "SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
172 if (! DBM::is_result($r)) {
177 include_once 'include/security.php';
178 $groups = Group::getIdsByContactId($contact['id']);
180 if (count($groups)) {
181 for ($x = 0; $x < count($groups); $x ++)
182 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
183 $gs = implode('|', $groups);
185 $gs = '<<>>' ; // Impossible to match
188 $sql_extra = sprintf(
190 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
191 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
192 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
193 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
195 intval($contact['id']),
196 intval($contact['id']),
208 if (! strlen($last_update)) {
209 $last_update = 'now -30 days';
212 if (isset($category)) {
213 $sql_post_table = sprintf(
214 "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` ",
215 dbesc(protect_sprintf($category)),
216 intval(TERM_OBJ_POST),
217 intval(TERM_CATEGORY),
220 //$sql_extra .= file_tag_file_query('item',$category,'category');
225 $sql_extra .= " AND `contact`.`self` = 1 ";
229 $check_date = datetime_convert('UTC', 'UTC', $last_update, 'Y-m-d H:i:s');
232 "SELECT `item`.*, `item`.`id` AS `item_id`,
233 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
234 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
235 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
236 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
237 FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
238 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
239 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
240 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
241 WHERE `item`.`uid` = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
242 AND `item`.`wall` AND `item`.`changed` > '%s'
244 ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
251 * Will check further below if this actually returned results.
252 * We will provide an empty feed if that is the case.
257 $doc = new DOMDocument('1.0', 'utf-8');
258 $doc->formatOutput = true;
260 $alternatelink = $owner['url'];
262 if (isset($category)) {
263 $alternatelink .= "/category/".$category;
267 $author = "dfrn:owner";
272 $root = self::addHeader($doc, $owner, $author, $alternatelink, true);
274 /// @TODO This hook can't work anymore
275 // call_hooks('atom_feed', $atom);
277 if (!DBM::is_result($items) || $onlyheader) {
278 $atom = trim($doc->saveXML());
280 call_hooks('atom_feed_end', $atom);
285 foreach ($items as $item) {
286 // prevent private email from leaking.
287 if ($item['network'] == NETWORK_MAIL) {
291 // public feeds get html, our own nodes use bbcode
295 // catch any email that's in a public conversation and make sure it doesn't leak
296 if ($item['private']) {
303 $entry = self::entry($doc, $type, $item, $owner, true);
304 $root->appendChild($entry);
307 $atom = trim($doc->saveXML());
309 call_hooks('atom_feed_end', $atom);
315 * @brief Generate an atom entry for a given item id
317 * @param int $item_id The item id
318 * @param boolean $conversation Show the conversation. If false show the single post.
320 * @return string DFRN feed entry
322 public static function itemFeed($item_id, $conversation = false)
325 $condition = '`item`.`parent`';
327 $condition = '`item`.`id`';
331 "SELECT `item`.*, `item`.`id` AS `item_id`,
332 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
333 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
334 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
335 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
337 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
338 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
339 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
340 WHERE %s = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
341 AND NOT `item`.`private`",
346 if (!DBM::is_result($r)) {
353 if ($item['uid'] != 0) {
354 $owner = User::getOwnerDataById($item['uid']);
359 $owner = ['uid' => 0, 'nick' => 'feed-item'];
362 $doc = new DOMDocument('1.0', 'utf-8');
363 $doc->formatOutput = true;
367 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
368 $doc->appendChild($root);
370 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
371 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
372 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
373 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
374 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
375 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
376 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
377 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
378 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
380 //$root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
382 foreach ($items as $item) {
383 $entry = self::entry($doc, $type, $item, $owner, true, 0);
384 $root->appendChild($entry);
387 $root = self::entry($doc, $type, $item, $owner, true, 0, true);
390 $atom = trim($doc->saveXML());
395 * @brief Create XML text for DFRN mails
397 * @param array $item message elements
398 * @param array $owner Owner record
400 * @return string DFRN mail
401 * @todo Add type-hints
403 public static function mail($item, $owner)
405 $doc = new DOMDocument('1.0', 'utf-8');
406 $doc->formatOutput = true;
408 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
410 $mail = $doc->createElement("dfrn:mail");
411 $sender = $doc->createElement("dfrn:sender");
413 XML::addElement($doc, $sender, "dfrn:name", $owner['name']);
414 XML::addElement($doc, $sender, "dfrn:uri", $owner['url']);
415 XML::addElement($doc, $sender, "dfrn:avatar", $owner['thumb']);
417 $mail->appendChild($sender);
419 XML::addElement($doc, $mail, "dfrn:id", $item['uri']);
420 XML::addElement($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
421 XML::addElement($doc, $mail, "dfrn:sentdate", datetime_convert('UTC', 'UTC', $item['created'] . '+00:00', ATOM_TIME));
422 XML::addElement($doc, $mail, "dfrn:subject", $item['title']);
423 XML::addElement($doc, $mail, "dfrn:content", $item['body']);
425 $root->appendChild($mail);
427 return(trim($doc->saveXML()));
431 * @brief Create XML text for DFRN friend suggestions
433 * @param array $item suggestion elements
434 * @param array $owner Owner record
436 * @return string DFRN suggestions
437 * @todo Add type-hints
439 public static function fsuggest($item, $owner)
441 $doc = new DOMDocument('1.0', 'utf-8');
442 $doc->formatOutput = true;
444 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
446 $suggest = $doc->createElement("dfrn:suggest");
448 XML::addElement($doc, $suggest, "dfrn:url", $item['url']);
449 XML::addElement($doc, $suggest, "dfrn:name", $item['name']);
450 XML::addElement($doc, $suggest, "dfrn:photo", $item['photo']);
451 XML::addElement($doc, $suggest, "dfrn:request", $item['request']);
452 XML::addElement($doc, $suggest, "dfrn:note", $item['note']);
454 $root->appendChild($suggest);
456 return(trim($doc->saveXML()));
460 * @brief Create XML text for DFRN relocations
462 * @param array $owner Owner record
463 * @param int $uid User ID
465 * @return string DFRN relocations
466 * @todo Add type-hints
468 public static function relocate($owner, $uid)
471 /* get site pubkey. this could be a new installation with no site keys*/
472 $pubkey = Config::get('system', 'site_pubkey');
474 $res = FriendicaCrypto::newKeypair(2048);
475 Config::set('system', 'site_prvkey', $res['prvkey']);
476 Config::set('system', 'site_pubkey', $res['pubkey']);
480 "SELECT `resource-id` , `scale`, type FROM `photo`
481 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;",
485 $ext = Image::supportedTypes();
487 foreach ($rp as $p) {
488 $photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
493 $doc = new DOMDocument('1.0', 'utf-8');
494 $doc->formatOutput = true;
496 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
498 $relocate = $doc->createElement("dfrn:relocate");
500 XML::addElement($doc, $relocate, "dfrn:url", $owner['url']);
501 XML::addElement($doc, $relocate, "dfrn:name", $owner['name']);
502 XML::addElement($doc, $relocate, "dfrn:addr", $owner['addr']);
503 XML::addElement($doc, $relocate, "dfrn:avatar", $owner['avatar']);
504 XML::addElement($doc, $relocate, "dfrn:photo", $photos[4]);
505 XML::addElement($doc, $relocate, "dfrn:thumb", $photos[5]);
506 XML::addElement($doc, $relocate, "dfrn:micro", $photos[6]);
507 XML::addElement($doc, $relocate, "dfrn:request", $owner['request']);
508 XML::addElement($doc, $relocate, "dfrn:confirm", $owner['confirm']);
509 XML::addElement($doc, $relocate, "dfrn:notify", $owner['notify']);
510 XML::addElement($doc, $relocate, "dfrn:poll", $owner['poll']);
511 XML::addElement($doc, $relocate, "dfrn:sitepubkey", Config::get('system', 'site_pubkey'));
513 $root->appendChild($relocate);
515 return(trim($doc->saveXML()));
519 * @brief Adds the header elements for the DFRN protocol
521 * @param object $doc XML document
522 * @param array $owner Owner record
523 * @param string $authorelement Element name for the author
524 * @param string $alternatelink link to profile or category
525 * @param bool $public Is it a header for public posts?
527 * @return object XML root object
528 * @todo Add type-hints
530 private static function addHeader($doc, $owner, $authorelement, $alternatelink = "", $public = false)
533 if ($alternatelink == "") {
534 $alternatelink = $owner['url'];
537 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
538 $doc->appendChild($root);
540 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
541 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
542 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
543 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
544 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
545 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
546 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
547 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
548 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
550 XML::addElement($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
551 XML::addElement($doc, $root, "title", $owner["name"]);
553 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION];
554 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
556 $attributes = ["rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/"];
557 XML::addElement($doc, $root, "link", "", $attributes);
559 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $alternatelink];
560 XML::addElement($doc, $root, "link", "", $attributes);
564 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
565 OStatus::hublinks($doc, $root, $owner["nick"]);
567 $attributes = ["rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
568 XML::addElement($doc, $root, "link", "", $attributes);
570 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
571 XML::addElement($doc, $root, "link", "", $attributes);
573 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
574 XML::addElement($doc, $root, "link", "", $attributes);
577 // For backward compatibility we keep this element
578 if ($owner['page-flags'] == PAGE_COMMUNITY) {
579 XML::addElement($doc, $root, "dfrn:community", 1);
582 // The former element is replaced by this one
583 XML::addElement($doc, $root, "dfrn:account_type", $owner["account-type"]);
585 /// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
587 XML::addElement($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
589 $author = self::addAuthor($doc, $owner, $authorelement, $public);
590 $root->appendChild($author);
596 * @brief Adds the author element in the header for the DFRN protocol
598 * @param object $doc XML document
599 * @param array $owner Owner record
600 * @param string $authorelement Element name for the author
601 * @param boolean $public boolean
603 * @return object XML author object
604 * @todo Add type-hints
606 private static function addAuthor($doc, $owner, $authorelement, $public)
608 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
610 "SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
611 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
612 intval($owner['uid'])
614 if (DBM::is_result($r)) {
620 $author = $doc->createElement($authorelement);
622 $namdate = datetime_convert('UTC', 'UTC', $owner['name-date'].'+00:00', ATOM_TIME);
623 $uridate = datetime_convert('UTC', 'UTC', $owner['uri-date'].'+00:00', ATOM_TIME);
624 $picdate = datetime_convert('UTC', 'UTC', $owner['avatar-date'].'+00:00', ATOM_TIME);
628 if (!$public || !$hidewall) {
629 $attributes = ["dfrn:updated" => $namdate];
632 XML::addElement($doc, $author, "name", $owner["name"], $attributes);
633 XML::addElement($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
634 XML::addElement($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
636 $attributes = ["rel" => "photo", "type" => "image/jpeg",
637 "media:width" => 175, "media:height" => 175, "href" => $owner['photo']];
639 if (!$public || !$hidewall) {
640 $attributes["dfrn:updated"] = $picdate;
643 XML::addElement($doc, $author, "link", "", $attributes);
645 $attributes["rel"] = "avatar";
646 XML::addElement($doc, $author, "link", "", $attributes);
649 XML::addElement($doc, $author, "dfrn:hide", "true");
652 // The following fields will only be generated if the data isn't meant for a public feed
657 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
660 XML::addElement($doc, $author, "dfrn:birthday", $birthday);
663 // Only show contact details when we are allowed to
665 "SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
666 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
667 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
669 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
670 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
671 intval($owner['uid'])
673 if (DBM::is_result($r)) {
676 XML::addElement($doc, $author, "poco:displayName", $profile["name"]);
677 XML::addElement($doc, $author, "poco:updated", $namdate);
679 if (trim($profile["dob"]) > '0001-01-01') {
680 XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
683 XML::addElement($doc, $author, "poco:note", $profile["about"]);
684 XML::addElement($doc, $author, "poco:preferredUsername", $profile["nickname"]);
686 $savetz = date_default_timezone_get();
687 date_default_timezone_set($profile["timezone"]);
688 XML::addElement($doc, $author, "poco:utcOffset", date("P"));
689 date_default_timezone_set($savetz);
691 if (trim($profile["homepage"]) != "") {
692 $urls = $doc->createElement("poco:urls");
693 XML::addElement($doc, $urls, "poco:type", "homepage");
694 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
695 XML::addElement($doc, $urls, "poco:primary", "true");
696 $author->appendChild($urls);
699 if (trim($profile["pub_keywords"]) != "") {
700 $keywords = explode(",", $profile["pub_keywords"]);
702 foreach ($keywords as $keyword) {
703 XML::addElement($doc, $author, "poco:tags", trim($keyword));
707 if (trim($profile["xmpp"]) != "") {
708 $ims = $doc->createElement("poco:ims");
709 XML::addElement($doc, $ims, "poco:type", "xmpp");
710 XML::addElement($doc, $ims, "poco:value", $profile["xmpp"]);
711 XML::addElement($doc, $ims, "poco:primary", "true");
712 $author->appendChild($ims);
715 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
716 $element = $doc->createElement("poco:address");
718 XML::addElement($doc, $element, "poco:formatted", Profile::formatLocation($profile));
720 if (trim($profile["locality"]) != "") {
721 XML::addElement($doc, $element, "poco:locality", $profile["locality"]);
724 if (trim($profile["region"]) != "") {
725 XML::addElement($doc, $element, "poco:region", $profile["region"]);
728 if (trim($profile["country-name"]) != "") {
729 XML::addElement($doc, $element, "poco:country", $profile["country-name"]);
732 $author->appendChild($element);
740 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
742 * @param object $doc XML document
743 * @param string $element Element name for the author
744 * @param string $contact_url Link of the contact
745 * @param array $item Item elements
747 * @return object XML author object
748 * @todo Add type-hints
750 private static function addEntryAuthor($doc, $element, $contact_url, $item)
752 $contact = Contact::getDetailsByURL($contact_url, $item["uid"]);
754 $author = $doc->createElement($element);
755 XML::addElement($doc, $author, "name", $contact["name"]);
756 XML::addElement($doc, $author, "uri", $contact["url"]);
757 XML::addElement($doc, $author, "dfrn:handle", $contact["addr"]);
760 /// - Check real image type and image size
761 /// - Check which of these boths elements we should use
764 "type" => "image/jpeg",
766 "media:height" => 80,
767 "href" => $contact["photo"]];
768 XML::addElement($doc, $author, "link", "", $attributes);
772 "type" => "image/jpeg",
774 "media:height" => 80,
775 "href" => $contact["photo"]];
776 XML::addElement($doc, $author, "link", "", $attributes);
782 * @brief Adds the activity elements
784 * @param object $doc XML document
785 * @param string $element Element name for the activity
786 * @param string $activity activity value
788 * @return object XML activity object
789 * @todo Add type-hints
791 private static function createActivity($doc, $element, $activity)
794 $entry = $doc->createElement($element);
796 $r = parse_xml_string($activity, false);
801 XML::addElement($doc, $entry, "activity:object-type", $r->type);
804 XML::addElement($doc, $entry, "id", $r->id);
807 XML::addElement($doc, $entry, "title", $r->title);
811 if (substr($r->link, 0, 1) == '<') {
812 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
813 $r->link = str_replace('&', '&', $r->link);
816 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
818 // XML does need a single element as root element so we add a dummy element here
819 $data = parse_xml_string("<dummy>" . $r->link . "</dummy>", false);
820 if (is_object($data)) {
821 foreach ($data->link as $link) {
823 foreach ($link->attributes() as $parameter => $value) {
824 $attributes[$parameter] = $value;
826 XML::addElement($doc, $entry, "link", "", $attributes);
830 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
831 XML::addElement($doc, $entry, "link", "", $attributes);
835 XML::addElement($doc, $entry, "content", bbcode($r->content), ["type" => "html"]);
845 * @brief Adds the elements for attachments
847 * @param object $doc XML document
848 * @param object $root XML root
849 * @param array $item Item element
851 * @return object XML attachment object
852 * @todo Add type-hints
854 private static function getAttachment($doc, $root, $item)
856 $arr = explode('[/attach],', $item['attach']);
858 foreach ($arr as $r) {
860 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
862 $attributes = ["rel" => "enclosure",
863 "href" => $matches[1],
864 "type" => $matches[3]];
866 if (intval($matches[2])) {
867 $attributes["length"] = intval($matches[2]);
870 if (trim($matches[4]) != "") {
871 $attributes["title"] = trim($matches[4]);
874 XML::addElement($doc, $root, "link", "", $attributes);
881 * @brief Adds the "entry" elements for the DFRN protocol
883 * @param object $doc XML document
884 * @param string $type "text" or "html"
885 * @param array $item Item element
886 * @param array $owner Owner record
887 * @param bool $comment Trigger the sending of the "comment" element
888 * @param int $cid Contact ID of the recipient
889 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
891 * @return object XML entry object
892 * @todo Add type-hints
894 private static function entry($doc, $type, $item, $owner, $comment = false, $cid = 0, $single = false)
898 if (!$item['parent']) {
902 if ($item['deleted']) {
903 $attributes = ["ref" => $item['uri'], "when" => datetime_convert('UTC', 'UTC', $item['edited'] . '+00:00', ATOM_TIME)];
904 return XML::createElement($doc, "at:deleted-entry", "", $attributes);
908 $entry = $doc->createElement("entry");
910 $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry');
911 $doc->appendChild($entry);
913 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
914 $entry->setAttribute("xmlns:at", NAMESPACE_TOMB);
915 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
916 $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
917 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
918 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
919 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
920 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
921 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
924 if ($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid']) {
925 $body = fix_private_photos($item['body'], $owner['uid'], $item, $cid);
927 $body = $item['body'];
930 // Remove the abstract element. It is only locally important.
931 $body = remove_abstract($body);
933 if ($type == 'html') {
936 if ($item['title'] != "") {
937 $htmlbody = "[b]".$item['title']."[/b]\n\n".$htmlbody;
940 $htmlbody = bbcode($htmlbody, false, false, 7);
943 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
944 $entry->appendChild($author);
946 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
947 $entry->appendChild($dfrnowner);
949 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
950 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
951 $parent = q("SELECT `guid`,`plink` FROM `item` WHERE `uri` = '%s' AND `uid` = %d", dbesc($parent_item), intval($item['uid']));
952 $attributes = ["ref" => $parent_item, "type" => "text/html",
953 "href" => $parent[0]['plink'],
954 "dfrn:diaspora_guid" => $parent[0]['guid']];
955 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
958 // Add conversation data. This is used for OStatus
959 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
960 $conversation_uri = $conversation_href;
962 if (isset($parent_item)) {
963 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $item['parent-uri']);
964 if (DBM::is_result($r)) {
965 if ($r['conversation-uri'] != '') {
966 $conversation_uri = $r['conversation-uri'];
968 if ($r['conversation-href'] != '') {
969 $conversation_href = $r['conversation-href'];
975 "href" => $conversation_href,
976 "ref" => $conversation_uri];
978 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
980 XML::addElement($doc, $entry, "id", $item["uri"]);
981 XML::addElement($doc, $entry, "title", $item["title"]);
983 XML::addElement($doc, $entry, "published", datetime_convert("UTC", "UTC", $item["created"] . "+00:00", ATOM_TIME));
984 XML::addElement($doc, $entry, "updated", datetime_convert("UTC", "UTC", $item["edited"] . "+00:00", ATOM_TIME));
986 // "dfrn:env" is used to read the content
987 XML::addElement($doc, $entry, "dfrn:env", base64url_encode($body, true));
989 // The "content" field is not read by the receiver. We could remove it when the type is "text"
990 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
991 XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
993 // We save this value in "plink". Maybe we should read it from there as well?
999 ["rel" => "alternate", "type" => "text/html",
1000 "href" => System::baseUrl() . "/display/" . $item["guid"]]
1003 // "comment-allow" is some old fashioned stuff for old Friendica versions.
1004 // It is included in the rewritten code for completeness
1006 XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
1009 if ($item['location']) {
1010 XML::addElement($doc, $entry, "dfrn:location", $item['location']);
1013 if ($item['coord']) {
1014 XML::addElement($doc, $entry, "georss:point", $item['coord']);
1017 if (($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])) {
1018 XML::addElement($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
1021 if ($item['extid']) {
1022 XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
1025 if ($item['bookmark']) {
1026 XML::addElement($doc, $entry, "dfrn:bookmark", "true");
1030 XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
1033 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
1035 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
1036 // It is needed for relayed comments to Diaspora.
1037 if ($item['signed_text']) {
1038 $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer']]));
1039 XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
1042 XML::addElement($doc, $entry, "activity:verb", construct_verb($item));
1044 if ($item['object-type'] != "") {
1045 XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
1046 } elseif ($item['id'] == $item['parent']) {
1047 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1049 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
1052 $actobj = self::createActivity($doc, "activity:object", $item['object']);
1054 $entry->appendChild($actobj);
1057 $actarg = self::createActivity($doc, "activity:target", $item['target']);
1059 $entry->appendChild($actarg);
1062 $tags = item_getfeedtags($item);
1065 foreach ($tags as $t) {
1066 if (($type != 'html') || ($t[0] != "@")) {
1067 XML::addElement($doc, $entry, "category", "", ["scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]]);
1073 foreach ($tags as $t) {
1075 $mentioned[$t[1]] = $t[1];
1080 foreach ($mentioned as $mention) {
1082 "SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1083 intval($owner["uid"]),
1084 dbesc(normalise_link($mention))
1087 if (DBM::is_result($r) && ($r[0]["forum"] || $r[0]["prv"])) {
1093 ["rel" => "mentioned",
1094 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1103 ["rel" => "mentioned",
1104 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1110 self::getAttachment($doc, $entry, $item);
1116 * @brief encrypts data via AES
1118 * @param string $data The data that is to be encrypted
1119 * @param string $key The AES key
1121 * @return string encrypted data
1123 private static function aesEncrypt($data, $key)
1125 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1129 * @brief decrypts data via AES
1131 * @param string $encrypted The encrypted data
1132 * @param string $key The AES key
1134 * @return string decrypted data
1136 public static function aesDecrypt($encrypted, $key)
1138 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1142 * @brief Delivers the atom content to the contacts
1144 * @param array $owner Owner record
1145 * @param array $contact Contact record of the receiver
1146 * @param string $atom Content that will be transmitted
1147 * @param bool $dissolve (to be documented)
1149 * @return int Deliver status. -1 means an error.
1150 * @todo Add array type-hint for $owner, $contact
1152 public static function deliver($owner, $contact, $atom, $dissolve = false)
1156 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1158 if ($contact['duplex'] && $contact['dfrn-id']) {
1159 $idtosend = '0:' . $orig_id;
1161 if ($contact['duplex'] && $contact['issued-id']) {
1162 $idtosend = '1:' . $orig_id;
1165 $rino = Config::get('system', 'rino_encrypt');
1166 $rino = intval($rino);
1168 logger("Local rino version: ". $rino, LOGGER_DEBUG);
1170 $ssl_val = intval(Config::get('system', 'ssl_policy'));
1174 case SSL_POLICY_FULL:
1175 $ssl_policy = 'full';
1177 case SSL_POLICY_SELFSIGN:
1178 $ssl_policy = 'self';
1180 case SSL_POLICY_NONE:
1182 $ssl_policy = 'none';
1186 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1188 logger('dfrn_deliver: ' . $url);
1190 $ret = z_fetch_url($url);
1192 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1193 return -2; // timed out
1196 $xml = $ret['body'];
1198 $curl_stat = $a->get_curl_code();
1200 return -3; // timed out
1203 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1209 if (strpos($xml, '<?xml') === false) {
1210 logger('dfrn_deliver: no valid XML returned');
1211 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1215 $res = parse_xml_string($xml);
1217 if ((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id))) {
1218 return (($res->status) ? $res->status : 3);
1222 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1223 $challenge = hex2bin((string) $res->challenge);
1224 $perm = (($res->perm) ? $res->perm : null);
1225 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1226 $rino_remote_version = intval($res->rino);
1227 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1229 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
1231 if ($owner['page-flags'] == PAGE_PRVGROUP) {
1235 $final_dfrn_id = '';
1238 if ((($perm == 'rw') && (! intval($contact['writable'])))
1239 || (($perm == 'r') && (intval($contact['writable'])))
1242 "update contact set writable = %d where id = %d",
1243 intval(($perm == 'rw') ? 1 : 0),
1244 intval($contact['id'])
1246 $contact['writable'] = (string) 1 - intval($contact['writable']);
1250 if (($contact['duplex'] && strlen($contact['pubkey']))
1251 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1252 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
1254 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
1255 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
1257 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
1258 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
1261 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1263 if (strpos($final_dfrn_id, ':') == 1) {
1264 $final_dfrn_id = substr($final_dfrn_id, 2);
1267 if ($final_dfrn_id != $orig_id) {
1268 logger('dfrn_deliver: wrong dfrn_id.');
1269 // did not decode properly - cannot trust this site
1273 $postvars['dfrn_id'] = $idtosend;
1274 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1276 $postvars['dissolve'] = '1';
1280 if ((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1281 $postvars['data'] = $atom;
1282 $postvars['perm'] = 'rw';
1284 $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
1285 $postvars['perm'] = 'r';
1288 $postvars['ssl_policy'] = $ssl_policy;
1291 $postvars['page'] = $page;
1295 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1296 logger('rino version: '. $rino_remote_version);
1298 switch ($rino_remote_version) {
1302 $rino_remote_version = 1;
1303 // Deprecated rino version!
1304 $key = openssl_random_pseudo_bytes(16);
1305 $data = self::aesEncrypt($postvars['data'], $key);
1309 $KeyObject = Key::createNewRandomKey();
1310 } catch (EnvironmentIsBrokenException $ex) {
1311 logger('Cannot safely create a key');
1316 $data = Crypto::encrypt($postvars['data'], $key);
1317 } catch (EnvironmentIsBrokenException $ex) {
1318 logger('Cannot safely perform encryption');
1322 $key = $KeyObject->saveToAsciiSafeString();
1325 logger("rino: invalid requested version '$rino_remote_version'");
1329 $postvars['rino'] = $rino_remote_version;
1330 $postvars['data'] = bin2hex($data);
1332 //logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1335 if ($dfrn_version >= 2.1) {
1336 if (($contact['duplex'] && strlen($contact['pubkey']))
1337 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1338 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
1340 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1342 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1345 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1346 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1348 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1352 logger('md5 rawkey ' . md5($postvars['key']));
1354 $postvars['key'] = bin2hex($postvars['key']);
1358 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), LOGGER_DATA);
1360 $xml = post_url($contact['notify'], $postvars);
1362 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1364 $curl_stat = $a->get_curl_code();
1365 if ((!$curl_stat) || (!strlen($xml))) {
1366 return -9; // timed out
1369 if (($curl_stat == 503) && (stristr($a->get_curl_headers(), 'retry-after'))) {
1373 if (strpos($xml, '<?xml') === false) {
1374 logger('dfrn_deliver: phase 2: no valid XML returned');
1375 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1379 if ($contact['term-date'] > NULL_DATE) {
1380 logger("dfrn_deliver: $url back from the dead - removing mark for death");
1381 Contact::unmarkForArchival($contact);
1384 $res = parse_xml_string($xml);
1386 if (!isset($res->status)) {
1390 if (!empty($res->message)) {
1391 logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1394 return intval($res->status);
1398 * @brief Add new birthday event for this person
1400 * @param array $contact Contact record
1401 * @param string $birthday Birthday of the contact
1403 * @todo Add array type-hint for $contact
1405 private static function birthdayEvent($contact, $birthday)
1407 // Check for duplicates
1409 "SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1410 intval($contact["uid"]),
1411 intval($contact["id"]),
1412 dbesc(datetime_convert("UTC", "UTC", $birthday)),
1416 if (DBM::is_result($r)) {
1420 logger("updating birthday: ".$birthday." for contact ".$contact["id"]);
1422 $bdtext = sprintf(t("%s\'s birthday"), $contact["name"]);
1423 $bdtext2 = sprintf(t("Happy Birthday %s"), " [url=".$contact["url"]."]".$contact["name"]."[/url]");
1426 "INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1427 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1428 intval($contact["uid"]),
1429 intval($contact["id"]),
1430 dbesc(datetime_convert()),
1431 dbesc(datetime_convert()),
1432 dbesc(datetime_convert("UTC", "UTC", $birthday)),
1433 dbesc(datetime_convert("UTC", "UTC", $birthday . " + 1 day ")),
1441 * @brief Fetch the author data from head or entry items
1443 * @param object $xpath XPath object
1444 * @param object $context In which context should the data be searched
1445 * @param array $importer Record of the importer user mixed with contact of the content
1446 * @param string $element Element name from which the data is fetched
1447 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1448 * @param string $xml optional, default empty
1450 * @return array Relevant data of the author
1451 * @todo Find good type-hints for all parameter
1453 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
1456 $author["name"] = $xpath->evaluate($element."/atom:name/text()", $context)->item(0)->nodeValue;
1457 $author["link"] = $xpath->evaluate($element."/atom:uri/text()", $context)->item(0)->nodeValue;
1460 "SELECT `id`, `uid`, `url`, `network`, `avatar-date`, `name-date`, `uri-date`, `addr`,
1461 `name`, `nick`, `about`, `location`, `keywords`, `xmpp`, `bdyear`, `bd`, `hidden`, `contact-type`
1462 FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
1463 intval($importer["uid"]),
1464 dbesc(normalise_link($author["link"])),
1465 dbesc(NETWORK_STATUSNET)
1468 if (DBM::is_result($r)) {
1470 $author["contact-id"] = $r[0]["id"];
1471 $author["network"] = $r[0]["network"];
1474 logger("Contact ".$author["link"]." wasn't found for user ".$importer["uid"]." XML: ".$xml, LOGGER_DEBUG);
1477 $author["contact-id"] = $importer["id"];
1478 $author["network"] = $importer["network"];
1482 // Until now we aren't serving different sizes - but maybe later
1484 /// @todo check if "avatar" or "photo" would be the best field in the specification
1485 $avatars = $xpath->query($element."/atom:link[@rel='avatar']", $context);
1486 foreach ($avatars as $avatar) {
1489 foreach ($avatar->attributes as $attributes) {
1490 /// @TODO Rewrite these similar if () to one switch
1491 if ($attributes->name == "href") {
1492 $href = $attributes->textContent;
1494 if ($attributes->name == "width") {
1495 $width = $attributes->textContent;
1497 if ($attributes->name == "updated") {
1498 $contact["avatar-date"] = $attributes->textContent;
1501 if (($width > 0) && ($href != "")) {
1502 $avatarlist[$width] = $href;
1505 if (count($avatarlist) > 0) {
1506 krsort($avatarlist);
1507 $author["avatar"] = current($avatarlist);
1510 if (DBM::is_result($r) && !$onlyfetch) {
1511 logger("Check if contact details for contact " . $r[0]["id"] . " (" . $r[0]["nick"] . ") have to be updated.", LOGGER_DEBUG);
1513 $poco = ["url" => $contact["url"]];
1515 // When was the last change to name or uri?
1516 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1517 foreach ($name_element->attributes as $attributes) {
1518 if ($attributes->name == "updated") {
1519 $poco["name-date"] = $attributes->textContent;
1523 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1524 foreach ($link_element->attributes as $attributes) {
1525 if ($attributes->name == "updated") {
1526 $poco["uri-date"] = $attributes->textContent;
1530 // Update contact data
1531 $value = $xpath->evaluate($element . "/dfrn:handle/text()", $context)->item(0)->nodeValue;
1533 $poco["addr"] = $value;
1536 $value = $xpath->evaluate($element . "/poco:displayName/text()", $context)->item(0)->nodeValue;
1538 $poco["name"] = $value;
1541 $value = $xpath->evaluate($element . "/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
1543 $poco["nick"] = $value;
1546 $value = $xpath->evaluate($element . "/poco:note/text()", $context)->item(0)->nodeValue;
1548 $poco["about"] = $value;
1551 $value = $xpath->evaluate($element . "/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
1553 $poco["location"] = $value;
1556 /// @todo Only search for elements with "poco:type" = "xmpp"
1557 $value = $xpath->evaluate($element . "/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
1559 $poco["xmpp"] = $value;
1562 /// @todo Add support for the following fields that we don't support by now in the contact table:
1563 /// - poco:utcOffset
1569 // If the "hide" element is present then the profile isn't searchable.
1570 $hide = intval($xpath->evaluate($element . "/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
1572 logger("Hidden status for contact " . $contact["url"] . ": " . $hide, LOGGER_DEBUG);
1574 // If the contact isn't searchable then set the contact to "hidden".
1575 // Problem: This can be manually overridden by the user.
1577 $contact["hidden"] = true;
1580 // Save the keywords into the contact table
1582 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1583 foreach ($tagelements as $tag) {
1584 $tags[$tag->nodeValue] = $tag->nodeValue;
1588 $poco["keywords"] = implode(", ", $tags);
1591 // "dfrn:birthday" contains the birthday converted to UTC
1592 $old_bdyear = $contact["bdyear"];
1594 $birthday = $xpath->evaluate($element . "/dfrn:birthday/text()", $context)->item(0)->nodeValue;
1596 if (strtotime($birthday) > time()) {
1597 $bd_timestamp = strtotime($birthday);
1599 $poco["bdyear"] = date("Y", $bd_timestamp);
1602 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1603 $value = $xpath->evaluate($element . "/poco:birthday/text()", $context)->item(0)->nodeValue;
1605 if (!in_array($value, ["", "0000-00-00", "0001-01-01"])) {
1606 $bdyear = date("Y");
1607 $value = str_replace("0000", $bdyear, $value);
1609 if (strtotime($value) < time()) {
1610 $value = str_replace($bdyear, $bdyear + 1, $value);
1611 $bdyear = $bdyear + 1;
1614 $poco["bd"] = $value;
1617 $contact = array_merge($contact, $poco);
1619 if ($old_bdyear != $contact["bdyear"]) {
1620 self::birthdayEvent($contact, $birthday);
1623 // Get all field names
1625 foreach ($r[0] as $field => $data) {
1626 $fields[$field] = $data;
1629 unset($fields["id"]);
1630 unset($fields["uid"]);
1631 unset($fields["url"]);
1632 unset($fields["avatar-date"]);
1633 unset($fields["name-date"]);
1634 unset($fields["uri-date"]);
1636 // Update check for this field has to be done differently
1637 $datefields = ["name-date", "uri-date"];
1638 foreach ($datefields as $field) {
1639 if (strtotime($contact[$field]) > strtotime($r[0][$field])) {
1640 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $r[0][$field] . "'", LOGGER_DEBUG);
1645 foreach ($fields as $field => $data) {
1646 if ($contact[$field] != $r[0][$field]) {
1647 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $r[0][$field] . "'", LOGGER_DEBUG);
1653 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1656 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1657 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1658 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1659 WHERE `id` = %d AND `network` = '%s'",
1660 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
1661 dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1662 dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
1663 dbesc(DBM::date($contact["name-date"])), dbesc(DBM::date($contact["uri-date"])),
1664 intval($contact["id"]), dbesc($contact["network"])
1668 Contact::updateAvatar(
1672 (strtotime($contact["avatar-date"]) > strtotime($r[0]["avatar-date"]))
1676 * The generation is a sign for the reliability of the provided data.
1677 * It is used in the socgraph.php to prevent that old contact data
1678 * that was relayed over several servers can overwrite contact
1679 * data that we received directly.
1682 $poco["generation"] = 2;
1683 $poco["photo"] = $author["avatar"];
1684 $poco["hide"] = $hide;
1685 $poco["contact-type"] = $contact["contact-type"];
1686 $gcid = GContact::update($poco);
1688 GContact::link($gcid, $importer["uid"], $contact["id"]);
1695 * @brief Transforms activity objects into an XML string
1697 * @param object $xpath XPath object
1698 * @param object $activity Activity object
1699 * @param string $element element name
1701 * @return string XML string
1702 * @todo Find good type-hints for all parameter
1704 private static function transformActivity($xpath, $activity, $element)
1706 if (!is_object($activity)) {
1710 $obj_doc = new DOMDocument("1.0", "utf-8");
1711 $obj_doc->formatOutput = true;
1713 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1715 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1716 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1718 $id = $xpath->query("atom:id", $activity)->item(0);
1719 if (is_object($id)) {
1720 $obj_element->appendChild($obj_doc->importNode($id, true));
1723 $title = $xpath->query("atom:title", $activity)->item(0);
1724 if (is_object($title)) {
1725 $obj_element->appendChild($obj_doc->importNode($title, true));
1728 $links = $xpath->query("atom:link", $activity);
1729 if (is_object($links)) {
1730 foreach ($links as $link) {
1731 $obj_element->appendChild($obj_doc->importNode($link, true));
1735 $content = $xpath->query("atom:content", $activity)->item(0);
1736 if (is_object($content)) {
1737 $obj_element->appendChild($obj_doc->importNode($content, true));
1740 $obj_doc->appendChild($obj_element);
1742 $objxml = $obj_doc->saveXML($obj_element);
1744 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1745 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1750 * @brief Processes the mail elements
1752 * @param object $xpath XPath object
1753 * @param object $mail mail elements
1754 * @param array $importer Record of the importer user mixed with contact of the content
1756 * @todo Find good type-hints for all parameter
1758 private static function processMail($xpath, $mail, $importer)
1760 logger("Processing mails");
1762 /// @TODO Rewrite this to one statement
1764 $msg["uid"] = $importer["importer_uid"];
1765 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1766 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1767 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1768 $msg["contact-id"] = $importer["id"];
1769 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1770 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1771 $msg["created"] = $xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue;
1772 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1773 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1775 $msg["replied"] = 0;
1777 dba::insert('mail', $msg);
1779 // send notifications.
1780 /// @TODO Arange this mess
1782 "type" => NOTIFY_MAIL,
1783 "notify_flags" => $importer["notify-flags"],
1784 "language" => $importer["language"],
1785 "to_name" => $importer["username"],
1786 "to_email" => $importer["email"],
1787 "uid" => $importer["importer_uid"],
1789 "source_name" => $msg["from-name"],
1790 "source_link" => $importer["url"],
1791 "source_photo" => $importer["thumb"],
1792 "verb" => ACTIVITY_POST,
1796 notification($notif_params);
1798 logger("Mail is processed, notification was sent.");
1802 * @brief Processes the suggestion elements
1804 * @param object $xpath XPath object
1805 * @param object $suggestion suggestion elements
1806 * @param array $importer Record of the importer user mixed with contact of the content
1808 * @todo Find good type-hints for all parameter
1810 private static function processSuggestion($xpath, $suggestion, $importer)
1814 logger("Processing suggestions");
1816 /// @TODO Rewrite this to one statement
1818 $suggest["uid"] = $importer["importer_uid"];
1819 $suggest["cid"] = $importer["id"];
1820 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1821 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1822 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1823 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1824 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1826 // Does our member already have a friend matching this description?
1829 "SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1830 dbesc($suggest["name"]),
1831 dbesc(normalise_link($suggest["url"])),
1832 intval($suggest["uid"])
1836 * The valid result means the friend we're about to send a friend
1837 * suggestion already has them in their contact, which means no further
1838 * action is required.
1840 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1842 if (DBM::is_result($r)) {
1846 // Do we already have an fcontact record for this person?
1850 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1851 dbesc($suggest["url"]),
1852 dbesc($suggest["name"]),
1853 dbesc($suggest["request"])
1855 if (DBM::is_result($r)) {
1858 // OK, we do. Do we already have an introduction for this person ?
1860 "SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1861 intval($suggest["uid"]),
1866 * The valid result means the friend we're about to send a friend
1867 * suggestion already has them in their contact, which means no further
1868 * action is required.
1870 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1872 if (DBM::is_result($r)) {
1878 "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1879 dbesc($suggest["name"]),
1880 dbesc($suggest["url"]),
1881 dbesc($suggest["photo"]),
1882 dbesc($suggest["request"])
1886 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1887 dbesc($suggest["url"]),
1888 dbesc($suggest["name"]),
1889 dbesc($suggest["request"])
1893 * If no record in fcontact is found, below INSERT statement will not
1894 * link an introduction to it.
1896 if (!DBM::is_result($r)) {
1897 // database record did not get created. Quietly give up.
1903 $hash = random_string();
1906 "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1907 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1908 intval($suggest["uid"]),
1910 intval($suggest["cid"]),
1911 dbesc($suggest["body"]),
1913 dbesc(datetime_convert()),
1919 "type" => NOTIFY_SUGGEST,
1920 "notify_flags" => $importer["notify-flags"],
1921 "language" => $importer["language"],
1922 "to_name" => $importer["username"],
1923 "to_email" => $importer["email"],
1924 "uid" => $importer["importer_uid"],
1926 "link" => System::baseUrl()."/notifications/intros",
1927 "source_name" => $importer["name"],
1928 "source_link" => $importer["url"],
1929 "source_photo" => $importer["photo"],
1930 "verb" => ACTIVITY_REQ_FRIEND,
1938 * @brief Processes the relocation elements
1940 * @param object $xpath XPath object
1941 * @param object $relocation relocation elements
1942 * @param array $importer Record of the importer user mixed with contact of the content
1944 * @todo Find good type-hints for all parameter
1946 private static function processRelocation($xpath, $relocation, $importer)
1948 logger("Processing relocations");
1950 /// @TODO Rewrite this to one statement
1952 $relocate["uid"] = $importer["importer_uid"];
1953 $relocate["cid"] = $importer["id"];
1954 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1955 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
1956 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1957 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
1958 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1959 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1960 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1961 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1962 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1963 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1964 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1965 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1967 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
1968 $relocate["avatar"] = $relocate["photo"];
1971 if ($relocate["addr"] == "") {
1972 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
1977 "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
1978 intval($importer["id"]),
1979 intval($importer["importer_uid"])
1982 if (!DBM::is_result($r)) {
1983 logger("Query failed to execute, no result returned in " . __FUNCTION__);
1989 // Update the gcontact entry
1990 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
1993 "UPDATE `gcontact` SET
2002 WHERE `nurl` = '%s';",
2003 dbesc($relocate["name"]),
2004 dbesc($relocate["avatar"]),
2005 dbesc($relocate["url"]),
2006 dbesc(normalise_link($relocate["url"])),
2007 dbesc($relocate["addr"]),
2008 dbesc($relocate["addr"]),
2009 dbesc($relocate["notify"]),
2010 dbesc($relocate["server_url"]),
2011 dbesc(normalise_link($old["url"]))
2014 // Update the contact table. We try to find every entry.
2016 "UPDATE `contact` SET
2026 `site-pubkey` = '%s'
2027 WHERE (`id` = %d AND `uid` = %d) OR (`nurl` = '%s');",
2028 dbesc($relocate["name"]),
2029 dbesc($relocate["avatar"]),
2030 dbesc($relocate["url"]),
2031 dbesc(normalise_link($relocate["url"])),
2032 dbesc($relocate["addr"]),
2033 dbesc($relocate["request"]),
2034 dbesc($relocate["confirm"]),
2035 dbesc($relocate["notify"]),
2036 dbesc($relocate["poll"]),
2037 dbesc($relocate["sitepubkey"]),
2038 intval($importer["id"]),
2039 intval($importer["importer_uid"]),
2040 dbesc(normalise_link($old["url"]))
2043 Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
2050 /// @todo This is an extreme performance killer
2052 'owner-link' => [$old["url"], $relocate["url"]],
2053 'author-link' => [$old["url"], $relocate["url"]],
2054 //'owner-avatar' => array($old["photo"], $relocate["photo"]),
2055 //'author-avatar' => array($old["photo"], $relocate["photo"]),
2057 foreach ($fields as $n => $f) {
2059 "SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
2062 intval($importer["importer_uid"])
2065 if (DBM::is_result($r)) {
2067 "UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
2072 intval($importer["importer_uid"])
2082 /// merge with current record, current contents have priority
2083 /// update record, set url-updated
2084 /// update profile photos
2085 /// schedule a scan?
2090 * @brief Updates an item
2092 * @param array $current the current item record
2093 * @param array $item the new item record
2094 * @param array $importer Record of the importer user mixed with contact of the content
2095 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2097 * @todo set proper type-hints (array?)
2099 private static function updateContent($current, $item, $importer, $entrytype)
2103 if (edited_timestamp_is_newer($current, $item)) {
2104 // do not accept (ignore) an earlier edit than one we currently have.
2105 if (datetime_convert("UTC", "UTC", $item["edited"]) < $current["edited"]) {
2109 $fields = ['title' => $item["title"], 'body' => $item["body"],
2110 'tag' => $item["tag"], 'changed' => datetime_convert(),
2111 'edited' => datetime_convert("UTC", "UTC", $item["edited"])];
2113 $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
2114 dba::update('item', $fields, $condition);
2116 create_tags_from_itemuri($item["uri"], $importer["importer_uid"]);
2117 update_thread_uri($item["uri"], $importer["importer_uid"]);
2121 if ($entrytype == DFRN_REPLY_RC) {
2122 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $current["id"]);
2129 * @brief Detects the entry type of the item
2131 * @param array $importer Record of the importer user mixed with contact of the content
2132 * @param array $item the new item record
2134 * @return int Is it a toplevel entry, a comment or a relayed comment?
2135 * @todo set proper type-hints (array?)
2137 private static function getEntryType($importer, $item)
2139 if ($item["parent-uri"] != $item["uri"]) {
2142 if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
2145 logger("possible community action");
2147 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2150 // was the top-level post for this action written by somebody on this site?
2151 // Specifically, the recipient?
2153 $is_a_remote_action = false;
2156 "SELECT `item`.`parent-uri` FROM `item`
2157 WHERE `item`.`uri` = '%s'
2159 dbesc($item["parent-uri"])
2161 if (DBM::is_result($r)) {
2163 "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2164 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2165 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2166 AND `item`.`uid` = %d
2169 dbesc($r[0]["parent-uri"]),
2170 dbesc($r[0]["parent-uri"]),
2171 dbesc($r[0]["parent-uri"]),
2172 intval($importer["importer_uid"])
2174 if (DBM::is_result($r)) {
2175 $is_a_remote_action = true;
2180 * Does this have the characteristics of a community or private group action?
2181 * If it's an action to a wall post on a community/prvgroup page it's a
2182 * valid community action. Also forum_mode makes it valid for sure.
2183 * If neither, it's not.
2186 /// @TODO Maybe merge these if() blocks into one?
2187 if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2188 $is_a_remote_action = false;
2189 logger("not a community action");
2192 if ($is_a_remote_action) {
2193 return DFRN_REPLY_RC;
2198 return DFRN_TOP_LEVEL;
2203 * @brief Send a "poke"
2205 * @param array $item the new item record
2206 * @param array $importer Record of the importer user mixed with contact of the content
2207 * @param int $posted_id The record number of item record that was just posted
2209 * @todo set proper type-hints (array?)
2211 private static function doPoke($item, $importer, $posted_id)
2213 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2217 $xo = parse_xml_string($item["object"], false);
2219 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2220 // somebody was poked/prodded. Was it me?
2221 foreach ($xo->link as $l) {
2222 $atts = $l->attributes();
2223 switch ($atts["rel"]) {
2225 $Blink = $atts["href"];
2232 if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2233 // send a notification
2236 "type" => NOTIFY_POKE,
2237 "notify_flags" => $importer["notify-flags"],
2238 "language" => $importer["language"],
2239 "to_name" => $importer["username"],
2240 "to_email" => $importer["email"],
2241 "uid" => $importer["importer_uid"],
2243 "link" => System::baseUrl()."/display/".urlencode(get_item_guid($posted_id)),
2244 "source_name" => stripslashes($item["author-name"]),
2245 "source_link" => $item["author-link"],
2246 "source_photo" => ((link_compare($item["author-link"], $importer["url"]))
2247 ? $importer["thumb"] : $item["author-avatar"]),
2248 "verb" => $item["verb"],
2249 "otype" => "person",
2250 "activity" => $verb,
2251 "parent" => $item["parent"]]
2258 * @brief Processes several actions, depending on the verb
2260 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2261 * @param array $importer Record of the importer user mixed with contact of the content
2262 * @param array $item the new item record
2263 * @param bool $is_like Is the verb a "like"?
2265 * @return bool Should the processing of the entries be continued?
2266 * @todo set proper type-hints (array?)
2268 private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2270 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2272 if (($entrytype == DFRN_TOP_LEVEL)) {
2273 // The filling of the the "contact" variable is done for legcy reasons
2274 // The functions below are partly used by ostatus.php as well - where we have this variable
2275 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2277 $nickname = $contact["nick"];
2279 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2280 // This function once was responsible for DFRN and OStatus.
2281 if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2282 logger("New follower");
2283 new_follower($importer, $contact, $item, $nickname);
2286 if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2287 logger("Lost follower");
2288 lose_follower($importer, $contact, $item);
2291 if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2292 logger("New friend request");
2293 new_follower($importer, $contact, $item, $nickname, true);
2296 if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2297 logger("Lost sharer");
2298 lose_sharer($importer, $contact, $item);
2302 if (($item["verb"] == ACTIVITY_LIKE)
2303 || ($item["verb"] == ACTIVITY_DISLIKE)
2304 || ($item["verb"] == ACTIVITY_ATTEND)
2305 || ($item["verb"] == ACTIVITY_ATTENDNO)
2306 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
2309 $item["type"] = "activity";
2310 $item["gravity"] = GRAVITY_LIKE;
2311 // only one like or dislike per person
2312 // splitted into two queries for performance issues
2314 "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `parent-uri` = '%s' AND NOT `deleted` LIMIT 1",
2315 intval($item["uid"]),
2316 dbesc($item["author-link"]),
2317 dbesc($item["verb"]),
2318 dbesc($item["parent-uri"])
2320 if (DBM::is_result($r)) {
2325 "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `thr-parent` = '%s' AND NOT `deleted` LIMIT 1",
2326 intval($item["uid"]),
2327 dbesc($item["author-link"]),
2328 dbesc($item["verb"]),
2329 dbesc($item["parent-uri"])
2331 if (DBM::is_result($r)) {
2338 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2339 $xo = parse_xml_string($item["object"], false);
2340 $xt = parse_xml_string($item["target"], false);
2342 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2344 "SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2346 intval($importer["importer_uid"])
2349 if (!DBM::is_result($r)) {
2350 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2354 // extract tag, if not duplicate, add to parent item
2356 if (!(stristr($r[0]["tag"], trim($xo->content)))) {
2358 "UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2359 dbesc($r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2362 create_tags_from_item($r[0]["id"]);
2372 * @brief Processes the link elements
2374 * @param object $links link elements
2375 * @param array $item the item record
2377 * @todo set proper type-hints
2379 private static function parseLinks($links, &$item)
2386 foreach ($links as $link) {
2387 foreach ($link->attributes as $attributes) {
2388 /// @TODO Rewrite these repeated (same) if () statements to a switch()
2389 if ($attributes->name == "href") {
2390 $href = $attributes->textContent;
2392 if ($attributes->name == "rel") {
2393 $rel = $attributes->textContent;
2395 if ($attributes->name == "type") {
2396 $type = $attributes->textContent;
2398 if ($attributes->name == "length") {
2399 $length = $attributes->textContent;
2401 if ($attributes->name == "title") {
2402 $title = $attributes->textContent;
2405 if (($rel != "") && ($href != "")) {
2408 $item["plink"] = $href;
2412 if (strlen($item["attach"])) {
2413 $item["attach"] .= ",";
2416 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2424 * @brief Processes the entry elements which contain the items and comments
2426 * @param array $header Array of the header elements that always stay the same
2427 * @param object $xpath XPath object
2428 * @param object $entry entry elements
2429 * @param array $importer Record of the importer user mixed with contact of the content
2430 * @param object $xml xml
2432 * @todo Add type-hints
2434 private static function processEntry($header, $xpath, $entry, $importer, $xml)
2436 logger("Processing entries");
2440 $item["protocol"] = PROTOCOL_DFRN;
2442 $item["source"] = $xml;
2445 $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
2447 $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
2450 "SELECT `id`, `uid`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2451 dbesc($item["uri"]),
2452 intval($importer["importer_uid"])
2455 // Is there an existing item?
2456 if (DBM::is_result($current) && edited_timestamp_is_newer($current[0], $item)
2457 && (datetime_convert("UTC", "UTC", $item["edited"]) < $current[0]["edited"])
2459 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2464 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2466 $item["owner-name"] = $owner["name"];
2467 $item["owner-link"] = $owner["link"];
2468 $item["owner-avatar"] = $owner["avatar"];
2471 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2473 $item["author-name"] = $author["name"];
2474 $item["author-link"] = $author["link"];
2475 $item["author-avatar"] = $author["avatar"];
2477 $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
2479 $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2481 $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
2482 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2483 // make sure nobody is trying to sneak some html tags by us
2484 $item["body"] = notags(base64url_decode($item["body"]));
2486 $item["body"] = limit_body_size($item["body"]);
2488 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2489 if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
2490 $base_url = get_app()->get_baseurl();
2491 $item['body'] = reltoabs($item['body'], $base_url);
2493 $item['body'] = html2bb_video($item['body']);
2495 $item['body'] = OEmbed::HTML2BBCode($item['body']);
2497 $config = HTMLPurifier_Config::createDefault();
2498 $config->set('Cache.DefinitionImpl', null);
2500 // we shouldn't need a whitelist, because the bbcode converter
2501 // will strip out any unsupported tags.
2503 $purifier = new HTMLPurifier($config);
2504 $item['body'] = $purifier->purify($item['body']);
2506 $item['body'] = @html2bbcode($item['body']);
2509 /// @todo We should check for a repeated post and if we know the repeated author.
2511 // We don't need the content element since "dfrn:env" is always present
2512 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2514 $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
2516 $georsspoint = $xpath->query("georss:point", $entry);
2518 $item["coord"] = $georsspoint->item(0)->nodeValue;
2521 $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
2523 $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
2525 if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true") {
2526 $item["bookmark"] = true;
2529 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2530 if ($notice_info && ($notice_info->length > 0)) {
2531 foreach ($notice_info->item(0)->attributes as $attributes) {
2532 if ($attributes->name == "source") {
2533 $item["app"] = strip_tags($attributes->textContent);
2538 $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
2540 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "item_store"
2541 $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
2542 if ($dsprsig != "") {
2543 $item["dsprsig"] = $dsprsig;
2546 $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
2548 if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "") {
2549 $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
2552 $object = $xpath->query("activity:object", $entry)->item(0);
2553 $item["object"] = self::transformActivity($xpath, $object, "object");
2555 if (trim($item["object"]) != "") {
2556 $r = parse_xml_string($item["object"], false);
2557 if (isset($r->type)) {
2558 $item["object-type"] = $r->type;
2562 $target = $xpath->query("activity:target", $entry)->item(0);
2563 $item["target"] = self::transformActivity($xpath, $target, "target");
2565 $categories = $xpath->query("atom:category", $entry);
2567 foreach ($categories as $category) {
2570 foreach ($category->attributes as $attributes) {
2571 if ($attributes->name == "term") {
2572 $term = $attributes->textContent;
2575 if ($attributes->name == "scheme") {
2576 $scheme = $attributes->textContent;
2580 if (($term != "") && ($scheme != "")) {
2581 $parts = explode(":", $scheme);
2582 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2583 $termhash = array_shift($parts);
2584 $termurl = implode(":", $parts);
2586 if (strlen($item["tag"])) {
2587 $item["tag"] .= ",";
2590 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2598 $links = $xpath->query("atom:link", $entry);
2600 self::parseLinks($links, $item);
2603 $item['conversation-uri'] = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
2605 $conv = $xpath->query('ostatus:conversation', $entry);
2606 if (is_object($conv->item(0))) {
2607 foreach ($conv->item(0)->attributes as $attributes) {
2608 if ($attributes->name == "ref") {
2609 $item['conversation-uri'] = $attributes->textContent;
2611 if ($attributes->name == "href") {
2612 $item['conversation-href'] = $attributes->textContent;
2617 // Is it a reply or a top level posting?
2618 $item["parent-uri"] = $item["uri"];
2620 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2621 if (is_object($inreplyto->item(0))) {
2622 foreach ($inreplyto->item(0)->attributes as $attributes) {
2623 if ($attributes->name == "ref") {
2624 $item["parent-uri"] = $attributes->textContent;
2629 // Get the type of the item (Top level post, reply or remote reply)
2630 $entrytype = self::getEntryType($importer, $item);
2632 // Now assign the rest of the values that depend on the type of the message
2633 if (in_array($entrytype, [DFRN_REPLY, DFRN_REPLY_RC])) {
2634 if (!isset($item["object-type"])) {
2635 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2638 if ($item["contact-id"] != $owner["contact-id"]) {
2639 $item["contact-id"] = $owner["contact-id"];
2642 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2643 $item["network"] = $owner["network"];
2646 if ($item["contact-id"] != $author["contact-id"]) {
2647 $item["contact-id"] = $author["contact-id"];
2650 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2651 $item["network"] = $author["network"];
2654 /// @TODO maybe remove this old-lost code then?
2655 // This code was taken from the old DFRN code
2656 // When activated, forums don't work.
2657 // And: Why should we disallow commenting by followers?
2658 // the behaviour is now similar to the Diaspora part.
2659 //if ($importer["rel"] == CONTACT_IS_FOLLOWER) {
2660 // logger("Contact ".$importer["id"]." is only follower. Quitting", LOGGER_DEBUG);
2665 if ($entrytype == DFRN_REPLY_RC) {
2666 $item["type"] = "remote-comment";
2668 } elseif ($entrytype == DFRN_TOP_LEVEL) {
2669 if (!isset($item["object-type"])) {
2670 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2674 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2675 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2676 $ev = bbtoevent($item["body"]);
2677 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2678 logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2679 /// @TODO Mixure of "/' ahead ...
2680 $ev["cid"] = $importer["id"];
2681 $ev["uid"] = $importer["uid"];
2682 $ev["uri"] = $item["uri"];
2683 $ev["edited"] = $item["edited"];
2684 $ev['private'] = $item['private'];
2685 $ev["guid"] = $item["guid"];
2688 "SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2689 dbesc($item["uri"]),
2690 intval($importer["uid"])
2692 if (DBM::is_result($r)) {
2693 $ev["id"] = $r[0]["id"];
2696 $event_id = event_store($ev);
2697 logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2703 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2704 logger("Exiting because 'processVerbs' told us so", LOGGER_DEBUG);
2708 // Update content if 'updated' changes
2709 if (DBM::is_result($current)) {
2710 if (self::updateContent($r[0], $item, $importer, $entrytype)) {
2711 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2713 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2718 if (in_array($entrytype, [DFRN_REPLY, DFRN_REPLY_RC])) {
2719 $posted_id = item_store($item);
2723 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2725 $item["id"] = $posted_id;
2728 "SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2730 intval($importer["importer_uid"])
2732 if (DBM::is_result($r)) {
2733 $parent = $r[0]["parent"];
2734 $parent_uri = $r[0]["parent-uri"];
2737 if ($posted_id && $parent && ($entrytype == DFRN_REPLY_RC)) {
2738 logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
2739 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $posted_id);
2744 } else { // $entrytype == DFRN_TOP_LEVEL
2745 if (!link_compare($item["owner-link"], $importer["url"])) {
2747 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2748 * but otherwise there's a possible data mixup on the sender's system.
2749 * the tgroup delivery code called from item_store will correct it if it's a forum,
2750 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2752 logger('Correcting item owner.', LOGGER_DEBUG);
2753 $item["owner-name"] = $importer["senderName"];
2754 $item["owner-link"] = $importer["url"];
2755 $item["owner-avatar"] = $importer["thumb"];
2758 if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!tgroup_check($importer["importer_uid"], $item))) {
2759 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2763 // This is my contact on another system, but it's really me.
2764 // Turn this into a wall post.
2765 $notify = item_is_remote_self($importer, $item);
2767 $posted_id = item_store($item, false, $notify);
2769 logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2771 if (stristr($item["verb"], ACTIVITY_POKE)) {
2772 self::doPoke($item, $importer, $posted_id);
2778 * @brief Deletes items
2780 * @param object $xpath XPath object
2781 * @param object $deletion deletion elements
2782 * @param array $importer Record of the importer user mixed with contact of the content
2784 * @todo set proper type-hints
2786 private static function processDeletion($xpath, $deletion, $importer)
2788 logger("Processing deletions");
2790 foreach ($deletion->attributes as $attributes) {
2791 if ($attributes->name == "ref") {
2792 $uri = $attributes->textContent;
2794 if ($attributes->name == "when") {
2795 $when = $attributes->textContent;
2799 $when = datetime_convert("UTC", "UTC", $when, "Y-m-d H:i:s");
2801 $when = datetime_convert("UTC", "UTC", "now", "Y-m-d H:i:s");
2804 if (!$uri || !$importer["id"]) {
2808 /// @todo Only select the used fields
2810 "SELECT `item`.*, `contact`.`self` FROM `item` INNER JOIN `contact` on `item`.`contact-id` = `contact`.`id`
2811 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2813 intval($importer["uid"]),
2814 intval($importer["id"])
2816 if (!DBM::is_result($r)) {
2817 logger("Item with uri " . $uri . " from contact " . $importer["id"] . " for user " . $importer["uid"] . " wasn't found.", LOGGER_DEBUG);
2822 $entrytype = self::getEntryType($importer, $item);
2824 if (!$item["deleted"]) {
2825 logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG);
2830 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2831 logger("Deleting event ".$item["event-id"], LOGGER_DEBUG);
2832 event_delete($item["event-id"]);
2835 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2836 $xo = parse_xml_string($item["object"], false);
2837 $xt = parse_xml_string($item["target"], false);
2839 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2841 "SELECT `id`, `contact-id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2843 intval($importer["importer_uid"])
2845 if (DBM::is_result($i)) {
2846 // For tags, the owner cannot remove the tag on the author's copy of the post.
2848 $owner_remove = (($item["contact-id"] == $i[0]["contact-id"]) ? true: false);
2849 $author_remove = (($item["origin"] && $item["self"]) ? true : false);
2850 $author_copy = (($item["origin"]) ? true : false);
2852 if ($owner_remove && $author_copy) {
2855 if ($author_remove || $owner_remove) {
2856 $tags = explode(',', $i[0]["tag"]);
2859 foreach ($tags as $tag) {
2860 if (trim($tag) !== trim($xo->body)) {
2861 $newtags[] = trim($tag);
2866 "UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2867 dbesc(implode(',', $newtags)),
2870 create_tags_from_item($i[0]["id"]);
2876 if ($entrytype == DFRN_TOP_LEVEL) {
2878 "UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2879 `body` = '', `title` = ''
2880 WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2882 dbesc(datetime_convert()),
2884 intval($importer["uid"])
2886 create_tags_from_itemuri($uri, $importer["uid"]);
2887 Term::createFromItemURI($uri, $importer["uid"]);
2888 update_thread_uri($uri, $importer["uid"]);
2891 "UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2892 `body` = '', `title` = ''
2893 WHERE `uri` = '%s' AND `uid` IN (0, %d)",
2895 dbesc(datetime_convert()),
2897 intval($importer["uid"])
2899 create_tags_from_itemuri($uri, $importer["uid"]);
2900 Term::createFromItemURI($uri, $importer["uid"]);
2901 update_thread_uri($uri, $importer["importer_uid"]);
2903 // if this is a relayed delete, propagate it to other recipients
2905 if ($entrytype == DFRN_REPLY_RC) {
2906 logger("Notifying followers about deletion of post " . $item["id"], LOGGER_DEBUG);
2907 Worker::add(PRIORITY_HIGH, "Notifier", "drop", $item["id"]);
2914 * @brief Imports a DFRN message
2916 * @param string $xml The DFRN message
2917 * @param array $importer Record of the importer user mixed with contact of the content
2918 * @param bool $sort_by_date Is used when feeds are polled
2919 * @return integer Import status
2920 * @todo set proper type-hints
2922 public static function import($xml, $importer, $sort_by_date = false)
2928 $doc = new DOMDocument();
2929 @$doc->loadXML($xml);
2931 $xpath = new DOMXPath($doc);
2932 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2933 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2934 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2935 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2936 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2937 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2938 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2939 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2940 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2941 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2944 $header["uid"] = $importer["uid"];
2945 $header["network"] = NETWORK_DFRN;
2946 $header["type"] = "remote";
2947 $header["wall"] = 0;
2948 $header["origin"] = 0;
2949 $header["contact-id"] = $importer["id"];
2951 // Update the contact table if the data has changed
2953 // The "atom:author" is only present in feeds
2954 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2955 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2958 // Only the "dfrn:owner" in the head section contains all data
2959 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2960 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2963 logger("Import DFRN message for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2965 // The account type is new since 3.5.1
2966 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2967 $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()")->item(0)->nodeValue);
2969 if ($accounttype != $importer["contact-type"]) {
2970 dba::update('contact', ['contact-type' => $accounttype], ['id' => $importer["id"]]);
2974 // is it a public forum? Private forums aren't supported with this method
2975 // This is deprecated since 3.5.1
2976 $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()")->item(0)->nodeValue);
2978 if ($forum != $importer["forum"]) {
2979 $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2980 dba::update('contact', ['forum' => $forum], $condition);
2983 // We are processing relocations even if we are ignoring a contact
2984 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2985 foreach ($relocations as $relocation) {
2986 self::processRelocation($xpath, $relocation, $importer);
2989 if ($importer["readonly"]) {
2990 // We aren't receiving stuff from this person. But we will quietly ignore them
2991 // rather than a blatant "go away" message.
2992 logger('ignoring contact '.$importer["id"]);
2996 $mails = $xpath->query("/atom:feed/dfrn:mail");
2997 foreach ($mails as $mail) {
2998 self::processMail($xpath, $mail, $importer);
3001 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
3002 foreach ($suggestions as $suggestion) {
3003 self::processSuggestion($xpath, $suggestion, $importer);
3006 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
3007 foreach ($deletions as $deletion) {
3008 self::processDeletion($xpath, $deletion, $importer);
3011 if (!$sort_by_date) {
3012 $entries = $xpath->query("/atom:feed/atom:entry");
3013 foreach ($entries as $entry) {
3014 self::processEntry($header, $xpath, $entry, $importer, $xml);
3018 $entries = $xpath->query("/atom:feed/atom:entry");
3019 foreach ($entries as $entry) {
3020 $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
3021 $newentries[strtotime($created)] = $entry;
3024 // Now sort after the publishing date
3027 foreach ($newentries as $entry) {
3028 self::processEntry($header, $xpath, $entry, $importer, $xml);
3031 logger("Import done for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
3037 * @param string $contact_nick contact nickname
3039 public static function autoRedir(App $a, $contact_nick)
3042 if (x($_REQUEST, 'redir') && intval($_REQUEST['redir'])) {
3046 if ((! $contact_nick) || ($contact_nick === $a->user['nickname'])) {
3051 // We need to find out if $contact_nick is a user on this hub, and if so, if I
3052 // am a contact of that user. However, that user may have other contacts with the
3053 // same nickname as me on other hubs or other networks. Exclude these by requiring
3054 // that the contact have a local URL. I will be the only person with my nickname at
3055 // this URL, so if a result is found, then I am a contact of the $contact_nick user.
3057 // We also have to make sure that I'm a legitimate contact--I'm not blocked or pending.
3059 $baseurl = System::baseUrl();
3060 $domain_st = strpos($baseurl, "://");
3061 if ($domain_st === false) {
3064 $baseurl = substr($baseurl, $domain_st + 3);
3065 $nurl = normalise_link($baseurl);
3067 /// @todo Why is there a query for "url" *and* "nurl"? Especially this normalising is strange.
3068 $r = q("SELECT `id` FROM `contact` WHERE `uid` = (SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1)
3069 AND `nick` = '%s' AND NOT `self` AND (`url` LIKE '%%%s%%' OR `nurl` LIKE '%%%s%%') AND NOT `blocked` AND NOT `pending` LIMIT 1",
3070 dbesc($contact_nick),
3071 dbesc($a->user['nickname']),
3075 if ((! DBM::is_result($r)) || $r[0]['id'] == remote_user()) {
3079 $r = q("SELECT * FROM contact WHERE nick = '%s'
3080 AND network = '%s' AND uid = %d AND url LIKE '%%%s%%' LIMIT 1",
3081 dbesc($contact_nick),
3082 dbesc(NETWORK_DFRN),
3083 intval(local_user()),
3086 if (! DBM::is_result($r)) {
3092 $dfrn_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
3094 if ($r[0]['duplex'] && $r[0]['issued-id']) {
3095 $orig_id = $r[0]['issued-id'];
3096 $dfrn_id = '1:' . $orig_id;
3098 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
3099 $orig_id = $r[0]['dfrn-id'];
3100 $dfrn_id = '0:' . $orig_id;
3103 // ensure that we've got a valid ID. There may be some edge cases with forums and non-duplex mode
3104 // that may have triggered some of the "went to {profile/intro} and got an RSS feed" issues
3106 if (strlen($dfrn_id) < 3) {
3110 $sec = random_string();
3112 dba::insert('profile_check', ['uid' => local_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id, 'sec' => $sec, 'expire' => time() + 45]);
3114 $url = curPageURL();
3116 logger('auto_redir: ' . $r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
3117 $dest = (($url) ? '&destination_url=' . $url : '');
3118 goaway($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
3119 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest);