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;
14 use Friendica\Content\OEmbed;
15 use Friendica\Content\Text\BBCode;
16 use Friendica\Content\Text\HTML;
17 use Friendica\Core\Addon;
18 use Friendica\Core\Config;
19 use Friendica\Core\L10n;
20 use Friendica\Core\Logger;
21 use Friendica\Core\Protocol;
22 use Friendica\Core\System;
23 use Friendica\Database\DBA;
24 use Friendica\Model\Contact;
25 use Friendica\Model\Conversation;
26 use Friendica\Model\Event;
27 use Friendica\Model\GContact;
28 use Friendica\Model\Item;
29 use Friendica\Model\PermissionSet;
30 use Friendica\Model\Profile;
31 use Friendica\Model\User;
32 use Friendica\Object\Image;
33 use Friendica\Util\Crypto;
34 use Friendica\Util\DateTimeFormat;
35 use Friendica\Util\Network;
36 use Friendica\Util\Strings;
37 use Friendica\Util\XML;
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 TOP_LEVEL = 0; // Top level posting
54 const REPLY = 1; // Regular reply that is stored locally
55 const REPLY_RC = 2; // Reply that will be relayed
58 * @brief Generates an array of contact and user for DFRN imports
60 * This array contains not only the receiver but also the sender of the message.
62 * @param integer $cid Contact id
63 * @param integer $uid User id
65 * @return array importer
67 public static function getImporter($cid, $uid = 0)
69 $condition = ['id' => $cid, 'blocked' => false, 'pending' => false];
70 $contact = DBA::selectFirst('contact', [], $condition);
71 if (!DBA::isResult($contact)) {
75 $contact['cpubkey'] = $contact['pubkey'];
76 $contact['cprvkey'] = $contact['prvkey'];
77 $contact['senderName'] = $contact['name'];
80 $condition = ['uid' => $uid, 'account_expired' => false, 'account_removed' => false];
81 $user = DBA::selectFirst('user', [], $condition);
82 if (!DBA::isResult($user)) {
86 $user['importer_uid'] = $user['uid'];
87 $user['uprvkey'] = $user['prvkey'];
89 $user = ['importer_uid' => 0, 'uprvkey' => '', 'timezone' => 'UTC',
90 'nickname' => '', 'sprvkey' => '', 'spubkey' => '',
91 'page-flags' => 0, 'account-type' => 0, 'prvnets' => 0];
94 return array_merge($contact, $user);
98 * @brief Generates the atom entries for delivery.php
100 * This function is used whenever content is transmitted via DFRN.
102 * @param array $items Item elements
103 * @param array $owner Owner record
105 * @return string DFRN entries
106 * @todo Find proper type-hints
108 public static function entries($items, $owner)
110 $doc = new DOMDocument('1.0', 'utf-8');
111 $doc->formatOutput = true;
113 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
115 if (! count($items)) {
116 return trim($doc->saveXML());
119 foreach ($items as $item) {
120 // These values aren't sent when sending from the queue.
121 /// @todo Check if we can set these values from the queue or if they are needed at all.
122 $item["entry:comment-allow"] = defaults($item, "entry:comment-allow", true);
123 $item["entry:cid"] = defaults($item, "entry:cid", 0);
125 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
126 $root->appendChild($entry);
129 return trim($doc->saveXML());
133 * @brief Generate an atom feed for the given user
135 * This function is called when another server is pulling data from the user feed.
137 * @param string $dfrn_id DFRN ID from the requesting party
138 * @param string $owner_nick Owner nick name
139 * @param string $last_update Date of the last update
140 * @param int $direction Can be -1, 0 or 1.
141 * @param boolean $onlyheader Output only the header without content? (Default is "no")
143 * @return string DFRN feed entries
145 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false)
149 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
150 $public_feed = (($dfrn_id) ? false : true);
151 $starred = false; // not yet implemented, possible security issues
154 if ($public_feed && $a->argc > 2) {
155 for ($x = 2; $x < $a->argc; $x++) {
156 if ($a->argv[$x] == 'converse') {
159 if ($a->argv[$x] == 'starred') {
162 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
163 $category = $a->argv[$x+1];
168 // default permissions - anonymous user
170 $sql_extra = " AND NOT `item`.`private` ";
173 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
174 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
175 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
176 DBA::escape($owner_nick)
179 if (! DBA::isResult($r)) {
180 Logger::log(sprintf('No contact found for nickname=%d', $owner_nick), Logger::WARNING);
185 $owner_id = $owner['uid'];
186 $owner_nick = $owner['nickname'];
188 $sql_post_table = "";
190 if (! $public_feed) {
192 switch ($direction) {
194 $sql_extra = sprintf(" AND `issued-id` = '%s' ", DBA::escape($dfrn_id));
198 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
199 $my_id = '1:' . $dfrn_id;
202 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
203 $my_id = '0:' . $dfrn_id;
211 "SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
215 if (! DBA::isResult($r)) {
216 Logger::log(sprintf('No contact found for uid=%d', $owner_id), Logger::WARNING);
222 $set = PermissionSet::get($owner_id, $contact['id']);
225 $sql_extra = " AND `item`.`psid` IN (" . implode(',', $set) .")";
227 $sql_extra = " AND NOT `item`.`private`";
237 if (! strlen($last_update)) {
238 $last_update = 'now -30 days';
241 if (isset($category)) {
242 $sql_post_table = sprintf(
243 "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` ",
244 DBA::escape(Strings::protectSprintf($category)),
245 intval(TERM_OBJ_POST),
246 intval(TERM_CATEGORY),
249 //$sql_extra .= FileTag::fileQuery('item',$category,'category');
252 if ($public_feed && ! $converse) {
253 $sql_extra .= " AND `contact`.`self` = 1 ";
256 $check_date = DateTimeFormat::utc($last_update);
260 FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
261 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
262 WHERE `item`.`uid` = %d AND `item`.`wall` AND `item`.`changed` > '%s'
264 ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
266 DBA::escape($check_date),
271 foreach ($r as $item) {
272 $ids[] = $item['id'];
276 $ret = Item::select(Item::DELIVER_FIELDLIST, ['id' => $ids]);
277 $items = Item::inArray($ret);
283 * Will check further below if this actually returned results.
284 * We will provide an empty feed if that is the case.
287 $doc = new DOMDocument('1.0', 'utf-8');
288 $doc->formatOutput = true;
290 $alternatelink = $owner['url'];
292 if (isset($category)) {
293 $alternatelink .= "/category/".$category;
297 $author = "dfrn:owner";
302 $root = self::addHeader($doc, $owner, $author, $alternatelink, true);
304 /// @TODO This hook can't work anymore
305 // Addon::callHooks('atom_feed', $atom);
307 if (!DBA::isResult($items) || $onlyheader) {
308 $atom = trim($doc->saveXML());
310 Addon::callHooks('atom_feed_end', $atom);
315 foreach ($items as $item) {
316 // prevent private email from leaking.
317 if ($item['network'] == Protocol::MAIL) {
321 // public feeds get html, our own nodes use bbcode
325 // catch any email that's in a public conversation and make sure it doesn't leak
326 if ($item['private']) {
333 $entry = self::entry($doc, $type, $item, $owner, true);
334 $root->appendChild($entry);
337 $atom = trim($doc->saveXML());
339 Addon::callHooks('atom_feed_end', $atom);
345 * @brief Generate an atom entry for a given item id
347 * @param int $item_id The item id
348 * @param boolean $conversation Show the conversation. If false show the single post.
350 * @return string DFRN feed entry
352 public static function itemFeed($item_id, $conversation = false)
355 $condition = ['parent' => $item_id];
357 $condition = ['id' => $item_id];
360 $ret = Item::select(Item::DELIVER_FIELDLIST, $condition);
361 $items = Item::inArray($ret);
362 if (!DBA::isResult($items)) {
368 if ($item['uid'] != 0) {
369 $owner = User::getOwnerDataById($item['uid']);
374 $owner = ['uid' => 0, 'nick' => 'feed-item'];
377 $doc = new DOMDocument('1.0', 'utf-8');
378 $doc->formatOutput = true;
382 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
383 $doc->appendChild($root);
385 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
386 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
387 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
388 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
389 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
390 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
391 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
392 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
393 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
395 //$root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
397 foreach ($items as $item) {
398 $entry = self::entry($doc, $type, $item, $owner, true, 0);
399 $root->appendChild($entry);
402 $root = self::entry($doc, $type, $item, $owner, true, 0, true);
405 $atom = trim($doc->saveXML());
410 * @brief Create XML text for DFRN mails
412 * @param array $item message elements
413 * @param array $owner Owner record
415 * @return string DFRN mail
416 * @todo Find proper type-hints
418 public static function mail($item, $owner)
420 $doc = new DOMDocument('1.0', 'utf-8');
421 $doc->formatOutput = true;
423 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
425 $mail = $doc->createElement("dfrn:mail");
426 $sender = $doc->createElement("dfrn:sender");
428 XML::addElement($doc, $sender, "dfrn:name", $owner['name']);
429 XML::addElement($doc, $sender, "dfrn:uri", $owner['url']);
430 XML::addElement($doc, $sender, "dfrn:avatar", $owner['thumb']);
432 $mail->appendChild($sender);
434 XML::addElement($doc, $mail, "dfrn:id", $item['uri']);
435 XML::addElement($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
436 XML::addElement($doc, $mail, "dfrn:sentdate", DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
437 XML::addElement($doc, $mail, "dfrn:subject", $item['title']);
438 XML::addElement($doc, $mail, "dfrn:content", $item['body']);
440 $root->appendChild($mail);
442 return trim($doc->saveXML());
446 * @brief Create XML text for DFRN friend suggestions
448 * @param array $item suggestion elements
449 * @param array $owner Owner record
451 * @return string DFRN suggestions
452 * @todo Find proper type-hints
454 public static function fsuggest($item, $owner)
456 $doc = new DOMDocument('1.0', 'utf-8');
457 $doc->formatOutput = true;
459 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
461 $suggest = $doc->createElement("dfrn:suggest");
463 XML::addElement($doc, $suggest, "dfrn:url", $item['url']);
464 XML::addElement($doc, $suggest, "dfrn:name", $item['name']);
465 XML::addElement($doc, $suggest, "dfrn:photo", $item['photo']);
466 XML::addElement($doc, $suggest, "dfrn:request", $item['request']);
467 XML::addElement($doc, $suggest, "dfrn:note", $item['note']);
469 $root->appendChild($suggest);
471 return trim($doc->saveXML());
475 * @brief Create XML text for DFRN relocations
477 * @param array $owner Owner record
478 * @param int $uid User ID
480 * @return string DFRN relocations
481 * @todo Find proper type-hints
483 public static function relocate($owner, $uid)
486 /* get site pubkey. this could be a new installation with no site keys*/
487 $pubkey = Config::get('system', 'site_pubkey');
489 $res = Crypto::newKeypair(1024);
490 Config::set('system', 'site_prvkey', $res['prvkey']);
491 Config::set('system', 'site_pubkey', $res['pubkey']);
495 "SELECT `resource-id` , `scale`, type FROM `photo`
496 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;",
500 $ext = Image::supportedTypes();
502 foreach ($rp as $p) {
503 $photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
507 $doc = new DOMDocument('1.0', 'utf-8');
508 $doc->formatOutput = true;
510 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
512 $relocate = $doc->createElement("dfrn:relocate");
514 XML::addElement($doc, $relocate, "dfrn:url", $owner['url']);
515 XML::addElement($doc, $relocate, "dfrn:name", $owner['name']);
516 XML::addElement($doc, $relocate, "dfrn:addr", $owner['addr']);
517 XML::addElement($doc, $relocate, "dfrn:avatar", $owner['avatar']);
518 XML::addElement($doc, $relocate, "dfrn:photo", $photos[4]);
519 XML::addElement($doc, $relocate, "dfrn:thumb", $photos[5]);
520 XML::addElement($doc, $relocate, "dfrn:micro", $photos[6]);
521 XML::addElement($doc, $relocate, "dfrn:request", $owner['request']);
522 XML::addElement($doc, $relocate, "dfrn:confirm", $owner['confirm']);
523 XML::addElement($doc, $relocate, "dfrn:notify", $owner['notify']);
524 XML::addElement($doc, $relocate, "dfrn:poll", $owner['poll']);
525 XML::addElement($doc, $relocate, "dfrn:sitepubkey", Config::get('system', 'site_pubkey'));
527 $root->appendChild($relocate);
529 return trim($doc->saveXML());
533 * @brief Adds the header elements for the DFRN protocol
535 * @param object $doc XML document
536 * @param array $owner Owner record
537 * @param string $authorelement Element name for the author
538 * @param string $alternatelink link to profile or category
539 * @param bool $public Is it a header for public posts?
541 * @return object XML root object
542 * @todo Find proper type-hints
544 private static function addHeader($doc, $owner, $authorelement, $alternatelink = "", $public = false)
547 if ($alternatelink == "") {
548 $alternatelink = $owner['url'];
551 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
552 $doc->appendChild($root);
554 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
555 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
556 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
557 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
558 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
559 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
560 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
561 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
562 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
564 XML::addElement($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
565 XML::addElement($doc, $root, "title", $owner["name"]);
567 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION];
568 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
570 $attributes = ["rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/"];
571 XML::addElement($doc, $root, "link", "", $attributes);
573 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $alternatelink];
574 XML::addElement($doc, $root, "link", "", $attributes);
578 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
579 OStatus::hublinks($doc, $root, $owner["nick"]);
581 $attributes = ["rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
582 XML::addElement($doc, $root, "link", "", $attributes);
584 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
585 XML::addElement($doc, $root, "link", "", $attributes);
587 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
588 XML::addElement($doc, $root, "link", "", $attributes);
591 // For backward compatibility we keep this element
592 if ($owner['page-flags'] == Contact::PAGE_COMMUNITY) {
593 XML::addElement($doc, $root, "dfrn:community", 1);
596 // The former element is replaced by this one
597 XML::addElement($doc, $root, "dfrn:account_type", $owner["account-type"]);
599 /// @todo We need a way to transmit the different page flags like "Contact::PAGE_PRVGROUP"
601 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
603 $author = self::addAuthor($doc, $owner, $authorelement, $public);
604 $root->appendChild($author);
610 * @brief Adds the author element in the header for the DFRN protocol
612 * @param object $doc XML document
613 * @param array $owner Owner record
614 * @param string $authorelement Element name for the author
615 * @param boolean $public boolean
617 * @return object XML author object
618 * @todo Find proper type-hints
620 private static function addAuthor($doc, $owner, $authorelement, $public)
622 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
624 "SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
625 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
626 intval($owner['uid'])
628 if (DBA::isResult($r)) {
634 $author = $doc->createElement($authorelement);
636 $namdate = DateTimeFormat::utc($owner['name-date'].'+00:00', DateTimeFormat::ATOM);
637 $uridate = DateTimeFormat::utc($owner['uri-date'].'+00:00', DateTimeFormat::ATOM);
638 $picdate = DateTimeFormat::utc($owner['avatar-date'].'+00:00', DateTimeFormat::ATOM);
642 if (!$public || !$hidewall) {
643 $attributes = ["dfrn:updated" => $namdate];
646 XML::addElement($doc, $author, "name", $owner["name"], $attributes);
647 XML::addElement($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
648 XML::addElement($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
650 $attributes = ["rel" => "photo", "type" => "image/jpeg",
651 "media:width" => 300, "media:height" => 300, "href" => $owner['photo']];
653 if (!$public || !$hidewall) {
654 $attributes["dfrn:updated"] = $picdate;
657 XML::addElement($doc, $author, "link", "", $attributes);
659 $attributes["rel"] = "avatar";
660 XML::addElement($doc, $author, "link", "", $attributes);
663 XML::addElement($doc, $author, "dfrn:hide", "true");
666 // The following fields will only be generated if the data isn't meant for a public feed
671 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
674 XML::addElement($doc, $author, "dfrn:birthday", $birthday);
677 // Only show contact details when we are allowed to
679 "SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
680 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
681 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
683 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
684 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
685 intval($owner['uid'])
687 if (DBA::isResult($r)) {
690 XML::addElement($doc, $author, "poco:displayName", $profile["name"]);
691 XML::addElement($doc, $author, "poco:updated", $namdate);
693 if (trim($profile["dob"]) > '0001-01-01') {
694 XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
697 XML::addElement($doc, $author, "poco:note", $profile["about"]);
698 XML::addElement($doc, $author, "poco:preferredUsername", $profile["nickname"]);
700 $savetz = date_default_timezone_get();
701 date_default_timezone_set($profile["timezone"]);
702 XML::addElement($doc, $author, "poco:utcOffset", date("P"));
703 date_default_timezone_set($savetz);
705 if (trim($profile["homepage"]) != "") {
706 $urls = $doc->createElement("poco:urls");
707 XML::addElement($doc, $urls, "poco:type", "homepage");
708 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
709 XML::addElement($doc, $urls, "poco:primary", "true");
710 $author->appendChild($urls);
713 if (trim($profile["pub_keywords"]) != "") {
714 $keywords = explode(",", $profile["pub_keywords"]);
716 foreach ($keywords as $keyword) {
717 XML::addElement($doc, $author, "poco:tags", trim($keyword));
721 if (trim($profile["xmpp"]) != "") {
722 $ims = $doc->createElement("poco:ims");
723 XML::addElement($doc, $ims, "poco:type", "xmpp");
724 XML::addElement($doc, $ims, "poco:value", $profile["xmpp"]);
725 XML::addElement($doc, $ims, "poco:primary", "true");
726 $author->appendChild($ims);
729 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
730 $element = $doc->createElement("poco:address");
732 XML::addElement($doc, $element, "poco:formatted", Profile::formatLocation($profile));
734 if (trim($profile["locality"]) != "") {
735 XML::addElement($doc, $element, "poco:locality", $profile["locality"]);
738 if (trim($profile["region"]) != "") {
739 XML::addElement($doc, $element, "poco:region", $profile["region"]);
742 if (trim($profile["country-name"]) != "") {
743 XML::addElement($doc, $element, "poco:country", $profile["country-name"]);
746 $author->appendChild($element);
754 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
756 * @param object $doc XML document
757 * @param string $element Element name for the author
758 * @param string $contact_url Link of the contact
759 * @param array $item Item elements
761 * @return object XML author object
762 * @todo Find proper type-hints
764 private static function addEntryAuthor($doc, $element, $contact_url, $item)
766 $contact = Contact::getDetailsByURL($contact_url, $item["uid"]);
768 $author = $doc->createElement($element);
769 XML::addElement($doc, $author, "name", $contact["name"]);
770 XML::addElement($doc, $author, "uri", $contact["url"]);
771 XML::addElement($doc, $author, "dfrn:handle", $contact["addr"]);
774 /// - Check real image type and image size
775 /// - Check which of these boths elements we should use
778 "type" => "image/jpeg",
780 "media:height" => 80,
781 "href" => $contact["photo"]];
782 XML::addElement($doc, $author, "link", "", $attributes);
786 "type" => "image/jpeg",
788 "media:height" => 80,
789 "href" => $contact["photo"]];
790 XML::addElement($doc, $author, "link", "", $attributes);
796 * @brief Adds the activity elements
798 * @param object $doc XML document
799 * @param string $element Element name for the activity
800 * @param string $activity activity value
802 * @return object XML activity object
803 * @todo Find proper type-hints
805 private static function createActivity($doc, $element, $activity)
808 $entry = $doc->createElement($element);
810 $r = XML::parseString($activity, false);
816 XML::addElement($doc, $entry, "activity:object-type", $r->type);
820 XML::addElement($doc, $entry, "id", $r->id);
824 XML::addElement($doc, $entry, "title", $r->title);
828 if (substr($r->link, 0, 1) == '<') {
829 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
830 $r->link = str_replace('&', '&', $r->link);
833 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
835 // XML does need a single element as root element so we add a dummy element here
836 $data = XML::parseString("<dummy>" . $r->link . "</dummy>", false);
837 if (is_object($data)) {
838 foreach ($data->link as $link) {
840 foreach ($link->attributes() as $parameter => $value) {
841 $attributes[$parameter] = $value;
843 XML::addElement($doc, $entry, "link", "", $attributes);
847 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
848 XML::addElement($doc, $entry, "link", "", $attributes);
852 XML::addElement($doc, $entry, "content", BBCode::convert($r->content), ["type" => "html"]);
862 * @brief Adds the elements for attachments
864 * @param object $doc XML document
865 * @param object $root XML root
866 * @param array $item Item element
868 * @return object XML attachment object
869 * @todo Find proper type-hints
871 private static function getAttachment($doc, $root, $item)
873 $arr = explode('[/attach],', $item['attach']);
875 foreach ($arr as $r) {
877 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
879 $attributes = ["rel" => "enclosure",
880 "href" => $matches[1],
881 "type" => $matches[3]];
883 if (intval($matches[2])) {
884 $attributes["length"] = intval($matches[2]);
887 if (trim($matches[4]) != "") {
888 $attributes["title"] = trim($matches[4]);
891 XML::addElement($doc, $root, "link", "", $attributes);
898 * @brief Adds the "entry" elements for the DFRN protocol
900 * @param object $doc XML document
901 * @param string $type "text" or "html"
902 * @param array $item Item element
903 * @param array $owner Owner record
904 * @param bool $comment Trigger the sending of the "comment" element
905 * @param int $cid Contact ID of the recipient
906 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
908 * @return object XML entry object
909 * @todo Find proper type-hints
911 private static function entry($doc, $type, array $item, array $owner, $comment = false, $cid = 0, $single = false)
915 if (!$item['parent']) {
919 if ($item['deleted']) {
920 $attributes = ["ref" => $item['uri'], "when" => DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM)];
921 return XML::createElement($doc, "at:deleted-entry", "", $attributes);
925 $entry = $doc->createElement("entry");
927 $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry');
928 $doc->appendChild($entry);
930 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
931 $entry->setAttribute("xmlns:at", NAMESPACE_TOMB);
932 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
933 $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
934 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
935 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
936 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
937 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
938 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
941 if ($item['private']) {
942 $body = Item::fixPrivatePhotos($item['body'], $owner['uid'], $item, $cid);
944 $body = $item['body'];
947 // Remove the abstract element. It is only locally important.
948 $body = BBCode::stripAbstract($body);
951 if ($type == 'html') {
954 if ($item['title'] != "") {
955 $htmlbody = "[b]" . $item['title'] . "[/b]\n\n" . $htmlbody;
958 $htmlbody = BBCode::convert($htmlbody, false, 7);
961 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
962 $entry->appendChild($author);
964 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
965 $entry->appendChild($dfrnowner);
967 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
968 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
969 $parent = Item::selectFirst(['guid', 'plink'], ['uri' => $parent_item, 'uid' => $item['uid']]);
970 $attributes = ["ref" => $parent_item, "type" => "text/html",
971 "href" => $parent['plink'],
972 "dfrn:diaspora_guid" => $parent['guid']];
973 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
976 // Add conversation data. This is used for OStatus
977 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
978 $conversation_uri = $conversation_href;
980 if (isset($parent_item)) {
981 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $item['parent-uri']]);
982 if (DBA::isResult($conversation)) {
983 if ($conversation['conversation-uri'] != '') {
984 $conversation_uri = $conversation['conversation-uri'];
986 if ($conversation['conversation-href'] != '') {
987 $conversation_href = $conversation['conversation-href'];
993 "href" => $conversation_href,
994 "ref" => $conversation_uri];
996 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
998 XML::addElement($doc, $entry, "id", $item["uri"]);
999 XML::addElement($doc, $entry, "title", $item["title"]);
1001 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"] . "+00:00", DateTimeFormat::ATOM));
1002 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"] . "+00:00", DateTimeFormat::ATOM));
1004 // "dfrn:env" is used to read the content
1005 XML::addElement($doc, $entry, "dfrn:env", Strings::base64UrlEncode($body, true));
1007 // The "content" field is not read by the receiver. We could remove it when the type is "text"
1008 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
1009 XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
1011 // We save this value in "plink". Maybe we should read it from there as well?
1017 ["rel" => "alternate", "type" => "text/html",
1018 "href" => System::baseUrl() . "/display/" . $item["guid"]]
1021 // "comment-allow" is some old fashioned stuff for old Friendica versions.
1022 // It is included in the rewritten code for completeness
1024 XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
1027 if ($item['location']) {
1028 XML::addElement($doc, $entry, "dfrn:location", $item['location']);
1031 if ($item['coord']) {
1032 XML::addElement($doc, $entry, "georss:point", $item['coord']);
1035 if ($item['private']) {
1036 XML::addElement($doc, $entry, "dfrn:private", ($item['private'] ? $item['private'] : 1));
1039 if ($item['extid']) {
1040 XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
1043 if ($item['post-type'] == Item::PT_PAGE) {
1044 XML::addElement($doc, $entry, "dfrn:bookmark", "true");
1048 XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
1051 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
1053 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
1054 // It is needed for relayed comments to Diaspora.
1055 if ($item['signed_text']) {
1056 $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer']]));
1057 XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
1060 XML::addElement($doc, $entry, "activity:verb", self::constructVerb($item));
1062 if ($item['object-type'] != "") {
1063 XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
1064 } elseif ($item['id'] == $item['parent']) {
1065 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1067 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
1070 $actobj = self::createActivity($doc, "activity:object", $item['object']);
1072 $entry->appendChild($actobj);
1075 $actarg = self::createActivity($doc, "activity:target", $item['target']);
1077 $entry->appendChild($actarg);
1080 $tags = Item::getFeedTags($item);
1082 /// @TODO Combine this with similar below if() block?
1084 foreach ($tags as $t) {
1085 if (($type != 'html') || ($t[0] != "@")) {
1086 XML::addElement($doc, $entry, "category", "", ["scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]]);
1092 foreach ($tags as $t) {
1094 $mentioned[$t[1]] = $t[1];
1099 foreach ($mentioned as $mention) {
1100 $condition = ['uid' => $owner["uid"], 'nurl' => Strings::normaliseLink($mention)];
1101 $contact = DBA::selectFirst('contact', ['forum', 'prv'], $condition);
1103 if (DBA::isResult($contact) && ($contact["forum"] || $contact["prv"])) {
1109 ["rel" => "mentioned",
1110 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1119 ["rel" => "mentioned",
1120 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1126 self::getAttachment($doc, $entry, $item);
1132 * @brief encrypts data via AES
1134 * @param string $data The data that is to be encrypted
1135 * @param string $key The AES key
1137 * @return string encrypted data
1139 private static function aesEncrypt($data, $key)
1141 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1145 * @brief decrypts data via AES
1147 * @param string $encrypted The encrypted data
1148 * @param string $key The AES key
1150 * @return string decrypted data
1152 public static function aesDecrypt($encrypted, $key)
1154 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1158 * @brief Delivers the atom content to the contacts
1160 * @param array $owner Owner record
1161 * @param array $contact Contact record of the receiver
1162 * @param string $atom Content that will be transmitted
1163 * @param bool $dissolve (to be documented)
1165 * @return int Deliver status. Negative values mean an error.
1166 * @todo Add array type-hint for $owner, $contact
1168 public static function deliver($owner, $contact, $atom, $dissolve = false, $legacy_transport = false)
1172 // At first try the Diaspora transport layer
1173 if (!$dissolve && !$legacy_transport) {
1174 $curlResult = self::transmit($owner, $contact, $atom);
1175 if ($curlResult >= 200) {
1176 Logger::log('Delivery via Diaspora transport layer was successful with status ' . $curlResult);
1181 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1183 if ($contact['duplex'] && $contact['dfrn-id']) {
1184 $idtosend = '0:' . $orig_id;
1186 if ($contact['duplex'] && $contact['issued-id']) {
1187 $idtosend = '1:' . $orig_id;
1190 $rino = Config::get('system', 'rino_encrypt');
1191 $rino = intval($rino);
1193 Logger::log("Local rino version: ". $rino, Logger::DEBUG);
1195 $ssl_val = intval(Config::get('system', 'ssl_policy'));
1199 case SSL_POLICY_FULL:
1200 $ssl_policy = 'full';
1202 case SSL_POLICY_SELFSIGN:
1203 $ssl_policy = 'self';
1205 case SSL_POLICY_NONE:
1207 $ssl_policy = 'none';
1211 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1213 Logger::log('dfrn_deliver: ' . $url);
1215 $curlResult = Network::curl($url);
1217 if ($curlResult->isTimeout()) {
1218 Contact::markForArchival($contact);
1219 return -2; // timed out
1222 $xml = $curlResult->getBody();
1224 $curl_stat = $curlResult->getReturnCode();
1225 if (empty($curl_stat)) {
1226 Contact::markForArchival($contact);
1227 return -3; // timed out
1230 Logger::log('dfrn_deliver: ' . $xml, Logger::DATA);
1233 Contact::markForArchival($contact);
1237 if (strpos($xml, '<?xml') === false) {
1238 Logger::log('dfrn_deliver: no valid XML returned');
1239 Logger::log('dfrn_deliver: returned XML: ' . $xml, Logger::DATA);
1240 Contact::markForArchival($contact);
1244 $res = XML::parseString($xml);
1246 if (!is_object($res) || (intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
1247 Contact::markForArchival($contact);
1249 if (empty($res->status)) {
1252 $status = $res->status;
1259 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1260 $challenge = hex2bin((string) $res->challenge);
1261 $perm = (($res->perm) ? $res->perm : null);
1262 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1263 $rino_remote_version = intval($res->rino);
1264 $page = (($owner['page-flags'] == Contact::PAGE_COMMUNITY) ? 1 : 0);
1266 Logger::log("Remote rino version: ".$rino_remote_version." for ".$contact["url"], Logger::DEBUG);
1268 if ($owner['page-flags'] == Contact::PAGE_PRVGROUP) {
1272 $final_dfrn_id = '';
1275 if ((($perm == 'rw') && !intval($contact['writable']))
1276 || (($perm == 'r') && intval($contact['writable']))
1278 DBA::update('contact', ['writable' => ($perm == 'rw')], ['id' => $contact['id']]);
1280 $contact['writable'] = (string) 1 - intval($contact['writable']);
1284 if (($contact['duplex'] && strlen($contact['pubkey']))
1285 || ($owner['page-flags'] == Contact::PAGE_COMMUNITY && strlen($contact['pubkey']))
1286 || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
1288 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
1289 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
1291 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
1292 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
1295 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1297 if (strpos($final_dfrn_id, ':') == 1) {
1298 $final_dfrn_id = substr($final_dfrn_id, 2);
1301 if ($final_dfrn_id != $orig_id) {
1302 Logger::log('dfrn_deliver: wrong dfrn_id.');
1303 // did not decode properly - cannot trust this site
1304 Contact::markForArchival($contact);
1308 $postvars['dfrn_id'] = $idtosend;
1309 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1311 $postvars['dissolve'] = '1';
1314 if ((($contact['rel']) && ($contact['rel'] != Contact::SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == Contact::PAGE_COMMUNITY)) {
1315 $postvars['data'] = $atom;
1316 $postvars['perm'] = 'rw';
1318 $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
1319 $postvars['perm'] = 'r';
1322 $postvars['ssl_policy'] = $ssl_policy;
1325 $postvars['page'] = $page;
1329 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1330 Logger::log('rino version: '. $rino_remote_version);
1332 switch ($rino_remote_version) {
1334 $key = openssl_random_pseudo_bytes(16);
1335 $data = self::aesEncrypt($postvars['data'], $key);
1339 Logger::log("rino: invalid requested version '$rino_remote_version'");
1340 Contact::markForArchival($contact);
1344 $postvars['rino'] = $rino_remote_version;
1345 $postvars['data'] = bin2hex($data);
1347 if ($dfrn_version >= 2.1) {
1348 if (($contact['duplex'] && strlen($contact['pubkey']))
1349 || ($owner['page-flags'] == Contact::PAGE_COMMUNITY && strlen($contact['pubkey']))
1350 || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
1352 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1354 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1357 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == Contact::PAGE_COMMUNITY)) {
1358 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1360 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1364 Logger::log('md5 rawkey ' . md5($postvars['key']));
1366 $postvars['key'] = bin2hex($postvars['key']);
1370 Logger::log('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), Logger::DATA);
1372 $postResult = Network::post($contact['notify'], $postvars);
1374 $xml = $postResult->getBody();
1376 Logger::log('dfrn_deliver: ' . "RECEIVED: " . $xml, Logger::DATA);
1378 $curl_stat = $postResult->getReturnCode();
1379 if (empty($curl_stat) || empty($xml)) {
1380 Contact::markForArchival($contact);
1381 return -9; // timed out
1384 if (($curl_stat == 503) && stristr($postResult->getHeader(), 'retry-after')) {
1385 Contact::markForArchival($contact);
1389 if (strpos($xml, '<?xml') === false) {
1390 Logger::log('dfrn_deliver: phase 2: no valid XML returned');
1391 Logger::log('dfrn_deliver: phase 2: returned XML: ' . $xml, Logger::DATA);
1392 Contact::markForArchival($contact);
1396 $res = XML::parseString($xml);
1398 if (!isset($res->status)) {
1399 Contact::markForArchival($contact);
1403 // Possibly old servers had returned an empty value when everything was okay
1404 if (empty($res->status)) {
1408 if (!empty($res->message)) {
1409 Logger::log('Delivery returned status '.$res->status.' - '.$res->message, Logger::DEBUG);
1412 if (($res->status >= 200) && ($res->status <= 299)) {
1413 Contact::unmarkForArchival($contact);
1416 return intval($res->status);
1420 * @brief Transmits atom content to the contacts via the Diaspora transport layer
1422 * @param array $owner Owner record
1423 * @param array $contact Contact record of the receiver
1424 * @param string $atom Content that will be transmitted
1426 * @return int Deliver status. Negative values mean an error.
1428 public static function transmit($owner, $contact, $atom, $public_batch = false)
1432 if (!$public_batch) {
1433 if (empty($contact['addr'])) {
1434 Logger::log('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.');
1435 if (Contact::updateFromProbe($contact['id'])) {
1436 $new_contact = DBA::selectFirst('contact', ['addr'], ['id' => $contact['id']]);
1437 $contact['addr'] = $new_contact['addr'];
1440 if (empty($contact['addr'])) {
1441 Logger::log('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
1442 Contact::markForArchival($contact);
1447 $fcontact = Diaspora::personByHandle($contact['addr']);
1448 if (empty($fcontact)) {
1449 Logger::log('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
1450 Contact::markForArchival($contact);
1453 $pubkey = $fcontact['pubkey'];
1458 $envelope = Diaspora::buildMessage($atom, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
1460 // Create the endpoint for public posts. This is some WIP and should later be added to the probing
1461 if ($public_batch && empty($contact["batch"])) {
1462 $parts = parse_url($contact["notify"]);
1463 $path_parts = explode('/', $parts['path']);
1464 array_pop($path_parts);
1465 $parts['path'] = implode('/', $path_parts);
1466 $contact["batch"] = Network::unparseURL($parts);
1469 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
1471 $content_type = ($public_batch ? "application/magic-envelope+xml" : "application/json");
1473 $postResult = Network::post($dest_url, $envelope, ["Content-Type: ".$content_type]);
1474 $xml = $postResult->getBody();
1476 $curl_stat = $postResult->getReturnCode();
1477 if (empty($curl_stat) || empty($xml)) {
1478 Logger::log('Empty answer from ' . $contact['id'] . ' - ' . $dest_url);
1479 Contact::markForArchival($contact);
1480 return -9; // timed out
1483 if (($curl_stat == 503) && (stristr($postResult->getHeader(), 'retry-after'))) {
1484 Contact::markForArchival($contact);
1488 if (strpos($xml, '<?xml') === false) {
1489 Logger::log('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url);
1490 Logger::log('Returned XML: ' . $xml, Logger::DATA);
1491 Contact::markForArchival($contact);
1495 $res = XML::parseString($xml);
1497 if (empty($res->status)) {
1498 Contact::markForArchival($contact);
1502 if (!empty($res->message)) {
1503 Logger::log('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message, Logger::DEBUG);
1506 if (($res->status >= 200) && ($res->status <= 299)) {
1507 Contact::unmarkForArchival($contact);
1510 return intval($res->status);
1514 * @brief Add new birthday event for this person
1516 * @param array $contact Contact record
1517 * @param string $birthday Birthday of the contact
1519 * @todo Add array type-hint for $contact
1521 private static function birthdayEvent($contact, $birthday)
1523 // Check for duplicates
1524 $condition = ['uid' => $contact['uid'], 'cid' => $contact['id'],
1525 'start' => DateTimeFormat::utc($birthday), 'type' => 'birthday'];
1526 if (DBA::exists('event', $condition)) {
1530 Logger::log('updating birthday: ' . $birthday . ' for contact ' . $contact['id']);
1532 $bdtext = L10n::t('%s\'s birthday', $contact['name']);
1533 $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]');
1536 "INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1537 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1538 intval($contact['uid']),
1539 intval($contact['id']),
1540 DBA::escape(DateTimeFormat::utcNow()),
1541 DBA::escape(DateTimeFormat::utcNow()),
1542 DBA::escape(DateTimeFormat::utc($birthday)),
1543 DBA::escape(DateTimeFormat::utc($birthday . ' + 1 day ')),
1544 DBA::escape($bdtext),
1545 DBA::escape($bdtext2),
1546 DBA::escape('birthday')
1551 * @brief Fetch the author data from head or entry items
1553 * @param object $xpath XPath object
1554 * @param object $context In which context should the data be searched
1555 * @param array $importer Record of the importer user mixed with contact of the content
1556 * @param string $element Element name from which the data is fetched
1557 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1558 * @param string $xml optional, default empty
1560 * @return array Relevant data of the author
1561 * @todo Find good type-hints for all parameter
1563 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
1566 $author["name"] = XML::getFirstNodeValue($xpath, $element."/atom:name/text()", $context);
1567 $author["link"] = XML::getFirstNodeValue($xpath, $element."/atom:uri/text()", $context);
1569 $fields = ['id', 'uid', 'url', 'network', 'avatar-date', 'avatar', 'name-date', 'uri-date', 'addr',
1570 'name', 'nick', 'about', 'location', 'keywords', 'xmpp', 'bdyear', 'bd', 'hidden', 'contact-type'];
1571 $condition = ["`uid` = ? AND `nurl` = ? AND `network` != ?",
1572 $importer["importer_uid"], Strings::normaliseLink($author["link"]), Protocol::STATUSNET];
1573 $contact_old = DBA::selectFirst('contact', $fields, $condition);
1575 if (DBA::isResult($contact_old)) {
1576 $author["contact-id"] = $contact_old["id"];
1577 $author["network"] = $contact_old["network"];
1580 Logger::log("Contact ".$author["link"]." wasn't found for user ".$importer["importer_uid"]." XML: ".$xml, Logger::DEBUG);
1583 $author["contact-unknown"] = true;
1584 $author["contact-id"] = $importer["id"];
1585 $author["network"] = $importer["network"];
1589 // Until now we aren't serving different sizes - but maybe later
1591 /// @todo check if "avatar" or "photo" would be the best field in the specification
1592 $avatars = $xpath->query($element . "/atom:link[@rel='avatar']", $context);
1593 foreach ($avatars as $avatar) {
1596 foreach ($avatar->attributes as $attributes) {
1597 /// @TODO Rewrite these similar if() to one switch
1598 if ($attributes->name == "href") {
1599 $href = $attributes->textContent;
1601 if ($attributes->name == "width") {
1602 $width = $attributes->textContent;
1604 if ($attributes->name == "updated") {
1605 $author["avatar-date"] = $attributes->textContent;
1608 if (($width > 0) && ($href != "")) {
1609 $avatarlist[$width] = $href;
1613 if (count($avatarlist) > 0) {
1614 krsort($avatarlist);
1615 $author["avatar"] = current($avatarlist);
1618 if (empty($author['avatar']) && !empty($author['link'])) {
1619 $cid = Contact::getIdForURL($author['link'], 0);
1621 $contact = DBA::selectFirst('contact', ['avatar'], ['id' => $cid]);
1622 if (DBA::isResult($contact)) {
1623 $author['avatar'] = $contact['avatar'];
1628 if (empty($author['avatar'])) {
1629 Logger::log('Empty author: ' . $xml);
1632 if (DBA::isResult($contact_old) && !$onlyfetch) {
1633 Logger::log("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", Logger::DEBUG);
1635 $poco = ["url" => $contact_old["url"]];
1637 // When was the last change to name or uri?
1638 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1639 foreach ($name_element->attributes as $attributes) {
1640 if ($attributes->name == "updated") {
1641 $poco["name-date"] = $attributes->textContent;
1645 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1646 foreach ($link_element->attributes as $attributes) {
1647 if ($attributes->name == "updated") {
1648 $poco["uri-date"] = $attributes->textContent;
1652 // Update contact data
1653 $value = XML::getFirstNodeValue($xpath, $element . "/dfrn:handle/text()", $context);
1655 $poco["addr"] = $value;
1658 $value = XML::getFirstNodeValue($xpath, $element . "/poco:displayName/text()", $context);
1660 $poco["name"] = $value;
1663 $value = XML::getFirstNodeValue($xpath, $element . "/poco:preferredUsername/text()", $context);
1665 $poco["nick"] = $value;
1668 $value = XML::getFirstNodeValue($xpath, $element . "/poco:note/text()", $context);
1670 $poco["about"] = $value;
1673 $value = XML::getFirstNodeValue($xpath, $element . "/poco:address/poco:formatted/text()", $context);
1675 $poco["location"] = $value;
1678 /// @todo Only search for elements with "poco:type" = "xmpp"
1679 $value = XML::getFirstNodeValue($xpath, $element . "/poco:ims/poco:value/text()", $context);
1681 $poco["xmpp"] = $value;
1684 /// @todo Add support for the following fields that we don't support by now in the contact table:
1685 /// - poco:utcOffset
1691 // If the "hide" element is present then the profile isn't searchable.
1692 $hide = intval(XML::getFirstNodeValue($xpath, $element . "/dfrn:hide/text()", $context) == "true");
1694 Logger::log("Hidden status for contact " . $contact_old["url"] . ": " . $hide, Logger::DEBUG);
1696 // If the contact isn't searchable then set the contact to "hidden".
1697 // Problem: This can be manually overridden by the user.
1699 $contact_old["hidden"] = true;
1702 // Save the keywords into the contact table
1704 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1705 foreach ($tagelements as $tag) {
1706 $tags[$tag->nodeValue] = $tag->nodeValue;
1710 $poco["keywords"] = implode(", ", $tags);
1713 // "dfrn:birthday" contains the birthday converted to UTC
1714 $birthday = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1716 if (strtotime($birthday) > time()) {
1717 $bd_timestamp = strtotime($birthday);
1719 $poco["bdyear"] = date("Y", $bd_timestamp);
1722 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1723 $value = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1725 if (!in_array($value, ["", "0000-00-00", "0001-01-01"])) {
1726 $bdyear = date("Y");
1727 $value = str_replace("0000", $bdyear, $value);
1729 if (strtotime($value) < time()) {
1730 $value = str_replace($bdyear, $bdyear + 1, $value);
1731 $bdyear = $bdyear + 1;
1734 $poco["bd"] = $value;
1737 $contact = array_merge($contact_old, $poco);
1739 if ($contact_old["bdyear"] != $contact["bdyear"]) {
1740 self::birthdayEvent($contact, $birthday);
1743 // Get all field names
1745 foreach ($contact_old as $field => $data) {
1746 $fields[$field] = $data;
1749 unset($fields["id"]);
1750 unset($fields["uid"]);
1751 unset($fields["url"]);
1752 unset($fields["avatar-date"]);
1753 unset($fields["avatar"]);
1754 unset($fields["name-date"]);
1755 unset($fields["uri-date"]);
1758 // Update check for this field has to be done differently
1759 $datefields = ["name-date", "uri-date"];
1760 foreach ($datefields as $field) {
1761 // The date fields arrives as '2018-07-17T10:44:45Z' - the database return '2018-07-17 10:44:45'
1762 // The fields have to be in the same format to be comparable, since strtotime does add timezones.
1763 $contact[$field] = DateTimeFormat::utc($contact[$field]);
1765 if (strtotime($contact[$field]) > strtotime($contact_old[$field])) {
1766 Logger::log("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", Logger::DEBUG);
1771 foreach ($fields as $field => $data) {
1772 if ($contact[$field] != $contact_old[$field]) {
1773 Logger::log("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", Logger::DEBUG);
1779 Logger::log("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", Logger::DEBUG);
1782 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1783 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1784 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1785 WHERE `id` = %d AND `network` = '%s'",
1786 DBA::escape($contact["name"]), DBA::escape($contact["nick"]), DBA::escape($contact["about"]), DBA::escape($contact["location"]),
1787 DBA::escape($contact["addr"]), DBA::escape($contact["keywords"]), DBA::escape($contact["bdyear"]),
1788 DBA::escape($contact["bd"]), intval($contact["hidden"]), DBA::escape($contact["xmpp"]),
1789 DBA::escape(DateTimeFormat::utc($contact["name-date"])), DBA::escape(DateTimeFormat::utc($contact["uri-date"])),
1790 intval($contact["id"]), DBA::escape($contact["network"])
1794 Contact::updateAvatar(
1796 $importer['importer_uid'],
1798 (strtotime($contact['avatar-date']) > strtotime($contact_old['avatar-date']) || ($author['avatar'] != $contact_old['avatar']))
1802 * The generation is a sign for the reliability of the provided data.
1803 * It is used in the socgraph.php to prevent that old contact data
1804 * that was relayed over several servers can overwrite contact
1805 * data that we received directly.
1808 $poco["generation"] = 2;
1809 $poco["photo"] = $author["avatar"];
1810 $poco["hide"] = $hide;
1811 $poco["contact-type"] = $contact["contact-type"];
1812 $gcid = GContact::update($poco);
1814 GContact::link($gcid, $importer["importer_uid"], $contact["id"]);
1821 * @brief Transforms activity objects into an XML string
1823 * @param object $xpath XPath object
1824 * @param object $activity Activity object
1825 * @param string $element element name
1827 * @return string XML string
1828 * @todo Find good type-hints for all parameter
1830 private static function transformActivity($xpath, $activity, $element)
1832 if (!is_object($activity)) {
1836 $obj_doc = new DOMDocument("1.0", "utf-8");
1837 $obj_doc->formatOutput = true;
1839 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1841 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1842 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1844 $id = $xpath->query("atom:id", $activity)->item(0);
1845 if (is_object($id)) {
1846 $obj_element->appendChild($obj_doc->importNode($id, true));
1849 $title = $xpath->query("atom:title", $activity)->item(0);
1850 if (is_object($title)) {
1851 $obj_element->appendChild($obj_doc->importNode($title, true));
1854 $links = $xpath->query("atom:link", $activity);
1855 if (is_object($links)) {
1856 foreach ($links as $link) {
1857 $obj_element->appendChild($obj_doc->importNode($link, true));
1861 $content = $xpath->query("atom:content", $activity)->item(0);
1862 if (is_object($content)) {
1863 $obj_element->appendChild($obj_doc->importNode($content, true));
1866 $obj_doc->appendChild($obj_element);
1868 $objxml = $obj_doc->saveXML($obj_element);
1870 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1871 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1876 * @brief Processes the mail elements
1878 * @param object $xpath XPath object
1879 * @param object $mail mail elements
1880 * @param array $importer Record of the importer user mixed with contact of the content
1882 * @todo Find good type-hints for all parameter
1884 private static function processMail($xpath, $mail, $importer)
1886 Logger::log("Processing mails");
1888 /// @TODO Rewrite this to one statement
1890 $msg["uid"] = $importer["importer_uid"];
1891 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1892 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1893 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1894 $msg["contact-id"] = $importer["id"];
1895 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1896 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1897 $msg["created"] = DateTimeFormat::utc($xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue);
1898 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1899 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1901 $msg["replied"] = 0;
1903 DBA::insert('mail', $msg);
1905 $msg["id"] = DBA::lastInsertId();
1907 // send notifications.
1908 /// @TODO Arange this mess
1910 "type" => NOTIFY_MAIL,
1911 "notify_flags" => $importer["notify-flags"],
1912 "language" => $importer["language"],
1913 "to_name" => $importer["username"],
1914 "to_email" => $importer["email"],
1915 "uid" => $importer["importer_uid"],
1917 "source_name" => $msg["from-name"],
1918 "source_link" => $importer["url"],
1919 "source_photo" => $importer["thumb"],
1920 "verb" => ACTIVITY_POST,
1924 notification($notif_params);
1926 Logger::log("Mail is processed, notification was sent.");
1930 * @brief Processes the suggestion elements
1932 * @param object $xpath XPath object
1933 * @param object $suggestion suggestion elements
1934 * @param array $importer Record of the importer user mixed with contact of the content
1936 * @todo Find good type-hints for all parameter
1938 private static function processSuggestion($xpath, $suggestion, $importer)
1942 Logger::log("Processing suggestions");
1944 /// @TODO Rewrite this to one statement
1946 $suggest["uid"] = $importer["importer_uid"];
1947 $suggest["cid"] = $importer["id"];
1948 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1949 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1950 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1951 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1952 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1954 // Does our member already have a friend matching this description?
1957 * The valid result means the friend we're about to send a friend
1958 * suggestion already has them in their contact, which means no further
1959 * action is required.
1961 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1963 $condition = ['name' => $suggest["name"], 'nurl' => Strings::normaliseLink($suggest["url"]),
1964 'uid' => $suggest["uid"]];
1965 if (DBA::exists('contact', $condition)) {
1969 // Do we already have an fcontact record for this person?
1972 $condition = ['url' => $suggest["url"], 'name' => $suggest["name"], 'request' => $suggest["request"]];
1973 $fcontact = DBA::selectFirst('fcontact', ['id'], $condition);
1974 if (DBA::isResult($fcontact)) {
1975 $fid = $fcontact["id"];
1977 // OK, we do. Do we already have an introduction for this person?
1978 if (DBA::exists('intro', ['uid' => $suggest["uid"], 'fid' => $fid])) {
1980 * The valid result means the friend we're about to send a friend
1981 * suggestion already has them in their contact, which means no further
1982 * action is required.
1984 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1991 "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1992 DBA::escape($suggest["name"]),
1993 DBA::escape($suggest["url"]),
1994 DBA::escape($suggest["photo"]),
1995 DBA::escape($suggest["request"])
1999 $condition = ['url' => $suggest["url"], 'name' => $suggest["name"], 'request' => $suggest["request"]];
2000 $fcontact = DBA::selectFirst('fcontact', ['id'], $condition);
2003 * If no record in fcontact is found, below INSERT statement will not
2004 * link an introduction to it.
2006 if (!DBA::isResult($fcontact)) {
2007 // Database record did not get created. Quietly give up.
2013 $hash = Strings::getRandomHex();
2016 "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
2017 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
2018 intval($suggest["uid"]),
2020 intval($suggest["cid"]),
2021 DBA::escape($suggest["body"]),
2023 DBA::escape(DateTimeFormat::utcNow()),
2029 "type" => NOTIFY_SUGGEST,
2030 "notify_flags" => $importer["notify-flags"],
2031 "language" => $importer["language"],
2032 "to_name" => $importer["username"],
2033 "to_email" => $importer["email"],
2034 "uid" => $importer["importer_uid"],
2036 "link" => System::baseUrl()."/notifications/intros",
2037 "source_name" => $importer["name"],
2038 "source_link" => $importer["url"],
2039 "source_photo" => $importer["photo"],
2040 "verb" => ACTIVITY_REQ_FRIEND,
2048 * @brief Processes the relocation elements
2050 * @param object $xpath XPath object
2051 * @param object $relocation relocation elements
2052 * @param array $importer Record of the importer user mixed with contact of the content
2054 * @todo Find good type-hints for all parameter
2056 private static function processRelocation($xpath, $relocation, $importer)
2058 Logger::log("Processing relocations");
2060 /// @TODO Rewrite this to one statement
2062 $relocate["uid"] = $importer["importer_uid"];
2063 $relocate["cid"] = $importer["id"];
2064 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
2065 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
2066 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
2067 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
2068 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
2069 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
2070 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
2071 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
2072 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
2073 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
2074 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
2075 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
2077 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
2078 $relocate["avatar"] = $relocate["photo"];
2081 if ($relocate["addr"] == "") {
2082 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
2087 "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d",
2088 intval($importer["id"]),
2089 intval($importer["importer_uid"])
2092 if (!DBA::isResult($r)) {
2093 Logger::log("Query failed to execute, no result returned in " . __FUNCTION__);
2099 // Update the gcontact entry
2100 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
2102 $fields = ['name' => $relocate["name"], 'photo' => $relocate["avatar"],
2103 'url' => $relocate["url"], 'nurl' => Strings::normaliseLink($relocate["url"]),
2104 'addr' => $relocate["addr"], 'connect' => $relocate["addr"],
2105 'notify' => $relocate["notify"], 'server_url' => $relocate["server_url"]];
2106 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($old["url"])]);
2108 // Update the contact table. We try to find every entry.
2109 $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
2110 'url' => $relocate["url"], 'nurl' => Strings::normaliseLink($relocate["url"]),
2111 'addr' => $relocate["addr"], 'request' => $relocate["request"],
2112 'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
2113 'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
2114 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], Strings::normaliseLink($old["url"])];
2116 DBA::update('contact', $fields, $condition);
2118 Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
2120 Logger::log('Contacts are updated.');
2123 /// merge with current record, current contents have priority
2124 /// update record, set url-updated
2125 /// update profile photos
2126 /// schedule a scan?
2131 * @brief Updates an item
2133 * @param array $current the current item record
2134 * @param array $item the new item record
2135 * @param array $importer Record of the importer user mixed with contact of the content
2136 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2138 * @todo set proper type-hints (array?)
2140 private static function updateContent($current, $item, $importer, $entrytype)
2144 if (self::isEditedTimestampNewer($current, $item)) {
2145 // do not accept (ignore) an earlier edit than one we currently have.
2146 if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
2150 $fields = ['title' => defaults($item, 'title', ''), 'body' => defaults($item, 'body', ''),
2151 'tag' => defaults($item, 'tag', ''), 'changed' => DateTimeFormat::utcNow(),
2152 'edited' => DateTimeFormat::utc($item["edited"])];
2154 $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
2155 Item::update($fields, $condition);
2163 * @brief Detects the entry type of the item
2165 * @param array $importer Record of the importer user mixed with contact of the content
2166 * @param array $item the new item record
2168 * @return int Is it a toplevel entry, a comment or a relayed comment?
2169 * @todo set proper type-hints (array?)
2171 private static function getEntryType($importer, $item)
2173 if ($item["parent-uri"] != $item["uri"]) {
2176 if ($importer["page-flags"] == Contact::PAGE_COMMUNITY || $importer["page-flags"] == Contact::PAGE_PRVGROUP) {
2179 Logger::log("possible community action");
2181 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2184 // was the top-level post for this action written by somebody on this site?
2185 // Specifically, the recipient?
2187 $is_a_remote_action = false;
2189 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item["parent-uri"]]);
2190 if (DBA::isResult($parent)) {
2192 "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2193 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2194 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2195 AND `item`.`uid` = %d
2198 DBA::escape($parent["parent-uri"]),
2199 DBA::escape($parent["parent-uri"]),
2200 DBA::escape($parent["parent-uri"]),
2201 intval($importer["importer_uid"])
2203 if (DBA::isResult($r)) {
2204 $is_a_remote_action = true;
2209 * Does this have the characteristics of a community or private group action?
2210 * If it's an action to a wall post on a community/prvgroup page it's a
2211 * valid community action. Also forum_mode makes it valid for sure.
2212 * If neither, it's not.
2214 if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2215 $is_a_remote_action = false;
2216 Logger::log("not a community action");
2219 if ($is_a_remote_action) {
2220 return DFRN::REPLY_RC;
2225 return DFRN::TOP_LEVEL;
2230 * @brief Send a "poke"
2232 * @param array $item the new item record
2233 * @param array $importer Record of the importer user mixed with contact of the content
2234 * @param int $posted_id The record number of item record that was just posted
2236 * @todo set proper type-hints (array?)
2238 private static function doPoke($item, $importer, $posted_id)
2240 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2244 $xo = XML::parseString($item["object"], false);
2246 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2247 // somebody was poked/prodded. Was it me?
2248 foreach ($xo->link as $l) {
2249 $atts = $l->attributes();
2250 switch ($atts["rel"]) {
2252 $Blink = $atts["href"];
2259 if ($Blink && Strings::compareLink($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2260 $author = DBA::selectFirst('contact', ['name', 'thumb', 'url'], ['id' => $item['author-id']]);
2262 $item['id'] = $posted_id;
2264 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => $importer["importer_uid"]]);
2265 $item["parent"] = $parent['id'];
2267 // send a notification
2270 "type" => NOTIFY_POKE,
2271 "notify_flags" => $importer["notify-flags"],
2272 "language" => $importer["language"],
2273 "to_name" => $importer["username"],
2274 "to_email" => $importer["email"],
2275 "uid" => $importer["importer_uid"],
2277 "link" => System::baseUrl()."/display/".urlencode(Item::getGuidById($posted_id)),
2278 "source_name" => $author["name"],
2279 "source_link" => $author["url"],
2280 "source_photo" => $author["thumb"],
2281 "verb" => $item["verb"],
2282 "otype" => "person",
2283 "activity" => $verb,
2284 "parent" => $item["parent"]]
2291 * @brief Processes several actions, depending on the verb
2293 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2294 * @param array $importer Record of the importer user mixed with contact of the content
2295 * @param array $item the new item record
2296 * @param bool $is_like Is the verb a "like"?
2298 * @return bool Should the processing of the entries be continued?
2299 * @todo set proper type-hints (array?)
2301 private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2303 Logger::log("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, Logger::DEBUG);
2305 if (($entrytype == DFRN::TOP_LEVEL)) {
2306 // The filling of the the "contact" variable is done for legcy reasons
2307 // The functions below are partly used by ostatus.php as well - where we have this variable
2308 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2310 $nickname = $contact["nick"];
2312 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2313 // This function once was responsible for DFRN and OStatus.
2314 if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2315 Logger::log("New follower");
2316 Contact::addRelationship($importer, $contact, $item, $nickname);
2319 if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2320 Logger::log("Lost follower");
2321 Contact::removeFollower($importer, $contact, $item);
2324 if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2325 Logger::log("New friend request");
2326 Contact::addRelationship($importer, $contact, $item, $nickname, true);
2329 if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2330 Logger::log("Lost sharer");
2331 Contact::removeSharer($importer, $contact, $item);
2335 if (($item["verb"] == ACTIVITY_LIKE)
2336 || ($item["verb"] == ACTIVITY_DISLIKE)
2337 || ($item["verb"] == ACTIVITY_ATTEND)
2338 || ($item["verb"] == ACTIVITY_ATTENDNO)
2339 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
2342 $item["gravity"] = GRAVITY_ACTIVITY;
2343 // only one like or dislike per person
2344 // splitted into two queries for performance issues
2345 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2346 'verb' => $item["verb"], 'parent-uri' => $item["parent-uri"]];
2347 if (Item::exists($condition)) {
2351 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2352 'verb' => $item["verb"], 'thr-parent' => $item["parent-uri"]];
2353 if (Item::exists($condition)) {
2357 // The owner of an activity must be the author
2358 $item["owner-name"] = $item["author-name"];
2359 $item["owner-link"] = $item["author-link"];
2360 $item["owner-avatar"] = $item["author-avatar"];
2361 $item["owner-id"] = $item["author-id"];
2366 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2367 $xo = XML::parseString($item["object"], false);
2368 $xt = XML::parseString($item["target"], false);
2370 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2371 $item_tag = Item::selectFirst(['id', 'tag'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]);
2373 if (!DBA::isResult($item_tag)) {
2374 Logger::log("Query failed to execute, no result returned in " . __FUNCTION__);
2378 // extract tag, if not duplicate, add to parent item
2380 if (!stristr($item_tag["tag"], trim($xo->content))) {
2381 $tag = $item_tag["tag"] . (strlen($item_tag["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2382 Item::update(['tag' => $tag], ['id' => $item_tag["id"]]);
2392 * @brief Processes the link elements
2394 * @param object $links link elements
2395 * @param array $item the item record
2397 * @todo set proper type-hints
2399 private static function parseLinks($links, &$item)
2406 foreach ($links as $link) {
2407 foreach ($link->attributes as $attributes) {
2408 switch ($attributes->name) {
2409 case "href" : $href = $attributes->textContent; break;
2410 case "rel" : $rel = $attributes->textContent; break;
2411 case "type" : $type = $attributes->textContent; break;
2412 case "length": $length = $attributes->textContent; break;
2413 case "title" : $title = $attributes->textContent; break;
2416 if (($rel != "") && ($href != "")) {
2419 $item["plink"] = $href;
2424 if (!empty($item["attach"])) {
2425 $item["attach"] .= ",";
2427 $item["attach"] = "";
2430 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2438 * @brief Processes the entry elements which contain the items and comments
2440 * @param array $header Array of the header elements that always stay the same
2441 * @param object $xpath XPath object
2442 * @param object $entry entry elements
2443 * @param array $importer Record of the importer user mixed with contact of the content
2444 * @param object $xml xml
2446 * @todo Add type-hints
2448 private static function processEntry($header, $xpath, $entry, $importer, $xml)
2450 Logger::log("Processing entries");
2454 $item["protocol"] = Conversation::PARCEL_DFRN;
2456 $item["source"] = $xml;
2459 $item["uri"] = XML::getFirstNodeValue($xpath, "atom:id/text()", $entry);
2461 $item["edited"] = XML::getFirstNodeValue($xpath, "atom:updated/text()", $entry);
2463 $current = Item::selectFirst(['id', 'uid', 'edited', 'body'],
2464 ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
2466 // Is there an existing item?
2467 if (DBA::isResult($current) && !self::isEditedTimestampNewer($current, $item)) {
2468 Logger::log("Item ".$item["uri"]." (".$item['edited'].") already existed.", Logger::DEBUG);
2473 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true, $xml);
2475 $owner_unknown = (isset($owner["contact-unknown"]) && $owner["contact-unknown"]);
2477 $item["owner-name"] = $owner["name"];
2478 $item["owner-link"] = $owner["link"];
2479 $item["owner-avatar"] = $owner["avatar"];
2480 $item["owner-id"] = Contact::getIdForURL($owner["link"], 0);
2483 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true, $xml);
2485 $item["author-name"] = $author["name"];
2486 $item["author-link"] = $author["link"];
2487 $item["author-avatar"] = $author["avatar"];
2488 $item["author-id"] = Contact::getIdForURL($author["link"], 0);
2490 $item["title"] = XML::getFirstNodeValue($xpath, "atom:title/text()", $entry);
2492 $item["created"] = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2494 $item["body"] = XML::getFirstNodeValue($xpath, "dfrn:env/text()", $entry);
2495 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2496 // make sure nobody is trying to sneak some html tags by us
2497 $item["body"] = Strings::removeTags(Strings::base64UrlDecode($item["body"]));
2499 $item["body"] = BBCode::limitBodySize($item["body"]);
2501 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2502 if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
2503 $base_url = get_app()->getBaseURL();
2504 $item['body'] = HTML::relToAbs($item['body'], $base_url);
2506 $item['body'] = HTML::toBBCodeVideo($item['body']);
2508 $item['body'] = OEmbed::HTML2BBCode($item['body']);
2510 $config = HTMLPurifier_Config::createDefault();
2511 $config->set('Cache.DefinitionImpl', null);
2513 // we shouldn't need a whitelist, because the bbcode converter
2514 // will strip out any unsupported tags.
2516 $purifier = new HTMLPurifier($config);
2517 $item['body'] = $purifier->purify($item['body']);
2519 $item['body'] = @HTML::toBBCode($item['body']);
2522 /// @todo We should check for a repeated post and if we know the repeated author.
2524 // We don't need the content element since "dfrn:env" is always present
2525 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2527 $item["location"] = XML::getFirstNodeValue($xpath, "dfrn:location/text()", $entry);
2529 $item["coord"] = XML::getFirstNodeValue($xpath, "georss:point", $entry);
2531 $item["private"] = XML::getFirstNodeValue($xpath, "dfrn:private/text()", $entry);
2533 $item["extid"] = XML::getFirstNodeValue($xpath, "dfrn:extid/text()", $entry);
2535 if (XML::getFirstNodeValue($xpath, "dfrn:bookmark/text()", $entry) == "true") {
2536 $item["post-type"] = Item::PT_PAGE;
2539 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2540 if ($notice_info && ($notice_info->length > 0)) {
2541 foreach ($notice_info->item(0)->attributes as $attributes) {
2542 if ($attributes->name == "source") {
2543 $item["app"] = strip_tags($attributes->textContent);
2548 $item["guid"] = XML::getFirstNodeValue($xpath, "dfrn:diaspora_guid/text()", $entry);
2550 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
2551 $dsprsig = XML::unescape(XML::getFirstNodeValue($xpath, "dfrn:diaspora_signature/text()", $entry));
2552 if ($dsprsig != "") {
2553 $item["dsprsig"] = $dsprsig;
2556 $item["verb"] = XML::getFirstNodeValue($xpath, "activity:verb/text()", $entry);
2558 if (XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry) != "") {
2559 $item["object-type"] = XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry);
2562 $object = $xpath->query("activity:object", $entry)->item(0);
2563 $item["object"] = self::transformActivity($xpath, $object, "object");
2565 if (trim($item["object"]) != "") {
2566 $r = XML::parseString($item["object"], false);
2567 if (isset($r->type)) {
2568 $item["object-type"] = $r->type;
2572 $target = $xpath->query("activity:target", $entry)->item(0);
2573 $item["target"] = self::transformActivity($xpath, $target, "target");
2575 $categories = $xpath->query("atom:category", $entry);
2577 foreach ($categories as $category) {
2580 foreach ($category->attributes as $attributes) {
2581 if ($attributes->name == "term") {
2582 $term = $attributes->textContent;
2585 if ($attributes->name == "scheme") {
2586 $scheme = $attributes->textContent;
2590 if (($term != "") && ($scheme != "")) {
2591 $parts = explode(":", $scheme);
2592 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2593 $termhash = array_shift($parts);
2594 $termurl = implode(":", $parts);
2596 if (!empty($item["tag"])) {
2597 $item["tag"] .= ",";
2602 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2610 $links = $xpath->query("atom:link", $entry);
2612 self::parseLinks($links, $item);
2615 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
2617 $conv = $xpath->query('ostatus:conversation', $entry);
2618 if (is_object($conv->item(0))) {
2619 foreach ($conv->item(0)->attributes as $attributes) {
2620 if ($attributes->name == "ref") {
2621 $item['conversation-uri'] = $attributes->textContent;
2623 if ($attributes->name == "href") {
2624 $item['conversation-href'] = $attributes->textContent;
2629 // Is it a reply or a top level posting?
2630 $item["parent-uri"] = $item["uri"];
2632 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2633 if (is_object($inreplyto->item(0))) {
2634 foreach ($inreplyto->item(0)->attributes as $attributes) {
2635 if ($attributes->name == "ref") {
2636 $item["parent-uri"] = $attributes->textContent;
2641 // Get the type of the item (Top level post, reply or remote reply)
2642 $entrytype = self::getEntryType($importer, $item);
2644 // Now assign the rest of the values that depend on the type of the message
2645 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2646 if (!isset($item["object-type"])) {
2647 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2650 if ($item["contact-id"] != $owner["contact-id"]) {
2651 $item["contact-id"] = $owner["contact-id"];
2654 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2655 $item["network"] = $owner["network"];
2658 if ($item["contact-id"] != $author["contact-id"]) {
2659 $item["contact-id"] = $author["contact-id"];
2662 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2663 $item["network"] = $author["network"];
2667 if ($entrytype == DFRN::REPLY_RC) {
2669 } elseif ($entrytype == DFRN::TOP_LEVEL) {
2670 if (!isset($item["object-type"])) {
2671 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2675 if (($item["object-type"] == ACTIVITY_OBJ_EVENT) && !$owner_unknown) {
2676 Logger::log("Item ".$item["uri"]." seems to contain an event.", Logger::DEBUG);
2677 $ev = Event::fromBBCode($item["body"]);
2678 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2679 Logger::log("Event in item ".$item["uri"]." was found.", Logger::DEBUG);
2680 $ev["cid"] = $importer["id"];
2681 $ev["uid"] = $importer["importer_uid"];
2682 $ev["uri"] = $item["uri"];
2683 $ev["edited"] = $item["edited"];
2684 $ev["private"] = $item["private"];
2685 $ev["guid"] = $item["guid"];
2686 $ev["plink"] = $item["plink"];
2688 $condition = ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]];
2689 $event = DBA::selectFirst('event', ['id'], $condition);
2690 if (DBA::isResult($event)) {
2691 $ev["id"] = $event["id"];
2694 $event_id = Event::store($ev);
2695 Logger::log("Event ".$event_id." was stored", Logger::DEBUG);
2701 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2702 Logger::log("Exiting because 'processVerbs' told us so", Logger::DEBUG);
2706 // This check is done here to be able to receive connection requests in "processVerbs"
2707 if (($entrytype == DFRN::TOP_LEVEL) && $owner_unknown) {
2708 Logger::log("Item won't be stored because user " . $importer["importer_uid"] . " doesn't follow " . $item["owner-link"] . ".", Logger::DEBUG);
2713 // Update content if 'updated' changes
2714 if (DBA::isResult($current)) {
2715 if (self::updateContent($current, $item, $importer, $entrytype)) {
2716 Logger::log("Item ".$item["uri"]." was updated.", Logger::DEBUG);
2718 Logger::log("Item " . $item["uri"] . " already existed.", Logger::DEBUG);
2723 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2724 $posted_id = Item::insert($item);
2728 Logger::log("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, Logger::DEBUG);
2730 if ($item['uid'] == 0) {
2731 Item::distribute($posted_id);
2736 } else { // $entrytype == DFRN::TOP_LEVEL
2737 if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
2738 Logger::log("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", Logger::DEBUG);
2741 if (!Strings::compareLink($item["owner-link"], $importer["url"])) {
2743 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2744 * but otherwise there's a possible data mixup on the sender's system.
2745 * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2746 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2748 Logger::log('Correcting item owner.', Logger::DEBUG);
2749 $item["owner-link"] = $importer["url"];
2750 $item["owner-id"] = Contact::getIdForURL($importer["url"], 0);
2753 if (($importer["rel"] == Contact::FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2754 Logger::log("Contact ".$importer["id"]." is only follower and tgroup check was negative.", Logger::DEBUG);
2758 // This is my contact on another system, but it's really me.
2759 // Turn this into a wall post.
2760 $notify = Item::isRemoteSelf($importer, $item);
2762 $posted_id = Item::insert($item, false, $notify);
2765 $posted_id = $notify;
2768 Logger::log("Item was stored with id ".$posted_id, Logger::DEBUG);
2770 if ($item['uid'] == 0) {
2771 Item::distribute($posted_id);
2774 if (stristr($item["verb"], ACTIVITY_POKE)) {
2775 self::doPoke($item, $importer, $posted_id);
2781 * @brief Deletes items
2783 * @param object $xpath XPath object
2784 * @param object $deletion deletion elements
2785 * @param array $importer Record of the importer user mixed with contact of the content
2787 * @todo set proper type-hints
2789 private static function processDeletion($xpath, $deletion, $importer)
2791 Logger::log("Processing deletions");
2794 foreach ($deletion->attributes as $attributes) {
2795 if ($attributes->name == "ref") {
2796 $uri = $attributes->textContent;
2800 if (!$uri || !$importer["id"]) {
2804 $condition = ['uri' => $uri, 'uid' => $importer["importer_uid"]];
2805 $item = Item::selectFirst(['id', 'parent', 'contact-id', 'file', 'deleted'], $condition);
2806 if (!DBA::isResult($item)) {
2807 Logger::log("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", Logger::DEBUG);
2811 if (strstr($item['file'], '[')) {
2812 Logger::log("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " is filed. So it won't be deleted.", Logger::DEBUG);
2816 // When it is a starting post it has to belong to the person that wants to delete it
2817 if (($item['id'] == $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2818 Logger::log("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", Logger::DEBUG);
2822 // Comments can be deleted by the thread owner or comment owner
2823 if (($item['id'] != $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2824 $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2825 if (!Item::exists($condition)) {
2826 Logger::log("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", Logger::DEBUG);
2831 if ($item["deleted"]) {
2835 Logger::log('deleting item '.$item['id'].' uri='.$uri, Logger::DEBUG);
2837 Item::delete(['id' => $item['id']]);
2841 * @brief Imports a DFRN message
2843 * @param string $xml The DFRN message
2844 * @param array $importer Record of the importer user mixed with contact of the content
2845 * @param bool $sort_by_date Is used when feeds are polled
2846 * @return integer Import status
2847 * @todo set proper type-hints
2849 public static function import($xml, $importer, $sort_by_date = false)
2855 $doc = new DOMDocument();
2856 @$doc->loadXML($xml);
2858 $xpath = new DOMXPath($doc);
2859 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2860 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2861 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2862 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2863 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2864 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2865 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2866 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2867 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2868 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2871 $header["uid"] = $importer["importer_uid"];
2872 $header["network"] = Protocol::DFRN;
2873 $header["wall"] = 0;
2874 $header["origin"] = 0;
2875 $header["contact-id"] = $importer["id"];
2877 // Update the contact table if the data has changed
2879 // The "atom:author" is only present in feeds
2880 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2881 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2884 // Only the "dfrn:owner" in the head section contains all data
2885 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2886 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2889 Logger::log("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], Logger::DEBUG);
2891 // is it a public forum? Private forums aren't exposed with this method
2892 $forum = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:community/text()"));
2894 // The account type is new since 3.5.1
2895 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2896 $accounttype = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:account_type/text()"));
2898 if ($accounttype != $importer["contact-type"]) {
2899 DBA::update('contact', ['contact-type' => $accounttype], ['id' => $importer["id"]]);
2901 // A forum contact can either have set "forum" or "prv" - but not both
2902 if (($accounttype == Contact::ACCOUNT_TYPE_COMMUNITY) && (($forum != $importer["forum"]) || ($forum == $importer["prv"]))) {
2903 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer["id"]];
2904 DBA::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2906 } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
2907 $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2908 DBA::update('contact', ['forum' => $forum], $condition);
2912 // We are processing relocations even if we are ignoring a contact
2913 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2914 foreach ($relocations as $relocation) {
2915 self::processRelocation($xpath, $relocation, $importer);
2918 if (($importer["uid"] != 0) && !$importer["readonly"]) {
2919 $mails = $xpath->query("/atom:feed/dfrn:mail");
2920 foreach ($mails as $mail) {
2921 self::processMail($xpath, $mail, $importer);
2924 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2925 foreach ($suggestions as $suggestion) {
2926 self::processSuggestion($xpath, $suggestion, $importer);
2930 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2931 foreach ($deletions as $deletion) {
2932 self::processDeletion($xpath, $deletion, $importer);
2935 if (!$sort_by_date) {
2936 $entries = $xpath->query("/atom:feed/atom:entry");
2937 foreach ($entries as $entry) {
2938 self::processEntry($header, $xpath, $entry, $importer, $xml);
2942 $entries = $xpath->query("/atom:feed/atom:entry");
2943 foreach ($entries as $entry) {
2944 $created = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2945 $newentries[strtotime($created)] = $entry;
2948 // Now sort after the publishing date
2951 foreach ($newentries as $entry) {
2952 self::processEntry($header, $xpath, $entry, $importer, $xml);
2955 Logger::log("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], Logger::DEBUG);
2961 * @param string $contact_nick contact nickname
2963 public static function autoRedir(App $a, $contact_nick)
2966 if (x($_REQUEST, 'redir') && intval($_REQUEST['redir'])) {
2970 if ((! $contact_nick) || ($contact_nick === $a->user['nickname'])) {
2975 // We need to find out if $contact_nick is a user on this hub, and if so, if I
2976 // am a contact of that user. However, that user may have other contacts with the
2977 // same nickname as me on other hubs or other networks. Exclude these by requiring
2978 // that the contact have a local URL. I will be the only person with my nickname at
2979 // this URL, so if a result is found, then I am a contact of the $contact_nick user.
2981 // We also have to make sure that I'm a legitimate contact--I'm not blocked or pending.
2983 $baseurl = System::baseUrl();
2984 $domain_st = strpos($baseurl, "://");
2985 if ($domain_st === false) {
2988 $baseurl = substr($baseurl, $domain_st + 3);
2989 $nurl = Strings::normaliseLink($baseurl);
2991 /// @todo Why is there a query for "url" *and* "nurl"? Especially this normalising is strange.
2992 $r = q("SELECT `id` FROM `contact` WHERE `uid` = (SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1)
2993 AND `nick` = '%s' AND NOT `self` AND (`url` LIKE '%%%s%%' OR `nurl` LIKE '%%%s%%') AND NOT `blocked` AND NOT `pending` LIMIT 1",
2994 DBA::escape($contact_nick),
2995 DBA::escape($a->user['nickname']),
2996 DBA::escape($baseurl),
2999 if ((! DBA::isResult($r)) || $r[0]['id'] == remote_user()) {
3003 $r = q("SELECT * FROM contact WHERE nick = '%s'
3004 AND network = '%s' AND uid = %d AND url LIKE '%%%s%%' LIMIT 1",
3005 DBA::escape($contact_nick),
3006 DBA::escape(Protocol::DFRN),
3007 intval(local_user()),
3008 DBA::escape($baseurl)
3010 if (! DBA::isResult($r)) {
3016 $dfrn_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
3018 if ($r[0]['duplex'] && $r[0]['issued-id']) {
3019 $orig_id = $r[0]['issued-id'];
3020 $dfrn_id = '1:' . $orig_id;
3022 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
3023 $orig_id = $r[0]['dfrn-id'];
3024 $dfrn_id = '0:' . $orig_id;
3027 // ensure that we've got a valid ID. There may be some edge cases with forums and non-duplex mode
3028 // that may have triggered some of the "went to {profile/intro} and got an RSS feed" issues
3030 if (strlen($dfrn_id) < 3) {
3034 $sec = Strings::getRandomHex();
3036 DBA::insert('profile_check', ['uid' => local_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id, 'sec' => $sec, 'expire' => time() + 45]);
3038 $url = curPageURL();
3040 Logger::log('auto_redir: ' . $r[0]['name'] . ' ' . $sec, Logger::DEBUG);
3041 $dest = (($url) ? '&destination_url=' . $url : '');
3042 System::externalRedirect($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
3043 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest);
3050 * @brief Returns the activity verb
3052 * @param array $item Item array
3054 * @return string activity verb
3056 private static function constructVerb(array $item)
3058 if ($item['verb']) {
3059 return $item['verb'];
3061 return ACTIVITY_POST;
3064 private static function tgroupCheck($uid, $item)
3068 // check that the message originated elsewhere and is a top-level post
3070 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['parent-uri'])) {
3074 $user = DBA::selectFirst('user', ['page-flags', 'nickname'], ['uid' => $uid]);
3075 if (!DBA::isResult($user)) {
3079 $community_page = ($user['page-flags'] == Contact::PAGE_COMMUNITY);
3080 $prvgroup = ($user['page-flags'] == Contact::PAGE_PRVGROUP);
3082 $link = Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']);
3085 * Diaspora uses their own hardwired link URL in @-tags
3086 * instead of the one we supply with webfinger
3088 $dlink = Strings::normaliseLink(System::baseUrl() . '/u/' . $user['nickname']);
3090 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
3092 foreach ($matches as $mtch) {
3093 if (Strings::compareLink($link, $mtch[1]) || Strings::compareLink($dlink, $mtch[1])) {
3095 Logger::log('mention found: ' . $mtch[2]);
3104 return $community_page || $prvgroup;
3108 * This function returns true if $update has an edited timestamp newer
3109 * than $existing, i.e. $update contains new data which should override
3110 * what's already there. If there is no timestamp yet, the update is
3111 * assumed to be newer. If the update has no timestamp, the existing
3112 * item is assumed to be up-to-date. If the timestamps are equal it
3113 * assumes the update has been seen before and should be ignored.
3116 private static function isEditedTimestampNewer($existing, $update)
3118 if (!x($existing, 'edited') || !$existing['edited']) {
3121 if (!x($update, 'edited') || !$update['edited']) {
3125 $existing_edited = DateTimeFormat::utc($existing['edited']);
3126 $update_edited = DateTimeFormat::utc($update['edited']);
3128 return (strcmp($existing_edited, $update_edited) < 0);