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\Content\Text\BBCode;
14 use Friendica\Core\Addon;
15 use Friendica\Core\Config;
16 use Friendica\Core\L10n;
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\Item;
24 use Friendica\Model\Profile;
25 use Friendica\Model\Term;
26 use Friendica\Model\User;
27 use Friendica\Object\Image;
28 use Friendica\Protocol\OStatus;
29 use Friendica\Util\Crypto;
30 use Friendica\Util\DateTimeFormat;
31 use Friendica\Util\Network;
32 use Friendica\Util\XML;
37 use HTMLPurifier_Config;
39 require_once 'boot.php';
40 require_once 'include/dba.php';
41 require_once "include/enotify.php";
42 require_once "include/items.php";
43 require_once "include/event.php";
44 require_once "include/text.php";
47 * @brief This class contain functions to create and send DFRN XML files
52 const DFRN_TOP_LEVEL = 0; // Top level posting
53 const DFRN_REPLY = 1; // Regular reply that is stored locally
54 const DFRN_REPLY_RC = 2; // Reply that will be relayed
57 * @brief Generates the atom entries for delivery.php
59 * This function is used whenever content is transmitted via DFRN.
61 * @param array $items Item elements
62 * @param array $owner Owner record
64 * @return string DFRN entries
65 * @todo Add type-hints
67 public static function entries($items, $owner)
69 $doc = new DOMDocument('1.0', 'utf-8');
70 $doc->formatOutput = true;
72 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
74 if (! count($items)) {
75 return trim($doc->saveXML());
78 foreach ($items as $item) {
79 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
80 $root->appendChild($entry);
83 return(trim($doc->saveXML()));
87 * @brief Generate an atom feed for the given user
89 * This function is called when another server is pulling data from the user feed.
91 * @param string $dfrn_id DFRN ID from the requesting party
92 * @param string $owner_nick Owner nick name
93 * @param string $last_update Date of the last update
94 * @param int $direction Can be -1, 0 or 1.
95 * @param boolean $onlyheader Output only the header without content? (Default is "no")
97 * @return string DFRN feed entries
99 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false)
103 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
104 $public_feed = (($dfrn_id) ? false : true);
105 $starred = false; // not yet implemented, possible security issues
108 if ($public_feed && $a->argc > 2) {
109 for ($x = 2; $x < $a->argc; $x++) {
110 if ($a->argv[$x] == 'converse') {
113 if ($a->argv[$x] == 'starred') {
116 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
117 $category = $a->argv[$x+1];
124 // default permissions - anonymous user
126 $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = '' ";
129 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
130 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
131 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
135 if (! DBM::is_result($r)) {
140 $owner_id = $owner['uid'];
141 $owner_nick = $owner['nickname'];
143 $sql_post_table = "";
145 if (! $public_feed) {
147 switch ($direction) {
149 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
153 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
154 $my_id = '1:' . $dfrn_id;
157 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
158 $my_id = '0:' . $dfrn_id;
166 "SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
170 if (! DBM::is_result($r)) {
175 include_once 'include/security.php';
176 $groups = Group::getIdsByContactId($contact['id']);
178 if (count($groups)) {
179 for ($x = 0; $x < count($groups); $x ++)
180 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
181 $gs = implode('|', $groups);
183 $gs = '<<>>' ; // Impossible to match
186 $sql_extra = sprintf(
188 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
189 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
190 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
191 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
193 intval($contact['id']),
194 intval($contact['id']),
206 if (! strlen($last_update)) {
207 $last_update = 'now -30 days';
210 if (isset($category)) {
211 $sql_post_table = sprintf(
212 "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` ",
213 dbesc(protect_sprintf($category)),
214 intval(TERM_OBJ_POST),
215 intval(TERM_CATEGORY),
218 //$sql_extra .= file_tag_file_query('item',$category,'category');
223 $sql_extra .= " AND `contact`.`self` = 1 ";
227 $check_date = DateTimeFormat::utc($last_update);
230 "SELECT `item`.*, `item`.`id` AS `item_id`,
231 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
232 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
233 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
234 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
235 FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
236 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
237 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
238 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
239 WHERE `item`.`uid` = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
240 AND `item`.`wall` AND `item`.`changed` > '%s'
242 ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
249 * Will check further below if this actually returned results.
250 * We will provide an empty feed if that is the case.
255 $doc = new DOMDocument('1.0', 'utf-8');
256 $doc->formatOutput = true;
258 $alternatelink = $owner['url'];
260 if (isset($category)) {
261 $alternatelink .= "/category/".$category;
265 $author = "dfrn:owner";
270 $root = self::addHeader($doc, $owner, $author, $alternatelink, true);
272 /// @TODO This hook can't work anymore
273 // Addon::callHooks('atom_feed', $atom);
275 if (!DBM::is_result($items) || $onlyheader) {
276 $atom = trim($doc->saveXML());
278 Addon::callHooks('atom_feed_end', $atom);
283 foreach ($items as $item) {
284 // prevent private email from leaking.
285 if ($item['network'] == NETWORK_MAIL) {
289 // public feeds get html, our own nodes use bbcode
293 // catch any email that's in a public conversation and make sure it doesn't leak
294 if ($item['private']) {
301 $entry = self::entry($doc, $type, $item, $owner, true);
302 $root->appendChild($entry);
305 $atom = trim($doc->saveXML());
307 Addon::callHooks('atom_feed_end', $atom);
313 * @brief Generate an atom entry for a given item id
315 * @param int $item_id The item id
316 * @param boolean $conversation Show the conversation. If false show the single post.
318 * @return string DFRN feed entry
320 public static function itemFeed($item_id, $conversation = false)
323 $condition = '`item`.`parent`';
325 $condition = '`item`.`id`';
329 "SELECT `item`.*, `item`.`id` AS `item_id`,
330 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
331 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
332 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
333 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
335 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
336 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
337 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
338 WHERE %s = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
339 AND NOT `item`.`private`",
344 if (!DBM::is_result($r)) {
351 if ($item['uid'] != 0) {
352 $owner = User::getOwnerDataById($item['uid']);
357 $owner = ['uid' => 0, 'nick' => 'feed-item'];
360 $doc = new DOMDocument('1.0', 'utf-8');
361 $doc->formatOutput = true;
365 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
366 $doc->appendChild($root);
368 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
369 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
370 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
371 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
372 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
373 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
374 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
375 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
376 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
378 //$root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
380 foreach ($items as $item) {
381 $entry = self::entry($doc, $type, $item, $owner, true, 0);
382 $root->appendChild($entry);
385 $root = self::entry($doc, $type, $item, $owner, true, 0, true);
388 $atom = trim($doc->saveXML());
393 * @brief Create XML text for DFRN mails
395 * @param array $item message elements
396 * @param array $owner Owner record
398 * @return string DFRN mail
399 * @todo Add type-hints
401 public static function mail($item, $owner)
403 $doc = new DOMDocument('1.0', 'utf-8');
404 $doc->formatOutput = true;
406 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
408 $mail = $doc->createElement("dfrn:mail");
409 $sender = $doc->createElement("dfrn:sender");
411 XML::addElement($doc, $sender, "dfrn:name", $owner['name']);
412 XML::addElement($doc, $sender, "dfrn:uri", $owner['url']);
413 XML::addElement($doc, $sender, "dfrn:avatar", $owner['thumb']);
415 $mail->appendChild($sender);
417 XML::addElement($doc, $mail, "dfrn:id", $item['uri']);
418 XML::addElement($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
419 XML::addElement($doc, $mail, "dfrn:sentdate", DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
420 XML::addElement($doc, $mail, "dfrn:subject", $item['title']);
421 XML::addElement($doc, $mail, "dfrn:content", $item['body']);
423 $root->appendChild($mail);
425 return(trim($doc->saveXML()));
429 * @brief Create XML text for DFRN friend suggestions
431 * @param array $item suggestion elements
432 * @param array $owner Owner record
434 * @return string DFRN suggestions
435 * @todo Add type-hints
437 public static function fsuggest($item, $owner)
439 $doc = new DOMDocument('1.0', 'utf-8');
440 $doc->formatOutput = true;
442 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
444 $suggest = $doc->createElement("dfrn:suggest");
446 XML::addElement($doc, $suggest, "dfrn:url", $item['url']);
447 XML::addElement($doc, $suggest, "dfrn:name", $item['name']);
448 XML::addElement($doc, $suggest, "dfrn:photo", $item['photo']);
449 XML::addElement($doc, $suggest, "dfrn:request", $item['request']);
450 XML::addElement($doc, $suggest, "dfrn:note", $item['note']);
452 $root->appendChild($suggest);
454 return(trim($doc->saveXML()));
458 * @brief Create XML text for DFRN relocations
460 * @param array $owner Owner record
461 * @param int $uid User ID
463 * @return string DFRN relocations
464 * @todo Add type-hints
466 public static function relocate($owner, $uid)
469 /* get site pubkey. this could be a new installation with no site keys*/
470 $pubkey = Config::get('system', 'site_pubkey');
472 $res = Crypto::newKeypair(1024);
473 Config::set('system', 'site_prvkey', $res['prvkey']);
474 Config::set('system', 'site_pubkey', $res['pubkey']);
478 "SELECT `resource-id` , `scale`, type FROM `photo`
479 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;",
483 $ext = Image::supportedTypes();
485 foreach ($rp as $p) {
486 $photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
491 $doc = new DOMDocument('1.0', 'utf-8');
492 $doc->formatOutput = true;
494 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
496 $relocate = $doc->createElement("dfrn:relocate");
498 XML::addElement($doc, $relocate, "dfrn:url", $owner['url']);
499 XML::addElement($doc, $relocate, "dfrn:name", $owner['name']);
500 XML::addElement($doc, $relocate, "dfrn:addr", $owner['addr']);
501 XML::addElement($doc, $relocate, "dfrn:avatar", $owner['avatar']);
502 XML::addElement($doc, $relocate, "dfrn:photo", $photos[4]);
503 XML::addElement($doc, $relocate, "dfrn:thumb", $photos[5]);
504 XML::addElement($doc, $relocate, "dfrn:micro", $photos[6]);
505 XML::addElement($doc, $relocate, "dfrn:request", $owner['request']);
506 XML::addElement($doc, $relocate, "dfrn:confirm", $owner['confirm']);
507 XML::addElement($doc, $relocate, "dfrn:notify", $owner['notify']);
508 XML::addElement($doc, $relocate, "dfrn:poll", $owner['poll']);
509 XML::addElement($doc, $relocate, "dfrn:sitepubkey", Config::get('system', 'site_pubkey'));
511 $root->appendChild($relocate);
513 return(trim($doc->saveXML()));
517 * @brief Adds the header elements for the DFRN protocol
519 * @param object $doc XML document
520 * @param array $owner Owner record
521 * @param string $authorelement Element name for the author
522 * @param string $alternatelink link to profile or category
523 * @param bool $public Is it a header for public posts?
525 * @return object XML root object
526 * @todo Add type-hints
528 private static function addHeader($doc, $owner, $authorelement, $alternatelink = "", $public = false)
531 if ($alternatelink == "") {
532 $alternatelink = $owner['url'];
535 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
536 $doc->appendChild($root);
538 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
539 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
540 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
541 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
542 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
543 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
544 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
545 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
546 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
548 XML::addElement($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
549 XML::addElement($doc, $root, "title", $owner["name"]);
551 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION];
552 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
554 $attributes = ["rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/"];
555 XML::addElement($doc, $root, "link", "", $attributes);
557 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $alternatelink];
558 XML::addElement($doc, $root, "link", "", $attributes);
562 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
563 OStatus::hublinks($doc, $root, $owner["nick"]);
565 $attributes = ["rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
566 XML::addElement($doc, $root, "link", "", $attributes);
568 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
569 XML::addElement($doc, $root, "link", "", $attributes);
571 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
572 XML::addElement($doc, $root, "link", "", $attributes);
575 // For backward compatibility we keep this element
576 if ($owner['page-flags'] == PAGE_COMMUNITY) {
577 XML::addElement($doc, $root, "dfrn:community", 1);
580 // The former element is replaced by this one
581 XML::addElement($doc, $root, "dfrn:account_type", $owner["account-type"]);
583 /// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
585 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
587 $author = self::addAuthor($doc, $owner, $authorelement, $public);
588 $root->appendChild($author);
594 * @brief Adds the author element in the header for the DFRN protocol
596 * @param object $doc XML document
597 * @param array $owner Owner record
598 * @param string $authorelement Element name for the author
599 * @param boolean $public boolean
601 * @return object XML author object
602 * @todo Add type-hints
604 private static function addAuthor($doc, $owner, $authorelement, $public)
606 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
608 "SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
609 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
610 intval($owner['uid'])
612 if (DBM::is_result($r)) {
618 $author = $doc->createElement($authorelement);
620 $namdate = DateTimeFormat::utc($owner['name-date'].'+00:00', DateTimeFormat::ATOM);
621 $uridate = DateTimeFormat::utc($owner['uri-date'].'+00:00', DateTimeFormat::ATOM);
622 $picdate = DateTimeFormat::utc($owner['avatar-date'].'+00:00', DateTimeFormat::ATOM);
626 if (!$public || !$hidewall) {
627 $attributes = ["dfrn:updated" => $namdate];
630 XML::addElement($doc, $author, "name", $owner["name"], $attributes);
631 XML::addElement($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
632 XML::addElement($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
634 $attributes = ["rel" => "photo", "type" => "image/jpeg",
635 "media:width" => 175, "media:height" => 175, "href" => $owner['photo']];
637 if (!$public || !$hidewall) {
638 $attributes["dfrn:updated"] = $picdate;
641 XML::addElement($doc, $author, "link", "", $attributes);
643 $attributes["rel"] = "avatar";
644 XML::addElement($doc, $author, "link", "", $attributes);
647 XML::addElement($doc, $author, "dfrn:hide", "true");
650 // The following fields will only be generated if the data isn't meant for a public feed
655 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
658 XML::addElement($doc, $author, "dfrn:birthday", $birthday);
661 // Only show contact details when we are allowed to
663 "SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
664 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
665 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
667 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
668 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
669 intval($owner['uid'])
671 if (DBM::is_result($r)) {
674 XML::addElement($doc, $author, "poco:displayName", $profile["name"]);
675 XML::addElement($doc, $author, "poco:updated", $namdate);
677 if (trim($profile["dob"]) > '0001-01-01') {
678 XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
681 XML::addElement($doc, $author, "poco:note", $profile["about"]);
682 XML::addElement($doc, $author, "poco:preferredUsername", $profile["nickname"]);
684 $savetz = date_default_timezone_get();
685 date_default_timezone_set($profile["timezone"]);
686 XML::addElement($doc, $author, "poco:utcOffset", date("P"));
687 date_default_timezone_set($savetz);
689 if (trim($profile["homepage"]) != "") {
690 $urls = $doc->createElement("poco:urls");
691 XML::addElement($doc, $urls, "poco:type", "homepage");
692 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
693 XML::addElement($doc, $urls, "poco:primary", "true");
694 $author->appendChild($urls);
697 if (trim($profile["pub_keywords"]) != "") {
698 $keywords = explode(",", $profile["pub_keywords"]);
700 foreach ($keywords as $keyword) {
701 XML::addElement($doc, $author, "poco:tags", trim($keyword));
705 if (trim($profile["xmpp"]) != "") {
706 $ims = $doc->createElement("poco:ims");
707 XML::addElement($doc, $ims, "poco:type", "xmpp");
708 XML::addElement($doc, $ims, "poco:value", $profile["xmpp"]);
709 XML::addElement($doc, $ims, "poco:primary", "true");
710 $author->appendChild($ims);
713 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
714 $element = $doc->createElement("poco:address");
716 XML::addElement($doc, $element, "poco:formatted", Profile::formatLocation($profile));
718 if (trim($profile["locality"]) != "") {
719 XML::addElement($doc, $element, "poco:locality", $profile["locality"]);
722 if (trim($profile["region"]) != "") {
723 XML::addElement($doc, $element, "poco:region", $profile["region"]);
726 if (trim($profile["country-name"]) != "") {
727 XML::addElement($doc, $element, "poco:country", $profile["country-name"]);
730 $author->appendChild($element);
738 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
740 * @param object $doc XML document
741 * @param string $element Element name for the author
742 * @param string $contact_url Link of the contact
743 * @param array $item Item elements
745 * @return object XML author object
746 * @todo Add type-hints
748 private static function addEntryAuthor($doc, $element, $contact_url, $item)
750 $contact = Contact::getDetailsByURL($contact_url, $item["uid"]);
752 $author = $doc->createElement($element);
753 XML::addElement($doc, $author, "name", $contact["name"]);
754 XML::addElement($doc, $author, "uri", $contact["url"]);
755 XML::addElement($doc, $author, "dfrn:handle", $contact["addr"]);
758 /// - Check real image type and image size
759 /// - Check which of these boths elements we should use
762 "type" => "image/jpeg",
764 "media:height" => 80,
765 "href" => $contact["photo"]];
766 XML::addElement($doc, $author, "link", "", $attributes);
770 "type" => "image/jpeg",
772 "media:height" => 80,
773 "href" => $contact["photo"]];
774 XML::addElement($doc, $author, "link", "", $attributes);
780 * @brief Adds the activity elements
782 * @param object $doc XML document
783 * @param string $element Element name for the activity
784 * @param string $activity activity value
786 * @return object XML activity object
787 * @todo Add type-hints
789 private static function createActivity($doc, $element, $activity)
792 $entry = $doc->createElement($element);
794 $r = XML::parseString($activity, false);
799 XML::addElement($doc, $entry, "activity:object-type", $r->type);
802 XML::addElement($doc, $entry, "id", $r->id);
805 XML::addElement($doc, $entry, "title", $r->title);
809 if (substr($r->link, 0, 1) == '<') {
810 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
811 $r->link = str_replace('&', '&', $r->link);
814 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
816 // XML does need a single element as root element so we add a dummy element here
817 $data = XML::parseString("<dummy>" . $r->link . "</dummy>", false);
818 if (is_object($data)) {
819 foreach ($data->link as $link) {
821 foreach ($link->attributes() as $parameter => $value) {
822 $attributes[$parameter] = $value;
824 XML::addElement($doc, $entry, "link", "", $attributes);
828 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
829 XML::addElement($doc, $entry, "link", "", $attributes);
833 XML::addElement($doc, $entry, "content", BBCode::convert($r->content), ["type" => "html"]);
843 * @brief Adds the elements for attachments
845 * @param object $doc XML document
846 * @param object $root XML root
847 * @param array $item Item element
849 * @return object XML attachment object
850 * @todo Add type-hints
852 private static function getAttachment($doc, $root, $item)
854 $arr = explode('[/attach],', $item['attach']);
856 foreach ($arr as $r) {
858 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
860 $attributes = ["rel" => "enclosure",
861 "href" => $matches[1],
862 "type" => $matches[3]];
864 if (intval($matches[2])) {
865 $attributes["length"] = intval($matches[2]);
868 if (trim($matches[4]) != "") {
869 $attributes["title"] = trim($matches[4]);
872 XML::addElement($doc, $root, "link", "", $attributes);
879 * @brief Adds the "entry" elements for the DFRN protocol
881 * @param object $doc XML document
882 * @param string $type "text" or "html"
883 * @param array $item Item element
884 * @param array $owner Owner record
885 * @param bool $comment Trigger the sending of the "comment" element
886 * @param int $cid Contact ID of the recipient
887 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
889 * @return object XML entry object
890 * @todo Add type-hints
892 private static function entry($doc, $type, $item, $owner, $comment = false, $cid = 0, $single = false)
896 if (!$item['parent']) {
900 if ($item['deleted']) {
901 $attributes = ["ref" => $item['uri'], "when" => DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM)];
902 return XML::createElement($doc, "at:deleted-entry", "", $attributes);
906 $entry = $doc->createElement("entry");
908 $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry');
909 $doc->appendChild($entry);
911 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
912 $entry->setAttribute("xmlns:at", NAMESPACE_TOMB);
913 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
914 $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
915 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
916 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
917 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
918 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
919 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
922 if ($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid']) {
923 $body = Item::fixPrivatePhotos($item['body'], $owner['uid'], $item, $cid);
925 $body = $item['body'];
928 // Remove the abstract element. It is only locally important.
929 $body = BBCode::stripAbstract($body);
932 if ($type == 'html') {
935 if ($item['title'] != "") {
936 $htmlbody = "[b]".$item['title']."[/b]\n\n".$htmlbody;
939 $htmlbody = BBCode::convert($htmlbody, false, 7);
942 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
943 $entry->appendChild($author);
945 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
946 $entry->appendChild($dfrnowner);
948 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
949 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
950 $parent = q("SELECT `guid`,`plink` FROM `item` WHERE `uri` = '%s' AND `uid` = %d", dbesc($parent_item), intval($item['uid']));
951 $attributes = ["ref" => $parent_item, "type" => "text/html",
952 "href" => $parent[0]['plink'],
953 "dfrn:diaspora_guid" => $parent[0]['guid']];
954 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
957 // Add conversation data. This is used for OStatus
958 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
959 $conversation_uri = $conversation_href;
961 if (isset($parent_item)) {
962 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $item['parent-uri']);
963 if (DBM::is_result($r)) {
964 if ($r['conversation-uri'] != '') {
965 $conversation_uri = $r['conversation-uri'];
967 if ($r['conversation-href'] != '') {
968 $conversation_href = $r['conversation-href'];
974 "href" => $conversation_href,
975 "ref" => $conversation_uri];
977 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
979 XML::addElement($doc, $entry, "id", $item["uri"]);
980 XML::addElement($doc, $entry, "title", $item["title"]);
982 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"] . "+00:00", DateTimeFormat::ATOM));
983 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"] . "+00:00", DateTimeFormat::ATOM));
985 // "dfrn:env" is used to read the content
986 XML::addElement($doc, $entry, "dfrn:env", base64url_encode($body, true));
988 // The "content" field is not read by the receiver. We could remove it when the type is "text"
989 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
990 XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
992 // We save this value in "plink". Maybe we should read it from there as well?
998 ["rel" => "alternate", "type" => "text/html",
999 "href" => System::baseUrl() . "/display/" . $item["guid"]]
1002 // "comment-allow" is some old fashioned stuff for old Friendica versions.
1003 // It is included in the rewritten code for completeness
1005 XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
1008 if ($item['location']) {
1009 XML::addElement($doc, $entry, "dfrn:location", $item['location']);
1012 if ($item['coord']) {
1013 XML::addElement($doc, $entry, "georss:point", $item['coord']);
1016 if (($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])) {
1017 XML::addElement($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
1020 if ($item['extid']) {
1021 XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
1024 if ($item['bookmark']) {
1025 XML::addElement($doc, $entry, "dfrn:bookmark", "true");
1029 XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
1032 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
1034 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
1035 // It is needed for relayed comments to Diaspora.
1036 if ($item['signed_text']) {
1037 $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer']]));
1038 XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
1041 XML::addElement($doc, $entry, "activity:verb", self::constructVerb($item));
1043 if ($item['object-type'] != "") {
1044 XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
1045 } elseif ($item['id'] == $item['parent']) {
1046 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1048 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
1051 $actobj = self::createActivity($doc, "activity:object", $item['object']);
1053 $entry->appendChild($actobj);
1056 $actarg = self::createActivity($doc, "activity:target", $item['target']);
1058 $entry->appendChild($actarg);
1061 $tags = Item::getFeedTags($item);
1064 foreach ($tags as $t) {
1065 if (($type != 'html') || ($t[0] != "@")) {
1066 XML::addElement($doc, $entry, "category", "", ["scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]]);
1072 foreach ($tags as $t) {
1074 $mentioned[$t[1]] = $t[1];
1079 foreach ($mentioned as $mention) {
1081 "SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1082 intval($owner["uid"]),
1083 dbesc(normalise_link($mention))
1086 if (DBM::is_result($r) && ($r[0]["forum"] || $r[0]["prv"])) {
1092 ["rel" => "mentioned",
1093 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1102 ["rel" => "mentioned",
1103 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1109 self::getAttachment($doc, $entry, $item);
1115 * @brief encrypts data via AES
1117 * @param string $data The data that is to be encrypted
1118 * @param string $key The AES key
1120 * @return string encrypted data
1122 private static function aesEncrypt($data, $key)
1124 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1128 * @brief decrypts data via AES
1130 * @param string $encrypted The encrypted data
1131 * @param string $key The AES key
1133 * @return string decrypted data
1135 public static function aesDecrypt($encrypted, $key)
1137 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1141 * @brief Delivers the atom content to the contacts
1143 * @param array $owner Owner record
1144 * @param array $contact Contact record of the receiver
1145 * @param string $atom Content that will be transmitted
1146 * @param bool $dissolve (to be documented)
1148 * @return int Deliver status. -1 means an error.
1149 * @todo Add array type-hint for $owner, $contact
1151 public static function deliver($owner, $contact, $atom, $dissolve = false)
1155 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1157 if ($contact['duplex'] && $contact['dfrn-id']) {
1158 $idtosend = '0:' . $orig_id;
1160 if ($contact['duplex'] && $contact['issued-id']) {
1161 $idtosend = '1:' . $orig_id;
1164 $rino = Config::get('system', 'rino_encrypt');
1165 $rino = intval($rino);
1167 logger("Local rino version: ". $rino, LOGGER_DEBUG);
1169 $ssl_val = intval(Config::get('system', 'ssl_policy'));
1173 case SSL_POLICY_FULL:
1174 $ssl_policy = 'full';
1176 case SSL_POLICY_SELFSIGN:
1177 $ssl_policy = 'self';
1179 case SSL_POLICY_NONE:
1181 $ssl_policy = 'none';
1185 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1187 logger('dfrn_deliver: ' . $url);
1189 $ret = Network::curl($url);
1191 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1192 return -2; // timed out
1195 $xml = $ret['body'];
1197 $curl_stat = $a->get_curl_code();
1199 return -3; // timed out
1202 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1208 if (strpos($xml, '<?xml') === false) {
1209 logger('dfrn_deliver: no valid XML returned');
1210 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1214 $res = XML::parseString($xml);
1216 if ((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id))) {
1217 return (($res->status) ? $res->status : 3);
1221 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1222 $challenge = hex2bin((string) $res->challenge);
1223 $perm = (($res->perm) ? $res->perm : null);
1224 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1225 $rino_remote_version = intval($res->rino);
1226 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1228 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
1230 if ($owner['page-flags'] == PAGE_PRVGROUP) {
1234 $final_dfrn_id = '';
1237 if ((($perm == 'rw') && (! intval($contact['writable'])))
1238 || (($perm == 'r') && (intval($contact['writable'])))
1241 "update contact set writable = %d where id = %d",
1242 intval(($perm == 'rw') ? 1 : 0),
1243 intval($contact['id'])
1245 $contact['writable'] = (string) 1 - intval($contact['writable']);
1249 if (($contact['duplex'] && strlen($contact['pubkey']))
1250 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1251 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
1253 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
1254 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
1256 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
1257 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
1260 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1262 if (strpos($final_dfrn_id, ':') == 1) {
1263 $final_dfrn_id = substr($final_dfrn_id, 2);
1266 if ($final_dfrn_id != $orig_id) {
1267 logger('dfrn_deliver: wrong dfrn_id.');
1268 // did not decode properly - cannot trust this site
1272 $postvars['dfrn_id'] = $idtosend;
1273 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1275 $postvars['dissolve'] = '1';
1279 if ((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1280 $postvars['data'] = $atom;
1281 $postvars['perm'] = 'rw';
1283 $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
1284 $postvars['perm'] = 'r';
1287 $postvars['ssl_policy'] = $ssl_policy;
1290 $postvars['page'] = $page;
1294 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1295 logger('rino version: '. $rino_remote_version);
1297 switch ($rino_remote_version) {
1299 $key = openssl_random_pseudo_bytes(16);
1300 $data = self::aesEncrypt($postvars['data'], $key);
1303 logger("rino: invalid requested version '$rino_remote_version'");
1307 $postvars['rino'] = $rino_remote_version;
1308 $postvars['data'] = bin2hex($data);
1310 if ($dfrn_version >= 2.1) {
1311 if (($contact['duplex'] && strlen($contact['pubkey']))
1312 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1313 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
1315 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1317 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1320 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1321 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1323 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1327 logger('md5 rawkey ' . md5($postvars['key']));
1329 $postvars['key'] = bin2hex($postvars['key']);
1333 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), LOGGER_DATA);
1335 $xml = Network::post($contact['notify'], $postvars);
1337 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1339 $curl_stat = $a->get_curl_code();
1340 if ((!$curl_stat) || (!strlen($xml))) {
1341 return -9; // timed out
1344 if (($curl_stat == 503) && (stristr($a->get_curl_headers(), 'retry-after'))) {
1348 if (strpos($xml, '<?xml') === false) {
1349 logger('dfrn_deliver: phase 2: no valid XML returned');
1350 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1354 $res = XML::parseString($xml);
1356 if (!isset($res->status)) {
1360 if (!empty($res->message)) {
1361 logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1364 if ($res->status == 200) {
1365 Contact::unmarkForArchival($contact);
1368 return intval($res->status);
1372 * @brief Add new birthday event for this person
1374 * @param array $contact Contact record
1375 * @param string $birthday Birthday of the contact
1377 * @todo Add array type-hint for $contact
1379 private static function birthdayEvent($contact, $birthday)
1381 // Check for duplicates
1383 "SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1384 intval($contact["uid"]),
1385 intval($contact["id"]),
1386 dbesc(DateTimeFormat::utc($birthday)),
1390 if (DBM::is_result($r)) {
1394 logger("updating birthday: ".$birthday." for contact ".$contact["id"]);
1396 $bdtext = L10n::t("%s\'s birthday", $contact["name"]);
1397 $bdtext2 = L10n::t("Happy Birthday %s", " [url=".$contact["url"]."]".$contact["name"]."[/url]");
1400 "INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1401 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1402 intval($contact["uid"]),
1403 intval($contact["id"]),
1404 dbesc(DateTimeFormat::utcNow()),
1405 dbesc(DateTimeFormat::utcNow()),
1406 dbesc(DateTimeFormat::utc($birthday)),
1407 dbesc(DateTimeFormat::utc($birthday . " + 1 day ")),
1415 * @brief Fetch the author data from head or entry items
1417 * @param object $xpath XPath object
1418 * @param object $context In which context should the data be searched
1419 * @param array $importer Record of the importer user mixed with contact of the content
1420 * @param string $element Element name from which the data is fetched
1421 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1422 * @param string $xml optional, default empty
1424 * @return array Relevant data of the author
1425 * @todo Find good type-hints for all parameter
1427 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
1430 $author["name"] = $xpath->evaluate($element."/atom:name/text()", $context)->item(0)->nodeValue;
1431 $author["link"] = $xpath->evaluate($element."/atom:uri/text()", $context)->item(0)->nodeValue;
1433 $contact_old = dba::fetch_first("SELECT `id`, `uid`, `url`, `network`, `avatar-date`, `avatar`, `name-date`, `uri-date`, `addr`,
1434 `name`, `nick`, `about`, `location`, `keywords`, `xmpp`, `bdyear`, `bd`, `hidden`, `contact-type`
1435 FROM `contact` WHERE `uid` = ? AND `nurl` = ? AND `network` != ?",
1437 normalise_link($author["link"]),
1441 if (DBM::is_result($contact_old)) {
1442 $author["contact-id"] = $contact_old["id"];
1443 $author["network"] = $contact_old["network"];
1446 logger("Contact ".$author["link"]." wasn't found for user ".$importer["uid"]." XML: ".$xml, LOGGER_DEBUG);
1449 $author["contact-id"] = $importer["id"];
1450 $author["network"] = $importer["network"];
1454 // Until now we aren't serving different sizes - but maybe later
1456 /// @todo check if "avatar" or "photo" would be the best field in the specification
1457 $avatars = $xpath->query($element."/atom:link[@rel='avatar']", $context);
1458 foreach ($avatars as $avatar) {
1461 foreach ($avatar->attributes as $attributes) {
1462 /// @TODO Rewrite these similar if () to one switch
1463 if ($attributes->name == "href") {
1464 $href = $attributes->textContent;
1466 if ($attributes->name == "width") {
1467 $width = $attributes->textContent;
1469 if ($attributes->name == "updated") {
1470 $author["avatar-date"] = $attributes->textContent;
1473 if (($width > 0) && ($href != "")) {
1474 $avatarlist[$width] = $href;
1477 if (count($avatarlist) > 0) {
1478 krsort($avatarlist);
1479 $author["avatar"] = current($avatarlist);
1482 if (DBM::is_result($contact_old) && !$onlyfetch) {
1483 logger("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", LOGGER_DEBUG);
1485 $poco = ["url" => $contact_old["url"]];
1487 // When was the last change to name or uri?
1488 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1489 foreach ($name_element->attributes as $attributes) {
1490 if ($attributes->name == "updated") {
1491 $poco["name-date"] = $attributes->textContent;
1495 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1496 foreach ($link_element->attributes as $attributes) {
1497 if ($attributes->name == "updated") {
1498 $poco["uri-date"] = $attributes->textContent;
1502 // Update contact data
1503 $value = $xpath->evaluate($element . "/dfrn:handle/text()", $context)->item(0)->nodeValue;
1505 $poco["addr"] = $value;
1508 $value = $xpath->evaluate($element . "/poco:displayName/text()", $context)->item(0)->nodeValue;
1510 $poco["name"] = $value;
1513 $value = $xpath->evaluate($element . "/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
1515 $poco["nick"] = $value;
1518 $value = $xpath->evaluate($element . "/poco:note/text()", $context)->item(0)->nodeValue;
1520 $poco["about"] = $value;
1523 $value = $xpath->evaluate($element . "/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
1525 $poco["location"] = $value;
1528 /// @todo Only search for elements with "poco:type" = "xmpp"
1529 $value = $xpath->evaluate($element . "/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
1531 $poco["xmpp"] = $value;
1534 /// @todo Add support for the following fields that we don't support by now in the contact table:
1535 /// - poco:utcOffset
1541 // If the "hide" element is present then the profile isn't searchable.
1542 $hide = intval($xpath->evaluate($element . "/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
1544 logger("Hidden status for contact " . $contact_old["url"] . ": " . $hide, LOGGER_DEBUG);
1546 // If the contact isn't searchable then set the contact to "hidden".
1547 // Problem: This can be manually overridden by the user.
1549 $contact_old["hidden"] = true;
1552 // Save the keywords into the contact table
1554 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1555 foreach ($tagelements as $tag) {
1556 $tags[$tag->nodeValue] = $tag->nodeValue;
1560 $poco["keywords"] = implode(", ", $tags);
1563 // "dfrn:birthday" contains the birthday converted to UTC
1564 $birthday = $xpath->evaluate($element . "/dfrn:birthday/text()", $context)->item(0)->nodeValue;
1566 if (strtotime($birthday) > time()) {
1567 $bd_timestamp = strtotime($birthday);
1569 $poco["bdyear"] = date("Y", $bd_timestamp);
1572 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1573 $value = $xpath->evaluate($element . "/poco:birthday/text()", $context)->item(0)->nodeValue;
1575 if (!in_array($value, ["", "0000-00-00", "0001-01-01"])) {
1576 $bdyear = date("Y");
1577 $value = str_replace("0000", $bdyear, $value);
1579 if (strtotime($value) < time()) {
1580 $value = str_replace($bdyear, $bdyear + 1, $value);
1581 $bdyear = $bdyear + 1;
1584 $poco["bd"] = $value;
1587 $contact = array_merge($contact_old, $poco);
1589 if ($contact_old["bdyear"] != $contact["bdyear"]) {
1590 self::birthdayEvent($contact, $birthday);
1593 // Get all field names
1595 foreach ($contact_old as $field => $data) {
1596 $fields[$field] = $data;
1599 unset($fields["id"]);
1600 unset($fields["uid"]);
1601 unset($fields["url"]);
1602 unset($fields["avatar-date"]);
1603 unset($fields["avatar"]);
1604 unset($fields["name-date"]);
1605 unset($fields["uri-date"]);
1608 // Update check for this field has to be done differently
1609 $datefields = ["name-date", "uri-date"];
1610 foreach ($datefields as $field) {
1611 if (strtotime($contact[$field]) > strtotime($contact_old[$field])) {
1612 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1617 foreach ($fields as $field => $data) {
1618 if ($contact[$field] != $contact_old[$field]) {
1619 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1625 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1628 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1629 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1630 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1631 WHERE `id` = %d AND `network` = '%s'",
1632 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
1633 dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1634 dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
1635 dbesc(DBM::date($contact["name-date"])), dbesc(DBM::date($contact["uri-date"])),
1636 intval($contact["id"]), dbesc($contact["network"])
1640 Contact::updateAvatar(
1644 (strtotime($contact['avatar-date']) > strtotime($contact_old['avatar-date']) || ($author['avatar'] != $contact_old['avatar']))
1648 * The generation is a sign for the reliability of the provided data.
1649 * It is used in the socgraph.php to prevent that old contact data
1650 * that was relayed over several servers can overwrite contact
1651 * data that we received directly.
1654 $poco["generation"] = 2;
1655 $poco["photo"] = $author["avatar"];
1656 $poco["hide"] = $hide;
1657 $poco["contact-type"] = $contact["contact-type"];
1658 $gcid = GContact::update($poco);
1660 GContact::link($gcid, $importer["uid"], $contact["id"]);
1667 * @brief Transforms activity objects into an XML string
1669 * @param object $xpath XPath object
1670 * @param object $activity Activity object
1671 * @param string $element element name
1673 * @return string XML string
1674 * @todo Find good type-hints for all parameter
1676 private static function transformActivity($xpath, $activity, $element)
1678 if (!is_object($activity)) {
1682 $obj_doc = new DOMDocument("1.0", "utf-8");
1683 $obj_doc->formatOutput = true;
1685 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1687 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1688 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1690 $id = $xpath->query("atom:id", $activity)->item(0);
1691 if (is_object($id)) {
1692 $obj_element->appendChild($obj_doc->importNode($id, true));
1695 $title = $xpath->query("atom:title", $activity)->item(0);
1696 if (is_object($title)) {
1697 $obj_element->appendChild($obj_doc->importNode($title, true));
1700 $links = $xpath->query("atom:link", $activity);
1701 if (is_object($links)) {
1702 foreach ($links as $link) {
1703 $obj_element->appendChild($obj_doc->importNode($link, true));
1707 $content = $xpath->query("atom:content", $activity)->item(0);
1708 if (is_object($content)) {
1709 $obj_element->appendChild($obj_doc->importNode($content, true));
1712 $obj_doc->appendChild($obj_element);
1714 $objxml = $obj_doc->saveXML($obj_element);
1716 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1717 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1722 * @brief Processes the mail elements
1724 * @param object $xpath XPath object
1725 * @param object $mail mail elements
1726 * @param array $importer Record of the importer user mixed with contact of the content
1728 * @todo Find good type-hints for all parameter
1730 private static function processMail($xpath, $mail, $importer)
1732 logger("Processing mails");
1734 /// @TODO Rewrite this to one statement
1736 $msg["uid"] = $importer["importer_uid"];
1737 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1738 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1739 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1740 $msg["contact-id"] = $importer["id"];
1741 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1742 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1743 $msg["created"] = DateTimeFormat::utc($xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue);
1744 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1745 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1747 $msg["replied"] = 0;
1749 dba::insert('mail', $msg);
1751 // send notifications.
1752 /// @TODO Arange this mess
1754 "type" => NOTIFY_MAIL,
1755 "notify_flags" => $importer["notify-flags"],
1756 "language" => $importer["language"],
1757 "to_name" => $importer["username"],
1758 "to_email" => $importer["email"],
1759 "uid" => $importer["importer_uid"],
1761 "source_name" => $msg["from-name"],
1762 "source_link" => $importer["url"],
1763 "source_photo" => $importer["thumb"],
1764 "verb" => ACTIVITY_POST,
1768 notification($notif_params);
1770 logger("Mail is processed, notification was sent.");
1774 * @brief Processes the suggestion elements
1776 * @param object $xpath XPath object
1777 * @param object $suggestion suggestion elements
1778 * @param array $importer Record of the importer user mixed with contact of the content
1780 * @todo Find good type-hints for all parameter
1782 private static function processSuggestion($xpath, $suggestion, $importer)
1786 logger("Processing suggestions");
1788 /// @TODO Rewrite this to one statement
1790 $suggest["uid"] = $importer["importer_uid"];
1791 $suggest["cid"] = $importer["id"];
1792 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1793 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1794 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1795 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1796 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1798 // Does our member already have a friend matching this description?
1801 "SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1802 dbesc($suggest["name"]),
1803 dbesc(normalise_link($suggest["url"])),
1804 intval($suggest["uid"])
1808 * The valid result means the friend we're about to send a friend
1809 * suggestion already has them in their contact, which means no further
1810 * action is required.
1812 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1814 if (DBM::is_result($r)) {
1818 // Do we already have an fcontact record for this person?
1822 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1823 dbesc($suggest["url"]),
1824 dbesc($suggest["name"]),
1825 dbesc($suggest["request"])
1827 if (DBM::is_result($r)) {
1830 // OK, we do. Do we already have an introduction for this person ?
1832 "SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1833 intval($suggest["uid"]),
1838 * The valid result means the friend we're about to send a friend
1839 * suggestion already has them in their contact, which means no further
1840 * action is required.
1842 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1844 if (DBM::is_result($r)) {
1850 "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1851 dbesc($suggest["name"]),
1852 dbesc($suggest["url"]),
1853 dbesc($suggest["photo"]),
1854 dbesc($suggest["request"])
1858 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1859 dbesc($suggest["url"]),
1860 dbesc($suggest["name"]),
1861 dbesc($suggest["request"])
1865 * If no record in fcontact is found, below INSERT statement will not
1866 * link an introduction to it.
1868 if (!DBM::is_result($r)) {
1869 // database record did not get created. Quietly give up.
1875 $hash = random_string();
1878 "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1879 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1880 intval($suggest["uid"]),
1882 intval($suggest["cid"]),
1883 dbesc($suggest["body"]),
1885 dbesc(DateTimeFormat::utcNow()),
1891 "type" => NOTIFY_SUGGEST,
1892 "notify_flags" => $importer["notify-flags"],
1893 "language" => $importer["language"],
1894 "to_name" => $importer["username"],
1895 "to_email" => $importer["email"],
1896 "uid" => $importer["importer_uid"],
1898 "link" => System::baseUrl()."/notifications/intros",
1899 "source_name" => $importer["name"],
1900 "source_link" => $importer["url"],
1901 "source_photo" => $importer["photo"],
1902 "verb" => ACTIVITY_REQ_FRIEND,
1910 * @brief Processes the relocation elements
1912 * @param object $xpath XPath object
1913 * @param object $relocation relocation elements
1914 * @param array $importer Record of the importer user mixed with contact of the content
1916 * @todo Find good type-hints for all parameter
1918 private static function processRelocation($xpath, $relocation, $importer)
1920 logger("Processing relocations");
1922 /// @TODO Rewrite this to one statement
1924 $relocate["uid"] = $importer["importer_uid"];
1925 $relocate["cid"] = $importer["id"];
1926 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1927 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
1928 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1929 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
1930 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1931 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1932 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1933 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1934 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1935 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1936 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1937 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1939 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
1940 $relocate["avatar"] = $relocate["photo"];
1943 if ($relocate["addr"] == "") {
1944 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
1949 "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
1950 intval($importer["id"]),
1951 intval($importer["importer_uid"])
1954 if (!DBM::is_result($r)) {
1955 logger("Query failed to execute, no result returned in " . __FUNCTION__);
1961 // Update the gcontact entry
1962 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
1965 "UPDATE `gcontact` SET
1974 WHERE `nurl` = '%s';",
1975 dbesc($relocate["name"]),
1976 dbesc($relocate["avatar"]),
1977 dbesc($relocate["url"]),
1978 dbesc(normalise_link($relocate["url"])),
1979 dbesc($relocate["addr"]),
1980 dbesc($relocate["addr"]),
1981 dbesc($relocate["notify"]),
1982 dbesc($relocate["server_url"]),
1983 dbesc(normalise_link($old["url"]))
1986 // Update the contact table. We try to find every entry.
1988 "UPDATE `contact` SET
1998 `site-pubkey` = '%s'
1999 WHERE (`id` = %d AND `uid` = %d) OR (`nurl` = '%s');",
2000 dbesc($relocate["name"]),
2001 dbesc($relocate["avatar"]),
2002 dbesc($relocate["url"]),
2003 dbesc(normalise_link($relocate["url"])),
2004 dbesc($relocate["addr"]),
2005 dbesc($relocate["request"]),
2006 dbesc($relocate["confirm"]),
2007 dbesc($relocate["notify"]),
2008 dbesc($relocate["poll"]),
2009 dbesc($relocate["sitepubkey"]),
2010 intval($importer["id"]),
2011 intval($importer["importer_uid"]),
2012 dbesc(normalise_link($old["url"]))
2015 Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
2022 /// @todo This is an extreme performance killer
2024 'owner-link' => [$old["url"], $relocate["url"]],
2025 'author-link' => [$old["url"], $relocate["url"]],
2026 //'owner-avatar' => array($old["photo"], $relocate["photo"]),
2027 //'author-avatar' => array($old["photo"], $relocate["photo"]),
2029 foreach ($fields as $n => $f) {
2031 "SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
2034 intval($importer["importer_uid"])
2037 if (DBM::is_result($r)) {
2039 "UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
2044 intval($importer["importer_uid"])
2054 /// merge with current record, current contents have priority
2055 /// update record, set url-updated
2056 /// update profile photos
2057 /// schedule a scan?
2062 * @brief Updates an item
2064 * @param array $current the current item record
2065 * @param array $item the new item record
2066 * @param array $importer Record of the importer user mixed with contact of the content
2067 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2069 * @todo set proper type-hints (array?)
2071 private static function updateContent($current, $item, $importer, $entrytype)
2075 if (self::isEditedTimestampNewer($current, $item)) {
2076 // do not accept (ignore) an earlier edit than one we currently have.
2077 if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
2081 $fields = ['title' => $item["title"], 'body' => $item["body"],
2082 'tag' => $item["tag"], 'changed' => DateTimeFormat::utcNow(),
2083 'edited' => DateTimeFormat::utc($item["edited"])];
2085 $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
2086 Item::update($fields, $condition);
2090 if ($entrytype == DFRN_REPLY_RC) {
2091 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $current["id"]);
2098 * @brief Detects the entry type of the item
2100 * @param array $importer Record of the importer user mixed with contact of the content
2101 * @param array $item the new item record
2103 * @return int Is it a toplevel entry, a comment or a relayed comment?
2104 * @todo set proper type-hints (array?)
2106 private static function getEntryType($importer, $item)
2108 if ($item["parent-uri"] != $item["uri"]) {
2111 if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
2114 logger("possible community action");
2116 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2119 // was the top-level post for this action written by somebody on this site?
2120 // Specifically, the recipient?
2122 $is_a_remote_action = false;
2125 "SELECT `item`.`parent-uri` FROM `item`
2126 WHERE `item`.`uri` = '%s'
2128 dbesc($item["parent-uri"])
2130 if (DBM::is_result($r)) {
2132 "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2133 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2134 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2135 AND `item`.`uid` = %d
2138 dbesc($r[0]["parent-uri"]),
2139 dbesc($r[0]["parent-uri"]),
2140 dbesc($r[0]["parent-uri"]),
2141 intval($importer["importer_uid"])
2143 if (DBM::is_result($r)) {
2144 $is_a_remote_action = true;
2149 * Does this have the characteristics of a community or private group action?
2150 * If it's an action to a wall post on a community/prvgroup page it's a
2151 * valid community action. Also forum_mode makes it valid for sure.
2152 * If neither, it's not.
2154 if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2155 $is_a_remote_action = false;
2156 logger("not a community action");
2159 if ($is_a_remote_action) {
2160 return DFRN_REPLY_RC;
2165 return DFRN_TOP_LEVEL;
2170 * @brief Send a "poke"
2172 * @param array $item the new item record
2173 * @param array $importer Record of the importer user mixed with contact of the content
2174 * @param int $posted_id The record number of item record that was just posted
2176 * @todo set proper type-hints (array?)
2178 private static function doPoke($item, $importer, $posted_id)
2180 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2184 $xo = XML::parseString($item["object"], false);
2186 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2187 // somebody was poked/prodded. Was it me?
2188 foreach ($xo->link as $l) {
2189 $atts = $l->attributes();
2190 switch ($atts["rel"]) {
2192 $Blink = $atts["href"];
2199 if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2200 // send a notification
2203 "type" => NOTIFY_POKE,
2204 "notify_flags" => $importer["notify-flags"],
2205 "language" => $importer["language"],
2206 "to_name" => $importer["username"],
2207 "to_email" => $importer["email"],
2208 "uid" => $importer["importer_uid"],
2210 "link" => System::baseUrl()."/display/".urlencode(Item::getGuidById($posted_id)),
2211 "source_name" => stripslashes($item["author-name"]),
2212 "source_link" => $item["author-link"],
2213 "source_photo" => ((link_compare($item["author-link"], $importer["url"]))
2214 ? $importer["thumb"] : $item["author-avatar"]),
2215 "verb" => $item["verb"],
2216 "otype" => "person",
2217 "activity" => $verb,
2218 "parent" => $item["parent"]]
2225 * @brief Processes several actions, depending on the verb
2227 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2228 * @param array $importer Record of the importer user mixed with contact of the content
2229 * @param array $item the new item record
2230 * @param bool $is_like Is the verb a "like"?
2232 * @return bool Should the processing of the entries be continued?
2233 * @todo set proper type-hints (array?)
2235 private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2237 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2239 if (($entrytype == DFRN_TOP_LEVEL)) {
2240 // The filling of the the "contact" variable is done for legcy reasons
2241 // The functions below are partly used by ostatus.php as well - where we have this variable
2242 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2244 $nickname = $contact["nick"];
2246 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2247 // This function once was responsible for DFRN and OStatus.
2248 if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2249 logger("New follower");
2250 Contact::addRelationship($importer, $contact, $item, $nickname);
2253 if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2254 logger("Lost follower");
2255 Contact::removeFollower($importer, $contact, $item);
2258 if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2259 logger("New friend request");
2260 Contact::addRelationship($importer, $contact, $item, $nickname, true);
2263 if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2264 logger("Lost sharer");
2265 Contact::removeSharer($importer, $contact, $item);
2269 if (($item["verb"] == ACTIVITY_LIKE)
2270 || ($item["verb"] == ACTIVITY_DISLIKE)
2271 || ($item["verb"] == ACTIVITY_ATTEND)
2272 || ($item["verb"] == ACTIVITY_ATTENDNO)
2273 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
2276 $item["type"] = "activity";
2277 $item["gravity"] = GRAVITY_LIKE;
2278 // only one like or dislike per person
2279 // splitted into two queries for performance issues
2281 "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `parent-uri` = '%s' AND NOT `deleted` LIMIT 1",
2282 intval($item["uid"]),
2283 dbesc($item["author-link"]),
2284 dbesc($item["verb"]),
2285 dbesc($item["parent-uri"])
2287 if (DBM::is_result($r)) {
2292 "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `thr-parent` = '%s' AND NOT `deleted` LIMIT 1",
2293 intval($item["uid"]),
2294 dbesc($item["author-link"]),
2295 dbesc($item["verb"]),
2296 dbesc($item["parent-uri"])
2298 if (DBM::is_result($r)) {
2305 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2306 $xo = XML::parseString($item["object"], false);
2307 $xt = XML::parseString($item["target"], false);
2309 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2311 "SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2313 intval($importer["importer_uid"])
2316 if (!DBM::is_result($r)) {
2317 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2321 // extract tag, if not duplicate, add to parent item
2323 if (!stristr($r[0]["tag"], trim($xo->content))) {
2324 $tag = $r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2325 Item::update(['tag' => $tag], ['id' => $r[0]["id"]]);
2335 * @brief Processes the link elements
2337 * @param object $links link elements
2338 * @param array $item the item record
2340 * @todo set proper type-hints
2342 private static function parseLinks($links, &$item)
2349 foreach ($links as $link) {
2350 foreach ($link->attributes as $attributes) {
2351 switch ($attributes->name) {
2352 case "href" : $href = $attributes->textContent; break;
2353 case "rel" : $rel = $attributes->textContent; break;
2354 case "type" : $type = $attributes->textContent; break;
2355 case "length": $length = $attributes->textContent; break;
2356 case "title" : $title = $attributes->textContent; break;
2359 if (($rel != "") && ($href != "")) {
2362 $item["plink"] = $href;
2366 if (strlen($item["attach"])) {
2367 $item["attach"] .= ",";
2370 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2378 * @brief Processes the entry elements which contain the items and comments
2380 * @param array $header Array of the header elements that always stay the same
2381 * @param object $xpath XPath object
2382 * @param object $entry entry elements
2383 * @param array $importer Record of the importer user mixed with contact of the content
2384 * @param object $xml xml
2386 * @todo Add type-hints
2388 private static function processEntry($header, $xpath, $entry, $importer, $xml)
2390 logger("Processing entries");
2394 $item["protocol"] = PROTOCOL_DFRN;
2396 $item["source"] = $xml;
2399 $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
2401 $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
2403 $current = dba::selectFirst('item',
2404 ['id', 'uid', 'edited', 'body'],
2405 ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
2407 // Is there an existing item?
2408 if (DBM::is_result($current) && !self::isEditedTimestampNewer($current, $item)) {
2409 logger("Item ".$item["uri"]." (".$item['edited'].") already existed.", LOGGER_DEBUG);
2414 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2416 $item["owner-name"] = $owner["name"];
2417 $item["owner-link"] = $owner["link"];
2418 $item["owner-avatar"] = $owner["avatar"];
2421 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2423 $item["author-name"] = $author["name"];
2424 $item["author-link"] = $author["link"];
2425 $item["author-avatar"] = $author["avatar"];
2427 $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
2429 $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2431 $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
2432 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2433 // make sure nobody is trying to sneak some html tags by us
2434 $item["body"] = notags(base64url_decode($item["body"]));
2436 $item["body"] = BBCode::limitBodySize($item["body"]);
2438 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2439 if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
2440 $base_url = get_app()->get_baseurl();
2441 $item['body'] = reltoabs($item['body'], $base_url);
2443 $item['body'] = html2bb_video($item['body']);
2445 $item['body'] = OEmbed::HTML2BBCode($item['body']);
2447 $config = HTMLPurifier_Config::createDefault();
2448 $config->set('Cache.DefinitionImpl', null);
2450 // we shouldn't need a whitelist, because the bbcode converter
2451 // will strip out any unsupported tags.
2453 $purifier = new HTMLPurifier($config);
2454 $item['body'] = $purifier->purify($item['body']);
2456 $item['body'] = @Friendica\Content\Text\HTML::toBBCode($item['body']);
2459 /// @todo We should check for a repeated post and if we know the repeated author.
2461 // We don't need the content element since "dfrn:env" is always present
2462 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2464 $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
2466 $georsspoint = $xpath->query("georss:point", $entry);
2468 $item["coord"] = $georsspoint->item(0)->nodeValue;
2471 $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
2473 $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
2475 if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true") {
2476 $item["bookmark"] = true;
2479 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2480 if ($notice_info && ($notice_info->length > 0)) {
2481 foreach ($notice_info->item(0)->attributes as $attributes) {
2482 if ($attributes->name == "source") {
2483 $item["app"] = strip_tags($attributes->textContent);
2488 $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
2490 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
2491 $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
2492 if ($dsprsig != "") {
2493 $item["dsprsig"] = $dsprsig;
2496 $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
2498 if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "") {
2499 $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
2502 $object = $xpath->query("activity:object", $entry)->item(0);
2503 $item["object"] = self::transformActivity($xpath, $object, "object");
2505 if (trim($item["object"]) != "") {
2506 $r = XML::parseString($item["object"], false);
2507 if (isset($r->type)) {
2508 $item["object-type"] = $r->type;
2512 $target = $xpath->query("activity:target", $entry)->item(0);
2513 $item["target"] = self::transformActivity($xpath, $target, "target");
2515 $categories = $xpath->query("atom:category", $entry);
2517 foreach ($categories as $category) {
2520 foreach ($category->attributes as $attributes) {
2521 if ($attributes->name == "term") {
2522 $term = $attributes->textContent;
2525 if ($attributes->name == "scheme") {
2526 $scheme = $attributes->textContent;
2530 if (($term != "") && ($scheme != "")) {
2531 $parts = explode(":", $scheme);
2532 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2533 $termhash = array_shift($parts);
2534 $termurl = implode(":", $parts);
2536 if (strlen($item["tag"])) {
2537 $item["tag"] .= ",";
2540 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2548 $links = $xpath->query("atom:link", $entry);
2550 self::parseLinks($links, $item);
2553 $item['conversation-uri'] = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
2555 $conv = $xpath->query('ostatus:conversation', $entry);
2556 if (is_object($conv->item(0))) {
2557 foreach ($conv->item(0)->attributes as $attributes) {
2558 if ($attributes->name == "ref") {
2559 $item['conversation-uri'] = $attributes->textContent;
2561 if ($attributes->name == "href") {
2562 $item['conversation-href'] = $attributes->textContent;
2567 // Is it a reply or a top level posting?
2568 $item["parent-uri"] = $item["uri"];
2570 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2571 if (is_object($inreplyto->item(0))) {
2572 foreach ($inreplyto->item(0)->attributes as $attributes) {
2573 if ($attributes->name == "ref") {
2574 $item["parent-uri"] = $attributes->textContent;
2579 // Get the type of the item (Top level post, reply or remote reply)
2580 $entrytype = self::getEntryType($importer, $item);
2582 // Now assign the rest of the values that depend on the type of the message
2583 if (in_array($entrytype, [DFRN_REPLY, DFRN_REPLY_RC])) {
2584 if (!isset($item["object-type"])) {
2585 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2588 if ($item["contact-id"] != $owner["contact-id"]) {
2589 $item["contact-id"] = $owner["contact-id"];
2592 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2593 $item["network"] = $owner["network"];
2596 if ($item["contact-id"] != $author["contact-id"]) {
2597 $item["contact-id"] = $author["contact-id"];
2600 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2601 $item["network"] = $author["network"];
2605 if ($entrytype == DFRN_REPLY_RC) {
2606 $item["type"] = "remote-comment";
2608 } elseif ($entrytype == DFRN_TOP_LEVEL) {
2609 if (!isset($item["object-type"])) {
2610 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2614 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2615 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2616 $ev = bbtoevent($item["body"]);
2617 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2618 logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2619 $ev["cid"] = $importer["id"];
2620 $ev["uid"] = $importer["uid"];
2621 $ev["uri"] = $item["uri"];
2622 $ev["edited"] = $item["edited"];
2623 $ev["private"] = $item["private"];
2624 $ev["guid"] = $item["guid"];
2627 "SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2628 dbesc($item["uri"]),
2629 intval($importer["uid"])
2631 if (DBM::is_result($r)) {
2632 $ev["id"] = $r[0]["id"];
2635 $event_id = event_store($ev);
2636 logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2642 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2643 logger("Exiting because 'processVerbs' told us so", LOGGER_DEBUG);
2647 // Update content if 'updated' changes
2648 if (DBM::is_result($current)) {
2649 if (self::updateContent($current, $item, $importer, $entrytype)) {
2650 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2652 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2657 if (in_array($entrytype, [DFRN_REPLY, DFRN_REPLY_RC])) {
2658 $posted_id = Item::insert($item);
2662 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2664 $item["id"] = $posted_id;
2667 "SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2669 intval($importer["importer_uid"])
2671 if (DBM::is_result($r)) {
2672 $parent = $r[0]["parent"];
2673 $parent_uri = $r[0]["parent-uri"];
2676 if ($posted_id && $parent && ($entrytype == DFRN_REPLY_RC)) {
2677 logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
2678 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $posted_id);
2683 } else { // $entrytype == DFRN_TOP_LEVEL
2684 if (!link_compare($item["owner-link"], $importer["url"])) {
2686 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2687 * but otherwise there's a possible data mixup on the sender's system.
2688 * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2689 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2691 logger('Correcting item owner.', LOGGER_DEBUG);
2692 $item["owner-name"] = $importer["senderName"];
2693 $item["owner-link"] = $importer["url"];
2694 $item["owner-avatar"] = $importer["thumb"];
2697 if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2698 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2702 // This is my contact on another system, but it's really me.
2703 // Turn this into a wall post.
2704 $notify = Item::isRemoteSelf($importer, $item);
2706 $posted_id = Item::insert($item, false, $notify);
2708 logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2710 if (stristr($item["verb"], ACTIVITY_POKE)) {
2711 self::doPoke($item, $importer, $posted_id);
2717 * @brief Deletes items
2719 * @param object $xpath XPath object
2720 * @param object $deletion deletion elements
2721 * @param array $importer Record of the importer user mixed with contact of the content
2723 * @todo set proper type-hints
2725 private static function processDeletion($xpath, $deletion, $importer)
2727 logger("Processing deletions");
2729 foreach ($deletion->attributes as $attributes) {
2730 if ($attributes->name == "ref") {
2731 $uri = $attributes->textContent;
2735 if (!$uri || !$importer["id"]) {
2739 $condition = ["`uri` = ? AND `uid` = ? AND NOT `file` LIKE '%[%'", $uri, $importer["uid"]];
2740 $item = dba::selectFirst('item', ['id', 'parent', 'contact-id'], $condition);
2741 if (!DBM::is_result($item)) {
2742 logger("Item with uri " . $uri . " for user " . $importer["uid"] . " wasn't found.", LOGGER_DEBUG);
2746 // When it is a starting post it has to belong to the person that wants to delete it
2747 if (($item['id'] == $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2748 logger("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2752 // Comments can be deleted by the thread owner or comment owner
2753 if (($item['id'] != $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2754 $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2755 if (!dba::exists('item', $condition)) {
2756 logger("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2761 $entrytype = self::getEntryType($importer, $item);
2763 if (!$item["deleted"]) {
2764 logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG);
2769 Item::deleteById($item["id"]);
2771 if ($entrytype != DFRN_TOP_LEVEL) {
2772 // if this is a relayed delete, propagate it to other recipients
2773 if ($entrytype == DFRN_REPLY_RC) {
2774 logger("Notifying followers about deletion of post " . $item["id"], LOGGER_DEBUG);
2775 Worker::add(PRIORITY_HIGH, "Notifier", "drop", $item["id"]);
2781 * @brief Imports a DFRN message
2783 * @param string $xml The DFRN message
2784 * @param array $importer Record of the importer user mixed with contact of the content
2785 * @param bool $sort_by_date Is used when feeds are polled
2786 * @return integer Import status
2787 * @todo set proper type-hints
2789 public static function import($xml, $importer, $sort_by_date = false)
2795 $doc = new DOMDocument();
2796 @$doc->loadXML($xml);
2798 $xpath = new DOMXPath($doc);
2799 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2800 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2801 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2802 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2803 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2804 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2805 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2806 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2807 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2808 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2811 $header["uid"] = $importer["uid"];
2812 $header["network"] = NETWORK_DFRN;
2813 $header["type"] = "remote";
2814 $header["wall"] = 0;
2815 $header["origin"] = 0;
2816 $header["contact-id"] = $importer["id"];
2818 // Update the contact table if the data has changed
2820 // The "atom:author" is only present in feeds
2821 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2822 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2825 // Only the "dfrn:owner" in the head section contains all data
2826 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2827 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2830 logger("Import DFRN message for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2832 // The account type is new since 3.5.1
2833 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2834 $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()")->item(0)->nodeValue);
2836 if ($accounttype != $importer["contact-type"]) {
2837 dba::update('contact', ['contact-type' => $accounttype], ['id' => $importer["id"]]);
2841 // is it a public forum? Private forums aren't supported with this method
2842 // This is deprecated since 3.5.1
2843 $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()")->item(0)->nodeValue);
2845 if ($forum != $importer["forum"]) {
2846 $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2847 dba::update('contact', ['forum' => $forum], $condition);
2850 // We are processing relocations even if we are ignoring a contact
2851 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2852 foreach ($relocations as $relocation) {
2853 self::processRelocation($xpath, $relocation, $importer);
2856 if ($importer["readonly"]) {
2857 // We aren't receiving stuff from this person. But we will quietly ignore them
2858 // rather than a blatant "go away" message.
2859 logger('ignoring contact '.$importer["id"]);
2863 $mails = $xpath->query("/atom:feed/dfrn:mail");
2864 foreach ($mails as $mail) {
2865 self::processMail($xpath, $mail, $importer);
2868 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2869 foreach ($suggestions as $suggestion) {
2870 self::processSuggestion($xpath, $suggestion, $importer);
2873 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2874 foreach ($deletions as $deletion) {
2875 self::processDeletion($xpath, $deletion, $importer);
2878 if (!$sort_by_date) {
2879 $entries = $xpath->query("/atom:feed/atom:entry");
2880 foreach ($entries as $entry) {
2881 self::processEntry($header, $xpath, $entry, $importer, $xml);
2885 $entries = $xpath->query("/atom:feed/atom:entry");
2886 foreach ($entries as $entry) {
2887 $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2888 $newentries[strtotime($created)] = $entry;
2891 // Now sort after the publishing date
2894 foreach ($newentries as $entry) {
2895 self::processEntry($header, $xpath, $entry, $importer, $xml);
2898 logger("Import done for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2904 * @param string $contact_nick contact nickname
2906 public static function autoRedir(App $a, $contact_nick)
2909 if (x($_REQUEST, 'redir') && intval($_REQUEST['redir'])) {
2913 if ((! $contact_nick) || ($contact_nick === $a->user['nickname'])) {
2918 // We need to find out if $contact_nick is a user on this hub, and if so, if I
2919 // am a contact of that user. However, that user may have other contacts with the
2920 // same nickname as me on other hubs or other networks. Exclude these by requiring
2921 // that the contact have a local URL. I will be the only person with my nickname at
2922 // this URL, so if a result is found, then I am a contact of the $contact_nick user.
2924 // We also have to make sure that I'm a legitimate contact--I'm not blocked or pending.
2926 $baseurl = System::baseUrl();
2927 $domain_st = strpos($baseurl, "://");
2928 if ($domain_st === false) {
2931 $baseurl = substr($baseurl, $domain_st + 3);
2932 $nurl = normalise_link($baseurl);
2934 /// @todo Why is there a query for "url" *and* "nurl"? Especially this normalising is strange.
2935 $r = q("SELECT `id` FROM `contact` WHERE `uid` = (SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1)
2936 AND `nick` = '%s' AND NOT `self` AND (`url` LIKE '%%%s%%' OR `nurl` LIKE '%%%s%%') AND NOT `blocked` AND NOT `pending` LIMIT 1",
2937 dbesc($contact_nick),
2938 dbesc($a->user['nickname']),
2942 if ((! DBM::is_result($r)) || $r[0]['id'] == remote_user()) {
2946 $r = q("SELECT * FROM contact WHERE nick = '%s'
2947 AND network = '%s' AND uid = %d AND url LIKE '%%%s%%' LIMIT 1",
2948 dbesc($contact_nick),
2949 dbesc(NETWORK_DFRN),
2950 intval(local_user()),
2953 if (! DBM::is_result($r)) {
2959 $dfrn_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2961 if ($r[0]['duplex'] && $r[0]['issued-id']) {
2962 $orig_id = $r[0]['issued-id'];
2963 $dfrn_id = '1:' . $orig_id;
2965 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
2966 $orig_id = $r[0]['dfrn-id'];
2967 $dfrn_id = '0:' . $orig_id;
2970 // ensure that we've got a valid ID. There may be some edge cases with forums and non-duplex mode
2971 // that may have triggered some of the "went to {profile/intro} and got an RSS feed" issues
2973 if (strlen($dfrn_id) < 3) {
2977 $sec = random_string();
2979 dba::insert('profile_check', ['uid' => local_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id, 'sec' => $sec, 'expire' => time() + 45]);
2981 $url = curPageURL();
2983 logger('auto_redir: ' . $r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
2984 $dest = (($url) ? '&destination_url=' . $url : '');
2985 goaway($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
2986 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest);
2993 * @brief Returns the activity verb
2995 * @param array $item Item array
2997 * @return string activity verb
2999 private static function constructVerb(array $item)
3001 if ($item['verb']) {
3002 return $item['verb'];
3004 return ACTIVITY_POST;
3007 private static function tgroupCheck($uid, $item)
3011 // check that the message originated elsewhere and is a top-level post
3013 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['parent-uri'])) {
3017 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
3020 if (!DBM::is_result($u)) {
3024 $community_page = ($u[0]['page-flags'] == PAGE_COMMUNITY);
3025 $prvgroup = ($u[0]['page-flags'] == PAGE_PRVGROUP);
3027 $link = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
3030 * Diaspora uses their own hardwired link URL in @-tags
3031 * instead of the one we supply with webfinger
3033 $dlink = normalise_link(System::baseUrl() . '/u/' . $u[0]['nickname']);
3035 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
3037 foreach ($matches as $mtch) {
3038 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
3040 logger('mention found: ' . $mtch[2]);
3049 return $community_page || $prvgroup;
3053 * This function returns true if $update has an edited timestamp newer
3054 * than $existing, i.e. $update contains new data which should override
3055 * what's already there. If there is no timestamp yet, the update is
3056 * assumed to be newer. If the update has no timestamp, the existing
3057 * item is assumed to be up-to-date. If the timestamps are equal it
3058 * assumes the update has been seen before and should be ignored.
3061 private static function isEditedTimestampNewer($existing, $update)
3063 if (!x($existing, 'edited') || !$existing['edited']) {
3066 if (!x($update, 'edited') || !$update['edited']) {
3070 $existing_edited = DateTimeFormat::utc($existing['edited']);
3071 $update_edited = DateTimeFormat::utc($update['edited']);
3073 return (strcmp($existing_edited, $update_edited) < 0);