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\Content\Text\HTML;
15 use Friendica\Core\Addon;
16 use Friendica\Core\Config;
17 use Friendica\Core\L10n;
18 use Friendica\Core\System;
19 use Friendica\Core\Worker;
20 use Friendica\Database\DBM;
21 use Friendica\Model\Contact;
22 use Friendica\Model\Event;
23 use Friendica\Model\GContact;
24 use Friendica\Model\Group;
25 use Friendica\Model\Item;
26 use Friendica\Model\Profile;
27 use Friendica\Model\User;
28 use Friendica\Object\Image;
29 use Friendica\Protocol\OStatus;
30 use Friendica\Util\Crypto;
31 use Friendica\Util\DateTimeFormat;
32 use Friendica\Util\Network;
33 use Friendica\Util\XML;
34 use Friendica\Protocol\Diaspora;
39 use HTMLPurifier_Config;
41 require_once 'boot.php';
42 require_once 'include/dba.php';
43 require_once "include/enotify.php";
44 require_once "include/items.php";
45 require_once "include/text.php";
48 * @brief This class contain functions to create and send DFRN XML files
53 const DFRN_TOP_LEVEL = 0; // Top level posting
54 const DFRN_REPLY = 1; // Regular reply that is stored locally
55 const DFRN_REPLY_RC = 2; // Reply that will be relayed
58 * @brief Generates the atom entries for delivery.php
60 * This function is used whenever content is transmitted via DFRN.
62 * @param array $items Item elements
63 * @param array $owner Owner record
65 * @return string DFRN entries
66 * @todo Find proper type-hints
68 public static function entries($items, $owner)
70 $doc = new DOMDocument('1.0', 'utf-8');
71 $doc->formatOutput = true;
73 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
75 if (! count($items)) {
76 return trim($doc->saveXML());
79 foreach ($items as $item) {
80 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
81 $root->appendChild($entry);
84 return(trim($doc->saveXML()));
88 * @brief Generate an atom feed for the given user
90 * This function is called when another server is pulling data from the user feed.
92 * @param string $dfrn_id DFRN ID from the requesting party
93 * @param string $owner_nick Owner nick name
94 * @param string $last_update Date of the last update
95 * @param int $direction Can be -1, 0 or 1.
96 * @param boolean $onlyheader Output only the header without content? (Default is "no")
98 * @return string DFRN feed entries
100 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false)
104 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
105 $public_feed = (($dfrn_id) ? false : true);
106 $starred = false; // not yet implemented, possible security issues
109 if ($public_feed && $a->argc > 2) {
110 for ($x = 2; $x < $a->argc; $x++) {
111 if ($a->argv[$x] == 'converse') {
114 if ($a->argv[$x] == 'starred') {
117 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
118 $category = $a->argv[$x+1];
123 // default permissions - anonymous user
125 $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = '' ";
128 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
129 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
130 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
134 if (! DBM::is_result($r)) {
135 logger(sprintf('No contact found for nickname=%d', $owner_nick), LOGGER_WARNING);
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)) {
171 logger(sprintf('No contact found for uid=%d', $owner_id), LOGGER_WARNING);
176 include_once 'include/security.php';
177 $groups = Group::getIdsByContactId($contact['id']);
179 if (count($groups)) {
180 for ($x = 0; $x < count($groups); $x ++) {
181 $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 = DateTimeFormat::utc($last_update);
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 Find proper 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", DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
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 Find proper 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 Find proper 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 Find proper 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", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
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 Find proper 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 = DateTimeFormat::utc($owner['name-date'].'+00:00', DateTimeFormat::ATOM);
624 $uridate = DateTimeFormat::utc($owner['uri-date'].'+00:00', DateTimeFormat::ATOM);
625 $picdate = DateTimeFormat::utc($owner['avatar-date'].'+00:00', DateTimeFormat::ATOM);
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 Find proper 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 Find proper type-hints
792 private static function createActivity($doc, $element, $activity)
795 $entry = $doc->createElement($element);
797 $r = XML::parseString($activity, false);
803 XML::addElement($doc, $entry, "activity:object-type", $r->type);
807 XML::addElement($doc, $entry, "id", $r->id);
811 XML::addElement($doc, $entry, "title", $r->title);
815 if (substr($r->link, 0, 1) == '<') {
816 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
817 $r->link = str_replace('&', '&', $r->link);
820 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
822 // XML does need a single element as root element so we add a dummy element here
823 $data = XML::parseString("<dummy>" . $r->link . "</dummy>", false);
824 if (is_object($data)) {
825 foreach ($data->link as $link) {
827 foreach ($link->attributes() as $parameter => $value) {
828 $attributes[$parameter] = $value;
830 XML::addElement($doc, $entry, "link", "", $attributes);
834 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
835 XML::addElement($doc, $entry, "link", "", $attributes);
839 XML::addElement($doc, $entry, "content", BBCode::convert($r->content), ["type" => "html"]);
849 * @brief Adds the elements for attachments
851 * @param object $doc XML document
852 * @param object $root XML root
853 * @param array $item Item element
855 * @return object XML attachment object
856 * @todo Find proper type-hints
858 private static function getAttachment($doc, $root, $item)
860 $arr = explode('[/attach],', $item['attach']);
862 foreach ($arr as $r) {
864 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
866 $attributes = ["rel" => "enclosure",
867 "href" => $matches[1],
868 "type" => $matches[3]];
870 if (intval($matches[2])) {
871 $attributes["length"] = intval($matches[2]);
874 if (trim($matches[4]) != "") {
875 $attributes["title"] = trim($matches[4]);
878 XML::addElement($doc, $root, "link", "", $attributes);
885 * @brief Adds the "entry" elements for the DFRN protocol
887 * @param object $doc XML document
888 * @param string $type "text" or "html"
889 * @param array $item Item element
890 * @param array $owner Owner record
891 * @param bool $comment Trigger the sending of the "comment" element
892 * @param int $cid Contact ID of the recipient
893 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
895 * @return object XML entry object
896 * @todo Find proper type-hints
898 private static function entry($doc, $type, $item, $owner, $comment = false, $cid = 0, $single = false)
902 if (!$item['parent']) {
906 if ($item['deleted']) {
907 $attributes = ["ref" => $item['uri'], "when" => DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM)];
908 return XML::createElement($doc, "at:deleted-entry", "", $attributes);
912 $entry = $doc->createElement("entry");
914 $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry');
915 $doc->appendChild($entry);
917 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
918 $entry->setAttribute("xmlns:at", NAMESPACE_TOMB);
919 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
920 $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
921 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
922 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
923 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
924 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
925 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
928 if ($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid']) {
929 $body = Item::fixPrivatePhotos($item['body'], $owner['uid'], $item, $cid);
931 $body = $item['body'];
934 // Remove the abstract element. It is only locally important.
935 $body = BBCode::stripAbstract($body);
938 if ($type == 'html') {
941 if ($item['title'] != "") {
942 $htmlbody = "[b]".$item['title']."[/b]\n\n".$htmlbody;
945 $htmlbody = BBCode::convert($htmlbody, false, 7);
948 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
949 $entry->appendChild($author);
951 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
952 $entry->appendChild($dfrnowner);
954 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
955 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
956 $parent = q("SELECT `guid`,`plink` FROM `item` WHERE `uri` = '%s' AND `uid` = %d", dbesc($parent_item), intval($item['uid']));
957 $attributes = ["ref" => $parent_item, "type" => "text/html",
958 "href" => $parent[0]['plink'],
959 "dfrn:diaspora_guid" => $parent[0]['guid']];
960 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
963 // Add conversation data. This is used for OStatus
964 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
965 $conversation_uri = $conversation_href;
967 if (isset($parent_item)) {
968 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $item['parent-uri']);
969 if (DBM::is_result($r)) {
970 if ($r['conversation-uri'] != '') {
971 $conversation_uri = $r['conversation-uri'];
973 if ($r['conversation-href'] != '') {
974 $conversation_href = $r['conversation-href'];
980 "href" => $conversation_href,
981 "ref" => $conversation_uri];
983 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
985 XML::addElement($doc, $entry, "id", $item["uri"]);
986 XML::addElement($doc, $entry, "title", $item["title"]);
988 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"] . "+00:00", DateTimeFormat::ATOM));
989 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"] . "+00:00", DateTimeFormat::ATOM));
991 // "dfrn:env" is used to read the content
992 XML::addElement($doc, $entry, "dfrn:env", base64url_encode($body, true));
994 // The "content" field is not read by the receiver. We could remove it when the type is "text"
995 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
996 XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
998 // We save this value in "plink". Maybe we should read it from there as well?
1004 ["rel" => "alternate", "type" => "text/html",
1005 "href" => System::baseUrl() . "/display/" . $item["guid"]]
1008 // "comment-allow" is some old fashioned stuff for old Friendica versions.
1009 // It is included in the rewritten code for completeness
1011 XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
1014 if ($item['location']) {
1015 XML::addElement($doc, $entry, "dfrn:location", $item['location']);
1018 if ($item['coord']) {
1019 XML::addElement($doc, $entry, "georss:point", $item['coord']);
1022 if (($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])) {
1023 XML::addElement($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
1026 if ($item['extid']) {
1027 XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
1030 if ($item['bookmark']) {
1031 XML::addElement($doc, $entry, "dfrn:bookmark", "true");
1035 XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
1038 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
1040 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
1041 // It is needed for relayed comments to Diaspora.
1042 if ($item['signed_text']) {
1043 $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer']]));
1044 XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
1047 XML::addElement($doc, $entry, "activity:verb", self::constructVerb($item));
1049 if ($item['object-type'] != "") {
1050 XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
1051 } elseif ($item['id'] == $item['parent']) {
1052 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1054 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
1057 $actobj = self::createActivity($doc, "activity:object", $item['object']);
1059 $entry->appendChild($actobj);
1062 $actarg = self::createActivity($doc, "activity:target", $item['target']);
1064 $entry->appendChild($actarg);
1067 $tags = Item::getFeedTags($item);
1070 foreach ($tags as $t) {
1071 if (($type != 'html') || ($t[0] != "@")) {
1072 XML::addElement($doc, $entry, "category", "", ["scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]]);
1078 foreach ($tags as $t) {
1080 $mentioned[$t[1]] = $t[1];
1085 foreach ($mentioned as $mention) {
1087 "SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1088 intval($owner["uid"]),
1089 dbesc(normalise_link($mention))
1092 if (DBM::is_result($r) && ($r[0]["forum"] || $r[0]["prv"])) {
1098 ["rel" => "mentioned",
1099 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1108 ["rel" => "mentioned",
1109 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1115 self::getAttachment($doc, $entry, $item);
1121 * @brief encrypts data via AES
1123 * @param string $data The data that is to be encrypted
1124 * @param string $key The AES key
1126 * @return string encrypted data
1128 private static function aesEncrypt($data, $key)
1130 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1134 * @brief decrypts data via AES
1136 * @param string $encrypted The encrypted data
1137 * @param string $key The AES key
1139 * @return string decrypted data
1141 public static function aesDecrypt($encrypted, $key)
1143 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1147 * @brief Delivers the atom content to the contacts
1149 * @param array $owner Owner record
1150 * @param array $contact Contact record of the receiver
1151 * @param string $atom Content that will be transmitted
1152 * @param bool $dissolve (to be documented)
1154 * @return int Deliver status. Negative values mean an error.
1155 * @todo Add array type-hint for $owner, $contact
1157 public static function deliver($owner, $contact, $atom, $dissolve = false)
1161 // At first try the Diaspora transport layer
1162 $ret = self::transmit($owner, $contact, $atom);
1164 logger('Delivery via Diaspora transport layer was successful with status ' . $ret);
1168 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1170 if ($contact['duplex'] && $contact['dfrn-id']) {
1171 $idtosend = '0:' . $orig_id;
1173 if ($contact['duplex'] && $contact['issued-id']) {
1174 $idtosend = '1:' . $orig_id;
1177 $rino = Config::get('system', 'rino_encrypt');
1178 $rino = intval($rino);
1180 logger("Local rino version: ". $rino, LOGGER_DEBUG);
1182 $ssl_val = intval(Config::get('system', 'ssl_policy'));
1186 case SSL_POLICY_FULL:
1187 $ssl_policy = 'full';
1189 case SSL_POLICY_SELFSIGN:
1190 $ssl_policy = 'self';
1192 case SSL_POLICY_NONE:
1194 $ssl_policy = 'none';
1198 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1200 logger('dfrn_deliver: ' . $url);
1202 $ret = Network::curl($url);
1204 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1205 Contact::markForArchival($contact);
1206 return -2; // timed out
1209 $xml = $ret['body'];
1211 $curl_stat = $a->get_curl_code();
1212 if (empty($curl_stat)) {
1213 Contact::markForArchival($contact);
1214 return -3; // timed out
1217 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1220 Contact::markForArchival($contact);
1224 if (strpos($xml, '<?xml') === false) {
1225 logger('dfrn_deliver: no valid XML returned');
1226 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1227 Contact::markForArchival($contact);
1231 $res = XML::parseString($xml);
1233 if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
1234 Contact::markForArchival($contact);
1235 return ($res->status ? $res->status : 3);
1239 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1240 $challenge = hex2bin((string) $res->challenge);
1241 $perm = (($res->perm) ? $res->perm : null);
1242 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1243 $rino_remote_version = intval($res->rino);
1244 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1246 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
1248 if ($owner['page-flags'] == PAGE_PRVGROUP) {
1252 $final_dfrn_id = '';
1255 if ((($perm == 'rw') && (! intval($contact['writable'])))
1256 || (($perm == 'r') && (intval($contact['writable'])))
1259 "update contact set writable = %d where id = %d",
1260 intval(($perm == 'rw') ? 1 : 0),
1261 intval($contact['id'])
1263 $contact['writable'] = (string) 1 - intval($contact['writable']);
1267 if (($contact['duplex'] && strlen($contact['pubkey']))
1268 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1269 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
1271 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
1272 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
1274 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
1275 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
1278 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1280 if (strpos($final_dfrn_id, ':') == 1) {
1281 $final_dfrn_id = substr($final_dfrn_id, 2);
1284 if ($final_dfrn_id != $orig_id) {
1285 logger('dfrn_deliver: wrong dfrn_id.');
1286 // did not decode properly - cannot trust this site
1287 Contact::markForArchival($contact);
1291 $postvars['dfrn_id'] = $idtosend;
1292 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1294 $postvars['dissolve'] = '1';
1297 if ((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1298 $postvars['data'] = $atom;
1299 $postvars['perm'] = 'rw';
1301 $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
1302 $postvars['perm'] = 'r';
1305 $postvars['ssl_policy'] = $ssl_policy;
1308 $postvars['page'] = $page;
1312 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1313 logger('rino version: '. $rino_remote_version);
1315 switch ($rino_remote_version) {
1317 $key = openssl_random_pseudo_bytes(16);
1318 $data = self::aesEncrypt($postvars['data'], $key);
1321 logger("rino: invalid requested version '$rino_remote_version'");
1322 Contact::markForArchival($contact);
1326 $postvars['rino'] = $rino_remote_version;
1327 $postvars['data'] = bin2hex($data);
1329 if ($dfrn_version >= 2.1) {
1330 if (($contact['duplex'] && strlen($contact['pubkey']))
1331 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1332 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
1334 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1336 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1339 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1340 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1342 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1346 logger('md5 rawkey ' . md5($postvars['key']));
1348 $postvars['key'] = bin2hex($postvars['key']);
1352 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), LOGGER_DATA);
1354 $xml = Network::post($contact['notify'], $postvars);
1356 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1358 $curl_stat = $a->get_curl_code();
1359 if (empty($curl_stat) || empty($xml)) {
1360 Contact::markForArchival($contact);
1361 return -9; // timed out
1364 if (($curl_stat == 503) && stristr($a->get_curl_headers(), 'retry-after')) {
1365 Contact::markForArchival($contact);
1369 if (strpos($xml, '<?xml') === false) {
1370 logger('dfrn_deliver: phase 2: no valid XML returned');
1371 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1372 Contact::markForArchival($contact);
1376 $res = XML::parseString($xml);
1378 if (!isset($res->status)) {
1379 Contact::markForArchival($contact);
1383 // Possibly old servers had returned an empty value when everything was okay
1384 if (empty($res->status)) {
1388 if (!empty($res->message)) {
1389 logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1392 if (($res->status >= 200) && ($res->status <= 299)) {
1393 Contact::unmarkForArchival($contact);
1396 return intval($res->status);
1400 * @brief Transmits atom content to the contacts via the Diaspora transport layer
1402 * @param array $owner Owner record
1403 * @param array $contact Contact record of the receiver
1404 * @param string $atom Content that will be transmitted
1406 * @return int Deliver status. Negative values mean an error.
1408 public static function transmit($owner, $contact, $atom, $public_batch = false)
1412 if (!$public_batch) {
1413 if (empty($contact['addr'])) {
1414 logger('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.');
1415 if (Contact::updateFromProbe($contact['id'])) {
1416 $new_contact = dba::selectFirst('contact', ['addr'], ['id' => $contact['id']]);
1417 $contact['addr'] = $new_contact['addr'];
1420 if (empty($contact['addr'])) {
1421 logger('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
1422 Contact::markForArchival($contact);
1427 $fcontact = Diaspora::personByHandle($contact['addr']);
1428 if (empty($fcontact)) {
1429 logger('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
1430 Contact::markForArchival($contact);
1433 $pubkey = $fcontact['pubkey'];
1438 $envelope = Diaspora::buildMessage($atom, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
1440 // Create the endpoint for public posts. This is some WIP and should later be added to the probing
1441 if ($public_batch && empty($contact["batch"])) {
1442 $parts = parse_url($contact["notify"]);
1443 $path_parts = explode('/', $parts['path']);
1444 array_pop($path_parts);
1445 $parts['path'] = implode('/', $path_parts);
1446 $contact["batch"] = Network::unparseURL($parts);
1449 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
1451 $content_type = ($public_batch ? "application/magic-envelope+xml" : "application/json");
1453 $xml = Network::post($dest_url, $envelope, ["Content-Type: ".$content_type]);
1455 $curl_stat = $a->get_curl_code();
1456 if (empty($curl_stat) || empty($xml)) {
1457 logger('Empty answer from ' . $contact['id'] . ' - ' . $dest_url);
1458 Contact::markForArchival($contact);
1459 return -9; // timed out
1462 if (($curl_stat == 503) && (stristr($a->get_curl_headers(), 'retry-after'))) {
1463 Contact::markForArchival($contact);
1467 if (strpos($xml, '<?xml') === false) {
1468 logger('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url);
1469 logger('Returned XML: ' . $xml, LOGGER_DATA);
1470 Contact::markForArchival($contact);
1474 $res = XML::parseString($xml);
1476 if (empty($res->status)) {
1477 Contact::markForArchival($contact);
1481 if (!empty($res->message)) {
1482 logger('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1485 if (($res->status >= 200) && ($res->status <= 299)) {
1486 Contact::unmarkForArchival($contact);
1489 return intval($res->status);
1493 * @brief Add new birthday event for this person
1495 * @param array $contact Contact record
1496 * @param string $birthday Birthday of the contact
1498 * @todo Add array type-hint for $contact
1500 private static function birthdayEvent($contact, $birthday)
1502 // Check for duplicates
1504 "SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1505 intval($contact['uid']),
1506 intval($contact['id']),
1507 dbesc(DateTimeFormat::utc($birthday)),
1511 if (DBM::is_result($r)) {
1515 logger('updating birthday: ' . $birthday . ' for contact ' . $contact['id']);
1517 $bdtext = L10n::t('%s\'s birthday', $contact['name']);
1518 $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]');
1521 "INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1522 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1523 intval($contact['uid']),
1524 intval($contact['id']),
1525 dbesc(DateTimeFormat::utcNow()),
1526 dbesc(DateTimeFormat::utcNow()),
1527 dbesc(DateTimeFormat::utc($birthday)),
1528 dbesc(DateTimeFormat::utc($birthday . ' + 1 day ')),
1536 * @brief Fetch the author data from head or entry items
1538 * @param object $xpath XPath object
1539 * @param object $context In which context should the data be searched
1540 * @param array $importer Record of the importer user mixed with contact of the content
1541 * @param string $element Element name from which the data is fetched
1542 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1543 * @param string $xml optional, default empty
1545 * @return array Relevant data of the author
1546 * @todo Find good type-hints for all parameter
1548 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
1551 $author["name"] = $xpath->evaluate($element."/atom:name/text()", $context)->item(0)->nodeValue;
1552 $author["link"] = $xpath->evaluate($element."/atom:uri/text()", $context)->item(0)->nodeValue;
1554 $contact_old = dba::fetch_first("SELECT `id`, `uid`, `url`, `network`, `avatar-date`, `avatar`, `name-date`, `uri-date`, `addr`,
1555 `name`, `nick`, `about`, `location`, `keywords`, `xmpp`, `bdyear`, `bd`, `hidden`, `contact-type`
1556 FROM `contact` WHERE `uid` = ? AND `nurl` = ? AND `network` != ?",
1557 $importer["importer_uid"],
1558 normalise_link($author["link"]),
1562 if (DBM::is_result($contact_old)) {
1563 $author["contact-id"] = $contact_old["id"];
1564 $author["network"] = $contact_old["network"];
1567 logger("Contact ".$author["link"]." wasn't found for user ".$importer["importer_uid"]." XML: ".$xml, LOGGER_DEBUG);
1570 $author["contact-id"] = $importer["id"];
1571 $author["network"] = $importer["network"];
1575 // Until now we aren't serving different sizes - but maybe later
1577 /// @todo check if "avatar" or "photo" would be the best field in the specification
1578 $avatars = $xpath->query($element."/atom:link[@rel='avatar']", $context);
1579 foreach ($avatars as $avatar) {
1582 foreach ($avatar->attributes as $attributes) {
1583 /// @TODO Rewrite these similar if() to one switch
1584 if ($attributes->name == "href") {
1585 $href = $attributes->textContent;
1587 if ($attributes->name == "width") {
1588 $width = $attributes->textContent;
1590 if ($attributes->name == "updated") {
1591 $author["avatar-date"] = $attributes->textContent;
1594 if (($width > 0) && ($href != "")) {
1595 $avatarlist[$width] = $href;
1598 if (count($avatarlist) > 0) {
1599 krsort($avatarlist);
1600 $author["avatar"] = current($avatarlist);
1603 if (DBM::is_result($contact_old) && !$onlyfetch) {
1604 logger("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", LOGGER_DEBUG);
1606 $poco = ["url" => $contact_old["url"]];
1608 // When was the last change to name or uri?
1609 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1610 foreach ($name_element->attributes as $attributes) {
1611 if ($attributes->name == "updated") {
1612 $poco["name-date"] = $attributes->textContent;
1616 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1617 foreach ($link_element->attributes as $attributes) {
1618 if ($attributes->name == "updated") {
1619 $poco["uri-date"] = $attributes->textContent;
1623 // Update contact data
1624 $value = $xpath->evaluate($element . "/dfrn:handle/text()", $context)->item(0)->nodeValue;
1626 $poco["addr"] = $value;
1629 $value = $xpath->evaluate($element . "/poco:displayName/text()", $context)->item(0)->nodeValue;
1631 $poco["name"] = $value;
1634 $value = $xpath->evaluate($element . "/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
1636 $poco["nick"] = $value;
1639 $value = $xpath->evaluate($element . "/poco:note/text()", $context)->item(0)->nodeValue;
1641 $poco["about"] = $value;
1644 $value = $xpath->evaluate($element . "/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
1646 $poco["location"] = $value;
1649 /// @todo Only search for elements with "poco:type" = "xmpp"
1650 $value = $xpath->evaluate($element . "/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
1652 $poco["xmpp"] = $value;
1655 /// @todo Add support for the following fields that we don't support by now in the contact table:
1656 /// - poco:utcOffset
1662 // If the "hide" element is present then the profile isn't searchable.
1663 $hide = intval($xpath->evaluate($element . "/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
1665 logger("Hidden status for contact " . $contact_old["url"] . ": " . $hide, LOGGER_DEBUG);
1667 // If the contact isn't searchable then set the contact to "hidden".
1668 // Problem: This can be manually overridden by the user.
1670 $contact_old["hidden"] = true;
1673 // Save the keywords into the contact table
1675 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1676 foreach ($tagelements as $tag) {
1677 $tags[$tag->nodeValue] = $tag->nodeValue;
1681 $poco["keywords"] = implode(", ", $tags);
1684 // "dfrn:birthday" contains the birthday converted to UTC
1685 $birthday = $xpath->evaluate($element . "/dfrn:birthday/text()", $context)->item(0)->nodeValue;
1687 if (strtotime($birthday) > time()) {
1688 $bd_timestamp = strtotime($birthday);
1690 $poco["bdyear"] = date("Y", $bd_timestamp);
1693 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1694 $value = $xpath->evaluate($element . "/poco:birthday/text()", $context)->item(0)->nodeValue;
1696 if (!in_array($value, ["", "0000-00-00", "0001-01-01"])) {
1697 $bdyear = date("Y");
1698 $value = str_replace("0000", $bdyear, $value);
1700 if (strtotime($value) < time()) {
1701 $value = str_replace($bdyear, $bdyear + 1, $value);
1702 $bdyear = $bdyear + 1;
1705 $poco["bd"] = $value;
1708 $contact = array_merge($contact_old, $poco);
1710 if ($contact_old["bdyear"] != $contact["bdyear"]) {
1711 self::birthdayEvent($contact, $birthday);
1714 // Get all field names
1716 foreach ($contact_old as $field => $data) {
1717 $fields[$field] = $data;
1720 unset($fields["id"]);
1721 unset($fields["uid"]);
1722 unset($fields["url"]);
1723 unset($fields["avatar-date"]);
1724 unset($fields["avatar"]);
1725 unset($fields["name-date"]);
1726 unset($fields["uri-date"]);
1729 // Update check for this field has to be done differently
1730 $datefields = ["name-date", "uri-date"];
1731 foreach ($datefields as $field) {
1732 if (strtotime($contact[$field]) > strtotime($contact_old[$field])) {
1733 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1738 foreach ($fields as $field => $data) {
1739 if ($contact[$field] != $contact_old[$field]) {
1740 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1746 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1749 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1750 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1751 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1752 WHERE `id` = %d AND `network` = '%s'",
1753 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
1754 dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1755 dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
1756 dbesc(DBM::date($contact["name-date"])), dbesc(DBM::date($contact["uri-date"])),
1757 intval($contact["id"]), dbesc($contact["network"])
1761 Contact::updateAvatar(
1763 $importer['importer_uid'],
1765 (strtotime($contact['avatar-date']) > strtotime($contact_old['avatar-date']) || ($author['avatar'] != $contact_old['avatar']))
1769 * The generation is a sign for the reliability of the provided data.
1770 * It is used in the socgraph.php to prevent that old contact data
1771 * that was relayed over several servers can overwrite contact
1772 * data that we received directly.
1775 $poco["generation"] = 2;
1776 $poco["photo"] = $author["avatar"];
1777 $poco["hide"] = $hide;
1778 $poco["contact-type"] = $contact["contact-type"];
1779 $gcid = GContact::update($poco);
1781 GContact::link($gcid, $importer["importer_uid"], $contact["id"]);
1788 * @brief Transforms activity objects into an XML string
1790 * @param object $xpath XPath object
1791 * @param object $activity Activity object
1792 * @param string $element element name
1794 * @return string XML string
1795 * @todo Find good type-hints for all parameter
1797 private static function transformActivity($xpath, $activity, $element)
1799 if (!is_object($activity)) {
1803 $obj_doc = new DOMDocument("1.0", "utf-8");
1804 $obj_doc->formatOutput = true;
1806 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1808 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1809 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1811 $id = $xpath->query("atom:id", $activity)->item(0);
1812 if (is_object($id)) {
1813 $obj_element->appendChild($obj_doc->importNode($id, true));
1816 $title = $xpath->query("atom:title", $activity)->item(0);
1817 if (is_object($title)) {
1818 $obj_element->appendChild($obj_doc->importNode($title, true));
1821 $links = $xpath->query("atom:link", $activity);
1822 if (is_object($links)) {
1823 foreach ($links as $link) {
1824 $obj_element->appendChild($obj_doc->importNode($link, true));
1828 $content = $xpath->query("atom:content", $activity)->item(0);
1829 if (is_object($content)) {
1830 $obj_element->appendChild($obj_doc->importNode($content, true));
1833 $obj_doc->appendChild($obj_element);
1835 $objxml = $obj_doc->saveXML($obj_element);
1837 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1838 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1843 * @brief Processes the mail elements
1845 * @param object $xpath XPath object
1846 * @param object $mail mail elements
1847 * @param array $importer Record of the importer user mixed with contact of the content
1849 * @todo Find good type-hints for all parameter
1851 private static function processMail($xpath, $mail, $importer)
1853 logger("Processing mails");
1855 /// @TODO Rewrite this to one statement
1857 $msg["uid"] = $importer["importer_uid"];
1858 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1859 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1860 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1861 $msg["contact-id"] = $importer["id"];
1862 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1863 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1864 $msg["created"] = DateTimeFormat::utc($xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue);
1865 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1866 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1868 $msg["replied"] = 0;
1870 dba::insert('mail', $msg);
1872 // send notifications.
1873 /// @TODO Arange this mess
1875 "type" => NOTIFY_MAIL,
1876 "notify_flags" => $importer["notify-flags"],
1877 "language" => $importer["language"],
1878 "to_name" => $importer["username"],
1879 "to_email" => $importer["email"],
1880 "uid" => $importer["importer_uid"],
1882 "source_name" => $msg["from-name"],
1883 "source_link" => $importer["url"],
1884 "source_photo" => $importer["thumb"],
1885 "verb" => ACTIVITY_POST,
1889 notification($notif_params);
1891 logger("Mail is processed, notification was sent.");
1895 * @brief Processes the suggestion elements
1897 * @param object $xpath XPath object
1898 * @param object $suggestion suggestion elements
1899 * @param array $importer Record of the importer user mixed with contact of the content
1901 * @todo Find good type-hints for all parameter
1903 private static function processSuggestion($xpath, $suggestion, $importer)
1907 logger("Processing suggestions");
1909 /// @TODO Rewrite this to one statement
1911 $suggest["uid"] = $importer["importer_uid"];
1912 $suggest["cid"] = $importer["id"];
1913 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1914 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1915 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1916 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1917 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1919 // Does our member already have a friend matching this description?
1922 "SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1923 dbesc($suggest["name"]),
1924 dbesc(normalise_link($suggest["url"])),
1925 intval($suggest["uid"])
1929 * The valid result means the friend we're about to send a friend
1930 * suggestion already has them in their contact, which means no further
1931 * action is required.
1933 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1935 if (DBM::is_result($r)) {
1939 // Do we already have an fcontact record for this person?
1943 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1944 dbesc($suggest["url"]),
1945 dbesc($suggest["name"]),
1946 dbesc($suggest["request"])
1948 if (DBM::is_result($r)) {
1951 // OK, we do. Do we already have an introduction for this person ?
1953 "SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1954 intval($suggest["uid"]),
1959 * The valid result means the friend we're about to send a friend
1960 * suggestion already has them in their contact, which means no further
1961 * action is required.
1963 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1965 if (DBM::is_result($r)) {
1971 "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1972 dbesc($suggest["name"]),
1973 dbesc($suggest["url"]),
1974 dbesc($suggest["photo"]),
1975 dbesc($suggest["request"])
1979 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1980 dbesc($suggest["url"]),
1981 dbesc($suggest["name"]),
1982 dbesc($suggest["request"])
1986 * If no record in fcontact is found, below INSERT statement will not
1987 * link an introduction to it.
1989 if (!DBM::is_result($r)) {
1990 // database record did not get created. Quietly give up.
1996 $hash = random_string();
1999 "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
2000 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
2001 intval($suggest["uid"]),
2003 intval($suggest["cid"]),
2004 dbesc($suggest["body"]),
2006 dbesc(DateTimeFormat::utcNow()),
2012 "type" => NOTIFY_SUGGEST,
2013 "notify_flags" => $importer["notify-flags"],
2014 "language" => $importer["language"],
2015 "to_name" => $importer["username"],
2016 "to_email" => $importer["email"],
2017 "uid" => $importer["importer_uid"],
2019 "link" => System::baseUrl()."/notifications/intros",
2020 "source_name" => $importer["name"],
2021 "source_link" => $importer["url"],
2022 "source_photo" => $importer["photo"],
2023 "verb" => ACTIVITY_REQ_FRIEND,
2031 * @brief Processes the relocation elements
2033 * @param object $xpath XPath object
2034 * @param object $relocation relocation elements
2035 * @param array $importer Record of the importer user mixed with contact of the content
2037 * @todo Find good type-hints for all parameter
2039 private static function processRelocation($xpath, $relocation, $importer)
2041 logger("Processing relocations");
2043 /// @TODO Rewrite this to one statement
2045 $relocate["uid"] = $importer["importer_uid"];
2046 $relocate["cid"] = $importer["id"];
2047 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
2048 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
2049 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
2050 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
2051 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
2052 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
2053 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
2054 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
2055 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
2056 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
2057 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
2058 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
2060 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
2061 $relocate["avatar"] = $relocate["photo"];
2064 if ($relocate["addr"] == "") {
2065 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
2070 "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
2071 intval($importer["id"]),
2072 intval($importer["importer_uid"])
2075 if (!DBM::is_result($r)) {
2076 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2082 // Update the gcontact entry
2083 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
2085 $fields = ['name' => $relocate["name"], 'photo' => $relocate["avatar"],
2086 'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2087 'addr' => $relocate["addr"], 'connect' => $relocate["addr"],
2088 'notify' => $relocate["notify"], 'server_url' => $relocate["server_url"]];
2089 dba::update('gcontact', $fields, ['nurl' => normalise_link($old["url"])]);
2091 // Update the contact table. We try to find every entry.
2092 $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
2093 'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2094 'addr' => $relocate["addr"], 'request' => $relocate["request"],
2095 'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
2096 'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
2097 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], normalise_link($old["url"])];
2098 dba::update('contact', $fields, $condition);
2100 Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
2102 logger('Contacts are updated.');
2105 // This is an extreme performance killer
2106 Item::update(['owner-link' => $relocate["url"]], ['owner-link' => $old["url"], 'uid' => $importer["importer_uid"]]);
2107 Item::update(['author-link' => $relocate["url"]], ['author-link' => $old["url"], 'uid' => $importer["importer_uid"]]);
2109 logger('Items are updated.');
2112 /// merge with current record, current contents have priority
2113 /// update record, set url-updated
2114 /// update profile photos
2115 /// schedule a scan?
2120 * @brief Updates an item
2122 * @param array $current the current item record
2123 * @param array $item the new item record
2124 * @param array $importer Record of the importer user mixed with contact of the content
2125 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2127 * @todo set proper type-hints (array?)
2129 private static function updateContent($current, $item, $importer, $entrytype)
2133 if (self::isEditedTimestampNewer($current, $item)) {
2134 // do not accept (ignore) an earlier edit than one we currently have.
2135 if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
2139 $fields = ['title' => defaults($item, 'title', ''), 'body' => defaults($item, 'body', ''),
2140 'tag' => defaults($item, 'tag', ''), 'changed' => DateTimeFormat::utcNow(),
2141 'edited' => DateTimeFormat::utc($item["edited"])];
2143 $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
2144 Item::update($fields, $condition);
2148 if ($entrytype == DFRN_REPLY_RC) {
2149 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $current["id"]);
2156 * @brief Detects the entry type of the item
2158 * @param array $importer Record of the importer user mixed with contact of the content
2159 * @param array $item the new item record
2161 * @return int Is it a toplevel entry, a comment or a relayed comment?
2162 * @todo set proper type-hints (array?)
2164 private static function getEntryType($importer, $item)
2166 if ($item["parent-uri"] != $item["uri"]) {
2169 if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
2172 logger("possible community action");
2174 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2177 // was the top-level post for this action written by somebody on this site?
2178 // Specifically, the recipient?
2180 $is_a_remote_action = false;
2183 "SELECT `item`.`parent-uri` FROM `item`
2184 WHERE `item`.`uri` = '%s'
2186 dbesc($item["parent-uri"])
2188 if (DBM::is_result($r)) {
2190 "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2191 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2192 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2193 AND `item`.`uid` = %d
2196 dbesc($r[0]["parent-uri"]),
2197 dbesc($r[0]["parent-uri"]),
2198 dbesc($r[0]["parent-uri"]),
2199 intval($importer["importer_uid"])
2201 if (DBM::is_result($r)) {
2202 $is_a_remote_action = true;
2207 * Does this have the characteristics of a community or private group action?
2208 * If it's an action to a wall post on a community/prvgroup page it's a
2209 * valid community action. Also forum_mode makes it valid for sure.
2210 * If neither, it's not.
2212 if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2213 $is_a_remote_action = false;
2214 logger("not a community action");
2217 if ($is_a_remote_action) {
2218 return DFRN_REPLY_RC;
2223 return DFRN_TOP_LEVEL;
2228 * @brief Send a "poke"
2230 * @param array $item the new item record
2231 * @param array $importer Record of the importer user mixed with contact of the content
2232 * @param int $posted_id The record number of item record that was just posted
2234 * @todo set proper type-hints (array?)
2236 private static function doPoke($item, $importer, $posted_id)
2238 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2242 $xo = XML::parseString($item["object"], false);
2244 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2245 // somebody was poked/prodded. Was it me?
2246 foreach ($xo->link as $l) {
2247 $atts = $l->attributes();
2248 switch ($atts["rel"]) {
2250 $Blink = $atts["href"];
2257 if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2258 // send a notification
2261 "type" => NOTIFY_POKE,
2262 "notify_flags" => $importer["notify-flags"],
2263 "language" => $importer["language"],
2264 "to_name" => $importer["username"],
2265 "to_email" => $importer["email"],
2266 "uid" => $importer["importer_uid"],
2268 "link" => System::baseUrl()."/display/".urlencode(Item::getGuidById($posted_id)),
2269 "source_name" => stripslashes($item["author-name"]),
2270 "source_link" => $item["author-link"],
2271 "source_photo" => ((link_compare($item["author-link"], $importer["url"]))
2272 ? $importer["thumb"] : $item["author-avatar"]),
2273 "verb" => $item["verb"],
2274 "otype" => "person",
2275 "activity" => $verb,
2276 "parent" => $item["parent"]]
2283 * @brief Processes several actions, depending on the verb
2285 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2286 * @param array $importer Record of the importer user mixed with contact of the content
2287 * @param array $item the new item record
2288 * @param bool $is_like Is the verb a "like"?
2290 * @return bool Should the processing of the entries be continued?
2291 * @todo set proper type-hints (array?)
2293 private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2295 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2297 if (($entrytype == DFRN_TOP_LEVEL)) {
2298 // The filling of the the "contact" variable is done for legcy reasons
2299 // The functions below are partly used by ostatus.php as well - where we have this variable
2300 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2302 $nickname = $contact["nick"];
2304 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2305 // This function once was responsible for DFRN and OStatus.
2306 if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2307 logger("New follower");
2308 Contact::addRelationship($importer, $contact, $item, $nickname);
2311 if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2312 logger("Lost follower");
2313 Contact::removeFollower($importer, $contact, $item);
2316 if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2317 logger("New friend request");
2318 Contact::addRelationship($importer, $contact, $item, $nickname, true);
2321 if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2322 logger("Lost sharer");
2323 Contact::removeSharer($importer, $contact, $item);
2327 if (($item["verb"] == ACTIVITY_LIKE)
2328 || ($item["verb"] == ACTIVITY_DISLIKE)
2329 || ($item["verb"] == ACTIVITY_ATTEND)
2330 || ($item["verb"] == ACTIVITY_ATTENDNO)
2331 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
2334 $item["type"] = "activity";
2335 $item["gravity"] = GRAVITY_LIKE;
2336 // only one like or dislike per person
2337 // splitted into two queries for performance issues
2339 "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `parent-uri` = '%s' AND NOT `deleted` LIMIT 1",
2340 intval($item["uid"]),
2341 dbesc($item["author-link"]),
2342 dbesc($item["verb"]),
2343 dbesc($item["parent-uri"])
2345 if (DBM::is_result($r)) {
2350 "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `thr-parent` = '%s' AND NOT `deleted` LIMIT 1",
2351 intval($item["uid"]),
2352 dbesc($item["author-link"]),
2353 dbesc($item["verb"]),
2354 dbesc($item["parent-uri"])
2356 if (DBM::is_result($r)) {
2363 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2364 $xo = XML::parseString($item["object"], false);
2365 $xt = XML::parseString($item["target"], false);
2367 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2369 "SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2371 intval($importer["importer_uid"])
2374 if (!DBM::is_result($r)) {
2375 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2379 // extract tag, if not duplicate, add to parent item
2381 if (!stristr($r[0]["tag"], trim($xo->content))) {
2382 $tag = $r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2383 Item::update(['tag' => $tag], ['id' => $r[0]["id"]]);
2393 * @brief Processes the link elements
2395 * @param object $links link elements
2396 * @param array $item the item record
2398 * @todo set proper type-hints
2400 private static function parseLinks($links, &$item)
2407 foreach ($links as $link) {
2408 foreach ($link->attributes as $attributes) {
2409 switch ($attributes->name) {
2410 case "href" : $href = $attributes->textContent; break;
2411 case "rel" : $rel = $attributes->textContent; break;
2412 case "type" : $type = $attributes->textContent; break;
2413 case "length": $length = $attributes->textContent; break;
2414 case "title" : $title = $attributes->textContent; break;
2417 if (($rel != "") && ($href != "")) {
2420 $item["plink"] = $href;
2424 if (strlen($item["attach"])) {
2425 $item["attach"] .= ",";
2428 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2436 * @brief Processes the entry elements which contain the items and comments
2438 * @param array $header Array of the header elements that always stay the same
2439 * @param object $xpath XPath object
2440 * @param object $entry entry elements
2441 * @param array $importer Record of the importer user mixed with contact of the content
2442 * @param object $xml xml
2444 * @todo Add type-hints
2446 private static function processEntry($header, $xpath, $entry, $importer, $xml)
2448 logger("Processing entries");
2452 $item["protocol"] = PROTOCOL_DFRN;
2454 $item["source"] = $xml;
2457 $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
2459 $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
2461 $current = dba::selectFirst('item',
2462 ['id', 'uid', 'edited', 'body'],
2463 ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
2465 // Is there an existing item?
2466 if (DBM::is_result($current) && !self::isEditedTimestampNewer($current, $item)) {
2467 logger("Item ".$item["uri"]." (".$item['edited'].") already existed.", LOGGER_DEBUG);
2472 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2474 $item["owner-name"] = $owner["name"];
2475 $item["owner-link"] = $owner["link"];
2476 $item["owner-avatar"] = $owner["avatar"];
2479 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2481 $item["author-name"] = $author["name"];
2482 $item["author-link"] = $author["link"];
2483 $item["author-avatar"] = $author["avatar"];
2485 $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
2487 $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2489 $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
2490 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2491 // make sure nobody is trying to sneak some html tags by us
2492 $item["body"] = notags(base64url_decode($item["body"]));
2494 $item["body"] = BBCode::limitBodySize($item["body"]);
2496 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2497 if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
2498 $base_url = get_app()->get_baseurl();
2499 $item['body'] = reltoabs($item['body'], $base_url);
2501 $item['body'] = html2bb_video($item['body']);
2503 $item['body'] = OEmbed::HTML2BBCode($item['body']);
2505 $config = HTMLPurifier_Config::createDefault();
2506 $config->set('Cache.DefinitionImpl', null);
2508 // we shouldn't need a whitelist, because the bbcode converter
2509 // will strip out any unsupported tags.
2511 $purifier = new HTMLPurifier($config);
2512 $item['body'] = $purifier->purify($item['body']);
2514 $item['body'] = @HTML::toBBCode($item['body']);
2517 /// @todo We should check for a repeated post and if we know the repeated author.
2519 // We don't need the content element since "dfrn:env" is always present
2520 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2522 $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
2524 $georsspoint = $xpath->query("georss:point", $entry);
2526 $item["coord"] = $georsspoint->item(0)->nodeValue;
2529 $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
2531 $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
2533 if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true") {
2534 $item["bookmark"] = true;
2537 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2538 if ($notice_info && ($notice_info->length > 0)) {
2539 foreach ($notice_info->item(0)->attributes as $attributes) {
2540 if ($attributes->name == "source") {
2541 $item["app"] = strip_tags($attributes->textContent);
2546 $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
2548 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
2549 $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
2550 if ($dsprsig != "") {
2551 $item["dsprsig"] = $dsprsig;
2554 $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
2556 if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "") {
2557 $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
2560 $object = $xpath->query("activity:object", $entry)->item(0);
2561 $item["object"] = self::transformActivity($xpath, $object, "object");
2563 if (trim($item["object"]) != "") {
2564 $r = XML::parseString($item["object"], false);
2565 if (isset($r->type)) {
2566 $item["object-type"] = $r->type;
2570 $target = $xpath->query("activity:target", $entry)->item(0);
2571 $item["target"] = self::transformActivity($xpath, $target, "target");
2573 $categories = $xpath->query("atom:category", $entry);
2575 foreach ($categories as $category) {
2578 foreach ($category->attributes as $attributes) {
2579 if ($attributes->name == "term") {
2580 $term = $attributes->textContent;
2583 if ($attributes->name == "scheme") {
2584 $scheme = $attributes->textContent;
2588 if (($term != "") && ($scheme != "")) {
2589 $parts = explode(":", $scheme);
2590 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2591 $termhash = array_shift($parts);
2592 $termurl = implode(":", $parts);
2594 if (strlen($item["tag"])) {
2595 $item["tag"] .= ",";
2598 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2606 $links = $xpath->query("atom:link", $entry);
2608 self::parseLinks($links, $item);
2611 $item['conversation-uri'] = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
2613 $conv = $xpath->query('ostatus:conversation', $entry);
2614 if (is_object($conv->item(0))) {
2615 foreach ($conv->item(0)->attributes as $attributes) {
2616 if ($attributes->name == "ref") {
2617 $item['conversation-uri'] = $attributes->textContent;
2619 if ($attributes->name == "href") {
2620 $item['conversation-href'] = $attributes->textContent;
2625 // Is it a reply or a top level posting?
2626 $item["parent-uri"] = $item["uri"];
2628 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2629 if (is_object($inreplyto->item(0))) {
2630 foreach ($inreplyto->item(0)->attributes as $attributes) {
2631 if ($attributes->name == "ref") {
2632 $item["parent-uri"] = $attributes->textContent;
2637 // Get the type of the item (Top level post, reply or remote reply)
2638 $entrytype = self::getEntryType($importer, $item);
2640 // Now assign the rest of the values that depend on the type of the message
2641 if (in_array($entrytype, [DFRN_REPLY, DFRN_REPLY_RC])) {
2642 if (!isset($item["object-type"])) {
2643 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2646 if ($item["contact-id"] != $owner["contact-id"]) {
2647 $item["contact-id"] = $owner["contact-id"];
2650 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2651 $item["network"] = $owner["network"];
2654 if ($item["contact-id"] != $author["contact-id"]) {
2655 $item["contact-id"] = $author["contact-id"];
2658 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2659 $item["network"] = $author["network"];
2663 if ($entrytype == DFRN_REPLY_RC) {
2664 $item["type"] = "remote-comment";
2666 } elseif ($entrytype == DFRN_TOP_LEVEL) {
2667 if (!isset($item["object-type"])) {
2668 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2672 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2673 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2674 $ev = Event::fromBBCode($item["body"]);
2675 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2676 logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2677 $ev["cid"] = $importer["id"];
2678 $ev["uid"] = $importer["importer_uid"];
2679 $ev["uri"] = $item["uri"];
2680 $ev["edited"] = $item["edited"];
2681 $ev["private"] = $item["private"];
2682 $ev["guid"] = $item["guid"];
2685 "SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2686 dbesc($item["uri"]),
2687 intval($importer["importer_uid"])
2689 if (DBM::is_result($r)) {
2690 $ev["id"] = $r[0]["id"];
2693 $event_id = Event::store($ev);
2694 logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2700 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2701 logger("Exiting because 'processVerbs' told us so", LOGGER_DEBUG);
2705 // Update content if 'updated' changes
2706 if (DBM::is_result($current)) {
2707 if (self::updateContent($current, $item, $importer, $entrytype)) {
2708 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2710 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2715 if (in_array($entrytype, [DFRN_REPLY, DFRN_REPLY_RC])) {
2716 $posted_id = Item::insert($item);
2720 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2722 if ($item['uid'] == 0) {
2723 Item::distribute($posted_id);
2726 $item["id"] = $posted_id;
2729 "SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2731 intval($importer["importer_uid"])
2733 if (DBM::is_result($r)) {
2734 $parent = $r[0]["parent"];
2735 $parent_uri = $r[0]["parent-uri"];
2738 if ($posted_id && $parent && ($entrytype == DFRN_REPLY_RC)) {
2739 logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
2740 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $posted_id);
2745 } else { // $entrytype == DFRN_TOP_LEVEL
2746 if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
2747 logger("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", LOGGER_DEBUG);
2750 if (!link_compare($item["owner-link"], $importer["url"])) {
2752 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2753 * but otherwise there's a possible data mixup on the sender's system.
2754 * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2755 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2757 logger('Correcting item owner.', LOGGER_DEBUG);
2758 $item["owner-name"] = $importer["senderName"];
2759 $item["owner-link"] = $importer["url"];
2760 $item["owner-avatar"] = $importer["thumb"];
2763 if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2764 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2768 // This is my contact on another system, but it's really me.
2769 // Turn this into a wall post.
2770 $notify = Item::isRemoteSelf($importer, $item);
2772 $posted_id = Item::insert($item, false, $notify);
2775 $posted_id = $notify;
2778 logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2780 if ($item['uid'] == 0) {
2781 Item::distribute($posted_id);
2784 if (stristr($item["verb"], ACTIVITY_POKE)) {
2785 self::doPoke($item, $importer, $posted_id);
2791 * @brief Deletes items
2793 * @param object $xpath XPath object
2794 * @param object $deletion deletion elements
2795 * @param array $importer Record of the importer user mixed with contact of the content
2797 * @todo set proper type-hints
2799 private static function processDeletion($xpath, $deletion, $importer)
2801 logger("Processing deletions");
2804 foreach ($deletion->attributes as $attributes) {
2805 if ($attributes->name == "ref") {
2806 $uri = $attributes->textContent;
2810 if (!$uri || !$importer["id"]) {
2814 $condition = ["`uri` = ? AND `uid` = ? AND NOT `file` LIKE '%[%'", $uri, $importer["importer_uid"]];
2815 $item = dba::selectFirst('item', ['id', 'parent', 'contact-id'], $condition);
2816 if (!DBM::is_result($item)) {
2817 logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", LOGGER_DEBUG);
2821 // When it is a starting post it has to belong to the person that wants to delete it
2822 if (($item['id'] == $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2823 logger("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2827 // Comments can be deleted by the thread owner or comment owner
2828 if (($item['id'] != $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2829 $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2830 if (!dba::exists('item', $condition)) {
2831 logger("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2836 $entrytype = self::getEntryType($importer, $item);
2838 if (!$item["deleted"]) {
2839 logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG);
2844 Item::deleteById($item["id"]);
2846 if ($entrytype != DFRN_TOP_LEVEL) {
2847 // if this is a relayed delete, propagate it to other recipients
2848 if ($entrytype == DFRN_REPLY_RC) {
2849 logger("Notifying followers about deletion of post " . $item["id"], LOGGER_DEBUG);
2850 Worker::add(PRIORITY_HIGH, "Notifier", "drop", $item["id"]);
2856 * @brief Imports a DFRN message
2858 * @param string $xml The DFRN message
2859 * @param array $importer Record of the importer user mixed with contact of the content
2860 * @param bool $sort_by_date Is used when feeds are polled
2861 * @return integer Import status
2862 * @todo set proper type-hints
2864 public static function import($xml, $importer, $sort_by_date = false)
2870 $doc = new DOMDocument();
2871 @$doc->loadXML($xml);
2873 $xpath = new DOMXPath($doc);
2874 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2875 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2876 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2877 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2878 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2879 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2880 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2881 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2882 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2883 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2886 $header["uid"] = $importer["importer_uid"];
2887 $header["network"] = NETWORK_DFRN;
2888 $header["type"] = "remote";
2889 $header["wall"] = 0;
2890 $header["origin"] = 0;
2891 $header["contact-id"] = $importer["id"];
2893 // Update the contact table if the data has changed
2895 // The "atom:author" is only present in feeds
2896 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2897 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2900 // Only the "dfrn:owner" in the head section contains all data
2901 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2902 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2905 logger("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2907 // is it a public forum? Private forums aren't exposed with this method
2908 $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()")->item(0)->nodeValue);
2910 // The account type is new since 3.5.1
2911 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2912 $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()")->item(0)->nodeValue);
2914 if ($accounttype != $importer["contact-type"]) {
2915 dba::update('contact', ['contact-type' => $accounttype], ['id' => $importer["id"]]);
2917 // A forum contact can either have set "forum" or "prv" - but not both
2918 if (($accounttype == ACCOUNT_TYPE_COMMUNITY) && (($forum != $importer["forum"]) || ($forum == $importer["prv"]))) {
2919 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer["id"]];
2920 dba::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2922 } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
2923 $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2924 dba::update('contact', ['forum' => $forum], $condition);
2928 // We are processing relocations even if we are ignoring a contact
2929 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2930 foreach ($relocations as $relocation) {
2931 self::processRelocation($xpath, $relocation, $importer);
2934 if (($importer["uid"] != 0) && !$importer["readonly"]) {
2935 $mails = $xpath->query("/atom:feed/dfrn:mail");
2936 foreach ($mails as $mail) {
2937 self::processMail($xpath, $mail, $importer);
2940 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2941 foreach ($suggestions as $suggestion) {
2942 self::processSuggestion($xpath, $suggestion, $importer);
2946 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2947 foreach ($deletions as $deletion) {
2948 self::processDeletion($xpath, $deletion, $importer);
2951 if (!$sort_by_date) {
2952 $entries = $xpath->query("/atom:feed/atom:entry");
2953 foreach ($entries as $entry) {
2954 self::processEntry($header, $xpath, $entry, $importer, $xml);
2958 $entries = $xpath->query("/atom:feed/atom:entry");
2959 foreach ($entries as $entry) {
2960 $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2961 $newentries[strtotime($created)] = $entry;
2964 // Now sort after the publishing date
2967 foreach ($newentries as $entry) {
2968 self::processEntry($header, $xpath, $entry, $importer, $xml);
2971 logger("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2977 * @param string $contact_nick contact nickname
2979 public static function autoRedir(App $a, $contact_nick)
2982 if (x($_REQUEST, 'redir') && intval($_REQUEST['redir'])) {
2986 if ((! $contact_nick) || ($contact_nick === $a->user['nickname'])) {
2991 // We need to find out if $contact_nick is a user on this hub, and if so, if I
2992 // am a contact of that user. However, that user may have other contacts with the
2993 // same nickname as me on other hubs or other networks. Exclude these by requiring
2994 // that the contact have a local URL. I will be the only person with my nickname at
2995 // this URL, so if a result is found, then I am a contact of the $contact_nick user.
2997 // We also have to make sure that I'm a legitimate contact--I'm not blocked or pending.
2999 $baseurl = System::baseUrl();
3000 $domain_st = strpos($baseurl, "://");
3001 if ($domain_st === false) {
3004 $baseurl = substr($baseurl, $domain_st + 3);
3005 $nurl = normalise_link($baseurl);
3007 /// @todo Why is there a query for "url" *and* "nurl"? Especially this normalising is strange.
3008 $r = q("SELECT `id` FROM `contact` WHERE `uid` = (SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1)
3009 AND `nick` = '%s' AND NOT `self` AND (`url` LIKE '%%%s%%' OR `nurl` LIKE '%%%s%%') AND NOT `blocked` AND NOT `pending` LIMIT 1",
3010 dbesc($contact_nick),
3011 dbesc($a->user['nickname']),
3015 if ((! DBM::is_result($r)) || $r[0]['id'] == remote_user()) {
3019 $r = q("SELECT * FROM contact WHERE nick = '%s'
3020 AND network = '%s' AND uid = %d AND url LIKE '%%%s%%' LIMIT 1",
3021 dbesc($contact_nick),
3022 dbesc(NETWORK_DFRN),
3023 intval(local_user()),
3026 if (! DBM::is_result($r)) {
3032 $dfrn_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
3034 if ($r[0]['duplex'] && $r[0]['issued-id']) {
3035 $orig_id = $r[0]['issued-id'];
3036 $dfrn_id = '1:' . $orig_id;
3038 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
3039 $orig_id = $r[0]['dfrn-id'];
3040 $dfrn_id = '0:' . $orig_id;
3043 // ensure that we've got a valid ID. There may be some edge cases with forums and non-duplex mode
3044 // that may have triggered some of the "went to {profile/intro} and got an RSS feed" issues
3046 if (strlen($dfrn_id) < 3) {
3050 $sec = random_string();
3052 dba::insert('profile_check', ['uid' => local_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id, 'sec' => $sec, 'expire' => time() + 45]);
3054 $url = curPageURL();
3056 logger('auto_redir: ' . $r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
3057 $dest = (($url) ? '&destination_url=' . $url : '');
3058 goaway($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
3059 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest);
3066 * @brief Returns the activity verb
3068 * @param array $item Item array
3070 * @return string activity verb
3072 private static function constructVerb(array $item)
3074 if ($item['verb']) {
3075 return $item['verb'];
3077 return ACTIVITY_POST;
3080 private static function tgroupCheck($uid, $item)
3084 // check that the message originated elsewhere and is a top-level post
3086 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['parent-uri'])) {
3090 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
3093 if (!DBM::is_result($u)) {
3097 $community_page = ($u[0]['page-flags'] == PAGE_COMMUNITY);
3098 $prvgroup = ($u[0]['page-flags'] == PAGE_PRVGROUP);
3100 $link = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
3103 * Diaspora uses their own hardwired link URL in @-tags
3104 * instead of the one we supply with webfinger
3106 $dlink = normalise_link(System::baseUrl() . '/u/' . $u[0]['nickname']);
3108 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
3110 foreach ($matches as $mtch) {
3111 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
3113 logger('mention found: ' . $mtch[2]);
3122 return $community_page || $prvgroup;
3126 * This function returns true if $update has an edited timestamp newer
3127 * than $existing, i.e. $update contains new data which should override
3128 * what's already there. If there is no timestamp yet, the update is
3129 * assumed to be newer. If the update has no timestamp, the existing
3130 * item is assumed to be up-to-date. If the timestamps are equal it
3131 * assumes the update has been seen before and should be ignored.
3134 private static function isEditedTimestampNewer($existing, $update)
3136 if (!x($existing, 'edited') || !$existing['edited']) {
3139 if (!x($update, 'edited') || !$update['edited']) {
3143 $existing_edited = DateTimeFormat::utc($existing['edited']);
3144 $update_edited = DateTimeFormat::utc($update['edited']);
3146 return (strcmp($existing_edited, $update_edited) < 0);