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\Logger;
20 use Friendica\Core\Protocol;
21 use Friendica\Core\System;
22 use Friendica\Database\DBA;
23 use Friendica\Model\Contact;
24 use Friendica\Model\Conversation;
25 use Friendica\Model\Event;
26 use Friendica\Model\GContact;
27 use Friendica\Model\Item;
28 use Friendica\Model\PermissionSet;
29 use Friendica\Model\Profile;
30 use Friendica\Model\User;
31 use Friendica\Object\Image;
32 use Friendica\Util\Crypto;
33 use Friendica\Util\DateTimeFormat;
34 use Friendica\Util\Network;
35 use Friendica\Util\Strings;
36 use Friendica\Util\XML;
38 use HTMLPurifier_Config;
41 * @brief This class contain functions to create and send DFRN XML files
46 const TOP_LEVEL = 0; // Top level posting
47 const REPLY = 1; // Regular reply that is stored locally
48 const REPLY_RC = 2; // Reply that will be relayed
51 * @brief Generates an array of contact and user for DFRN imports
53 * This array contains not only the receiver but also the sender of the message.
55 * @param integer $cid Contact id
56 * @param integer $uid User id
58 * @return array importer
60 public static function getImporter($cid, $uid = 0)
62 $condition = ['id' => $cid, 'blocked' => false, 'pending' => false];
63 $contact = DBA::selectFirst('contact', [], $condition);
64 if (!DBA::isResult($contact)) {
68 $contact['cpubkey'] = $contact['pubkey'];
69 $contact['cprvkey'] = $contact['prvkey'];
70 $contact['senderName'] = $contact['name'];
73 $condition = ['uid' => $uid, 'account_expired' => false, 'account_removed' => false];
74 $user = DBA::selectFirst('user', [], $condition);
75 if (!DBA::isResult($user)) {
79 $user['importer_uid'] = $user['uid'];
80 $user['uprvkey'] = $user['prvkey'];
82 $user = ['importer_uid' => 0, 'uprvkey' => '', 'timezone' => 'UTC',
83 'nickname' => '', 'sprvkey' => '', 'spubkey' => '',
84 'page-flags' => 0, 'account-type' => 0, 'prvnets' => 0];
87 return array_merge($contact, $user);
91 * @brief Generates the atom entries for delivery.php
93 * This function is used whenever content is transmitted via DFRN.
95 * @param array $items Item elements
96 * @param array $owner Owner record
98 * @return string DFRN entries
99 * @todo Find proper type-hints
101 public static function entries($items, $owner)
103 $doc = new DOMDocument('1.0', 'utf-8');
104 $doc->formatOutput = true;
106 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
108 if (! count($items)) {
109 return trim($doc->saveXML());
112 foreach ($items as $item) {
113 // These values aren't sent when sending from the queue.
114 /// @todo Check if we can set these values from the queue or if they are needed at all.
115 $item["entry:comment-allow"] = defaults($item, "entry:comment-allow", true);
116 $item["entry:cid"] = defaults($item, "entry:cid", 0);
118 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
119 $root->appendChild($entry);
122 return trim($doc->saveXML());
126 * @brief Generate an atom feed for the given user
128 * This function is called when another server is pulling data from the user feed.
130 * @param string $dfrn_id DFRN ID from the requesting party
131 * @param string $owner_nick Owner nick name
132 * @param string $last_update Date of the last update
133 * @param int $direction Can be -1, 0 or 1.
134 * @param boolean $onlyheader Output only the header without content? (Default is "no")
136 * @return string DFRN feed entries
138 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false)
142 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
143 $public_feed = (($dfrn_id) ? false : true);
144 $starred = false; // not yet implemented, possible security issues
147 if ($public_feed && $a->argc > 2) {
148 for ($x = 2; $x < $a->argc; $x++) {
149 if ($a->argv[$x] == 'converse') {
152 if ($a->argv[$x] == 'starred') {
155 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
156 $category = $a->argv[$x+1];
161 // default permissions - anonymous user
163 $sql_extra = " AND NOT `item`.`private` ";
166 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
167 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
168 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
169 DBA::escape($owner_nick)
172 if (! DBA::isResult($r)) {
173 Logger::log(sprintf('No contact found for nickname=%d', $owner_nick), Logger::WARNING);
178 $owner_id = $owner['uid'];
179 $owner_nick = $owner['nickname'];
181 $sql_post_table = "";
183 if (! $public_feed) {
185 switch ($direction) {
187 $sql_extra = sprintf(" AND `issued-id` = '%s' ", DBA::escape($dfrn_id));
191 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
192 $my_id = '1:' . $dfrn_id;
195 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
196 $my_id = '0:' . $dfrn_id;
204 "SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
208 if (! DBA::isResult($r)) {
209 Logger::log(sprintf('No contact found for uid=%d', $owner_id), Logger::WARNING);
215 $set = PermissionSet::get($owner_id, $contact['id']);
218 $sql_extra = " AND `item`.`psid` IN (" . implode(',', $set) .")";
220 $sql_extra = " AND NOT `item`.`private`";
230 if (! strlen($last_update)) {
231 $last_update = 'now -30 days';
234 if (isset($category)) {
235 $sql_post_table = sprintf(
236 "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` ",
237 DBA::escape(Strings::protectSprintf($category)),
238 intval(TERM_OBJ_POST),
239 intval(TERM_CATEGORY),
242 //$sql_extra .= FileTag::fileQuery('item',$category,'category');
245 if ($public_feed && ! $converse) {
246 $sql_extra .= " AND `contact`.`self` = 1 ";
249 $check_date = DateTimeFormat::utc($last_update);
253 FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
254 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
255 WHERE `item`.`uid` = %d AND `item`.`wall` AND `item`.`changed` > '%s'
257 ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
259 DBA::escape($check_date),
264 foreach ($r as $item) {
265 $ids[] = $item['id'];
269 $ret = Item::select(Item::DELIVER_FIELDLIST, ['id' => $ids]);
270 $items = Item::inArray($ret);
276 * Will check further below if this actually returned results.
277 * We will provide an empty feed if that is the case.
280 $doc = new DOMDocument('1.0', 'utf-8');
281 $doc->formatOutput = true;
283 $alternatelink = $owner['url'];
285 if (isset($category)) {
286 $alternatelink .= "/category/".$category;
290 $author = "dfrn:owner";
295 $root = self::addHeader($doc, $owner, $author, $alternatelink, true);
297 /// @TODO This hook can't work anymore
298 // Addon::callHooks('atom_feed', $atom);
300 if (!DBA::isResult($items) || $onlyheader) {
301 $atom = trim($doc->saveXML());
303 Addon::callHooks('atom_feed_end', $atom);
308 foreach ($items as $item) {
309 // prevent private email from leaking.
310 if ($item['network'] == Protocol::MAIL) {
314 // public feeds get html, our own nodes use bbcode
318 // catch any email that's in a public conversation and make sure it doesn't leak
319 if ($item['private']) {
326 $entry = self::entry($doc, $type, $item, $owner, true);
327 $root->appendChild($entry);
330 $atom = trim($doc->saveXML());
332 Addon::callHooks('atom_feed_end', $atom);
338 * @brief Generate an atom entry for a given item id
340 * @param int $item_id The item id
341 * @param boolean $conversation Show the conversation. If false show the single post.
343 * @return string DFRN feed entry
345 public static function itemFeed($item_id, $conversation = false)
348 $condition = ['parent' => $item_id];
350 $condition = ['id' => $item_id];
353 $ret = Item::select(Item::DELIVER_FIELDLIST, $condition);
354 $items = Item::inArray($ret);
355 if (!DBA::isResult($items)) {
361 if ($item['uid'] != 0) {
362 $owner = User::getOwnerDataById($item['uid']);
367 $owner = ['uid' => 0, 'nick' => 'feed-item'];
370 $doc = new DOMDocument('1.0', 'utf-8');
371 $doc->formatOutput = true;
375 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
376 $doc->appendChild($root);
378 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
379 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
380 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
381 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
382 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
383 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
384 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
385 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
386 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
388 //$root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
390 foreach ($items as $item) {
391 $entry = self::entry($doc, $type, $item, $owner, true, 0);
392 $root->appendChild($entry);
395 $root = self::entry($doc, $type, $item, $owner, true, 0, true);
398 $atom = trim($doc->saveXML());
403 * @brief Create XML text for DFRN mails
405 * @param array $item message elements
406 * @param array $owner Owner record
408 * @return string DFRN mail
409 * @todo Find proper type-hints
411 public static function mail($item, $owner)
413 $doc = new DOMDocument('1.0', 'utf-8');
414 $doc->formatOutput = true;
416 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
418 $mail = $doc->createElement("dfrn:mail");
419 $sender = $doc->createElement("dfrn:sender");
421 XML::addElement($doc, $sender, "dfrn:name", $owner['name']);
422 XML::addElement($doc, $sender, "dfrn:uri", $owner['url']);
423 XML::addElement($doc, $sender, "dfrn:avatar", $owner['thumb']);
425 $mail->appendChild($sender);
427 XML::addElement($doc, $mail, "dfrn:id", $item['uri']);
428 XML::addElement($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
429 XML::addElement($doc, $mail, "dfrn:sentdate", DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
430 XML::addElement($doc, $mail, "dfrn:subject", $item['title']);
431 XML::addElement($doc, $mail, "dfrn:content", $item['body']);
433 $root->appendChild($mail);
435 return trim($doc->saveXML());
439 * @brief Create XML text for DFRN friend suggestions
441 * @param array $item suggestion elements
442 * @param array $owner Owner record
444 * @return string DFRN suggestions
445 * @todo Find proper type-hints
447 public static function fsuggest($item, $owner)
449 $doc = new DOMDocument('1.0', 'utf-8');
450 $doc->formatOutput = true;
452 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
454 $suggest = $doc->createElement("dfrn:suggest");
456 XML::addElement($doc, $suggest, "dfrn:url", $item['url']);
457 XML::addElement($doc, $suggest, "dfrn:name", $item['name']);
458 XML::addElement($doc, $suggest, "dfrn:photo", $item['photo']);
459 XML::addElement($doc, $suggest, "dfrn:request", $item['request']);
460 XML::addElement($doc, $suggest, "dfrn:note", $item['note']);
462 $root->appendChild($suggest);
464 return trim($doc->saveXML());
468 * @brief Create XML text for DFRN relocations
470 * @param array $owner Owner record
471 * @param int $uid User ID
473 * @return string DFRN relocations
474 * @todo Find proper type-hints
476 public static function relocate($owner, $uid)
479 /* get site pubkey. this could be a new installation with no site keys*/
480 $pubkey = Config::get('system', 'site_pubkey');
482 $res = Crypto::newKeypair(1024);
483 Config::set('system', 'site_prvkey', $res['prvkey']);
484 Config::set('system', 'site_pubkey', $res['pubkey']);
488 "SELECT `resource-id` , `scale`, type FROM `photo`
489 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;",
493 $ext = Image::supportedTypes();
495 foreach ($rp as $p) {
496 $photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
500 $doc = new DOMDocument('1.0', 'utf-8');
501 $doc->formatOutput = true;
503 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
505 $relocate = $doc->createElement("dfrn:relocate");
507 XML::addElement($doc, $relocate, "dfrn:url", $owner['url']);
508 XML::addElement($doc, $relocate, "dfrn:name", $owner['name']);
509 XML::addElement($doc, $relocate, "dfrn:addr", $owner['addr']);
510 XML::addElement($doc, $relocate, "dfrn:avatar", $owner['avatar']);
511 XML::addElement($doc, $relocate, "dfrn:photo", $photos[4]);
512 XML::addElement($doc, $relocate, "dfrn:thumb", $photos[5]);
513 XML::addElement($doc, $relocate, "dfrn:micro", $photos[6]);
514 XML::addElement($doc, $relocate, "dfrn:request", $owner['request']);
515 XML::addElement($doc, $relocate, "dfrn:confirm", $owner['confirm']);
516 XML::addElement($doc, $relocate, "dfrn:notify", $owner['notify']);
517 XML::addElement($doc, $relocate, "dfrn:poll", $owner['poll']);
518 XML::addElement($doc, $relocate, "dfrn:sitepubkey", Config::get('system', 'site_pubkey'));
520 $root->appendChild($relocate);
522 return trim($doc->saveXML());
526 * @brief Adds the header elements for the DFRN protocol
528 * @param object $doc XML document
529 * @param array $owner Owner record
530 * @param string $authorelement Element name for the author
531 * @param string $alternatelink link to profile or category
532 * @param bool $public Is it a header for public posts?
534 * @return object XML root object
535 * @todo Find proper type-hints
537 private static function addHeader($doc, $owner, $authorelement, $alternatelink = "", $public = false)
540 if ($alternatelink == "") {
541 $alternatelink = $owner['url'];
544 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
545 $doc->appendChild($root);
547 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
548 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
549 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
550 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
551 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
552 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
553 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
554 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
555 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
557 XML::addElement($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
558 XML::addElement($doc, $root, "title", $owner["name"]);
560 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION];
561 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
563 $attributes = ["rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/"];
564 XML::addElement($doc, $root, "link", "", $attributes);
566 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $alternatelink];
567 XML::addElement($doc, $root, "link", "", $attributes);
571 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
572 OStatus::hublinks($doc, $root, $owner["nick"]);
574 $attributes = ["rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
575 XML::addElement($doc, $root, "link", "", $attributes);
577 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
578 XML::addElement($doc, $root, "link", "", $attributes);
580 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
581 XML::addElement($doc, $root, "link", "", $attributes);
584 // For backward compatibility we keep this element
585 if ($owner['page-flags'] == Contact::PAGE_COMMUNITY) {
586 XML::addElement($doc, $root, "dfrn:community", 1);
589 // The former element is replaced by this one
590 XML::addElement($doc, $root, "dfrn:account_type", $owner["account-type"]);
592 /// @todo We need a way to transmit the different page flags like "Contact::PAGE_PRVGROUP"
594 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
596 $author = self::addAuthor($doc, $owner, $authorelement, $public);
597 $root->appendChild($author);
603 * @brief Adds the author element in the header for the DFRN protocol
605 * @param object $doc XML document
606 * @param array $owner Owner record
607 * @param string $authorelement Element name for the author
608 * @param boolean $public boolean
610 * @return object XML author object
611 * @todo Find proper type-hints
613 private static function addAuthor($doc, $owner, $authorelement, $public)
615 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
617 "SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
618 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
619 intval($owner['uid'])
621 if (DBA::isResult($r)) {
627 $author = $doc->createElement($authorelement);
629 $namdate = DateTimeFormat::utc($owner['name-date'].'+00:00', DateTimeFormat::ATOM);
630 $uridate = DateTimeFormat::utc($owner['uri-date'].'+00:00', DateTimeFormat::ATOM);
631 $picdate = DateTimeFormat::utc($owner['avatar-date'].'+00:00', DateTimeFormat::ATOM);
635 if (!$public || !$hidewall) {
636 $attributes = ["dfrn:updated" => $namdate];
639 XML::addElement($doc, $author, "name", $owner["name"], $attributes);
640 XML::addElement($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
641 XML::addElement($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
643 $attributes = ["rel" => "photo", "type" => "image/jpeg",
644 "media:width" => 300, "media:height" => 300, "href" => $owner['photo']];
646 if (!$public || !$hidewall) {
647 $attributes["dfrn:updated"] = $picdate;
650 XML::addElement($doc, $author, "link", "", $attributes);
652 $attributes["rel"] = "avatar";
653 XML::addElement($doc, $author, "link", "", $attributes);
656 XML::addElement($doc, $author, "dfrn:hide", "true");
659 // The following fields will only be generated if the data isn't meant for a public feed
664 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
667 XML::addElement($doc, $author, "dfrn:birthday", $birthday);
670 // Only show contact details when we are allowed to
672 "SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
673 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
674 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
676 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
677 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
678 intval($owner['uid'])
680 if (DBA::isResult($r)) {
683 XML::addElement($doc, $author, "poco:displayName", $profile["name"]);
684 XML::addElement($doc, $author, "poco:updated", $namdate);
686 if (trim($profile["dob"]) > DBA::NULL_DATE) {
687 XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
690 XML::addElement($doc, $author, "poco:note", $profile["about"]);
691 XML::addElement($doc, $author, "poco:preferredUsername", $profile["nickname"]);
693 $savetz = date_default_timezone_get();
694 date_default_timezone_set($profile["timezone"]);
695 XML::addElement($doc, $author, "poco:utcOffset", date("P"));
696 date_default_timezone_set($savetz);
698 if (trim($profile["homepage"]) != "") {
699 $urls = $doc->createElement("poco:urls");
700 XML::addElement($doc, $urls, "poco:type", "homepage");
701 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
702 XML::addElement($doc, $urls, "poco:primary", "true");
703 $author->appendChild($urls);
706 if (trim($profile["pub_keywords"]) != "") {
707 $keywords = explode(",", $profile["pub_keywords"]);
709 foreach ($keywords as $keyword) {
710 XML::addElement($doc, $author, "poco:tags", trim($keyword));
714 if (trim($profile["xmpp"]) != "") {
715 $ims = $doc->createElement("poco:ims");
716 XML::addElement($doc, $ims, "poco:type", "xmpp");
717 XML::addElement($doc, $ims, "poco:value", $profile["xmpp"]);
718 XML::addElement($doc, $ims, "poco:primary", "true");
719 $author->appendChild($ims);
722 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
723 $element = $doc->createElement("poco:address");
725 XML::addElement($doc, $element, "poco:formatted", Profile::formatLocation($profile));
727 if (trim($profile["locality"]) != "") {
728 XML::addElement($doc, $element, "poco:locality", $profile["locality"]);
731 if (trim($profile["region"]) != "") {
732 XML::addElement($doc, $element, "poco:region", $profile["region"]);
735 if (trim($profile["country-name"]) != "") {
736 XML::addElement($doc, $element, "poco:country", $profile["country-name"]);
739 $author->appendChild($element);
747 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
749 * @param object $doc XML document
750 * @param string $element Element name for the author
751 * @param string $contact_url Link of the contact
752 * @param array $item Item elements
754 * @return object XML author object
755 * @todo Find proper type-hints
757 private static function addEntryAuthor($doc, $element, $contact_url, $item)
759 $contact = Contact::getDetailsByURL($contact_url, $item["uid"]);
761 $author = $doc->createElement($element);
762 XML::addElement($doc, $author, "name", $contact["name"]);
763 XML::addElement($doc, $author, "uri", $contact["url"]);
764 XML::addElement($doc, $author, "dfrn:handle", $contact["addr"]);
767 /// - Check real image type and image size
768 /// - Check which of these boths elements we should use
771 "type" => "image/jpeg",
773 "media:height" => 80,
774 "href" => $contact["photo"]];
775 XML::addElement($doc, $author, "link", "", $attributes);
779 "type" => "image/jpeg",
781 "media:height" => 80,
782 "href" => $contact["photo"]];
783 XML::addElement($doc, $author, "link", "", $attributes);
789 * @brief Adds the activity elements
791 * @param object $doc XML document
792 * @param string $element Element name for the activity
793 * @param string $activity activity value
795 * @return object XML activity object
796 * @todo Find proper type-hints
798 private static function createActivity($doc, $element, $activity)
801 $entry = $doc->createElement($element);
803 $r = XML::parseString($activity, false);
809 XML::addElement($doc, $entry, "activity:object-type", $r->type);
813 XML::addElement($doc, $entry, "id", $r->id);
817 XML::addElement($doc, $entry, "title", $r->title);
821 if (substr($r->link, 0, 1) == '<') {
822 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
823 $r->link = str_replace('&', '&', $r->link);
826 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
828 // XML does need a single element as root element so we add a dummy element here
829 $data = XML::parseString("<dummy>" . $r->link . "</dummy>", false);
830 if (is_object($data)) {
831 foreach ($data->link as $link) {
833 foreach ($link->attributes() as $parameter => $value) {
834 $attributes[$parameter] = $value;
836 XML::addElement($doc, $entry, "link", "", $attributes);
840 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
841 XML::addElement($doc, $entry, "link", "", $attributes);
845 XML::addElement($doc, $entry, "content", BBCode::convert($r->content), ["type" => "html"]);
855 * @brief Adds the elements for attachments
857 * @param object $doc XML document
858 * @param object $root XML root
859 * @param array $item Item element
861 * @return object XML attachment object
862 * @todo Find proper type-hints
864 private static function getAttachment($doc, $root, $item)
866 $arr = explode('[/attach],', $item['attach']);
868 foreach ($arr as $r) {
870 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
872 $attributes = ["rel" => "enclosure",
873 "href" => $matches[1],
874 "type" => $matches[3]];
876 if (intval($matches[2])) {
877 $attributes["length"] = intval($matches[2]);
880 if (trim($matches[4]) != "") {
881 $attributes["title"] = trim($matches[4]);
884 XML::addElement($doc, $root, "link", "", $attributes);
891 * @brief Adds the "entry" elements for the DFRN protocol
893 * @param object $doc XML document
894 * @param string $type "text" or "html"
895 * @param array $item Item element
896 * @param array $owner Owner record
897 * @param bool $comment Trigger the sending of the "comment" element
898 * @param int $cid Contact ID of the recipient
899 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
901 * @return object XML entry object
902 * @todo Find proper type-hints
904 private static function entry($doc, $type, array $item, array $owner, $comment = false, $cid = 0, $single = false)
908 if (!$item['parent']) {
912 if ($item['deleted']) {
913 $attributes = ["ref" => $item['uri'], "when" => DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM)];
914 return XML::createElement($doc, "at:deleted-entry", "", $attributes);
918 $entry = $doc->createElement("entry");
920 $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry');
921 $doc->appendChild($entry);
923 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
924 $entry->setAttribute("xmlns:at", NAMESPACE_TOMB);
925 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
926 $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
927 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
928 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
929 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
930 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
931 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
934 if ($item['private']) {
935 $body = Item::fixPrivatePhotos($item['body'], $owner['uid'], $item, $cid);
937 $body = $item['body'];
940 // Remove the abstract element. It is only locally important.
941 $body = BBCode::stripAbstract($body);
944 if ($type == 'html') {
947 if ($item['title'] != "") {
948 $htmlbody = "[b]" . $item['title'] . "[/b]\n\n" . $htmlbody;
951 $htmlbody = BBCode::convert($htmlbody, false, 7);
954 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
955 $entry->appendChild($author);
957 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
958 $entry->appendChild($dfrnowner);
960 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
961 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
962 $parent = Item::selectFirst(['guid', 'plink'], ['uri' => $parent_item, 'uid' => $item['uid']]);
963 $attributes = ["ref" => $parent_item, "type" => "text/html",
964 "href" => $parent['plink'],
965 "dfrn:diaspora_guid" => $parent['guid']];
966 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
969 // Add conversation data. This is used for OStatus
970 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
971 $conversation_uri = $conversation_href;
973 if (isset($parent_item)) {
974 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $item['parent-uri']]);
975 if (DBA::isResult($conversation)) {
976 if ($conversation['conversation-uri'] != '') {
977 $conversation_uri = $conversation['conversation-uri'];
979 if ($conversation['conversation-href'] != '') {
980 $conversation_href = $conversation['conversation-href'];
986 "href" => $conversation_href,
987 "ref" => $conversation_uri];
989 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
991 XML::addElement($doc, $entry, "id", $item["uri"]);
992 XML::addElement($doc, $entry, "title", $item["title"]);
994 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"] . "+00:00", DateTimeFormat::ATOM));
995 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"] . "+00:00", DateTimeFormat::ATOM));
997 // "dfrn:env" is used to read the content
998 XML::addElement($doc, $entry, "dfrn:env", Strings::base64UrlEncode($body, true));
1000 // The "content" field is not read by the receiver. We could remove it when the type is "text"
1001 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
1002 XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
1004 // We save this value in "plink". Maybe we should read it from there as well?
1010 ["rel" => "alternate", "type" => "text/html",
1011 "href" => System::baseUrl() . "/display/" . $item["guid"]]
1014 // "comment-allow" is some old fashioned stuff for old Friendica versions.
1015 // It is included in the rewritten code for completeness
1017 XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
1020 if ($item['location']) {
1021 XML::addElement($doc, $entry, "dfrn:location", $item['location']);
1024 if ($item['coord']) {
1025 XML::addElement($doc, $entry, "georss:point", $item['coord']);
1028 if ($item['private']) {
1029 XML::addElement($doc, $entry, "dfrn:private", ($item['private'] ? $item['private'] : 1));
1032 if ($item['extid']) {
1033 XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
1036 if ($item['post-type'] == Item::PT_PAGE) {
1037 XML::addElement($doc, $entry, "dfrn:bookmark", "true");
1041 XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
1044 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
1046 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
1047 // It is needed for relayed comments to Diaspora.
1048 if ($item['signed_text']) {
1049 $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer']]));
1050 XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
1053 XML::addElement($doc, $entry, "activity:verb", self::constructVerb($item));
1055 if ($item['object-type'] != "") {
1056 XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
1057 } elseif ($item['id'] == $item['parent']) {
1058 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1060 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
1063 $actobj = self::createActivity($doc, "activity:object", $item['object']);
1065 $entry->appendChild($actobj);
1068 $actarg = self::createActivity($doc, "activity:target", $item['target']);
1070 $entry->appendChild($actarg);
1073 $tags = Item::getFeedTags($item);
1075 /// @TODO Combine this with similar below if() block?
1077 foreach ($tags as $t) {
1078 if (($type != 'html') || ($t[0] != "@")) {
1079 XML::addElement($doc, $entry, "category", "", ["scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]]);
1085 foreach ($tags as $t) {
1087 $mentioned[$t[1]] = $t[1];
1092 foreach ($mentioned as $mention) {
1093 $condition = ['uid' => $owner["uid"], 'nurl' => Strings::normaliseLink($mention)];
1094 $contact = DBA::selectFirst('contact', ['forum', 'prv'], $condition);
1096 if (DBA::isResult($contact) && ($contact["forum"] || $contact["prv"])) {
1102 ["rel" => "mentioned",
1103 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1112 ["rel" => "mentioned",
1113 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1119 self::getAttachment($doc, $entry, $item);
1125 * @brief encrypts data via AES
1127 * @param string $data The data that is to be encrypted
1128 * @param string $key The AES key
1130 * @return string encrypted data
1132 private static function aesEncrypt($data, $key)
1134 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1138 * @brief decrypts data via AES
1140 * @param string $encrypted The encrypted data
1141 * @param string $key The AES key
1143 * @return string decrypted data
1145 public static function aesDecrypt($encrypted, $key)
1147 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1151 * @brief Delivers the atom content to the contacts
1153 * @param array $owner Owner record
1154 * @param array $contact Contact record of the receiver
1155 * @param string $atom Content that will be transmitted
1156 * @param bool $dissolve (to be documented)
1158 * @return int Deliver status. Negative values mean an error.
1159 * @todo Add array type-hint for $owner, $contact
1161 public static function deliver($owner, $contact, $atom, $dissolve = false, $legacy_transport = false)
1165 // At first try the Diaspora transport layer
1166 if (!$dissolve && !$legacy_transport) {
1167 $curlResult = self::transmit($owner, $contact, $atom);
1168 if ($curlResult >= 200) {
1169 Logger::log('Delivery via Diaspora transport layer was successful with status ' . $curlResult);
1174 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1176 if ($contact['duplex'] && $contact['dfrn-id']) {
1177 $idtosend = '0:' . $orig_id;
1179 if ($contact['duplex'] && $contact['issued-id']) {
1180 $idtosend = '1:' . $orig_id;
1183 $rino = Config::get('system', 'rino_encrypt');
1184 $rino = intval($rino);
1186 Logger::log("Local rino version: ". $rino, Logger::DEBUG);
1188 $ssl_val = intval(Config::get('system', 'ssl_policy'));
1192 case SSL_POLICY_FULL:
1193 $ssl_policy = 'full';
1195 case SSL_POLICY_SELFSIGN:
1196 $ssl_policy = 'self';
1198 case SSL_POLICY_NONE:
1200 $ssl_policy = 'none';
1204 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1206 Logger::log('dfrn_deliver: ' . $url);
1208 $curlResult = Network::curl($url);
1210 if ($curlResult->isTimeout()) {
1211 Contact::markForArchival($contact);
1212 return -2; // timed out
1215 $xml = $curlResult->getBody();
1217 $curl_stat = $curlResult->getReturnCode();
1218 if (empty($curl_stat)) {
1219 Contact::markForArchival($contact);
1220 return -3; // timed out
1223 Logger::log('dfrn_deliver: ' . $xml, Logger::DATA);
1226 Contact::markForArchival($contact);
1230 if (strpos($xml, '<?xml') === false) {
1231 Logger::log('dfrn_deliver: no valid XML returned');
1232 Logger::log('dfrn_deliver: returned XML: ' . $xml, Logger::DATA);
1233 Contact::markForArchival($contact);
1237 $res = XML::parseString($xml);
1239 if (!is_object($res) || (intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
1240 Contact::markForArchival($contact);
1242 if (empty($res->status)) {
1245 $status = $res->status;
1252 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1253 $challenge = hex2bin((string) $res->challenge);
1254 $perm = (($res->perm) ? $res->perm : null);
1255 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1256 $rino_remote_version = intval($res->rino);
1257 $page = (($owner['page-flags'] == Contact::PAGE_COMMUNITY) ? 1 : 0);
1259 Logger::log("Remote rino version: ".$rino_remote_version." for ".$contact["url"], Logger::DEBUG);
1261 if ($owner['page-flags'] == Contact::PAGE_PRVGROUP) {
1265 $final_dfrn_id = '';
1268 if ((($perm == 'rw') && !intval($contact['writable']))
1269 || (($perm == 'r') && intval($contact['writable']))
1271 DBA::update('contact', ['writable' => ($perm == 'rw')], ['id' => $contact['id']]);
1273 $contact['writable'] = (string) 1 - intval($contact['writable']);
1277 if (($contact['duplex'] && strlen($contact['pubkey']))
1278 || ($owner['page-flags'] == Contact::PAGE_COMMUNITY && strlen($contact['pubkey']))
1279 || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
1281 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
1282 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
1284 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
1285 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
1288 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1290 if (strpos($final_dfrn_id, ':') == 1) {
1291 $final_dfrn_id = substr($final_dfrn_id, 2);
1294 if ($final_dfrn_id != $orig_id) {
1295 Logger::log('dfrn_deliver: wrong dfrn_id.');
1296 // did not decode properly - cannot trust this site
1297 Contact::markForArchival($contact);
1301 $postvars['dfrn_id'] = $idtosend;
1302 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1304 $postvars['dissolve'] = '1';
1307 if ((($contact['rel']) && ($contact['rel'] != Contact::SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == Contact::PAGE_COMMUNITY)) {
1308 $postvars['data'] = $atom;
1309 $postvars['perm'] = 'rw';
1311 $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
1312 $postvars['perm'] = 'r';
1315 $postvars['ssl_policy'] = $ssl_policy;
1318 $postvars['page'] = $page;
1322 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1323 Logger::log('rino version: '. $rino_remote_version);
1325 switch ($rino_remote_version) {
1327 $key = openssl_random_pseudo_bytes(16);
1328 $data = self::aesEncrypt($postvars['data'], $key);
1332 Logger::log("rino: invalid requested version '$rino_remote_version'");
1333 Contact::markForArchival($contact);
1337 $postvars['rino'] = $rino_remote_version;
1338 $postvars['data'] = bin2hex($data);
1340 if ($dfrn_version >= 2.1) {
1341 if (($contact['duplex'] && strlen($contact['pubkey']))
1342 || ($owner['page-flags'] == Contact::PAGE_COMMUNITY && strlen($contact['pubkey']))
1343 || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
1345 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1347 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1350 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == Contact::PAGE_COMMUNITY)) {
1351 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1353 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1357 Logger::log('md5 rawkey ' . md5($postvars['key']));
1359 $postvars['key'] = bin2hex($postvars['key']);
1363 Logger::log('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), Logger::DATA);
1365 $postResult = Network::post($contact['notify'], $postvars);
1367 $xml = $postResult->getBody();
1369 Logger::log('dfrn_deliver: ' . "RECEIVED: " . $xml, Logger::DATA);
1371 $curl_stat = $postResult->getReturnCode();
1372 if (empty($curl_stat) || empty($xml)) {
1373 Contact::markForArchival($contact);
1374 return -9; // timed out
1377 if (($curl_stat == 503) && stristr($postResult->getHeader(), 'retry-after')) {
1378 Contact::markForArchival($contact);
1382 if (strpos($xml, '<?xml') === false) {
1383 Logger::log('dfrn_deliver: phase 2: no valid XML returned');
1384 Logger::log('dfrn_deliver: phase 2: returned XML: ' . $xml, Logger::DATA);
1385 Contact::markForArchival($contact);
1389 $res = XML::parseString($xml);
1391 if (!isset($res->status)) {
1392 Contact::markForArchival($contact);
1396 // Possibly old servers had returned an empty value when everything was okay
1397 if (empty($res->status)) {
1401 if (!empty($res->message)) {
1402 Logger::log('Delivery returned status '.$res->status.' - '.$res->message, Logger::DEBUG);
1405 if (($res->status >= 200) && ($res->status <= 299)) {
1406 Contact::unmarkForArchival($contact);
1409 return intval($res->status);
1413 * @brief Transmits atom content to the contacts via the Diaspora transport layer
1415 * @param array $owner Owner record
1416 * @param array $contact Contact record of the receiver
1417 * @param string $atom Content that will be transmitted
1419 * @return int Deliver status. Negative values mean an error.
1421 public static function transmit($owner, $contact, $atom, $public_batch = false)
1425 if (!$public_batch) {
1426 if (empty($contact['addr'])) {
1427 Logger::log('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.');
1428 if (Contact::updateFromProbe($contact['id'])) {
1429 $new_contact = DBA::selectFirst('contact', ['addr'], ['id' => $contact['id']]);
1430 $contact['addr'] = $new_contact['addr'];
1433 if (empty($contact['addr'])) {
1434 Logger::log('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
1435 Contact::markForArchival($contact);
1440 $fcontact = Diaspora::personByHandle($contact['addr']);
1441 if (empty($fcontact)) {
1442 Logger::log('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
1443 Contact::markForArchival($contact);
1446 $pubkey = $fcontact['pubkey'];
1451 $envelope = Diaspora::buildMessage($atom, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
1453 // Create the endpoint for public posts. This is some WIP and should later be added to the probing
1454 if ($public_batch && empty($contact["batch"])) {
1455 $parts = parse_url($contact["notify"]);
1456 $path_parts = explode('/', $parts['path']);
1457 array_pop($path_parts);
1458 $parts['path'] = implode('/', $path_parts);
1459 $contact["batch"] = Network::unparseURL($parts);
1462 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
1464 $content_type = ($public_batch ? "application/magic-envelope+xml" : "application/json");
1466 $postResult = Network::post($dest_url, $envelope, ["Content-Type: ".$content_type]);
1467 $xml = $postResult->getBody();
1469 $curl_stat = $postResult->getReturnCode();
1470 if (empty($curl_stat) || empty($xml)) {
1471 Logger::log('Empty answer from ' . $contact['id'] . ' - ' . $dest_url);
1472 Contact::markForArchival($contact);
1473 return -9; // timed out
1476 if (($curl_stat == 503) && (stristr($postResult->getHeader(), 'retry-after'))) {
1477 Contact::markForArchival($contact);
1481 if (strpos($xml, '<?xml') === false) {
1482 Logger::log('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url);
1483 Logger::log('Returned XML: ' . $xml, Logger::DATA);
1484 Contact::markForArchival($contact);
1488 $res = XML::parseString($xml);
1490 if (empty($res->status)) {
1491 Contact::markForArchival($contact);
1495 if (!empty($res->message)) {
1496 Logger::log('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message, Logger::DEBUG);
1499 if (($res->status >= 200) && ($res->status <= 299)) {
1500 Contact::unmarkForArchival($contact);
1503 return intval($res->status);
1507 * @brief Fetch the author data from head or entry items
1509 * @param object $xpath XPath object
1510 * @param object $context In which context should the data be searched
1511 * @param array $importer Record of the importer user mixed with contact of the content
1512 * @param string $element Element name from which the data is fetched
1513 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1514 * @param string $xml optional, default empty
1516 * @return array Relevant data of the author
1517 * @todo Find good type-hints for all parameter
1519 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
1522 $author["name"] = XML::getFirstNodeValue($xpath, $element."/atom:name/text()", $context);
1523 $author["link"] = XML::getFirstNodeValue($xpath, $element."/atom:uri/text()", $context);
1525 $fields = ['id', 'uid', 'url', 'network', 'avatar-date', 'avatar', 'name-date', 'uri-date', 'addr',
1526 'name', 'nick', 'about', 'location', 'keywords', 'xmpp', 'bdyear', 'bd', 'hidden', 'contact-type'];
1527 $condition = ["`uid` = ? AND `nurl` = ? AND `network` != ?",
1528 $importer["importer_uid"], Strings::normaliseLink($author["link"]), Protocol::STATUSNET];
1529 $contact_old = DBA::selectFirst('contact', $fields, $condition);
1531 if (DBA::isResult($contact_old)) {
1532 $author["contact-id"] = $contact_old["id"];
1533 $author["network"] = $contact_old["network"];
1536 Logger::log("Contact ".$author["link"]." wasn't found for user ".$importer["importer_uid"]." XML: ".$xml, Logger::DEBUG);
1539 $author["contact-unknown"] = true;
1540 $author["contact-id"] = $importer["id"];
1541 $author["network"] = $importer["network"];
1545 // Until now we aren't serving different sizes - but maybe later
1547 /// @todo check if "avatar" or "photo" would be the best field in the specification
1548 $avatars = $xpath->query($element . "/atom:link[@rel='avatar']", $context);
1549 foreach ($avatars as $avatar) {
1552 foreach ($avatar->attributes as $attributes) {
1553 /// @TODO Rewrite these similar if() to one switch
1554 if ($attributes->name == "href") {
1555 $href = $attributes->textContent;
1557 if ($attributes->name == "width") {
1558 $width = $attributes->textContent;
1560 if ($attributes->name == "updated") {
1561 $author["avatar-date"] = $attributes->textContent;
1564 if (($width > 0) && ($href != "")) {
1565 $avatarlist[$width] = $href;
1569 if (count($avatarlist) > 0) {
1570 krsort($avatarlist);
1571 $author["avatar"] = current($avatarlist);
1574 if (empty($author['avatar']) && !empty($author['link'])) {
1575 $cid = Contact::getIdForURL($author['link'], 0);
1577 $contact = DBA::selectFirst('contact', ['avatar'], ['id' => $cid]);
1578 if (DBA::isResult($contact)) {
1579 $author['avatar'] = $contact['avatar'];
1584 if (empty($author['avatar'])) {
1585 Logger::log('Empty author: ' . $xml);
1588 if (DBA::isResult($contact_old) && !$onlyfetch) {
1589 Logger::log("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", Logger::DEBUG);
1591 $poco = ["url" => $contact_old["url"]];
1593 // When was the last change to name or uri?
1594 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1595 foreach ($name_element->attributes as $attributes) {
1596 if ($attributes->name == "updated") {
1597 $poco["name-date"] = $attributes->textContent;
1601 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1602 foreach ($link_element->attributes as $attributes) {
1603 if ($attributes->name == "updated") {
1604 $poco["uri-date"] = $attributes->textContent;
1608 // Update contact data
1609 $value = XML::getFirstNodeValue($xpath, $element . "/dfrn:handle/text()", $context);
1611 $poco["addr"] = $value;
1614 $value = XML::getFirstNodeValue($xpath, $element . "/poco:displayName/text()", $context);
1616 $poco["name"] = $value;
1619 $value = XML::getFirstNodeValue($xpath, $element . "/poco:preferredUsername/text()", $context);
1621 $poco["nick"] = $value;
1624 $value = XML::getFirstNodeValue($xpath, $element . "/poco:note/text()", $context);
1626 $poco["about"] = $value;
1629 $value = XML::getFirstNodeValue($xpath, $element . "/poco:address/poco:formatted/text()", $context);
1631 $poco["location"] = $value;
1634 /// @todo Only search for elements with "poco:type" = "xmpp"
1635 $value = XML::getFirstNodeValue($xpath, $element . "/poco:ims/poco:value/text()", $context);
1637 $poco["xmpp"] = $value;
1640 /// @todo Add support for the following fields that we don't support by now in the contact table:
1641 /// - poco:utcOffset
1647 // If the "hide" element is present then the profile isn't searchable.
1648 $hide = intval(XML::getFirstNodeValue($xpath, $element . "/dfrn:hide/text()", $context) == "true");
1650 Logger::log("Hidden status for contact " . $contact_old["url"] . ": " . $hide, Logger::DEBUG);
1652 // If the contact isn't searchable then set the contact to "hidden".
1653 // Problem: This can be manually overridden by the user.
1655 $contact_old["hidden"] = true;
1658 // Save the keywords into the contact table
1660 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1661 foreach ($tagelements as $tag) {
1662 $tags[$tag->nodeValue] = $tag->nodeValue;
1666 $poco["keywords"] = implode(", ", $tags);
1669 // "dfrn:birthday" contains the birthday converted to UTC
1670 $birthday = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1672 if (strtotime($birthday) > time()) {
1673 $bd_timestamp = strtotime($birthday);
1675 $poco["bdyear"] = date("Y", $bd_timestamp);
1678 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1679 $value = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1681 if (!in_array($value, ["", "0000-00-00", DBA::NULL_DATE])) {
1682 $bdyear = date("Y");
1683 $value = str_replace(["0000", "0001"], $bdyear, $value);
1685 if (strtotime($value) < time()) {
1686 $value = str_replace($bdyear, $bdyear + 1, $value);
1687 $bdyear = $bdyear + 1;
1690 $poco["bd"] = $value;
1693 $contact = array_merge($contact_old, $poco);
1695 if ($contact_old["bdyear"] != $contact["bdyear"]) {
1696 Event::createBirthday($contact, $birthday);
1699 // Get all field names
1701 foreach ($contact_old as $field => $data) {
1702 $fields[$field] = $data;
1705 unset($fields["id"]);
1706 unset($fields["uid"]);
1707 unset($fields["url"]);
1708 unset($fields["avatar-date"]);
1709 unset($fields["avatar"]);
1710 unset($fields["name-date"]);
1711 unset($fields["uri-date"]);
1714 // Update check for this field has to be done differently
1715 $datefields = ["name-date", "uri-date"];
1716 foreach ($datefields as $field) {
1717 // The date fields arrives as '2018-07-17T10:44:45Z' - the database return '2018-07-17 10:44:45'
1718 // The fields have to be in the same format to be comparable, since strtotime does add timezones.
1719 $contact[$field] = DateTimeFormat::utc($contact[$field]);
1721 if (strtotime($contact[$field]) > strtotime($contact_old[$field])) {
1722 Logger::log("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", Logger::DEBUG);
1727 foreach ($fields as $field => $data) {
1728 if ($contact[$field] != $contact_old[$field]) {
1729 Logger::log("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", Logger::DEBUG);
1735 Logger::log("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", Logger::DEBUG);
1738 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1739 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1740 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1741 WHERE `id` = %d AND `network` = '%s'",
1742 DBA::escape($contact["name"]), DBA::escape($contact["nick"]), DBA::escape($contact["about"]), DBA::escape($contact["location"]),
1743 DBA::escape($contact["addr"]), DBA::escape($contact["keywords"]), DBA::escape($contact["bdyear"]),
1744 DBA::escape($contact["bd"]), intval($contact["hidden"]), DBA::escape($contact["xmpp"]),
1745 DBA::escape(DateTimeFormat::utc($contact["name-date"])), DBA::escape(DateTimeFormat::utc($contact["uri-date"])),
1746 intval($contact["id"]), DBA::escape($contact["network"])
1750 Contact::updateAvatar(
1752 $importer['importer_uid'],
1754 (strtotime($contact['avatar-date']) > strtotime($contact_old['avatar-date']) || ($author['avatar'] != $contact_old['avatar']))
1758 * The generation is a sign for the reliability of the provided data.
1759 * It is used in the socgraph.php to prevent that old contact data
1760 * that was relayed over several servers can overwrite contact
1761 * data that we received directly.
1764 $poco["generation"] = 2;
1765 $poco["photo"] = $author["avatar"];
1766 $poco["hide"] = $hide;
1767 $poco["contact-type"] = $contact["contact-type"];
1768 $gcid = GContact::update($poco);
1770 GContact::link($gcid, $importer["importer_uid"], $contact["id"]);
1777 * @brief Transforms activity objects into an XML string
1779 * @param object $xpath XPath object
1780 * @param object $activity Activity object
1781 * @param string $element element name
1783 * @return string XML string
1784 * @todo Find good type-hints for all parameter
1786 private static function transformActivity($xpath, $activity, $element)
1788 if (!is_object($activity)) {
1792 $obj_doc = new DOMDocument("1.0", "utf-8");
1793 $obj_doc->formatOutput = true;
1795 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1797 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1798 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1800 $id = $xpath->query("atom:id", $activity)->item(0);
1801 if (is_object($id)) {
1802 $obj_element->appendChild($obj_doc->importNode($id, true));
1805 $title = $xpath->query("atom:title", $activity)->item(0);
1806 if (is_object($title)) {
1807 $obj_element->appendChild($obj_doc->importNode($title, true));
1810 $links = $xpath->query("atom:link", $activity);
1811 if (is_object($links)) {
1812 foreach ($links as $link) {
1813 $obj_element->appendChild($obj_doc->importNode($link, true));
1817 $content = $xpath->query("atom:content", $activity)->item(0);
1818 if (is_object($content)) {
1819 $obj_element->appendChild($obj_doc->importNode($content, true));
1822 $obj_doc->appendChild($obj_element);
1824 $objxml = $obj_doc->saveXML($obj_element);
1826 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1827 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1832 * @brief Processes the mail elements
1834 * @param object $xpath XPath object
1835 * @param object $mail mail elements
1836 * @param array $importer Record of the importer user mixed with contact of the content
1838 * @todo Find good type-hints for all parameter
1840 private static function processMail($xpath, $mail, $importer)
1842 Logger::log("Processing mails");
1844 /// @TODO Rewrite this to one statement
1846 $msg["uid"] = $importer["importer_uid"];
1847 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1848 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1849 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1850 $msg["contact-id"] = $importer["id"];
1851 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1852 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1853 $msg["created"] = DateTimeFormat::utc($xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue);
1854 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1855 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1857 $msg["replied"] = 0;
1859 DBA::insert('mail', $msg);
1861 $msg["id"] = DBA::lastInsertId();
1863 // send notifications.
1864 /// @TODO Arange this mess
1866 "type" => NOTIFY_MAIL,
1867 "notify_flags" => $importer["notify-flags"],
1868 "language" => $importer["language"],
1869 "to_name" => $importer["username"],
1870 "to_email" => $importer["email"],
1871 "uid" => $importer["importer_uid"],
1873 "parent" => $msg["parent-uri"],
1874 "source_name" => $msg["from-name"],
1875 "source_link" => $importer["url"],
1876 "source_photo" => $importer["thumb"],
1877 "verb" => ACTIVITY_POST,
1881 notification($notif_params);
1883 Logger::log("Mail is processed, notification was sent.");
1887 * @brief Processes the suggestion elements
1889 * @param object $xpath XPath object
1890 * @param object $suggestion suggestion elements
1891 * @param array $importer Record of the importer user mixed with contact of the content
1893 * @todo Find good type-hints for all parameter
1895 private static function processSuggestion($xpath, $suggestion, $importer)
1899 Logger::log("Processing suggestions");
1901 /// @TODO Rewrite this to one statement
1903 $suggest["uid"] = $importer["importer_uid"];
1904 $suggest["cid"] = $importer["id"];
1905 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1906 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1907 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1908 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1909 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1911 // Does our member already have a friend matching this description?
1914 * The valid result means the friend we're about to send a friend
1915 * suggestion already has them in their contact, which means no further
1916 * action is required.
1918 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1920 $condition = ['name' => $suggest["name"], 'nurl' => Strings::normaliseLink($suggest["url"]),
1921 'uid' => $suggest["uid"]];
1922 if (DBA::exists('contact', $condition)) {
1926 // Do we already have an fcontact record for this person?
1929 $condition = ['url' => $suggest["url"], 'name' => $suggest["name"], 'request' => $suggest["request"]];
1930 $fcontact = DBA::selectFirst('fcontact', ['id'], $condition);
1931 if (DBA::isResult($fcontact)) {
1932 $fid = $fcontact["id"];
1934 // OK, we do. Do we already have an introduction for this person?
1935 if (DBA::exists('intro', ['uid' => $suggest["uid"], 'fid' => $fid])) {
1937 * The valid result means the friend we're about to send a friend
1938 * suggestion already has them in their contact, which means no further
1939 * action is required.
1941 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1948 "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1949 DBA::escape($suggest["name"]),
1950 DBA::escape($suggest["url"]),
1951 DBA::escape($suggest["photo"]),
1952 DBA::escape($suggest["request"])
1956 $condition = ['url' => $suggest["url"], 'name' => $suggest["name"], 'request' => $suggest["request"]];
1957 $fcontact = DBA::selectFirst('fcontact', ['id'], $condition);
1960 * If no record in fcontact is found, below INSERT statement will not
1961 * link an introduction to it.
1963 if (!DBA::isResult($fcontact)) {
1964 // Database record did not get created. Quietly give up.
1970 $hash = Strings::getRandomHex();
1973 "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1974 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1975 intval($suggest["uid"]),
1977 intval($suggest["cid"]),
1978 DBA::escape($suggest["body"]),
1980 DBA::escape(DateTimeFormat::utcNow()),
1986 "type" => NOTIFY_SUGGEST,
1987 "notify_flags" => $importer["notify-flags"],
1988 "language" => $importer["language"],
1989 "to_name" => $importer["username"],
1990 "to_email" => $importer["email"],
1991 "uid" => $importer["importer_uid"],
1993 "link" => System::baseUrl()."/notifications/intros",
1994 "source_name" => $importer["name"],
1995 "source_link" => $importer["url"],
1996 "source_photo" => $importer["photo"],
1997 "verb" => ACTIVITY_REQ_FRIEND,
2005 * @brief Processes the relocation elements
2007 * @param object $xpath XPath object
2008 * @param object $relocation relocation elements
2009 * @param array $importer Record of the importer user mixed with contact of the content
2011 * @todo Find good type-hints for all parameter
2013 private static function processRelocation($xpath, $relocation, $importer)
2015 Logger::log("Processing relocations");
2017 /// @TODO Rewrite this to one statement
2019 $relocate["uid"] = $importer["importer_uid"];
2020 $relocate["cid"] = $importer["id"];
2021 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
2022 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
2023 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
2024 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
2025 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
2026 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
2027 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
2028 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
2029 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
2030 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
2031 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
2032 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
2034 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
2035 $relocate["avatar"] = $relocate["photo"];
2038 if ($relocate["addr"] == "") {
2039 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
2044 "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d",
2045 intval($importer["id"]),
2046 intval($importer["importer_uid"])
2049 if (!DBA::isResult($r)) {
2050 Logger::log("Query failed to execute, no result returned in " . __FUNCTION__);
2056 // Update the gcontact entry
2057 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
2059 $fields = ['name' => $relocate["name"], 'photo' => $relocate["avatar"],
2060 'url' => $relocate["url"], 'nurl' => Strings::normaliseLink($relocate["url"]),
2061 'addr' => $relocate["addr"], 'connect' => $relocate["addr"],
2062 'notify' => $relocate["notify"], 'server_url' => $relocate["server_url"]];
2063 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($old["url"])]);
2065 // Update the contact table. We try to find every entry.
2066 $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
2067 'url' => $relocate["url"], 'nurl' => Strings::normaliseLink($relocate["url"]),
2068 'addr' => $relocate["addr"], 'request' => $relocate["request"],
2069 'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
2070 'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
2071 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], Strings::normaliseLink($old["url"])];
2073 DBA::update('contact', $fields, $condition);
2075 Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
2077 Logger::log('Contacts are updated.');
2080 /// merge with current record, current contents have priority
2081 /// update record, set url-updated
2082 /// update profile photos
2083 /// schedule a scan?
2088 * @brief Updates an item
2090 * @param array $current the current item record
2091 * @param array $item the new item record
2092 * @param array $importer Record of the importer user mixed with contact of the content
2093 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2095 * @todo set proper type-hints (array?)
2097 private static function updateContent($current, $item, $importer, $entrytype)
2101 if (self::isEditedTimestampNewer($current, $item)) {
2102 // do not accept (ignore) an earlier edit than one we currently have.
2103 if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
2107 $fields = ['title' => defaults($item, 'title', ''), 'body' => defaults($item, 'body', ''),
2108 'tag' => defaults($item, 'tag', ''), 'changed' => DateTimeFormat::utcNow(),
2109 'edited' => DateTimeFormat::utc($item["edited"])];
2111 $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
2112 Item::update($fields, $condition);
2120 * @brief Detects the entry type of the item
2122 * @param array $importer Record of the importer user mixed with contact of the content
2123 * @param array $item the new item record
2125 * @return int Is it a toplevel entry, a comment or a relayed comment?
2126 * @todo set proper type-hints (array?)
2128 private static function getEntryType($importer, $item)
2130 if ($item["parent-uri"] != $item["uri"]) {
2133 if ($importer["page-flags"] == Contact::PAGE_COMMUNITY || $importer["page-flags"] == Contact::PAGE_PRVGROUP) {
2136 Logger::log("possible community action");
2138 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2141 // was the top-level post for this action written by somebody on this site?
2142 // Specifically, the recipient?
2144 $is_a_remote_action = false;
2146 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item["parent-uri"]]);
2147 if (DBA::isResult($parent)) {
2149 "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2150 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2151 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2152 AND `item`.`uid` = %d
2155 DBA::escape($parent["parent-uri"]),
2156 DBA::escape($parent["parent-uri"]),
2157 DBA::escape($parent["parent-uri"]),
2158 intval($importer["importer_uid"])
2160 if (DBA::isResult($r)) {
2161 $is_a_remote_action = true;
2166 * Does this have the characteristics of a community or private group action?
2167 * If it's an action to a wall post on a community/prvgroup page it's a
2168 * valid community action. Also forum_mode makes it valid for sure.
2169 * If neither, it's not.
2171 if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2172 $is_a_remote_action = false;
2173 Logger::log("not a community action");
2176 if ($is_a_remote_action) {
2177 return DFRN::REPLY_RC;
2182 return DFRN::TOP_LEVEL;
2187 * @brief Send a "poke"
2189 * @param array $item the new item record
2190 * @param array $importer Record of the importer user mixed with contact of the content
2191 * @param int $posted_id The record number of item record that was just posted
2193 * @todo set proper type-hints (array?)
2195 private static function doPoke($item, $importer, $posted_id)
2197 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2201 $xo = XML::parseString($item["object"], false);
2203 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2204 // somebody was poked/prodded. Was it me?
2205 foreach ($xo->link as $l) {
2206 $atts = $l->attributes();
2207 switch ($atts["rel"]) {
2209 $Blink = $atts["href"];
2216 if ($Blink && Strings::compareLink($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2217 $author = DBA::selectFirst('contact', ['name', 'thumb', 'url'], ['id' => $item['author-id']]);
2219 $item['id'] = $posted_id;
2221 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => $importer["importer_uid"]]);
2222 $item["parent"] = $parent['id'];
2224 // send a notification
2227 "type" => NOTIFY_POKE,
2228 "notify_flags" => $importer["notify-flags"],
2229 "language" => $importer["language"],
2230 "to_name" => $importer["username"],
2231 "to_email" => $importer["email"],
2232 "uid" => $importer["importer_uid"],
2234 "link" => System::baseUrl()."/display/".urlencode(Item::getGuidById($posted_id)),
2235 "source_name" => $author["name"],
2236 "source_link" => $author["url"],
2237 "source_photo" => $author["thumb"],
2238 "verb" => $item["verb"],
2239 "otype" => "person",
2240 "activity" => $verb,
2241 "parent" => $item["parent"]]
2248 * @brief Processes several actions, depending on the verb
2250 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2251 * @param array $importer Record of the importer user mixed with contact of the content
2252 * @param array $item the new item record
2253 * @param bool $is_like Is the verb a "like"?
2255 * @return bool Should the processing of the entries be continued?
2256 * @todo set proper type-hints (array?)
2258 private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2260 Logger::log("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, Logger::DEBUG);
2262 if (($entrytype == DFRN::TOP_LEVEL)) {
2263 // The filling of the the "contact" variable is done for legcy reasons
2264 // The functions below are partly used by ostatus.php as well - where we have this variable
2265 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2267 $nickname = $contact["nick"];
2269 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2270 // This function once was responsible for DFRN and OStatus.
2271 if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2272 Logger::log("New follower");
2273 Contact::addRelationship($importer, $contact, $item, $nickname);
2276 if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2277 Logger::log("Lost follower");
2278 Contact::removeFollower($importer, $contact, $item);
2281 if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2282 Logger::log("New friend request");
2283 Contact::addRelationship($importer, $contact, $item, $nickname, true);
2286 if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2287 Logger::log("Lost sharer");
2288 Contact::removeSharer($importer, $contact, $item);
2292 if (($item["verb"] == ACTIVITY_LIKE)
2293 || ($item["verb"] == ACTIVITY_DISLIKE)
2294 || ($item["verb"] == ACTIVITY_ATTEND)
2295 || ($item["verb"] == ACTIVITY_ATTENDNO)
2296 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
2299 $item["gravity"] = GRAVITY_ACTIVITY;
2300 // only one like or dislike per person
2301 // splitted into two queries for performance issues
2302 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2303 'verb' => $item["verb"], 'parent-uri' => $item["parent-uri"]];
2304 if (Item::exists($condition)) {
2308 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2309 'verb' => $item["verb"], 'thr-parent' => $item["parent-uri"]];
2310 if (Item::exists($condition)) {
2314 // The owner of an activity must be the author
2315 $item["owner-name"] = $item["author-name"];
2316 $item["owner-link"] = $item["author-link"];
2317 $item["owner-avatar"] = $item["author-avatar"];
2318 $item["owner-id"] = $item["author-id"];
2323 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2324 $xo = XML::parseString($item["object"], false);
2325 $xt = XML::parseString($item["target"], false);
2327 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2328 $item_tag = Item::selectFirst(['id', 'tag'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]);
2330 if (!DBA::isResult($item_tag)) {
2331 Logger::log("Query failed to execute, no result returned in " . __FUNCTION__);
2335 // extract tag, if not duplicate, add to parent item
2337 if (!stristr($item_tag["tag"], trim($xo->content))) {
2338 $tag = $item_tag["tag"] . (strlen($item_tag["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2339 Item::update(['tag' => $tag], ['id' => $item_tag["id"]]);
2349 * @brief Processes the link elements
2351 * @param object $links link elements
2352 * @param array $item the item record
2354 * @todo set proper type-hints
2356 private static function parseLinks($links, &$item)
2363 foreach ($links as $link) {
2364 foreach ($link->attributes as $attributes) {
2365 switch ($attributes->name) {
2366 case "href" : $href = $attributes->textContent; break;
2367 case "rel" : $rel = $attributes->textContent; break;
2368 case "type" : $type = $attributes->textContent; break;
2369 case "length": $length = $attributes->textContent; break;
2370 case "title" : $title = $attributes->textContent; break;
2373 if (($rel != "") && ($href != "")) {
2376 $item["plink"] = $href;
2381 if (!empty($item["attach"])) {
2382 $item["attach"] .= ",";
2384 $item["attach"] = "";
2387 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2395 * @brief Processes the entry elements which contain the items and comments
2397 * @param array $header Array of the header elements that always stay the same
2398 * @param object $xpath XPath object
2399 * @param object $entry entry elements
2400 * @param array $importer Record of the importer user mixed with contact of the content
2401 * @param object $xml xml
2403 * @todo Add type-hints
2405 private static function processEntry($header, $xpath, $entry, $importer, $xml)
2407 Logger::log("Processing entries");
2411 $item["protocol"] = Conversation::PARCEL_DFRN;
2413 $item["source"] = $xml;
2416 $item["uri"] = XML::getFirstNodeValue($xpath, "atom:id/text()", $entry);
2418 $item["edited"] = XML::getFirstNodeValue($xpath, "atom:updated/text()", $entry);
2420 $current = Item::selectFirst(['id', 'uid', 'edited', 'body'],
2421 ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
2423 // Is there an existing item?
2424 if (DBA::isResult($current) && !self::isEditedTimestampNewer($current, $item)) {
2425 Logger::log("Item ".$item["uri"]." (".$item['edited'].") already existed.", Logger::DEBUG);
2430 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true, $xml);
2432 $owner_unknown = (isset($owner["contact-unknown"]) && $owner["contact-unknown"]);
2434 $item["owner-name"] = $owner["name"];
2435 $item["owner-link"] = $owner["link"];
2436 $item["owner-avatar"] = $owner["avatar"];
2437 $item["owner-id"] = Contact::getIdForURL($owner["link"], 0);
2440 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true, $xml);
2442 $item["author-name"] = $author["name"];
2443 $item["author-link"] = $author["link"];
2444 $item["author-avatar"] = $author["avatar"];
2445 $item["author-id"] = Contact::getIdForURL($author["link"], 0);
2447 $item["title"] = XML::getFirstNodeValue($xpath, "atom:title/text()", $entry);
2449 $item["created"] = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2451 $item["body"] = XML::getFirstNodeValue($xpath, "dfrn:env/text()", $entry);
2452 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2453 // make sure nobody is trying to sneak some html tags by us
2454 $item["body"] = Strings::escapeTags(Strings::base64UrlDecode($item["body"]));
2456 $item["body"] = BBCode::limitBodySize($item["body"]);
2458 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2459 if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
2460 $base_url = get_app()->getBaseURL();
2461 $item['body'] = HTML::relToAbs($item['body'], $base_url);
2463 $item['body'] = HTML::toBBCodeVideo($item['body']);
2465 $item['body'] = OEmbed::HTML2BBCode($item['body']);
2467 $config = HTMLPurifier_Config::createDefault();
2468 $config->set('Cache.DefinitionImpl', null);
2470 // we shouldn't need a whitelist, because the bbcode converter
2471 // will strip out any unsupported tags.
2473 $purifier = new HTMLPurifier($config);
2474 $item['body'] = $purifier->purify($item['body']);
2476 $item['body'] = @HTML::toBBCode($item['body']);
2479 /// @todo We should check for a repeated post and if we know the repeated author.
2481 // We don't need the content element since "dfrn:env" is always present
2482 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2484 $item["location"] = XML::getFirstNodeValue($xpath, "dfrn:location/text()", $entry);
2486 $item["coord"] = XML::getFirstNodeValue($xpath, "georss:point", $entry);
2488 $item["private"] = XML::getFirstNodeValue($xpath, "dfrn:private/text()", $entry);
2490 $item["extid"] = XML::getFirstNodeValue($xpath, "dfrn:extid/text()", $entry);
2492 if (XML::getFirstNodeValue($xpath, "dfrn:bookmark/text()", $entry) == "true") {
2493 $item["post-type"] = Item::PT_PAGE;
2496 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2497 if ($notice_info && ($notice_info->length > 0)) {
2498 foreach ($notice_info->item(0)->attributes as $attributes) {
2499 if ($attributes->name == "source") {
2500 $item["app"] = strip_tags($attributes->textContent);
2505 $item["guid"] = XML::getFirstNodeValue($xpath, "dfrn:diaspora_guid/text()", $entry);
2507 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
2508 $dsprsig = XML::unescape(XML::getFirstNodeValue($xpath, "dfrn:diaspora_signature/text()", $entry));
2509 if ($dsprsig != "") {
2510 $item["dsprsig"] = $dsprsig;
2513 $item["verb"] = XML::getFirstNodeValue($xpath, "activity:verb/text()", $entry);
2515 if (XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry) != "") {
2516 $item["object-type"] = XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry);
2519 $object = $xpath->query("activity:object", $entry)->item(0);
2520 $item["object"] = self::transformActivity($xpath, $object, "object");
2522 if (trim($item["object"]) != "") {
2523 $r = XML::parseString($item["object"], false);
2524 if (isset($r->type)) {
2525 $item["object-type"] = $r->type;
2529 $target = $xpath->query("activity:target", $entry)->item(0);
2530 $item["target"] = self::transformActivity($xpath, $target, "target");
2532 $categories = $xpath->query("atom:category", $entry);
2534 foreach ($categories as $category) {
2537 foreach ($category->attributes as $attributes) {
2538 if ($attributes->name == "term") {
2539 $term = $attributes->textContent;
2542 if ($attributes->name == "scheme") {
2543 $scheme = $attributes->textContent;
2547 if (($term != "") && ($scheme != "")) {
2548 $parts = explode(":", $scheme);
2549 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2550 $termhash = array_shift($parts);
2551 $termurl = implode(":", $parts);
2553 if (!empty($item["tag"])) {
2554 $item["tag"] .= ",";
2559 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2567 $links = $xpath->query("atom:link", $entry);
2569 self::parseLinks($links, $item);
2572 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
2574 $conv = $xpath->query('ostatus:conversation', $entry);
2575 if (is_object($conv->item(0))) {
2576 foreach ($conv->item(0)->attributes as $attributes) {
2577 if ($attributes->name == "ref") {
2578 $item['conversation-uri'] = $attributes->textContent;
2580 if ($attributes->name == "href") {
2581 $item['conversation-href'] = $attributes->textContent;
2586 // Is it a reply or a top level posting?
2587 $item["parent-uri"] = $item["uri"];
2589 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2590 if (is_object($inreplyto->item(0))) {
2591 foreach ($inreplyto->item(0)->attributes as $attributes) {
2592 if ($attributes->name == "ref") {
2593 $item["parent-uri"] = $attributes->textContent;
2598 // Get the type of the item (Top level post, reply or remote reply)
2599 $entrytype = self::getEntryType($importer, $item);
2601 // Now assign the rest of the values that depend on the type of the message
2602 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2603 if (!isset($item["object-type"])) {
2604 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2607 if ($item["contact-id"] != $owner["contact-id"]) {
2608 $item["contact-id"] = $owner["contact-id"];
2611 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2612 $item["network"] = $owner["network"];
2615 if ($item["contact-id"] != $author["contact-id"]) {
2616 $item["contact-id"] = $author["contact-id"];
2619 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2620 $item["network"] = $author["network"];
2624 if ($entrytype == DFRN::REPLY_RC) {
2626 } elseif ($entrytype == DFRN::TOP_LEVEL) {
2627 if (!isset($item["object-type"])) {
2628 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2632 if (($item["object-type"] == ACTIVITY_OBJ_EVENT) && !$owner_unknown) {
2633 Logger::log("Item ".$item["uri"]." seems to contain an event.", Logger::DEBUG);
2634 $ev = Event::fromBBCode($item["body"]);
2635 if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
2636 Logger::log("Event in item ".$item["uri"]." was found.", Logger::DEBUG);
2637 $ev["cid"] = $importer["id"];
2638 $ev["uid"] = $importer["importer_uid"];
2639 $ev["uri"] = $item["uri"];
2640 $ev["edited"] = $item["edited"];
2641 $ev["private"] = $item["private"];
2642 $ev["guid"] = $item["guid"];
2643 $ev["plink"] = $item["plink"];
2645 $condition = ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]];
2646 $event = DBA::selectFirst('event', ['id'], $condition);
2647 if (DBA::isResult($event)) {
2648 $ev["id"] = $event["id"];
2651 $event_id = Event::store($ev);
2652 Logger::log("Event ".$event_id." was stored", Logger::DEBUG);
2658 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2659 Logger::log("Exiting because 'processVerbs' told us so", Logger::DEBUG);
2663 // This check is done here to be able to receive connection requests in "processVerbs"
2664 if (($entrytype == DFRN::TOP_LEVEL) && $owner_unknown) {
2665 Logger::log("Item won't be stored because user " . $importer["importer_uid"] . " doesn't follow " . $item["owner-link"] . ".", Logger::DEBUG);
2670 // Update content if 'updated' changes
2671 if (DBA::isResult($current)) {
2672 if (self::updateContent($current, $item, $importer, $entrytype)) {
2673 Logger::log("Item ".$item["uri"]." was updated.", Logger::DEBUG);
2675 Logger::log("Item " . $item["uri"] . " already existed.", Logger::DEBUG);
2680 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2681 $posted_id = Item::insert($item);
2685 Logger::log("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, Logger::DEBUG);
2687 if ($item['uid'] == 0) {
2688 Item::distribute($posted_id);
2693 } else { // $entrytype == DFRN::TOP_LEVEL
2694 if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
2695 Logger::log("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", Logger::DEBUG);
2698 if (!Strings::compareLink($item["owner-link"], $importer["url"])) {
2700 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2701 * but otherwise there's a possible data mixup on the sender's system.
2702 * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2703 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2705 Logger::log('Correcting item owner.', Logger::DEBUG);
2706 $item["owner-link"] = $importer["url"];
2707 $item["owner-id"] = Contact::getIdForURL($importer["url"], 0);
2710 if (($importer["rel"] == Contact::FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2711 Logger::log("Contact ".$importer["id"]." is only follower and tgroup check was negative.", Logger::DEBUG);
2715 // This is my contact on another system, but it's really me.
2716 // Turn this into a wall post.
2717 $notify = Item::isRemoteSelf($importer, $item);
2719 $posted_id = Item::insert($item, false, $notify);
2722 $posted_id = $notify;
2725 Logger::log("Item was stored with id ".$posted_id, Logger::DEBUG);
2727 if ($item['uid'] == 0) {
2728 Item::distribute($posted_id);
2731 if (stristr($item["verb"], ACTIVITY_POKE)) {
2732 self::doPoke($item, $importer, $posted_id);
2738 * @brief Deletes items
2740 * @param object $xpath XPath object
2741 * @param object $deletion deletion elements
2742 * @param array $importer Record of the importer user mixed with contact of the content
2744 * @todo set proper type-hints
2746 private static function processDeletion($xpath, $deletion, $importer)
2748 Logger::log("Processing deletions");
2751 foreach ($deletion->attributes as $attributes) {
2752 if ($attributes->name == "ref") {
2753 $uri = $attributes->textContent;
2757 if (!$uri || !$importer["id"]) {
2761 $condition = ['uri' => $uri, 'uid' => $importer["importer_uid"]];
2762 $item = Item::selectFirst(['id', 'parent', 'contact-id', 'file', 'deleted'], $condition);
2763 if (!DBA::isResult($item)) {
2764 Logger::log("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", Logger::DEBUG);
2768 if (strstr($item['file'], '[')) {
2769 Logger::log("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " is filed. So it won't be deleted.", Logger::DEBUG);
2773 // When it is a starting post it has to belong to the person that wants to delete it
2774 if (($item['id'] == $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2775 Logger::log("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", Logger::DEBUG);
2779 // Comments can be deleted by the thread owner or comment owner
2780 if (($item['id'] != $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2781 $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2782 if (!Item::exists($condition)) {
2783 Logger::log("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", Logger::DEBUG);
2788 if ($item["deleted"]) {
2792 Logger::log('deleting item '.$item['id'].' uri='.$uri, Logger::DEBUG);
2794 Item::delete(['id' => $item['id']]);
2798 * @brief Imports a DFRN message
2800 * @param string $xml The DFRN message
2801 * @param array $importer Record of the importer user mixed with contact of the content
2802 * @param bool $sort_by_date Is used when feeds are polled
2803 * @return integer Import status
2804 * @todo set proper type-hints
2806 public static function import($xml, $importer, $sort_by_date = false)
2812 $doc = new DOMDocument();
2813 @$doc->loadXML($xml);
2815 $xpath = new DOMXPath($doc);
2816 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2817 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2818 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2819 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2820 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2821 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2822 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2823 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2824 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2825 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2828 $header["uid"] = $importer["importer_uid"];
2829 $header["network"] = Protocol::DFRN;
2830 $header["wall"] = 0;
2831 $header["origin"] = 0;
2832 $header["contact-id"] = $importer["id"];
2834 // Update the contact table if the data has changed
2836 // The "atom:author" is only present in feeds
2837 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2838 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2841 // Only the "dfrn:owner" in the head section contains all data
2842 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2843 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2846 Logger::log("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], Logger::DEBUG);
2848 // is it a public forum? Private forums aren't exposed with this method
2849 $forum = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:community/text()"));
2851 // The account type is new since 3.5.1
2852 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2853 $accounttype = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:account_type/text()"));
2855 if ($accounttype != $importer["contact-type"]) {
2856 DBA::update('contact', ['contact-type' => $accounttype], ['id' => $importer["id"]]);
2858 // A forum contact can either have set "forum" or "prv" - but not both
2859 if (($accounttype == Contact::ACCOUNT_TYPE_COMMUNITY) && (($forum != $importer["forum"]) || ($forum == $importer["prv"]))) {
2860 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer["id"]];
2861 DBA::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2863 } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
2864 $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2865 DBA::update('contact', ['forum' => $forum], $condition);
2869 // We are processing relocations even if we are ignoring a contact
2870 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2871 foreach ($relocations as $relocation) {
2872 self::processRelocation($xpath, $relocation, $importer);
2875 if (($importer["uid"] != 0) && !$importer["readonly"]) {
2876 $mails = $xpath->query("/atom:feed/dfrn:mail");
2877 foreach ($mails as $mail) {
2878 self::processMail($xpath, $mail, $importer);
2881 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2882 foreach ($suggestions as $suggestion) {
2883 self::processSuggestion($xpath, $suggestion, $importer);
2887 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2888 foreach ($deletions as $deletion) {
2889 self::processDeletion($xpath, $deletion, $importer);
2892 if (!$sort_by_date) {
2893 $entries = $xpath->query("/atom:feed/atom:entry");
2894 foreach ($entries as $entry) {
2895 self::processEntry($header, $xpath, $entry, $importer, $xml);
2899 $entries = $xpath->query("/atom:feed/atom:entry");
2900 foreach ($entries as $entry) {
2901 $created = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2902 $newentries[strtotime($created)] = $entry;
2905 // Now sort after the publishing date
2908 foreach ($newentries as $entry) {
2909 self::processEntry($header, $xpath, $entry, $importer, $xml);
2912 Logger::log("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], Logger::DEBUG);
2918 * @param string $contact_nick contact nickname
2920 public static function autoRedir(App $a, $contact_nick)
2923 if (!empty($_REQUEST['redir'])) {
2927 if ((! $contact_nick) || ($contact_nick === $a->user['nickname'])) {
2932 // We need to find out if $contact_nick is a user on this hub, and if so, if I
2933 // am a contact of that user. However, that user may have other contacts with the
2934 // same nickname as me on other hubs or other networks. Exclude these by requiring
2935 // that the contact have a local URL. I will be the only person with my nickname at
2936 // this URL, so if a result is found, then I am a contact of the $contact_nick user.
2938 // We also have to make sure that I'm a legitimate contact--I'm not blocked or pending.
2940 $baseurl = System::baseUrl();
2941 $domain_st = strpos($baseurl, "://");
2942 if ($domain_st === false) {
2945 $baseurl = substr($baseurl, $domain_st + 3);
2946 $nurl = Strings::normaliseLink($baseurl);
2948 /// @todo Why is there a query for "url" *and* "nurl"? Especially this normalising is strange.
2949 $r = q("SELECT `id` FROM `contact` WHERE `uid` = (SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1)
2950 AND `nick` = '%s' AND NOT `self` AND (`url` LIKE '%%%s%%' OR `nurl` LIKE '%%%s%%') AND NOT `blocked` AND NOT `pending` LIMIT 1",
2951 DBA::escape($contact_nick),
2952 DBA::escape($a->user['nickname']),
2953 DBA::escape($baseurl),
2956 if ((! DBA::isResult($r)) || $r[0]['id'] == remote_user()) {
2960 $r = q("SELECT * FROM contact WHERE nick = '%s'
2961 AND network = '%s' AND uid = %d AND url LIKE '%%%s%%' LIMIT 1",
2962 DBA::escape($contact_nick),
2963 DBA::escape(Protocol::DFRN),
2964 intval(local_user()),
2965 DBA::escape($baseurl)
2967 if (! DBA::isResult($r)) {
2973 $dfrn_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2975 if ($r[0]['duplex'] && $r[0]['issued-id']) {
2976 $orig_id = $r[0]['issued-id'];
2977 $dfrn_id = '1:' . $orig_id;
2979 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
2980 $orig_id = $r[0]['dfrn-id'];
2981 $dfrn_id = '0:' . $orig_id;
2984 // ensure that we've got a valid ID. There may be some edge cases with forums and non-duplex mode
2985 // that may have triggered some of the "went to {profile/intro} and got an RSS feed" issues
2987 if (strlen($dfrn_id) < 3) {
2991 $sec = Strings::getRandomHex();
2993 DBA::insert('profile_check', ['uid' => local_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id, 'sec' => $sec, 'expire' => time() + 45]);
2995 $url = curPageURL();
2997 Logger::log('auto_redir: ' . $r[0]['name'] . ' ' . $sec, Logger::DEBUG);
2998 $dest = (($url) ? '&destination_url=' . $url : '');
2999 System::externalRedirect($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
3000 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest);
3007 * @brief Returns the activity verb
3009 * @param array $item Item array
3011 * @return string activity verb
3013 private static function constructVerb(array $item)
3015 if ($item['verb']) {
3016 return $item['verb'];
3018 return ACTIVITY_POST;
3021 private static function tgroupCheck($uid, $item)
3025 // check that the message originated elsewhere and is a top-level post
3027 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['parent-uri'])) {
3031 $user = DBA::selectFirst('user', ['page-flags', 'nickname'], ['uid' => $uid]);
3032 if (!DBA::isResult($user)) {
3036 $community_page = ($user['page-flags'] == Contact::PAGE_COMMUNITY);
3037 $prvgroup = ($user['page-flags'] == Contact::PAGE_PRVGROUP);
3039 $link = Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']);
3042 * Diaspora uses their own hardwired link URL in @-tags
3043 * instead of the one we supply with webfinger
3045 $dlink = Strings::normaliseLink(System::baseUrl() . '/u/' . $user['nickname']);
3047 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
3049 foreach ($matches as $mtch) {
3050 if (Strings::compareLink($link, $mtch[1]) || Strings::compareLink($dlink, $mtch[1])) {
3052 Logger::log('mention found: ' . $mtch[2]);
3061 return $community_page || $prvgroup;
3065 * This function returns true if $update has an edited timestamp newer
3066 * than $existing, i.e. $update contains new data which should override
3067 * what's already there. If there is no timestamp yet, the update is
3068 * assumed to be newer. If the update has no timestamp, the existing
3069 * item is assumed to be up-to-date. If the timestamps are equal it
3070 * assumes the update has been seen before and should be ignored.
3073 private static function isEditedTimestampNewer($existing, $update)
3075 if (empty($existing['edited'])) {
3078 if (empty($update['edited'])) {
3082 $existing_edited = DateTimeFormat::utc($existing['edited']);
3083 $update_edited = DateTimeFormat::utc($update['edited']);
3085 return (strcmp($existing_edited, $update_edited) < 0);