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\Addon;
14 use Friendica\Core\Config;
15 use Friendica\Core\L10n;
16 use Friendica\Core\System;
17 use Friendica\Core\Worker;
18 use Friendica\Database\DBM;
19 use Friendica\Model\Contact;
20 use Friendica\Model\GContact;
21 use Friendica\Model\Group;
22 use Friendica\Model\Item;
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;
29 use Friendica\Util\Network;
30 use Friendica\Util\XML;
36 use HTMLPurifier_Config;
38 require_once 'boot.php';
39 require_once 'include/dba.php';
40 require_once "include/enotify.php";
41 require_once "include/threads.php";
42 require_once "include/items.php";
43 require_once "include/tags.php";
44 require_once "include/event.php";
45 require_once "include/text.php";
46 require_once "include/html2bbcode.php";
47 require_once "include/bbcode.php";
50 * @brief This class contain functions to create and send DFRN XML files
55 const DFRN_TOP_LEVEL = 0; // Top level posting
56 const DFRN_REPLY = 1; // Regular reply that is stored locally
57 const DFRN_REPLY_RC = 2; // Reply that will be relayed
60 * @brief Generates the atom entries for delivery.php
62 * This function is used whenever content is transmitted via DFRN.
64 * @param array $items Item elements
65 * @param array $owner Owner record
67 * @return string DFRN entries
68 * @todo Add type-hints
70 public static function entries($items, $owner)
72 $doc = new DOMDocument('1.0', 'utf-8');
73 $doc->formatOutput = true;
75 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
77 if (! count($items)) {
78 return trim($doc->saveXML());
81 foreach ($items as $item) {
82 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
83 $root->appendChild($entry);
86 return(trim($doc->saveXML()));
90 * @brief Generate an atom feed for the given user
92 * This function is called when another server is pulling data from the user feed.
94 * @param string $dfrn_id DFRN ID from the requesting party
95 * @param string $owner_nick Owner nick name
96 * @param string $last_update Date of the last update
97 * @param int $direction Can be -1, 0 or 1.
98 * @param boolean $onlyheader Output only the header without content? (Default is "no")
100 * @return string DFRN feed entries
102 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false)
106 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
107 $public_feed = (($dfrn_id) ? false : true);
108 $starred = false; // not yet implemented, possible security issues
111 if ($public_feed && $a->argc > 2) {
112 for ($x = 2; $x < $a->argc; $x++) {
113 if ($a->argv[$x] == 'converse') {
116 if ($a->argv[$x] == 'starred') {
119 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
120 $category = $a->argv[$x+1];
127 // default permissions - anonymous user
129 $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = '' ";
132 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
133 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
134 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
138 if (! DBM::is_result($r)) {
143 $owner_id = $owner['uid'];
144 $owner_nick = $owner['nickname'];
146 $sql_post_table = "";
148 if (! $public_feed) {
150 switch ($direction) {
152 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
156 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
157 $my_id = '1:' . $dfrn_id;
160 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
161 $my_id = '0:' . $dfrn_id;
169 "SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
173 if (! DBM::is_result($r)) {
178 include_once 'include/security.php';
179 $groups = Group::getIdsByContactId($contact['id']);
181 if (count($groups)) {
182 for ($x = 0; $x < count($groups); $x ++)
183 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
184 $gs = implode('|', $groups);
186 $gs = '<<>>' ; // Impossible to match
189 $sql_extra = sprintf(
191 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
192 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
193 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
194 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
196 intval($contact['id']),
197 intval($contact['id']),
209 if (! strlen($last_update)) {
210 $last_update = 'now -30 days';
213 if (isset($category)) {
214 $sql_post_table = sprintf(
215 "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` ",
216 dbesc(protect_sprintf($category)),
217 intval(TERM_OBJ_POST),
218 intval(TERM_CATEGORY),
221 //$sql_extra .= file_tag_file_query('item',$category,'category');
226 $sql_extra .= " AND `contact`.`self` = 1 ";
230 $check_date = datetime_convert('UTC', 'UTC', $last_update, 'Y-m-d H:i:s');
233 "SELECT `item`.*, `item`.`id` AS `item_id`,
234 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
235 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
236 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
237 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
238 FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
239 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
240 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
241 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
242 WHERE `item`.`uid` = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
243 AND `item`.`wall` AND `item`.`changed` > '%s'
245 ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
252 * Will check further below if this actually returned results.
253 * We will provide an empty feed if that is the case.
258 $doc = new DOMDocument('1.0', 'utf-8');
259 $doc->formatOutput = true;
261 $alternatelink = $owner['url'];
263 if (isset($category)) {
264 $alternatelink .= "/category/".$category;
268 $author = "dfrn:owner";
273 $root = self::addHeader($doc, $owner, $author, $alternatelink, true);
275 /// @TODO This hook can't work anymore
276 // Addon::callHooks('atom_feed', $atom);
278 if (!DBM::is_result($items) || $onlyheader) {
279 $atom = trim($doc->saveXML());
281 Addon::callHooks('atom_feed_end', $atom);
286 foreach ($items as $item) {
287 // prevent private email from leaking.
288 if ($item['network'] == NETWORK_MAIL) {
292 // public feeds get html, our own nodes use bbcode
296 // catch any email that's in a public conversation and make sure it doesn't leak
297 if ($item['private']) {
304 $entry = self::entry($doc, $type, $item, $owner, true);
305 $root->appendChild($entry);
308 $atom = trim($doc->saveXML());
310 Addon::callHooks('atom_feed_end', $atom);
316 * @brief Generate an atom entry for a given item id
318 * @param int $item_id The item id
319 * @param boolean $conversation Show the conversation. If false show the single post.
321 * @return string DFRN feed entry
323 public static function itemFeed($item_id, $conversation = false)
326 $condition = '`item`.`parent`';
328 $condition = '`item`.`id`';
332 "SELECT `item`.*, `item`.`id` AS `item_id`,
333 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
334 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
335 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
336 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
338 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
339 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
340 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
341 WHERE %s = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
342 AND NOT `item`.`private`",
347 if (!DBM::is_result($r)) {
354 if ($item['uid'] != 0) {
355 $owner = User::getOwnerDataById($item['uid']);
360 $owner = ['uid' => 0, 'nick' => 'feed-item'];
363 $doc = new DOMDocument('1.0', 'utf-8');
364 $doc->formatOutput = true;
368 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
369 $doc->appendChild($root);
371 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
372 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
373 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
374 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
375 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
376 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
377 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
378 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
379 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
381 //$root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
383 foreach ($items as $item) {
384 $entry = self::entry($doc, $type, $item, $owner, true, 0);
385 $root->appendChild($entry);
388 $root = self::entry($doc, $type, $item, $owner, true, 0, true);
391 $atom = trim($doc->saveXML());
396 * @brief Create XML text for DFRN mails
398 * @param array $item message elements
399 * @param array $owner Owner record
401 * @return string DFRN mail
402 * @todo Add type-hints
404 public static function mail($item, $owner)
406 $doc = new DOMDocument('1.0', 'utf-8');
407 $doc->formatOutput = true;
409 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
411 $mail = $doc->createElement("dfrn:mail");
412 $sender = $doc->createElement("dfrn:sender");
414 XML::addElement($doc, $sender, "dfrn:name", $owner['name']);
415 XML::addElement($doc, $sender, "dfrn:uri", $owner['url']);
416 XML::addElement($doc, $sender, "dfrn:avatar", $owner['thumb']);
418 $mail->appendChild($sender);
420 XML::addElement($doc, $mail, "dfrn:id", $item['uri']);
421 XML::addElement($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
422 XML::addElement($doc, $mail, "dfrn:sentdate", datetime_convert('UTC', 'UTC', $item['created'] . '+00:00', ATOM_TIME));
423 XML::addElement($doc, $mail, "dfrn:subject", $item['title']);
424 XML::addElement($doc, $mail, "dfrn:content", $item['body']);
426 $root->appendChild($mail);
428 return(trim($doc->saveXML()));
432 * @brief Create XML text for DFRN friend suggestions
434 * @param array $item suggestion elements
435 * @param array $owner Owner record
437 * @return string DFRN suggestions
438 * @todo Add type-hints
440 public static function fsuggest($item, $owner)
442 $doc = new DOMDocument('1.0', 'utf-8');
443 $doc->formatOutput = true;
445 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
447 $suggest = $doc->createElement("dfrn:suggest");
449 XML::addElement($doc, $suggest, "dfrn:url", $item['url']);
450 XML::addElement($doc, $suggest, "dfrn:name", $item['name']);
451 XML::addElement($doc, $suggest, "dfrn:photo", $item['photo']);
452 XML::addElement($doc, $suggest, "dfrn:request", $item['request']);
453 XML::addElement($doc, $suggest, "dfrn:note", $item['note']);
455 $root->appendChild($suggest);
457 return(trim($doc->saveXML()));
461 * @brief Create XML text for DFRN relocations
463 * @param array $owner Owner record
464 * @param int $uid User ID
466 * @return string DFRN relocations
467 * @todo Add type-hints
469 public static function relocate($owner, $uid)
472 /* get site pubkey. this could be a new installation with no site keys*/
473 $pubkey = Config::get('system', 'site_pubkey');
475 $res = Crypto::newKeypair(1024);
476 Config::set('system', 'site_prvkey', $res['prvkey']);
477 Config::set('system', 'site_pubkey', $res['pubkey']);
481 "SELECT `resource-id` , `scale`, type FROM `photo`
482 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;",
486 $ext = Image::supportedTypes();
488 foreach ($rp as $p) {
489 $photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
494 $doc = new DOMDocument('1.0', 'utf-8');
495 $doc->formatOutput = true;
497 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
499 $relocate = $doc->createElement("dfrn:relocate");
501 XML::addElement($doc, $relocate, "dfrn:url", $owner['url']);
502 XML::addElement($doc, $relocate, "dfrn:name", $owner['name']);
503 XML::addElement($doc, $relocate, "dfrn:addr", $owner['addr']);
504 XML::addElement($doc, $relocate, "dfrn:avatar", $owner['avatar']);
505 XML::addElement($doc, $relocate, "dfrn:photo", $photos[4]);
506 XML::addElement($doc, $relocate, "dfrn:thumb", $photos[5]);
507 XML::addElement($doc, $relocate, "dfrn:micro", $photos[6]);
508 XML::addElement($doc, $relocate, "dfrn:request", $owner['request']);
509 XML::addElement($doc, $relocate, "dfrn:confirm", $owner['confirm']);
510 XML::addElement($doc, $relocate, "dfrn:notify", $owner['notify']);
511 XML::addElement($doc, $relocate, "dfrn:poll", $owner['poll']);
512 XML::addElement($doc, $relocate, "dfrn:sitepubkey", Config::get('system', 'site_pubkey'));
514 $root->appendChild($relocate);
516 return(trim($doc->saveXML()));
520 * @brief Adds the header elements for the DFRN protocol
522 * @param object $doc XML document
523 * @param array $owner Owner record
524 * @param string $authorelement Element name for the author
525 * @param string $alternatelink link to profile or category
526 * @param bool $public Is it a header for public posts?
528 * @return object XML root object
529 * @todo Add type-hints
531 private static function addHeader($doc, $owner, $authorelement, $alternatelink = "", $public = false)
534 if ($alternatelink == "") {
535 $alternatelink = $owner['url'];
538 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
539 $doc->appendChild($root);
541 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
542 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
543 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
544 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
545 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
546 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
547 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
548 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
549 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
551 XML::addElement($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
552 XML::addElement($doc, $root, "title", $owner["name"]);
554 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION];
555 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
557 $attributes = ["rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/"];
558 XML::addElement($doc, $root, "link", "", $attributes);
560 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $alternatelink];
561 XML::addElement($doc, $root, "link", "", $attributes);
565 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
566 OStatus::hublinks($doc, $root, $owner["nick"]);
568 $attributes = ["rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
569 XML::addElement($doc, $root, "link", "", $attributes);
571 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
572 XML::addElement($doc, $root, "link", "", $attributes);
574 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
575 XML::addElement($doc, $root, "link", "", $attributes);
578 // For backward compatibility we keep this element
579 if ($owner['page-flags'] == PAGE_COMMUNITY) {
580 XML::addElement($doc, $root, "dfrn:community", 1);
583 // The former element is replaced by this one
584 XML::addElement($doc, $root, "dfrn:account_type", $owner["account-type"]);
586 /// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
588 XML::addElement($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
590 $author = self::addAuthor($doc, $owner, $authorelement, $public);
591 $root->appendChild($author);
597 * @brief Adds the author element in the header for the DFRN protocol
599 * @param object $doc XML document
600 * @param array $owner Owner record
601 * @param string $authorelement Element name for the author
602 * @param boolean $public boolean
604 * @return object XML author object
605 * @todo Add type-hints
607 private static function addAuthor($doc, $owner, $authorelement, $public)
609 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
611 "SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
612 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
613 intval($owner['uid'])
615 if (DBM::is_result($r)) {
621 $author = $doc->createElement($authorelement);
623 $namdate = datetime_convert('UTC', 'UTC', $owner['name-date'].'+00:00', ATOM_TIME);
624 $uridate = datetime_convert('UTC', 'UTC', $owner['uri-date'].'+00:00', ATOM_TIME);
625 $picdate = datetime_convert('UTC', 'UTC', $owner['avatar-date'].'+00:00', ATOM_TIME);
629 if (!$public || !$hidewall) {
630 $attributes = ["dfrn:updated" => $namdate];
633 XML::addElement($doc, $author, "name", $owner["name"], $attributes);
634 XML::addElement($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
635 XML::addElement($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
637 $attributes = ["rel" => "photo", "type" => "image/jpeg",
638 "media:width" => 175, "media:height" => 175, "href" => $owner['photo']];
640 if (!$public || !$hidewall) {
641 $attributes["dfrn:updated"] = $picdate;
644 XML::addElement($doc, $author, "link", "", $attributes);
646 $attributes["rel"] = "avatar";
647 XML::addElement($doc, $author, "link", "", $attributes);
650 XML::addElement($doc, $author, "dfrn:hide", "true");
653 // The following fields will only be generated if the data isn't meant for a public feed
658 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
661 XML::addElement($doc, $author, "dfrn:birthday", $birthday);
664 // Only show contact details when we are allowed to
666 "SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
667 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
668 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
670 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
671 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
672 intval($owner['uid'])
674 if (DBM::is_result($r)) {
677 XML::addElement($doc, $author, "poco:displayName", $profile["name"]);
678 XML::addElement($doc, $author, "poco:updated", $namdate);
680 if (trim($profile["dob"]) > '0001-01-01') {
681 XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
684 XML::addElement($doc, $author, "poco:note", $profile["about"]);
685 XML::addElement($doc, $author, "poco:preferredUsername", $profile["nickname"]);
687 $savetz = date_default_timezone_get();
688 date_default_timezone_set($profile["timezone"]);
689 XML::addElement($doc, $author, "poco:utcOffset", date("P"));
690 date_default_timezone_set($savetz);
692 if (trim($profile["homepage"]) != "") {
693 $urls = $doc->createElement("poco:urls");
694 XML::addElement($doc, $urls, "poco:type", "homepage");
695 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
696 XML::addElement($doc, $urls, "poco:primary", "true");
697 $author->appendChild($urls);
700 if (trim($profile["pub_keywords"]) != "") {
701 $keywords = explode(",", $profile["pub_keywords"]);
703 foreach ($keywords as $keyword) {
704 XML::addElement($doc, $author, "poco:tags", trim($keyword));
708 if (trim($profile["xmpp"]) != "") {
709 $ims = $doc->createElement("poco:ims");
710 XML::addElement($doc, $ims, "poco:type", "xmpp");
711 XML::addElement($doc, $ims, "poco:value", $profile["xmpp"]);
712 XML::addElement($doc, $ims, "poco:primary", "true");
713 $author->appendChild($ims);
716 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
717 $element = $doc->createElement("poco:address");
719 XML::addElement($doc, $element, "poco:formatted", Profile::formatLocation($profile));
721 if (trim($profile["locality"]) != "") {
722 XML::addElement($doc, $element, "poco:locality", $profile["locality"]);
725 if (trim($profile["region"]) != "") {
726 XML::addElement($doc, $element, "poco:region", $profile["region"]);
729 if (trim($profile["country-name"]) != "") {
730 XML::addElement($doc, $element, "poco:country", $profile["country-name"]);
733 $author->appendChild($element);
741 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
743 * @param object $doc XML document
744 * @param string $element Element name for the author
745 * @param string $contact_url Link of the contact
746 * @param array $item Item elements
748 * @return object XML author object
749 * @todo Add type-hints
751 private static function addEntryAuthor($doc, $element, $contact_url, $item)
753 $contact = Contact::getDetailsByURL($contact_url, $item["uid"]);
755 $author = $doc->createElement($element);
756 XML::addElement($doc, $author, "name", $contact["name"]);
757 XML::addElement($doc, $author, "uri", $contact["url"]);
758 XML::addElement($doc, $author, "dfrn:handle", $contact["addr"]);
761 /// - Check real image type and image size
762 /// - Check which of these boths elements we should use
765 "type" => "image/jpeg",
767 "media:height" => 80,
768 "href" => $contact["photo"]];
769 XML::addElement($doc, $author, "link", "", $attributes);
773 "type" => "image/jpeg",
775 "media:height" => 80,
776 "href" => $contact["photo"]];
777 XML::addElement($doc, $author, "link", "", $attributes);
783 * @brief Adds the activity elements
785 * @param object $doc XML document
786 * @param string $element Element name for the activity
787 * @param string $activity activity value
789 * @return object XML activity object
790 * @todo Add type-hints
792 private static function createActivity($doc, $element, $activity)
795 $entry = $doc->createElement($element);
797 $r = XML::parseString($activity, false);
802 XML::addElement($doc, $entry, "activity:object-type", $r->type);
805 XML::addElement($doc, $entry, "id", $r->id);
808 XML::addElement($doc, $entry, "title", $r->title);
812 if (substr($r->link, 0, 1) == '<') {
813 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
814 $r->link = str_replace('&', '&', $r->link);
817 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
819 // XML does need a single element as root element so we add a dummy element here
820 $data = XML::parseString("<dummy>" . $r->link . "</dummy>", false);
821 if (is_object($data)) {
822 foreach ($data->link as $link) {
824 foreach ($link->attributes() as $parameter => $value) {
825 $attributes[$parameter] = $value;
827 XML::addElement($doc, $entry, "link", "", $attributes);
831 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
832 XML::addElement($doc, $entry, "link", "", $attributes);
836 XML::addElement($doc, $entry, "content", bbcode($r->content), ["type" => "html"]);
846 * @brief Adds the elements for attachments
848 * @param object $doc XML document
849 * @param object $root XML root
850 * @param array $item Item element
852 * @return object XML attachment object
853 * @todo Add type-hints
855 private static function getAttachment($doc, $root, $item)
857 $arr = explode('[/attach],', $item['attach']);
859 foreach ($arr as $r) {
861 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
863 $attributes = ["rel" => "enclosure",
864 "href" => $matches[1],
865 "type" => $matches[3]];
867 if (intval($matches[2])) {
868 $attributes["length"] = intval($matches[2]);
871 if (trim($matches[4]) != "") {
872 $attributes["title"] = trim($matches[4]);
875 XML::addElement($doc, $root, "link", "", $attributes);
882 * @brief Adds the "entry" elements for the DFRN protocol
884 * @param object $doc XML document
885 * @param string $type "text" or "html"
886 * @param array $item Item element
887 * @param array $owner Owner record
888 * @param bool $comment Trigger the sending of the "comment" element
889 * @param int $cid Contact ID of the recipient
890 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
892 * @return object XML entry object
893 * @todo Add type-hints
895 private static function entry($doc, $type, $item, $owner, $comment = false, $cid = 0, $single = false)
899 if (!$item['parent']) {
903 if ($item['deleted']) {
904 $attributes = ["ref" => $item['uri'], "when" => datetime_convert('UTC', 'UTC', $item['edited'] . '+00:00', ATOM_TIME)];
905 return XML::createElement($doc, "at:deleted-entry", "", $attributes);
909 $entry = $doc->createElement("entry");
911 $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry');
912 $doc->appendChild($entry);
914 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
915 $entry->setAttribute("xmlns:at", NAMESPACE_TOMB);
916 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
917 $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
918 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
919 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
920 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
921 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
922 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
925 if ($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid']) {
926 $body = Item::fixPrivatePhotos($item['body'], $owner['uid'], $item, $cid);
928 $body = $item['body'];
931 // Remove the abstract element. It is only locally important.
932 $body = remove_abstract($body);
934 if ($type == 'html') {
937 if ($item['title'] != "") {
938 $htmlbody = "[b]".$item['title']."[/b]\n\n".$htmlbody;
941 $htmlbody = bbcode($htmlbody, false, false, 7);
944 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
945 $entry->appendChild($author);
947 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
948 $entry->appendChild($dfrnowner);
950 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
951 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
952 $parent = q("SELECT `guid`,`plink` FROM `item` WHERE `uri` = '%s' AND `uid` = %d", dbesc($parent_item), intval($item['uid']));
953 $attributes = ["ref" => $parent_item, "type" => "text/html",
954 "href" => $parent[0]['plink'],
955 "dfrn:diaspora_guid" => $parent[0]['guid']];
956 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
959 // Add conversation data. This is used for OStatus
960 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
961 $conversation_uri = $conversation_href;
963 if (isset($parent_item)) {
964 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $item['parent-uri']);
965 if (DBM::is_result($r)) {
966 if ($r['conversation-uri'] != '') {
967 $conversation_uri = $r['conversation-uri'];
969 if ($r['conversation-href'] != '') {
970 $conversation_href = $r['conversation-href'];
976 "href" => $conversation_href,
977 "ref" => $conversation_uri];
979 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
981 XML::addElement($doc, $entry, "id", $item["uri"]);
982 XML::addElement($doc, $entry, "title", $item["title"]);
984 XML::addElement($doc, $entry, "published", datetime_convert("UTC", "UTC", $item["created"] . "+00:00", ATOM_TIME));
985 XML::addElement($doc, $entry, "updated", datetime_convert("UTC", "UTC", $item["edited"] . "+00:00", ATOM_TIME));
987 // "dfrn:env" is used to read the content
988 XML::addElement($doc, $entry, "dfrn:env", base64url_encode($body, true));
990 // The "content" field is not read by the receiver. We could remove it when the type is "text"
991 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
992 XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
994 // We save this value in "plink". Maybe we should read it from there as well?
1000 ["rel" => "alternate", "type" => "text/html",
1001 "href" => System::baseUrl() . "/display/" . $item["guid"]]
1004 // "comment-allow" is some old fashioned stuff for old Friendica versions.
1005 // It is included in the rewritten code for completeness
1007 XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
1010 if ($item['location']) {
1011 XML::addElement($doc, $entry, "dfrn:location", $item['location']);
1014 if ($item['coord']) {
1015 XML::addElement($doc, $entry, "georss:point", $item['coord']);
1018 if (($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])) {
1019 XML::addElement($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
1022 if ($item['extid']) {
1023 XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
1026 if ($item['bookmark']) {
1027 XML::addElement($doc, $entry, "dfrn:bookmark", "true");
1031 XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
1034 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
1036 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
1037 // It is needed for relayed comments to Diaspora.
1038 if ($item['signed_text']) {
1039 $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer']]));
1040 XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
1043 XML::addElement($doc, $entry, "activity:verb", self::constructVerb($item));
1045 if ($item['object-type'] != "") {
1046 XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
1047 } elseif ($item['id'] == $item['parent']) {
1048 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1050 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
1053 $actobj = self::createActivity($doc, "activity:object", $item['object']);
1055 $entry->appendChild($actobj);
1058 $actarg = self::createActivity($doc, "activity:target", $item['target']);
1060 $entry->appendChild($actarg);
1063 $tags = Item::getFeedTags($item);
1066 foreach ($tags as $t) {
1067 if (($type != 'html') || ($t[0] != "@")) {
1068 XML::addElement($doc, $entry, "category", "", ["scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]]);
1074 foreach ($tags as $t) {
1076 $mentioned[$t[1]] = $t[1];
1081 foreach ($mentioned as $mention) {
1083 "SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1084 intval($owner["uid"]),
1085 dbesc(normalise_link($mention))
1088 if (DBM::is_result($r) && ($r[0]["forum"] || $r[0]["prv"])) {
1094 ["rel" => "mentioned",
1095 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1104 ["rel" => "mentioned",
1105 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1111 self::getAttachment($doc, $entry, $item);
1117 * @brief encrypts data via AES
1119 * @param string $data The data that is to be encrypted
1120 * @param string $key The AES key
1122 * @return string encrypted data
1124 private static function aesEncrypt($data, $key)
1126 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1130 * @brief decrypts data via AES
1132 * @param string $encrypted The encrypted data
1133 * @param string $key The AES key
1135 * @return string decrypted data
1137 public static function aesDecrypt($encrypted, $key)
1139 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1143 * @brief Delivers the atom content to the contacts
1145 * @param array $owner Owner record
1146 * @param array $contact Contact record of the receiver
1147 * @param string $atom Content that will be transmitted
1148 * @param bool $dissolve (to be documented)
1150 * @return int Deliver status. -1 means an error.
1151 * @todo Add array type-hint for $owner, $contact
1153 public static function deliver($owner, $contact, $atom, $dissolve = false)
1157 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1159 if ($contact['duplex'] && $contact['dfrn-id']) {
1160 $idtosend = '0:' . $orig_id;
1162 if ($contact['duplex'] && $contact['issued-id']) {
1163 $idtosend = '1:' . $orig_id;
1166 $rino = Config::get('system', 'rino_encrypt');
1167 $rino = intval($rino);
1169 logger("Local rino version: ". $rino, LOGGER_DEBUG);
1171 $ssl_val = intval(Config::get('system', 'ssl_policy'));
1175 case SSL_POLICY_FULL:
1176 $ssl_policy = 'full';
1178 case SSL_POLICY_SELFSIGN:
1179 $ssl_policy = 'self';
1181 case SSL_POLICY_NONE:
1183 $ssl_policy = 'none';
1187 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1189 logger('dfrn_deliver: ' . $url);
1191 $ret = Network::curl($url);
1193 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1194 return -2; // timed out
1197 $xml = $ret['body'];
1199 $curl_stat = $a->get_curl_code();
1201 return -3; // timed out
1204 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1210 if (strpos($xml, '<?xml') === false) {
1211 logger('dfrn_deliver: no valid XML returned');
1212 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1216 $res = XML::parseString($xml);
1218 if ((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id))) {
1219 return (($res->status) ? $res->status : 3);
1223 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1224 $challenge = hex2bin((string) $res->challenge);
1225 $perm = (($res->perm) ? $res->perm : null);
1226 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1227 $rino_remote_version = intval($res->rino);
1228 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1230 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
1232 if ($owner['page-flags'] == PAGE_PRVGROUP) {
1236 $final_dfrn_id = '';
1239 if ((($perm == 'rw') && (! intval($contact['writable'])))
1240 || (($perm == 'r') && (intval($contact['writable'])))
1243 "update contact set writable = %d where id = %d",
1244 intval(($perm == 'rw') ? 1 : 0),
1245 intval($contact['id'])
1247 $contact['writable'] = (string) 1 - intval($contact['writable']);
1251 if (($contact['duplex'] && strlen($contact['pubkey']))
1252 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1253 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
1255 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
1256 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
1258 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
1259 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
1262 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1264 if (strpos($final_dfrn_id, ':') == 1) {
1265 $final_dfrn_id = substr($final_dfrn_id, 2);
1268 if ($final_dfrn_id != $orig_id) {
1269 logger('dfrn_deliver: wrong dfrn_id.');
1270 // did not decode properly - cannot trust this site
1274 $postvars['dfrn_id'] = $idtosend;
1275 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1277 $postvars['dissolve'] = '1';
1281 if ((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1282 $postvars['data'] = $atom;
1283 $postvars['perm'] = 'rw';
1285 $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
1286 $postvars['perm'] = 'r';
1289 $postvars['ssl_policy'] = $ssl_policy;
1292 $postvars['page'] = $page;
1296 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1297 logger('rino version: '. $rino_remote_version);
1299 switch ($rino_remote_version) {
1301 $key = openssl_random_pseudo_bytes(16);
1302 $data = self::aesEncrypt($postvars['data'], $key);
1305 logger("rino: invalid requested version '$rino_remote_version'");
1309 $postvars['rino'] = $rino_remote_version;
1310 $postvars['data'] = bin2hex($data);
1312 if ($dfrn_version >= 2.1) {
1313 if (($contact['duplex'] && strlen($contact['pubkey']))
1314 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1315 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
1317 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1319 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1322 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1323 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1325 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1329 logger('md5 rawkey ' . md5($postvars['key']));
1331 $postvars['key'] = bin2hex($postvars['key']);
1335 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), LOGGER_DATA);
1337 $xml = Network::post($contact['notify'], $postvars);
1339 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1341 $curl_stat = $a->get_curl_code();
1342 if ((!$curl_stat) || (!strlen($xml))) {
1343 return -9; // timed out
1346 if (($curl_stat == 503) && (stristr($a->get_curl_headers(), 'retry-after'))) {
1350 if (strpos($xml, '<?xml') === false) {
1351 logger('dfrn_deliver: phase 2: no valid XML returned');
1352 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1356 if ($contact['term-date'] > NULL_DATE) {
1357 logger("dfrn_deliver: $url back from the dead - removing mark for death");
1358 Contact::unmarkForArchival($contact);
1361 $res = XML::parseString($xml);
1363 if (!isset($res->status)) {
1367 if (!empty($res->message)) {
1368 logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1371 return intval($res->status);
1375 * @brief Add new birthday event for this person
1377 * @param array $contact Contact record
1378 * @param string $birthday Birthday of the contact
1380 * @todo Add array type-hint for $contact
1382 private static function birthdayEvent($contact, $birthday)
1384 // Check for duplicates
1386 "SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1387 intval($contact["uid"]),
1388 intval($contact["id"]),
1389 dbesc(datetime_convert("UTC", "UTC", $birthday)),
1393 if (DBM::is_result($r)) {
1397 logger("updating birthday: ".$birthday." for contact ".$contact["id"]);
1399 $bdtext = L10n::t("%s\'s birthday", $contact["name"]);
1400 $bdtext2 = L10n::t("Happy Birthday %s", " [url=".$contact["url"]."]".$contact["name"]."[/url]");
1403 "INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1404 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1405 intval($contact["uid"]),
1406 intval($contact["id"]),
1407 dbesc(datetime_convert()),
1408 dbesc(datetime_convert()),
1409 dbesc(datetime_convert("UTC", "UTC", $birthday)),
1410 dbesc(datetime_convert("UTC", "UTC", $birthday . " + 1 day ")),
1418 * @brief Fetch the author data from head or entry items
1420 * @param object $xpath XPath object
1421 * @param object $context In which context should the data be searched
1422 * @param array $importer Record of the importer user mixed with contact of the content
1423 * @param string $element Element name from which the data is fetched
1424 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1425 * @param string $xml optional, default empty
1427 * @return array Relevant data of the author
1428 * @todo Find good type-hints for all parameter
1430 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
1433 $author["name"] = $xpath->evaluate($element."/atom:name/text()", $context)->item(0)->nodeValue;
1434 $author["link"] = $xpath->evaluate($element."/atom:uri/text()", $context)->item(0)->nodeValue;
1437 "SELECT `id`, `uid`, `url`, `network`, `avatar-date`, `name-date`, `uri-date`, `addr`,
1438 `name`, `nick`, `about`, `location`, `keywords`, `xmpp`, `bdyear`, `bd`, `hidden`, `contact-type`
1439 FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
1440 intval($importer["uid"]),
1441 dbesc(normalise_link($author["link"])),
1442 dbesc(NETWORK_STATUSNET)
1445 if (DBM::is_result($r)) {
1447 $author["contact-id"] = $r[0]["id"];
1448 $author["network"] = $r[0]["network"];
1451 logger("Contact ".$author["link"]." wasn't found for user ".$importer["uid"]." XML: ".$xml, LOGGER_DEBUG);
1454 $author["contact-id"] = $importer["id"];
1455 $author["network"] = $importer["network"];
1459 // Until now we aren't serving different sizes - but maybe later
1461 /// @todo check if "avatar" or "photo" would be the best field in the specification
1462 $avatars = $xpath->query($element."/atom:link[@rel='avatar']", $context);
1463 foreach ($avatars as $avatar) {
1466 foreach ($avatar->attributes as $attributes) {
1467 /// @TODO Rewrite these similar if () to one switch
1468 if ($attributes->name == "href") {
1469 $href = $attributes->textContent;
1471 if ($attributes->name == "width") {
1472 $width = $attributes->textContent;
1474 if ($attributes->name == "updated") {
1475 $contact["avatar-date"] = $attributes->textContent;
1478 if (($width > 0) && ($href != "")) {
1479 $avatarlist[$width] = $href;
1482 if (count($avatarlist) > 0) {
1483 krsort($avatarlist);
1484 $author["avatar"] = current($avatarlist);
1487 if (DBM::is_result($r) && !$onlyfetch) {
1488 logger("Check if contact details for contact " . $r[0]["id"] . " (" . $r[0]["nick"] . ") have to be updated.", LOGGER_DEBUG);
1490 $poco = ["url" => $contact["url"]];
1492 // When was the last change to name or uri?
1493 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1494 foreach ($name_element->attributes as $attributes) {
1495 if ($attributes->name == "updated") {
1496 $poco["name-date"] = $attributes->textContent;
1500 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1501 foreach ($link_element->attributes as $attributes) {
1502 if ($attributes->name == "updated") {
1503 $poco["uri-date"] = $attributes->textContent;
1507 // Update contact data
1508 $value = $xpath->evaluate($element . "/dfrn:handle/text()", $context)->item(0)->nodeValue;
1510 $poco["addr"] = $value;
1513 $value = $xpath->evaluate($element . "/poco:displayName/text()", $context)->item(0)->nodeValue;
1515 $poco["name"] = $value;
1518 $value = $xpath->evaluate($element . "/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
1520 $poco["nick"] = $value;
1523 $value = $xpath->evaluate($element . "/poco:note/text()", $context)->item(0)->nodeValue;
1525 $poco["about"] = $value;
1528 $value = $xpath->evaluate($element . "/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
1530 $poco["location"] = $value;
1533 /// @todo Only search for elements with "poco:type" = "xmpp"
1534 $value = $xpath->evaluate($element . "/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
1536 $poco["xmpp"] = $value;
1539 /// @todo Add support for the following fields that we don't support by now in the contact table:
1540 /// - poco:utcOffset
1546 // If the "hide" element is present then the profile isn't searchable.
1547 $hide = intval($xpath->evaluate($element . "/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
1549 logger("Hidden status for contact " . $contact["url"] . ": " . $hide, LOGGER_DEBUG);
1551 // If the contact isn't searchable then set the contact to "hidden".
1552 // Problem: This can be manually overridden by the user.
1554 $contact["hidden"] = true;
1557 // Save the keywords into the contact table
1559 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1560 foreach ($tagelements as $tag) {
1561 $tags[$tag->nodeValue] = $tag->nodeValue;
1565 $poco["keywords"] = implode(", ", $tags);
1568 // "dfrn:birthday" contains the birthday converted to UTC
1569 $old_bdyear = $contact["bdyear"];
1571 $birthday = $xpath->evaluate($element . "/dfrn:birthday/text()", $context)->item(0)->nodeValue;
1573 if (strtotime($birthday) > time()) {
1574 $bd_timestamp = strtotime($birthday);
1576 $poco["bdyear"] = date("Y", $bd_timestamp);
1579 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1580 $value = $xpath->evaluate($element . "/poco:birthday/text()", $context)->item(0)->nodeValue;
1582 if (!in_array($value, ["", "0000-00-00", "0001-01-01"])) {
1583 $bdyear = date("Y");
1584 $value = str_replace("0000", $bdyear, $value);
1586 if (strtotime($value) < time()) {
1587 $value = str_replace($bdyear, $bdyear + 1, $value);
1588 $bdyear = $bdyear + 1;
1591 $poco["bd"] = $value;
1594 $contact = array_merge($contact, $poco);
1596 if ($old_bdyear != $contact["bdyear"]) {
1597 self::birthdayEvent($contact, $birthday);
1600 // Get all field names
1602 foreach ($r[0] as $field => $data) {
1603 $fields[$field] = $data;
1606 unset($fields["id"]);
1607 unset($fields["uid"]);
1608 unset($fields["url"]);
1609 unset($fields["avatar-date"]);
1610 unset($fields["name-date"]);
1611 unset($fields["uri-date"]);
1613 // Update check for this field has to be done differently
1614 $datefields = ["name-date", "uri-date"];
1615 foreach ($datefields as $field) {
1616 if (strtotime($contact[$field]) > strtotime($r[0][$field])) {
1617 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $r[0][$field] . "'", LOGGER_DEBUG);
1622 foreach ($fields as $field => $data) {
1623 if ($contact[$field] != $r[0][$field]) {
1624 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $r[0][$field] . "'", LOGGER_DEBUG);
1630 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1633 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1634 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1635 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1636 WHERE `id` = %d AND `network` = '%s'",
1637 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
1638 dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1639 dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
1640 dbesc(DBM::date($contact["name-date"])), dbesc(DBM::date($contact["uri-date"])),
1641 intval($contact["id"]), dbesc($contact["network"])
1645 Contact::updateAvatar(
1649 (strtotime($contact["avatar-date"]) > strtotime($r[0]["avatar-date"]))
1653 * The generation is a sign for the reliability of the provided data.
1654 * It is used in the socgraph.php to prevent that old contact data
1655 * that was relayed over several servers can overwrite contact
1656 * data that we received directly.
1659 $poco["generation"] = 2;
1660 $poco["photo"] = $author["avatar"];
1661 $poco["hide"] = $hide;
1662 $poco["contact-type"] = $contact["contact-type"];
1663 $gcid = GContact::update($poco);
1665 GContact::link($gcid, $importer["uid"], $contact["id"]);
1672 * @brief Transforms activity objects into an XML string
1674 * @param object $xpath XPath object
1675 * @param object $activity Activity object
1676 * @param string $element element name
1678 * @return string XML string
1679 * @todo Find good type-hints for all parameter
1681 private static function transformActivity($xpath, $activity, $element)
1683 if (!is_object($activity)) {
1687 $obj_doc = new DOMDocument("1.0", "utf-8");
1688 $obj_doc->formatOutput = true;
1690 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1692 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1693 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1695 $id = $xpath->query("atom:id", $activity)->item(0);
1696 if (is_object($id)) {
1697 $obj_element->appendChild($obj_doc->importNode($id, true));
1700 $title = $xpath->query("atom:title", $activity)->item(0);
1701 if (is_object($title)) {
1702 $obj_element->appendChild($obj_doc->importNode($title, true));
1705 $links = $xpath->query("atom:link", $activity);
1706 if (is_object($links)) {
1707 foreach ($links as $link) {
1708 $obj_element->appendChild($obj_doc->importNode($link, true));
1712 $content = $xpath->query("atom:content", $activity)->item(0);
1713 if (is_object($content)) {
1714 $obj_element->appendChild($obj_doc->importNode($content, true));
1717 $obj_doc->appendChild($obj_element);
1719 $objxml = $obj_doc->saveXML($obj_element);
1721 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1722 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1727 * @brief Processes the mail elements
1729 * @param object $xpath XPath object
1730 * @param object $mail mail elements
1731 * @param array $importer Record of the importer user mixed with contact of the content
1733 * @todo Find good type-hints for all parameter
1735 private static function processMail($xpath, $mail, $importer)
1737 logger("Processing mails");
1739 /// @TODO Rewrite this to one statement
1741 $msg["uid"] = $importer["importer_uid"];
1742 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1743 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1744 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1745 $msg["contact-id"] = $importer["id"];
1746 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1747 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1748 $msg["created"] = $xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue;
1749 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1750 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1752 $msg["replied"] = 0;
1754 dba::insert('mail', $msg);
1756 // send notifications.
1757 /// @TODO Arange this mess
1759 "type" => NOTIFY_MAIL,
1760 "notify_flags" => $importer["notify-flags"],
1761 "language" => $importer["language"],
1762 "to_name" => $importer["username"],
1763 "to_email" => $importer["email"],
1764 "uid" => $importer["importer_uid"],
1766 "source_name" => $msg["from-name"],
1767 "source_link" => $importer["url"],
1768 "source_photo" => $importer["thumb"],
1769 "verb" => ACTIVITY_POST,
1773 notification($notif_params);
1775 logger("Mail is processed, notification was sent.");
1779 * @brief Processes the suggestion elements
1781 * @param object $xpath XPath object
1782 * @param object $suggestion suggestion elements
1783 * @param array $importer Record of the importer user mixed with contact of the content
1785 * @todo Find good type-hints for all parameter
1787 private static function processSuggestion($xpath, $suggestion, $importer)
1791 logger("Processing suggestions");
1793 /// @TODO Rewrite this to one statement
1795 $suggest["uid"] = $importer["importer_uid"];
1796 $suggest["cid"] = $importer["id"];
1797 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1798 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1799 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1800 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1801 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1803 // Does our member already have a friend matching this description?
1806 "SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1807 dbesc($suggest["name"]),
1808 dbesc(normalise_link($suggest["url"])),
1809 intval($suggest["uid"])
1813 * The valid result means the friend we're about to send a friend
1814 * suggestion already has them in their contact, which means no further
1815 * action is required.
1817 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1819 if (DBM::is_result($r)) {
1823 // Do we already have an fcontact record for this person?
1827 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1828 dbesc($suggest["url"]),
1829 dbesc($suggest["name"]),
1830 dbesc($suggest["request"])
1832 if (DBM::is_result($r)) {
1835 // OK, we do. Do we already have an introduction for this person ?
1837 "SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1838 intval($suggest["uid"]),
1843 * The valid result means the friend we're about to send a friend
1844 * suggestion already has them in their contact, which means no further
1845 * action is required.
1847 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1849 if (DBM::is_result($r)) {
1855 "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1856 dbesc($suggest["name"]),
1857 dbesc($suggest["url"]),
1858 dbesc($suggest["photo"]),
1859 dbesc($suggest["request"])
1863 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1864 dbesc($suggest["url"]),
1865 dbesc($suggest["name"]),
1866 dbesc($suggest["request"])
1870 * If no record in fcontact is found, below INSERT statement will not
1871 * link an introduction to it.
1873 if (!DBM::is_result($r)) {
1874 // database record did not get created. Quietly give up.
1880 $hash = random_string();
1883 "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1884 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1885 intval($suggest["uid"]),
1887 intval($suggest["cid"]),
1888 dbesc($suggest["body"]),
1890 dbesc(datetime_convert()),
1896 "type" => NOTIFY_SUGGEST,
1897 "notify_flags" => $importer["notify-flags"],
1898 "language" => $importer["language"],
1899 "to_name" => $importer["username"],
1900 "to_email" => $importer["email"],
1901 "uid" => $importer["importer_uid"],
1903 "link" => System::baseUrl()."/notifications/intros",
1904 "source_name" => $importer["name"],
1905 "source_link" => $importer["url"],
1906 "source_photo" => $importer["photo"],
1907 "verb" => ACTIVITY_REQ_FRIEND,
1915 * @brief Processes the relocation elements
1917 * @param object $xpath XPath object
1918 * @param object $relocation relocation elements
1919 * @param array $importer Record of the importer user mixed with contact of the content
1921 * @todo Find good type-hints for all parameter
1923 private static function processRelocation($xpath, $relocation, $importer)
1925 logger("Processing relocations");
1927 /// @TODO Rewrite this to one statement
1929 $relocate["uid"] = $importer["importer_uid"];
1930 $relocate["cid"] = $importer["id"];
1931 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1932 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
1933 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1934 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
1935 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1936 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1937 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1938 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1939 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1940 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1941 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1942 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1944 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
1945 $relocate["avatar"] = $relocate["photo"];
1948 if ($relocate["addr"] == "") {
1949 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
1954 "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
1955 intval($importer["id"]),
1956 intval($importer["importer_uid"])
1959 if (!DBM::is_result($r)) {
1960 logger("Query failed to execute, no result returned in " . __FUNCTION__);
1966 // Update the gcontact entry
1967 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
1970 "UPDATE `gcontact` SET
1979 WHERE `nurl` = '%s';",
1980 dbesc($relocate["name"]),
1981 dbesc($relocate["avatar"]),
1982 dbesc($relocate["url"]),
1983 dbesc(normalise_link($relocate["url"])),
1984 dbesc($relocate["addr"]),
1985 dbesc($relocate["addr"]),
1986 dbesc($relocate["notify"]),
1987 dbesc($relocate["server_url"]),
1988 dbesc(normalise_link($old["url"]))
1991 // Update the contact table. We try to find every entry.
1993 "UPDATE `contact` SET
2003 `site-pubkey` = '%s'
2004 WHERE (`id` = %d AND `uid` = %d) OR (`nurl` = '%s');",
2005 dbesc($relocate["name"]),
2006 dbesc($relocate["avatar"]),
2007 dbesc($relocate["url"]),
2008 dbesc(normalise_link($relocate["url"])),
2009 dbesc($relocate["addr"]),
2010 dbesc($relocate["request"]),
2011 dbesc($relocate["confirm"]),
2012 dbesc($relocate["notify"]),
2013 dbesc($relocate["poll"]),
2014 dbesc($relocate["sitepubkey"]),
2015 intval($importer["id"]),
2016 intval($importer["importer_uid"]),
2017 dbesc(normalise_link($old["url"]))
2020 Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
2027 /// @todo This is an extreme performance killer
2029 'owner-link' => [$old["url"], $relocate["url"]],
2030 'author-link' => [$old["url"], $relocate["url"]],
2031 //'owner-avatar' => array($old["photo"], $relocate["photo"]),
2032 //'author-avatar' => array($old["photo"], $relocate["photo"]),
2034 foreach ($fields as $n => $f) {
2036 "SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
2039 intval($importer["importer_uid"])
2042 if (DBM::is_result($r)) {
2044 "UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
2049 intval($importer["importer_uid"])
2059 /// merge with current record, current contents have priority
2060 /// update record, set url-updated
2061 /// update profile photos
2062 /// schedule a scan?
2067 * @brief Updates an item
2069 * @param array $current the current item record
2070 * @param array $item the new item record
2071 * @param array $importer Record of the importer user mixed with contact of the content
2072 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2074 * @todo set proper type-hints (array?)
2076 private static function updateContent($current, $item, $importer, $entrytype)
2080 if (self::isEditedTimestampNewer($current, $item)) {
2081 // do not accept (ignore) an earlier edit than one we currently have.
2082 if (datetime_convert("UTC", "UTC", $item["edited"]) < $current["edited"]) {
2086 $fields = ['title' => $item["title"], 'body' => $item["body"],
2087 'tag' => $item["tag"], 'changed' => datetime_convert(),
2088 'edited' => datetime_convert("UTC", "UTC", $item["edited"])];
2090 $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
2091 dba::update('item', $fields, $condition);
2093 create_tags_from_itemuri($item["uri"], $importer["importer_uid"]);
2094 update_thread_uri($item["uri"], $importer["importer_uid"]);
2098 if ($entrytype == DFRN_REPLY_RC) {
2099 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $current["id"]);
2106 * @brief Detects the entry type of the item
2108 * @param array $importer Record of the importer user mixed with contact of the content
2109 * @param array $item the new item record
2111 * @return int Is it a toplevel entry, a comment or a relayed comment?
2112 * @todo set proper type-hints (array?)
2114 private static function getEntryType($importer, $item)
2116 if ($item["parent-uri"] != $item["uri"]) {
2119 if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
2122 logger("possible community action");
2124 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2127 // was the top-level post for this action written by somebody on this site?
2128 // Specifically, the recipient?
2130 $is_a_remote_action = false;
2133 "SELECT `item`.`parent-uri` FROM `item`
2134 WHERE `item`.`uri` = '%s'
2136 dbesc($item["parent-uri"])
2138 if (DBM::is_result($r)) {
2140 "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2141 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2142 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2143 AND `item`.`uid` = %d
2146 dbesc($r[0]["parent-uri"]),
2147 dbesc($r[0]["parent-uri"]),
2148 dbesc($r[0]["parent-uri"]),
2149 intval($importer["importer_uid"])
2151 if (DBM::is_result($r)) {
2152 $is_a_remote_action = true;
2157 * Does this have the characteristics of a community or private group action?
2158 * If it's an action to a wall post on a community/prvgroup page it's a
2159 * valid community action. Also forum_mode makes it valid for sure.
2160 * If neither, it's not.
2162 if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2163 $is_a_remote_action = false;
2164 logger("not a community action");
2167 if ($is_a_remote_action) {
2168 return DFRN_REPLY_RC;
2173 return DFRN_TOP_LEVEL;
2178 * @brief Send a "poke"
2180 * @param array $item the new item record
2181 * @param array $importer Record of the importer user mixed with contact of the content
2182 * @param int $posted_id The record number of item record that was just posted
2184 * @todo set proper type-hints (array?)
2186 private static function doPoke($item, $importer, $posted_id)
2188 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2192 $xo = XML::parseString($item["object"], false);
2194 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2195 // somebody was poked/prodded. Was it me?
2196 foreach ($xo->link as $l) {
2197 $atts = $l->attributes();
2198 switch ($atts["rel"]) {
2200 $Blink = $atts["href"];
2207 if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2208 // send a notification
2211 "type" => NOTIFY_POKE,
2212 "notify_flags" => $importer["notify-flags"],
2213 "language" => $importer["language"],
2214 "to_name" => $importer["username"],
2215 "to_email" => $importer["email"],
2216 "uid" => $importer["importer_uid"],
2218 "link" => System::baseUrl()."/display/".urlencode(Item::getGuidById($posted_id)),
2219 "source_name" => stripslashes($item["author-name"]),
2220 "source_link" => $item["author-link"],
2221 "source_photo" => ((link_compare($item["author-link"], $importer["url"]))
2222 ? $importer["thumb"] : $item["author-avatar"]),
2223 "verb" => $item["verb"],
2224 "otype" => "person",
2225 "activity" => $verb,
2226 "parent" => $item["parent"]]
2233 * @brief Processes several actions, depending on the verb
2235 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2236 * @param array $importer Record of the importer user mixed with contact of the content
2237 * @param array $item the new item record
2238 * @param bool $is_like Is the verb a "like"?
2240 * @return bool Should the processing of the entries be continued?
2241 * @todo set proper type-hints (array?)
2243 private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2245 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2247 if (($entrytype == DFRN_TOP_LEVEL)) {
2248 // The filling of the the "contact" variable is done for legcy reasons
2249 // The functions below are partly used by ostatus.php as well - where we have this variable
2250 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2252 $nickname = $contact["nick"];
2254 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2255 // This function once was responsible for DFRN and OStatus.
2256 if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2257 logger("New follower");
2258 Contact::addRelationship($importer, $contact, $item, $nickname);
2261 if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2262 logger("Lost follower");
2263 Contact::removeFollower($importer, $contact, $item);
2266 if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2267 logger("New friend request");
2268 Contact::addRelationship($importer, $contact, $item, $nickname, true);
2271 if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2272 logger("Lost sharer");
2273 Contact::removeSharer($importer, $contact, $item);
2277 if (($item["verb"] == ACTIVITY_LIKE)
2278 || ($item["verb"] == ACTIVITY_DISLIKE)
2279 || ($item["verb"] == ACTIVITY_ATTEND)
2280 || ($item["verb"] == ACTIVITY_ATTENDNO)
2281 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
2284 $item["type"] = "activity";
2285 $item["gravity"] = GRAVITY_LIKE;
2286 // only one like or dislike per person
2287 // splitted into two queries for performance issues
2289 "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `parent-uri` = '%s' AND NOT `deleted` LIMIT 1",
2290 intval($item["uid"]),
2291 dbesc($item["author-link"]),
2292 dbesc($item["verb"]),
2293 dbesc($item["parent-uri"])
2295 if (DBM::is_result($r)) {
2300 "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `thr-parent` = '%s' AND NOT `deleted` LIMIT 1",
2301 intval($item["uid"]),
2302 dbesc($item["author-link"]),
2303 dbesc($item["verb"]),
2304 dbesc($item["parent-uri"])
2306 if (DBM::is_result($r)) {
2313 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2314 $xo = XML::parseString($item["object"], false);
2315 $xt = XML::parseString($item["target"], false);
2317 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2319 "SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2321 intval($importer["importer_uid"])
2324 if (!DBM::is_result($r)) {
2325 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2329 // extract tag, if not duplicate, add to parent item
2331 if (!(stristr($r[0]["tag"], trim($xo->content)))) {
2333 "UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2334 dbesc($r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2337 create_tags_from_item($r[0]["id"]);
2347 * @brief Processes the link elements
2349 * @param object $links link elements
2350 * @param array $item the item record
2352 * @todo set proper type-hints
2354 private static function parseLinks($links, &$item)
2361 foreach ($links as $link) {
2362 foreach ($link->attributes as $attributes) {
2363 switch ($attributes->name) {
2364 case "href" : $href = $attributes->textContent; break;
2365 case "rel" : $rel = $attributes->textContent; break;
2366 case "type" : $type = $attributes->textContent; break;
2367 case "length": $length = $attributes->textContent; break;
2368 case "title" : $title = $attributes->textContent; break;
2371 if (($rel != "") && ($href != "")) {
2374 $item["plink"] = $href;
2378 if (strlen($item["attach"])) {
2379 $item["attach"] .= ",";
2382 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2390 * @brief Processes the entry elements which contain the items and comments
2392 * @param array $header Array of the header elements that always stay the same
2393 * @param object $xpath XPath object
2394 * @param object $entry entry elements
2395 * @param array $importer Record of the importer user mixed with contact of the content
2396 * @param object $xml xml
2398 * @todo Add type-hints
2400 private static function processEntry($header, $xpath, $entry, $importer, $xml)
2402 logger("Processing entries");
2406 $item["protocol"] = PROTOCOL_DFRN;
2408 $item["source"] = $xml;
2411 $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
2413 $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
2416 "SELECT `id`, `uid`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2417 dbesc($item["uri"]),
2418 intval($importer["importer_uid"])
2421 // Is there an existing item?
2422 if (DBM::is_result($current) && self::isEditedTimestampNewer($current[0], $item)
2423 && (datetime_convert("UTC", "UTC", $item["edited"]) < $current[0]["edited"])
2425 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2430 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2432 $item["owner-name"] = $owner["name"];
2433 $item["owner-link"] = $owner["link"];
2434 $item["owner-avatar"] = $owner["avatar"];
2437 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2439 $item["author-name"] = $author["name"];
2440 $item["author-link"] = $author["link"];
2441 $item["author-avatar"] = $author["avatar"];
2443 $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
2445 $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2447 $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
2448 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2449 // make sure nobody is trying to sneak some html tags by us
2450 $item["body"] = notags(base64url_decode($item["body"]));
2452 $item["body"] = Item::limitBodySize($item["body"]);
2454 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2455 if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
2456 $base_url = get_app()->get_baseurl();
2457 $item['body'] = reltoabs($item['body'], $base_url);
2459 $item['body'] = html2bb_video($item['body']);
2461 $item['body'] = OEmbed::HTML2BBCode($item['body']);
2463 $config = HTMLPurifier_Config::createDefault();
2464 $config->set('Cache.DefinitionImpl', null);
2466 // we shouldn't need a whitelist, because the bbcode converter
2467 // will strip out any unsupported tags.
2469 $purifier = new HTMLPurifier($config);
2470 $item['body'] = $purifier->purify($item['body']);
2472 $item['body'] = @html2bbcode($item['body']);
2475 /// @todo We should check for a repeated post and if we know the repeated author.
2477 // We don't need the content element since "dfrn:env" is always present
2478 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2480 $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
2482 $georsspoint = $xpath->query("georss:point", $entry);
2484 $item["coord"] = $georsspoint->item(0)->nodeValue;
2487 $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
2489 $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
2491 if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true") {
2492 $item["bookmark"] = true;
2495 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2496 if ($notice_info && ($notice_info->length > 0)) {
2497 foreach ($notice_info->item(0)->attributes as $attributes) {
2498 if ($attributes->name == "source") {
2499 $item["app"] = strip_tags($attributes->textContent);
2504 $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
2506 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
2507 $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
2508 if ($dsprsig != "") {
2509 $item["dsprsig"] = $dsprsig;
2512 $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
2514 if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "") {
2515 $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
2518 $object = $xpath->query("activity:object", $entry)->item(0);
2519 $item["object"] = self::transformActivity($xpath, $object, "object");
2521 if (trim($item["object"]) != "") {
2522 $r = XML::parseString($item["object"], false);
2523 if (isset($r->type)) {
2524 $item["object-type"] = $r->type;
2528 $target = $xpath->query("activity:target", $entry)->item(0);
2529 $item["target"] = self::transformActivity($xpath, $target, "target");
2531 $categories = $xpath->query("atom:category", $entry);
2533 foreach ($categories as $category) {
2536 foreach ($category->attributes as $attributes) {
2537 if ($attributes->name == "term") {
2538 $term = $attributes->textContent;
2541 if ($attributes->name == "scheme") {
2542 $scheme = $attributes->textContent;
2546 if (($term != "") && ($scheme != "")) {
2547 $parts = explode(":", $scheme);
2548 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2549 $termhash = array_shift($parts);
2550 $termurl = implode(":", $parts);
2552 if (strlen($item["tag"])) {
2553 $item["tag"] .= ",";
2556 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2564 $links = $xpath->query("atom:link", $entry);
2566 self::parseLinks($links, $item);
2569 $item['conversation-uri'] = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
2571 $conv = $xpath->query('ostatus:conversation', $entry);
2572 if (is_object($conv->item(0))) {
2573 foreach ($conv->item(0)->attributes as $attributes) {
2574 if ($attributes->name == "ref") {
2575 $item['conversation-uri'] = $attributes->textContent;
2577 if ($attributes->name == "href") {
2578 $item['conversation-href'] = $attributes->textContent;
2583 // Is it a reply or a top level posting?
2584 $item["parent-uri"] = $item["uri"];
2586 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2587 if (is_object($inreplyto->item(0))) {
2588 foreach ($inreplyto->item(0)->attributes as $attributes) {
2589 if ($attributes->name == "ref") {
2590 $item["parent-uri"] = $attributes->textContent;
2595 // Get the type of the item (Top level post, reply or remote reply)
2596 $entrytype = self::getEntryType($importer, $item);
2598 // Now assign the rest of the values that depend on the type of the message
2599 if (in_array($entrytype, [DFRN_REPLY, DFRN_REPLY_RC])) {
2600 if (!isset($item["object-type"])) {
2601 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2604 if ($item["contact-id"] != $owner["contact-id"]) {
2605 $item["contact-id"] = $owner["contact-id"];
2608 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2609 $item["network"] = $owner["network"];
2612 if ($item["contact-id"] != $author["contact-id"]) {
2613 $item["contact-id"] = $author["contact-id"];
2616 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2617 $item["network"] = $author["network"];
2621 if ($entrytype == DFRN_REPLY_RC) {
2622 $item["type"] = "remote-comment";
2624 } elseif ($entrytype == DFRN_TOP_LEVEL) {
2625 if (!isset($item["object-type"])) {
2626 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2630 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2631 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2632 $ev = bbtoevent($item["body"]);
2633 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2634 logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2635 $ev["cid"] = $importer["id"];
2636 $ev["uid"] = $importer["uid"];
2637 $ev["uri"] = $item["uri"];
2638 $ev["edited"] = $item["edited"];
2639 $ev["private"] = $item["private"];
2640 $ev["guid"] = $item["guid"];
2643 "SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2644 dbesc($item["uri"]),
2645 intval($importer["uid"])
2647 if (DBM::is_result($r)) {
2648 $ev["id"] = $r[0]["id"];
2651 $event_id = event_store($ev);
2652 logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2658 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2659 logger("Exiting because 'processVerbs' told us so", LOGGER_DEBUG);
2663 // Update content if 'updated' changes
2664 if (DBM::is_result($current)) {
2665 if (self::updateContent($r[0], $item, $importer, $entrytype)) {
2666 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2668 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2673 if (in_array($entrytype, [DFRN_REPLY, DFRN_REPLY_RC])) {
2674 $posted_id = Item::insert($item);
2678 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2680 $item["id"] = $posted_id;
2683 "SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2685 intval($importer["importer_uid"])
2687 if (DBM::is_result($r)) {
2688 $parent = $r[0]["parent"];
2689 $parent_uri = $r[0]["parent-uri"];
2692 if ($posted_id && $parent && ($entrytype == DFRN_REPLY_RC)) {
2693 logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
2694 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $posted_id);
2699 } else { // $entrytype == DFRN_TOP_LEVEL
2700 if (!link_compare($item["owner-link"], $importer["url"])) {
2702 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2703 * but otherwise there's a possible data mixup on the sender's system.
2704 * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2705 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2707 logger('Correcting item owner.', LOGGER_DEBUG);
2708 $item["owner-name"] = $importer["senderName"];
2709 $item["owner-link"] = $importer["url"];
2710 $item["owner-avatar"] = $importer["thumb"];
2713 if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2714 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2718 // This is my contact on another system, but it's really me.
2719 // Turn this into a wall post.
2720 $notify = Item::isRemoteSelf($importer, $item);
2722 $posted_id = Item::insert($item, false, $notify);
2724 logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2726 if (stristr($item["verb"], ACTIVITY_POKE)) {
2727 self::doPoke($item, $importer, $posted_id);
2733 * @brief Deletes items
2735 * @param object $xpath XPath object
2736 * @param object $deletion deletion elements
2737 * @param array $importer Record of the importer user mixed with contact of the content
2739 * @todo set proper type-hints
2741 private static function processDeletion($xpath, $deletion, $importer)
2743 logger("Processing deletions");
2745 foreach ($deletion->attributes as $attributes) {
2746 if ($attributes->name == "ref") {
2747 $uri = $attributes->textContent;
2749 if ($attributes->name == "when") {
2750 $when = $attributes->textContent;
2754 $when = datetime_convert("UTC", "UTC", $when, "Y-m-d H:i:s");
2756 $when = datetime_convert("UTC", "UTC", "now", "Y-m-d H:i:s");
2759 if (!$uri || !$importer["id"]) {
2763 /// @todo Only select the used fields
2765 "SELECT `item`.*, `contact`.`self` FROM `item` INNER JOIN `contact` on `item`.`contact-id` = `contact`.`id`
2766 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2768 intval($importer["uid"]),
2769 intval($importer["id"])
2771 if (!DBM::is_result($r)) {
2772 logger("Item with uri " . $uri . " from contact " . $importer["id"] . " for user " . $importer["uid"] . " wasn't found.", LOGGER_DEBUG);
2777 $entrytype = self::getEntryType($importer, $item);
2779 if (!$item["deleted"]) {
2780 logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG);
2785 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2786 logger("Deleting event ".$item["event-id"], LOGGER_DEBUG);
2787 event_delete($item["event-id"]);
2790 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2791 $xo = XML::parseString($item["object"], false);
2792 $xt = XML::parseString($item["target"], false);
2794 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2796 "SELECT `id`, `contact-id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2798 intval($importer["importer_uid"])
2800 if (DBM::is_result($i)) {
2801 // For tags, the owner cannot remove the tag on the author's copy of the post.
2803 $owner_remove = (($item["contact-id"] == $i[0]["contact-id"]) ? true: false);
2804 $author_remove = (($item["origin"] && $item["self"]) ? true : false);
2805 $author_copy = (($item["origin"]) ? true : false);
2807 if ($owner_remove && $author_copy) {
2810 if ($author_remove || $owner_remove) {
2811 $tags = explode(',', $i[0]["tag"]);
2814 foreach ($tags as $tag) {
2815 if (trim($tag) !== trim($xo->body)) {
2816 $newtags[] = trim($tag);
2821 "UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2822 dbesc(implode(',', $newtags)),
2825 create_tags_from_item($i[0]["id"]);
2831 if ($entrytype == DFRN_TOP_LEVEL) {
2833 "UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2834 `body` = '', `title` = ''
2835 WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2837 dbesc(datetime_convert()),
2839 intval($importer["uid"])
2841 create_tags_from_itemuri($uri, $importer["uid"]);
2842 Term::createFromItemURI($uri, $importer["uid"]);
2843 update_thread_uri($uri, $importer["uid"]);
2846 "UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2847 `body` = '', `title` = ''
2848 WHERE `uri` = '%s' AND `uid` IN (0, %d)",
2850 dbesc(datetime_convert()),
2852 intval($importer["uid"])
2854 create_tags_from_itemuri($uri, $importer["uid"]);
2855 Term::createFromItemURI($uri, $importer["uid"]);
2856 update_thread_uri($uri, $importer["importer_uid"]);
2858 // if this is a relayed delete, propagate it to other recipients
2860 if ($entrytype == DFRN_REPLY_RC) {
2861 logger("Notifying followers about deletion of post " . $item["id"], LOGGER_DEBUG);
2862 Worker::add(PRIORITY_HIGH, "Notifier", "drop", $item["id"]);
2869 * @brief Imports a DFRN message
2871 * @param string $xml The DFRN message
2872 * @param array $importer Record of the importer user mixed with contact of the content
2873 * @param bool $sort_by_date Is used when feeds are polled
2874 * @return integer Import status
2875 * @todo set proper type-hints
2877 public static function import($xml, $importer, $sort_by_date = false)
2883 $doc = new DOMDocument();
2884 @$doc->loadXML($xml);
2886 $xpath = new DOMXPath($doc);
2887 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2888 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2889 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2890 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2891 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2892 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2893 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2894 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2895 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2896 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2899 $header["uid"] = $importer["uid"];
2900 $header["network"] = NETWORK_DFRN;
2901 $header["type"] = "remote";
2902 $header["wall"] = 0;
2903 $header["origin"] = 0;
2904 $header["contact-id"] = $importer["id"];
2906 // Update the contact table if the data has changed
2908 // The "atom:author" is only present in feeds
2909 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2910 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2913 // Only the "dfrn:owner" in the head section contains all data
2914 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2915 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2918 logger("Import DFRN message for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2920 // The account type is new since 3.5.1
2921 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2922 $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()")->item(0)->nodeValue);
2924 if ($accounttype != $importer["contact-type"]) {
2925 dba::update('contact', ['contact-type' => $accounttype], ['id' => $importer["id"]]);
2929 // is it a public forum? Private forums aren't supported with this method
2930 // This is deprecated since 3.5.1
2931 $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()")->item(0)->nodeValue);
2933 if ($forum != $importer["forum"]) {
2934 $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2935 dba::update('contact', ['forum' => $forum], $condition);
2938 // We are processing relocations even if we are ignoring a contact
2939 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2940 foreach ($relocations as $relocation) {
2941 self::processRelocation($xpath, $relocation, $importer);
2944 if ($importer["readonly"]) {
2945 // We aren't receiving stuff from this person. But we will quietly ignore them
2946 // rather than a blatant "go away" message.
2947 logger('ignoring contact '.$importer["id"]);
2951 $mails = $xpath->query("/atom:feed/dfrn:mail");
2952 foreach ($mails as $mail) {
2953 self::processMail($xpath, $mail, $importer);
2956 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2957 foreach ($suggestions as $suggestion) {
2958 self::processSuggestion($xpath, $suggestion, $importer);
2961 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2962 foreach ($deletions as $deletion) {
2963 self::processDeletion($xpath, $deletion, $importer);
2966 if (!$sort_by_date) {
2967 $entries = $xpath->query("/atom:feed/atom:entry");
2968 foreach ($entries as $entry) {
2969 self::processEntry($header, $xpath, $entry, $importer, $xml);
2973 $entries = $xpath->query("/atom:feed/atom:entry");
2974 foreach ($entries as $entry) {
2975 $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2976 $newentries[strtotime($created)] = $entry;
2979 // Now sort after the publishing date
2982 foreach ($newentries as $entry) {
2983 self::processEntry($header, $xpath, $entry, $importer, $xml);
2986 logger("Import done for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2992 * @param string $contact_nick contact nickname
2994 public static function autoRedir(App $a, $contact_nick)
2997 if (x($_REQUEST, 'redir') && intval($_REQUEST['redir'])) {
3001 if ((! $contact_nick) || ($contact_nick === $a->user['nickname'])) {
3006 // We need to find out if $contact_nick is a user on this hub, and if so, if I
3007 // am a contact of that user. However, that user may have other contacts with the
3008 // same nickname as me on other hubs or other networks. Exclude these by requiring
3009 // that the contact have a local URL. I will be the only person with my nickname at
3010 // this URL, so if a result is found, then I am a contact of the $contact_nick user.
3012 // We also have to make sure that I'm a legitimate contact--I'm not blocked or pending.
3014 $baseurl = System::baseUrl();
3015 $domain_st = strpos($baseurl, "://");
3016 if ($domain_st === false) {
3019 $baseurl = substr($baseurl, $domain_st + 3);
3020 $nurl = normalise_link($baseurl);
3022 /// @todo Why is there a query for "url" *and* "nurl"? Especially this normalising is strange.
3023 $r = q("SELECT `id` FROM `contact` WHERE `uid` = (SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1)
3024 AND `nick` = '%s' AND NOT `self` AND (`url` LIKE '%%%s%%' OR `nurl` LIKE '%%%s%%') AND NOT `blocked` AND NOT `pending` LIMIT 1",
3025 dbesc($contact_nick),
3026 dbesc($a->user['nickname']),
3030 if ((! DBM::is_result($r)) || $r[0]['id'] == remote_user()) {
3034 $r = q("SELECT * FROM contact WHERE nick = '%s'
3035 AND network = '%s' AND uid = %d AND url LIKE '%%%s%%' LIMIT 1",
3036 dbesc($contact_nick),
3037 dbesc(NETWORK_DFRN),
3038 intval(local_user()),
3041 if (! DBM::is_result($r)) {
3047 $dfrn_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
3049 if ($r[0]['duplex'] && $r[0]['issued-id']) {
3050 $orig_id = $r[0]['issued-id'];
3051 $dfrn_id = '1:' . $orig_id;
3053 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
3054 $orig_id = $r[0]['dfrn-id'];
3055 $dfrn_id = '0:' . $orig_id;
3058 // ensure that we've got a valid ID. There may be some edge cases with forums and non-duplex mode
3059 // that may have triggered some of the "went to {profile/intro} and got an RSS feed" issues
3061 if (strlen($dfrn_id) < 3) {
3065 $sec = random_string();
3067 dba::insert('profile_check', ['uid' => local_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id, 'sec' => $sec, 'expire' => time() + 45]);
3069 $url = curPageURL();
3071 logger('auto_redir: ' . $r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
3072 $dest = (($url) ? '&destination_url=' . $url : '');
3073 goaway($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
3074 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest);
3081 * @brief Returns the activity verb
3083 * @param array $item Item array
3085 * @return string activity verb
3087 private static function constructVerb(array $item)
3089 if ($item['verb']) {
3090 return $item['verb'];
3092 return ACTIVITY_POST;
3095 private static function tgroupCheck($uid, $item)
3099 // check that the message originated elsewhere and is a top-level post
3101 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['parent-uri'])) {
3105 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
3108 if (!DBM::is_result($u)) {
3112 $community_page = ($u[0]['page-flags'] == PAGE_COMMUNITY);
3113 $prvgroup = ($u[0]['page-flags'] == PAGE_PRVGROUP);
3115 $link = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
3118 * Diaspora uses their own hardwired link URL in @-tags
3119 * instead of the one we supply with webfinger
3121 $dlink = normalise_link(System::baseUrl() . '/u/' . $u[0]['nickname']);
3123 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
3125 foreach ($matches as $mtch) {
3126 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
3128 logger('mention found: ' . $mtch[2]);
3137 return $community_page || $prvgroup;
3141 * This function returns true if $update has an edited timestamp newer
3142 * than $existing, i.e. $update contains new data which should override
3143 * what's already there. If there is no timestamp yet, the update is
3144 * assumed to be newer. If the update has no timestamp, the existing
3145 * item is assumed to be up-to-date. If the timestamps are equal it
3146 * assumes the update has been seen before and should be ignored.
3149 private static function isEditedTimestampNewer($existing, $update)
3151 if (!x($existing, 'edited') || !$existing['edited']) {
3154 if (!x($update, 'edited') || !$update['edited']) {
3158 $existing_edited = datetime_convert('UTC', 'UTC', $existing['edited']);
3159 $update_edited = datetime_convert('UTC', 'UTC', $update['edited']);
3161 return (strcmp($existing_edited, $update_edited) < 0);