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\App\BaseURL;
15 use Friendica\Content\OEmbed;
16 use Friendica\Content\Text\BBCode;
17 use Friendica\Content\Text\HTML;
18 use Friendica\Core\Config;
19 use Friendica\Core\Hook;
20 use Friendica\Core\Logger;
21 use Friendica\Core\Protocol;
22 use Friendica\Core\System;
23 use Friendica\Core\Session;
24 use Friendica\Database\DBA;
25 use Friendica\Model\Contact;
26 use Friendica\Model\Conversation;
27 use Friendica\Model\Event;
28 use Friendica\Model\GContact;
29 use Friendica\Model\Item;
30 use Friendica\Model\Mail;
31 use Friendica\Model\PermissionSet;
32 use Friendica\Model\Profile;
33 use Friendica\Model\User;
34 use Friendica\Network\Probe;
35 use Friendica\Object\Image;
36 use Friendica\Util\Crypto;
37 use Friendica\Util\DateTimeFormat;
38 use Friendica\Util\Network;
39 use Friendica\Util\Strings;
40 use Friendica\Util\XML;
42 use HTMLPurifier_Config;
45 * @brief This class contain functions to create and send DFRN XML files
50 const TOP_LEVEL = 0; // Top level posting
51 const REPLY = 1; // Regular reply that is stored locally
52 const REPLY_RC = 2; // Reply that will be relayed
55 * @brief Generates an array of contact and user for DFRN imports
57 * This array contains not only the receiver but also the sender of the message.
59 * @param integer $cid Contact id
60 * @param integer $uid User id
62 * @return array importer
65 public static function getImporter($cid, $uid = 0)
67 $condition = ['id' => $cid, 'blocked' => false, 'pending' => false];
68 $contact = DBA::selectFirst('contact', [], $condition);
69 if (!DBA::isResult($contact)) {
73 $contact['cpubkey'] = $contact['pubkey'];
74 $contact['cprvkey'] = $contact['prvkey'];
75 $contact['senderName'] = $contact['name'];
78 $condition = ['uid' => $uid, 'account_expired' => false, 'account_removed' => false];
79 $user = DBA::selectFirst('user', [], $condition);
80 if (!DBA::isResult($user)) {
84 $user['importer_uid'] = $user['uid'];
85 $user['uprvkey'] = $user['prvkey'];
87 $user = ['importer_uid' => 0, 'uprvkey' => '', 'timezone' => 'UTC',
88 'nickname' => '', 'sprvkey' => '', 'spubkey' => '',
89 'page-flags' => 0, 'account-type' => 0, 'prvnets' => 0];
92 return array_merge($contact, $user);
96 * @brief Generates the atom entries for delivery.php
98 * This function is used whenever content is transmitted via DFRN.
100 * @param array $items Item elements
101 * @param array $owner Owner record
103 * @return string DFRN entries
104 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
105 * @throws \ImagickException
106 * @todo Find proper type-hints
108 public static function entries($items, $owner)
110 $doc = new DOMDocument('1.0', 'utf-8');
111 $doc->formatOutput = true;
113 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
115 if (! count($items)) {
116 return trim($doc->saveXML());
119 foreach ($items as $item) {
120 // These values aren't sent when sending from the queue.
121 /// @todo Check if we can set these values from the queue or if they are needed at all.
122 $item["entry:comment-allow"] = defaults($item, "entry:comment-allow", true);
123 $item["entry:cid"] = defaults($item, "entry:cid", 0);
125 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
127 $root->appendChild($entry);
131 return trim($doc->saveXML());
135 * @brief Generate an atom feed for the given user
137 * This function is called when another server is pulling data from the user feed.
139 * @param string $dfrn_id DFRN ID from the requesting party
140 * @param string $owner_nick Owner nick name
141 * @param string $last_update Date of the last update
142 * @param int $direction Can be -1, 0 or 1.
143 * @param boolean $onlyheader Output only the header without content? (Default is "no")
145 * @return string DFRN feed entries
146 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
147 * @throws \ImagickException
149 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false)
153 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
154 $public_feed = (($dfrn_id) ? false : true);
155 $starred = false; // not yet implemented, possible security issues
158 if ($public_feed && $a->argc > 2) {
159 for ($x = 2; $x < $a->argc; $x++) {
160 if ($a->argv[$x] == 'converse') {
163 if ($a->argv[$x] == 'starred') {
166 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
167 $category = $a->argv[$x+1];
172 // default permissions - anonymous user
174 $sql_extra = " AND NOT `item`.`private` ";
177 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
178 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
179 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
180 DBA::escape($owner_nick)
183 if (! DBA::isResult($r)) {
184 Logger::log(sprintf('No contact found for nickname=%d', $owner_nick), Logger::WARNING);
189 $owner_id = $owner['uid'];
191 $sql_post_table = "";
193 if (! $public_feed) {
194 switch ($direction) {
196 $sql_extra = sprintf(" AND `issued-id` = '%s' ", DBA::escape($dfrn_id));
199 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
202 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
210 "SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
214 if (! DBA::isResult($r)) {
215 Logger::log(sprintf('No contact found for uid=%d', $owner_id), Logger::WARNING);
221 $set = PermissionSet::get($owner_id, $contact['id']);
224 $sql_extra = " AND `item`.`psid` IN (" . implode(',', $set) .")";
226 $sql_extra = " AND NOT `item`.`private`";
236 if (! strlen($last_update)) {
237 $last_update = 'now -30 days';
240 if (isset($category)) {
241 $sql_post_table = sprintf(
242 "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` ",
243 DBA::escape(Strings::protectSprintf($category)),
244 intval(TERM_OBJ_POST),
245 intval(TERM_CATEGORY),
250 if ($public_feed && ! $converse) {
251 $sql_extra .= " AND `contact`.`self` = 1 ";
254 $check_date = DateTimeFormat::utc($last_update);
258 FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
259 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
260 WHERE `item`.`uid` = %d AND `item`.`wall` AND `item`.`changed` > '%s'
261 AND `item`.`visible` $sql_extra
262 ORDER BY `item`.`parent` ".$sort.", `item`.`received` ASC LIMIT 0, 300",
264 DBA::escape($check_date),
269 foreach ($r as $item) {
270 $ids[] = $item['id'];
274 $ret = Item::select(Item::DELIVER_FIELDLIST, ['id' => $ids]);
275 $items = Item::inArray($ret);
281 * Will check further below if this actually returned results.
282 * We will provide an empty feed if that is the case.
285 $doc = new DOMDocument('1.0', 'utf-8');
286 $doc->formatOutput = true;
288 $alternatelink = $owner['url'];
290 if (isset($category)) {
291 $alternatelink .= "/category/".$category;
295 $author = "dfrn:owner";
300 $root = self::addHeader($doc, $owner, $author, $alternatelink, true);
302 /// @TODO This hook can't work anymore
303 // \Friendica\Core\Hook::callAll('atom_feed', $atom);
305 if (!DBA::isResult($items) || $onlyheader) {
306 $atom = trim($doc->saveXML());
308 Hook::callAll('atom_feed_end', $atom);
313 foreach ($items as $item) {
314 // prevent private email from leaking.
315 if ($item['network'] == Protocol::MAIL) {
319 // public feeds get html, our own nodes use bbcode
323 // catch any email that's in a public conversation and make sure it doesn't leak
324 if ($item['private']) {
331 $entry = self::entry($doc, $type, $item, $owner, true);
333 $root->appendChild($entry);
337 $atom = trim($doc->saveXML());
339 Hook::callAll('atom_feed_end', $atom);
345 * @brief Generate an atom entry for a given item id
347 * @param int $item_id The item id
348 * @param boolean $conversation Show the conversation. If false show the single post.
350 * @return string DFRN feed entry
351 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
352 * @throws \ImagickException
354 public static function itemFeed($item_id, $conversation = false)
357 $condition = ['parent' => $item_id];
359 $condition = ['id' => $item_id];
362 $ret = Item::select(Item::DELIVER_FIELDLIST, $condition);
363 $items = Item::inArray($ret);
364 if (!DBA::isResult($items)) {
370 if ($item['uid'] != 0) {
371 $owner = User::getOwnerDataById($item['uid']);
376 $owner = ['uid' => 0, 'nick' => 'feed-item'];
379 $doc = new DOMDocument('1.0', 'utf-8');
380 $doc->formatOutput = true;
384 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
385 $doc->appendChild($root);
387 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
388 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
389 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
390 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
391 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
392 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
393 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
394 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
395 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
397 //$root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
399 foreach ($items as $item) {
400 $entry = self::entry($doc, $type, $item, $owner, true, 0);
402 $root->appendChild($entry);
406 self::entry($doc, $type, $item, $owner, true, 0, true);
409 $atom = trim($doc->saveXML());
414 * @brief Create XML text for DFRN mails
416 * @param array $item message elements
417 * @param array $owner Owner record
419 * @return string DFRN mail
420 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
421 * @todo Find proper type-hints
423 public static function mail($item, $owner)
425 $doc = new DOMDocument('1.0', 'utf-8');
426 $doc->formatOutput = true;
428 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
430 $mail = $doc->createElement("dfrn:mail");
431 $sender = $doc->createElement("dfrn:sender");
433 XML::addElement($doc, $sender, "dfrn:name", $owner['name']);
434 XML::addElement($doc, $sender, "dfrn:uri", $owner['url']);
435 XML::addElement($doc, $sender, "dfrn:avatar", $owner['thumb']);
437 $mail->appendChild($sender);
439 XML::addElement($doc, $mail, "dfrn:id", $item['uri']);
440 XML::addElement($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
441 XML::addElement($doc, $mail, "dfrn:sentdate", DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
442 XML::addElement($doc, $mail, "dfrn:subject", $item['title']);
443 XML::addElement($doc, $mail, "dfrn:content", $item['body']);
445 $root->appendChild($mail);
447 return trim($doc->saveXML());
451 * @brief Create XML text for DFRN friend suggestions
453 * @param array $item suggestion elements
454 * @param array $owner Owner record
456 * @return string DFRN suggestions
457 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
458 * @todo Find proper type-hints
460 public static function fsuggest($item, $owner)
462 $doc = new DOMDocument('1.0', 'utf-8');
463 $doc->formatOutput = true;
465 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
467 $suggest = $doc->createElement("dfrn:suggest");
469 XML::addElement($doc, $suggest, "dfrn:url", $item['url']);
470 XML::addElement($doc, $suggest, "dfrn:name", $item['name']);
471 XML::addElement($doc, $suggest, "dfrn:photo", $item['photo']);
472 XML::addElement($doc, $suggest, "dfrn:request", $item['request']);
473 XML::addElement($doc, $suggest, "dfrn:note", $item['note']);
475 $root->appendChild($suggest);
477 return trim($doc->saveXML());
481 * @brief Create XML text for DFRN relocations
483 * @param array $owner Owner record
484 * @param int $uid User ID
486 * @return string DFRN relocations
487 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
488 * @todo Find proper type-hints
490 public static function relocate($owner, $uid)
493 /* get site pubkey. this could be a new installation with no site keys*/
494 $pubkey = Config::get('system', 'site_pubkey');
496 $res = Crypto::newKeypair(1024);
497 Config::set('system', 'site_prvkey', $res['prvkey']);
498 Config::set('system', 'site_pubkey', $res['pubkey']);
502 "SELECT `resource-id` , `scale`, type FROM `photo`
503 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;",
507 $ext = Image::supportedTypes();
509 foreach ($rp as $p) {
510 $photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
514 $doc = new DOMDocument('1.0', 'utf-8');
515 $doc->formatOutput = true;
517 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
519 $relocate = $doc->createElement("dfrn:relocate");
521 XML::addElement($doc, $relocate, "dfrn:url", $owner['url']);
522 XML::addElement($doc, $relocate, "dfrn:name", $owner['name']);
523 XML::addElement($doc, $relocate, "dfrn:addr", $owner['addr']);
524 XML::addElement($doc, $relocate, "dfrn:avatar", $owner['avatar']);
525 XML::addElement($doc, $relocate, "dfrn:photo", $photos[4]);
526 XML::addElement($doc, $relocate, "dfrn:thumb", $photos[5]);
527 XML::addElement($doc, $relocate, "dfrn:micro", $photos[6]);
528 XML::addElement($doc, $relocate, "dfrn:request", $owner['request']);
529 XML::addElement($doc, $relocate, "dfrn:confirm", $owner['confirm']);
530 XML::addElement($doc, $relocate, "dfrn:notify", $owner['notify']);
531 XML::addElement($doc, $relocate, "dfrn:poll", $owner['poll']);
532 XML::addElement($doc, $relocate, "dfrn:sitepubkey", Config::get('system', 'site_pubkey'));
534 $root->appendChild($relocate);
536 return trim($doc->saveXML());
540 * @brief Adds the header elements for the DFRN protocol
542 * @param DOMDocument $doc XML document
543 * @param array $owner Owner record
544 * @param string $authorelement Element name for the author
545 * @param string $alternatelink link to profile or category
546 * @param bool $public Is it a header for public posts?
548 * @return object XML root object
549 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
550 * @todo Find proper type-hints
552 private static function addHeader(DOMDocument $doc, $owner, $authorelement, $alternatelink = "", $public = false)
555 if ($alternatelink == "") {
556 $alternatelink = $owner['url'];
559 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
560 $doc->appendChild($root);
562 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
563 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
564 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
565 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
566 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
567 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
568 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
569 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
570 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
572 XML::addElement($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
573 XML::addElement($doc, $root, "title", $owner["name"]);
575 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION];
576 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
578 $attributes = ["rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/"];
579 XML::addElement($doc, $root, "link", "", $attributes);
581 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $alternatelink];
582 XML::addElement($doc, $root, "link", "", $attributes);
586 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
587 OStatus::hublinks($doc, $root, $owner["nick"]);
589 $attributes = ["rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
590 XML::addElement($doc, $root, "link", "", $attributes);
592 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
593 XML::addElement($doc, $root, "link", "", $attributes);
595 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
596 XML::addElement($doc, $root, "link", "", $attributes);
599 // For backward compatibility we keep this element
600 if ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY) {
601 XML::addElement($doc, $root, "dfrn:community", 1);
604 // The former element is replaced by this one
605 XML::addElement($doc, $root, "dfrn:account_type", $owner["account-type"]);
607 /// @todo We need a way to transmit the different page flags like "User::PAGE_FLAGS_PRVGROUP"
609 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
611 $author = self::addAuthor($doc, $owner, $authorelement, $public);
612 $root->appendChild($author);
618 * @brief Adds the author element in the header for the DFRN protocol
620 * @param DOMDocument $doc XML document
621 * @param array $owner Owner record
622 * @param string $authorelement Element name for the author
623 * @param boolean $public boolean
625 * @return \DOMElement XML author object
626 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
627 * @todo Find proper type-hints
629 private static function addAuthor(DOMDocument $doc, array $owner, $authorelement, $public)
631 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
633 "SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
634 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
635 intval($owner['uid'])
637 if (DBA::isResult($r)) {
643 $author = $doc->createElement($authorelement);
645 $namdate = DateTimeFormat::utc($owner['name-date'].'+00:00', DateTimeFormat::ATOM);
646 $uridate = DateTimeFormat::utc($owner['uri-date'].'+00:00', DateTimeFormat::ATOM);
647 $picdate = DateTimeFormat::utc($owner['avatar-date'].'+00:00', DateTimeFormat::ATOM);
651 if (!$public || !$hidewall) {
652 $attributes = ["dfrn:updated" => $namdate];
655 XML::addElement($doc, $author, "name", $owner["name"], $attributes);
656 XML::addElement($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
657 XML::addElement($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
659 $attributes = ["rel" => "photo", "type" => "image/jpeg",
660 "media:width" => 300, "media:height" => 300, "href" => $owner['photo']];
662 if (!$public || !$hidewall) {
663 $attributes["dfrn:updated"] = $picdate;
666 XML::addElement($doc, $author, "link", "", $attributes);
668 $attributes["rel"] = "avatar";
669 XML::addElement($doc, $author, "link", "", $attributes);
672 XML::addElement($doc, $author, "dfrn:hide", "true");
675 // The following fields will only be generated if the data isn't meant for a public feed
680 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
683 XML::addElement($doc, $author, "dfrn:birthday", $birthday);
686 // Only show contact details when we are allowed to
688 "SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
689 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
690 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
692 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
693 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
694 intval($owner['uid'])
696 if (DBA::isResult($r)) {
699 XML::addElement($doc, $author, "poco:displayName", $profile["name"]);
700 XML::addElement($doc, $author, "poco:updated", $namdate);
702 if (trim($profile["dob"]) > DBA::NULL_DATE) {
703 XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
706 XML::addElement($doc, $author, "poco:note", $profile["about"]);
707 XML::addElement($doc, $author, "poco:preferredUsername", $profile["nickname"]);
709 $savetz = date_default_timezone_get();
710 date_default_timezone_set($profile["timezone"]);
711 XML::addElement($doc, $author, "poco:utcOffset", date("P"));
712 date_default_timezone_set($savetz);
714 if (trim($profile["homepage"]) != "") {
715 $urls = $doc->createElement("poco:urls");
716 XML::addElement($doc, $urls, "poco:type", "homepage");
717 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
718 XML::addElement($doc, $urls, "poco:primary", "true");
719 $author->appendChild($urls);
722 if (trim($profile["pub_keywords"]) != "") {
723 $keywords = explode(",", $profile["pub_keywords"]);
725 foreach ($keywords as $keyword) {
726 XML::addElement($doc, $author, "poco:tags", trim($keyword));
730 if (trim($profile["xmpp"]) != "") {
731 $ims = $doc->createElement("poco:ims");
732 XML::addElement($doc, $ims, "poco:type", "xmpp");
733 XML::addElement($doc, $ims, "poco:value", $profile["xmpp"]);
734 XML::addElement($doc, $ims, "poco:primary", "true");
735 $author->appendChild($ims);
738 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
739 $element = $doc->createElement("poco:address");
741 XML::addElement($doc, $element, "poco:formatted", Profile::formatLocation($profile));
743 if (trim($profile["locality"]) != "") {
744 XML::addElement($doc, $element, "poco:locality", $profile["locality"]);
747 if (trim($profile["region"]) != "") {
748 XML::addElement($doc, $element, "poco:region", $profile["region"]);
751 if (trim($profile["country-name"]) != "") {
752 XML::addElement($doc, $element, "poco:country", $profile["country-name"]);
755 $author->appendChild($element);
763 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
765 * @param DOMDocument $doc XML document
766 * @param string $element Element name for the author
767 * @param string $contact_url Link of the contact
768 * @param array $item Item elements
770 * @return \DOMElement XML author object
771 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
772 * @todo Find proper type-hints
774 private static function addEntryAuthor(DOMDocument $doc, $element, $contact_url, $item)
776 $author = $doc->createElement($element);
778 $contact = Contact::getDetailsByURL($contact_url, $item["uid"]);
779 if (!empty($contact)) {
780 XML::addElement($doc, $author, "name", $contact["name"]);
781 XML::addElement($doc, $author, "uri", $contact["url"]);
782 XML::addElement($doc, $author, "dfrn:handle", $contact["addr"]);
785 /// - Check real image type and image size
786 /// - Check which of these boths elements we should use
789 "type" => "image/jpeg",
791 "media:height" => 80,
792 "href" => $contact["photo"]];
793 XML::addElement($doc, $author, "link", "", $attributes);
797 "type" => "image/jpeg",
799 "media:height" => 80,
800 "href" => $contact["photo"]];
801 XML::addElement($doc, $author, "link", "", $attributes);
808 * @brief Adds the activity elements
810 * @param DOMDocument $doc XML document
811 * @param string $element Element name for the activity
812 * @param string $activity activity value
814 * @return \DOMElement XML activity object
815 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
816 * @todo Find proper type-hints
818 private static function createActivity(DOMDocument $doc, $element, $activity)
821 $entry = $doc->createElement($element);
823 $r = XML::parseString($activity, false);
829 XML::addElement($doc, $entry, "activity:object-type", $r->type);
833 XML::addElement($doc, $entry, "id", $r->id);
837 XML::addElement($doc, $entry, "title", $r->title);
841 if (substr($r->link, 0, 1) == '<') {
842 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
843 $r->link = str_replace('&', '&', $r->link);
846 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
848 // XML does need a single element as root element so we add a dummy element here
849 $data = XML::parseString("<dummy>" . $r->link . "</dummy>", false);
850 if (is_object($data)) {
851 foreach ($data->link as $link) {
853 foreach ($link->attributes() as $parameter => $value) {
854 $attributes[$parameter] = $value;
856 XML::addElement($doc, $entry, "link", "", $attributes);
860 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
861 XML::addElement($doc, $entry, "link", "", $attributes);
865 XML::addElement($doc, $entry, "content", BBCode::convert($r->content), ["type" => "html"]);
875 * @brief Adds the elements for attachments
877 * @param object $doc XML document
878 * @param object $root XML root
879 * @param array $item Item element
881 * @return void XML attachment object
882 * @todo Find proper type-hints
884 private static function getAttachment($doc, $root, $item)
886 $arr = explode('[/attach],', $item['attach']);
888 foreach ($arr as $r) {
890 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
892 $attributes = ["rel" => "enclosure",
893 "href" => $matches[1],
894 "type" => $matches[3]];
896 if (intval($matches[2])) {
897 $attributes["length"] = intval($matches[2]);
900 if (trim($matches[4]) != "") {
901 $attributes["title"] = trim($matches[4]);
904 XML::addElement($doc, $root, "link", "", $attributes);
911 * @brief Adds the "entry" elements for the DFRN protocol
913 * @param DOMDocument $doc XML document
914 * @param string $type "text" or "html"
915 * @param array $item Item element
916 * @param array $owner Owner record
917 * @param bool $comment Trigger the sending of the "comment" element
918 * @param int $cid Contact ID of the recipient
919 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
921 * @return null|\DOMElement XML entry object
922 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
923 * @throws \ImagickException
924 * @todo Find proper type-hints
926 private static function entry(DOMDocument $doc, $type, array $item, array $owner, $comment = false, $cid = 0, $single = false)
930 if (!$item['parent']) {
931 Logger::notice('Item without parent found.', ['type' => $type, 'item' => $item]);
935 if ($item['deleted']) {
936 $attributes = ["ref" => $item['uri'], "when" => DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM)];
937 return XML::createElement($doc, "at:deleted-entry", "", $attributes);
941 $entry = $doc->createElement("entry");
943 $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry');
944 $doc->appendChild($entry);
946 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
947 $entry->setAttribute("xmlns:at", NAMESPACE_TOMB);
948 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
949 $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
950 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
951 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
952 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
953 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
954 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
957 if ($item['private']) {
958 $body = Item::fixPrivatePhotos($item['body'], $owner['uid'], $item, $cid);
960 $body = $item['body'];
963 // Remove the abstract element. It is only locally important.
964 $body = BBCode::stripAbstract($body);
967 if ($type == 'html') {
970 if ($item['title'] != "") {
971 $htmlbody = "[b]" . $item['title'] . "[/b]\n\n" . $htmlbody;
974 $htmlbody = BBCode::convert($htmlbody, false, 7);
977 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
978 $entry->appendChild($author);
980 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
981 $entry->appendChild($dfrnowner);
983 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
984 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
985 $parent = Item::selectFirst(['guid', 'plink'], ['uri' => $parent_item, 'uid' => $item['uid']]);
986 $attributes = ["ref" => $parent_item, "type" => "text/html",
987 "href" => $parent['plink'],
988 "dfrn:diaspora_guid" => $parent['guid']];
989 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
992 // Add conversation data. This is used for OStatus
993 $conversation_href = System::baseUrl()."/display/".$item["parent-guid"];
994 $conversation_uri = $conversation_href;
996 if (isset($parent_item)) {
997 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $item['parent-uri']]);
998 if (DBA::isResult($conversation)) {
999 if ($conversation['conversation-uri'] != '') {
1000 $conversation_uri = $conversation['conversation-uri'];
1002 if ($conversation['conversation-href'] != '') {
1003 $conversation_href = $conversation['conversation-href'];
1009 "href" => $conversation_href,
1010 "ref" => $conversation_uri];
1012 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
1014 XML::addElement($doc, $entry, "id", $item["uri"]);
1015 XML::addElement($doc, $entry, "title", $item["title"]);
1017 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"] . "+00:00", DateTimeFormat::ATOM));
1018 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"] . "+00:00", DateTimeFormat::ATOM));
1020 // "dfrn:env" is used to read the content
1021 XML::addElement($doc, $entry, "dfrn:env", Strings::base64UrlEncode($body, true));
1023 // The "content" field is not read by the receiver. We could remove it when the type is "text"
1024 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
1025 XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
1027 // We save this value in "plink". Maybe we should read it from there as well?
1033 ["rel" => "alternate", "type" => "text/html",
1034 "href" => System::baseUrl() . "/display/" . $item["guid"]]
1037 // "comment-allow" is some old fashioned stuff for old Friendica versions.
1038 // It is included in the rewritten code for completeness
1040 XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
1043 if ($item['location']) {
1044 XML::addElement($doc, $entry, "dfrn:location", $item['location']);
1047 if ($item['coord']) {
1048 XML::addElement($doc, $entry, "georss:point", $item['coord']);
1051 if ($item['private']) {
1052 XML::addElement($doc, $entry, "dfrn:private", ($item['private'] ? $item['private'] : 1));
1055 if ($item['extid']) {
1056 XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
1059 if ($item['post-type'] == Item::PT_PAGE) {
1060 XML::addElement($doc, $entry, "dfrn:bookmark", "true");
1064 XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
1067 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
1069 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
1070 // It is needed for relayed comments to Diaspora.
1071 if ($item['signed_text']) {
1072 $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer']]));
1073 XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
1076 XML::addElement($doc, $entry, "activity:verb", self::constructVerb($item));
1078 if ($item['object-type'] != "") {
1079 XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
1080 } elseif ($item['id'] == $item['parent']) {
1081 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1083 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
1086 $actobj = self::createActivity($doc, "activity:object", $item['object']);
1088 $entry->appendChild($actobj);
1091 $actarg = self::createActivity($doc, "activity:target", $item['target']);
1093 $entry->appendChild($actarg);
1096 $tags = Item::getFeedTags($item);
1098 /// @TODO Combine this with similar below if() block?
1100 foreach ($tags as $t) {
1101 if (($type != 'html') || ($t[0] != "@")) {
1102 XML::addElement($doc, $entry, "category", "", ["scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]]);
1108 foreach ($tags as $t) {
1110 $mentioned[$t[1]] = $t[1];
1115 foreach ($mentioned as $mention) {
1116 $condition = ['uid' => $owner["uid"], 'nurl' => Strings::normaliseLink($mention)];
1117 $contact = DBA::selectFirst('contact', ['forum', 'prv'], $condition);
1119 if (DBA::isResult($contact) && ($contact["forum"] || $contact["prv"])) {
1125 ["rel" => "mentioned",
1126 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1135 ["rel" => "mentioned",
1136 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1142 self::getAttachment($doc, $entry, $item);
1148 * @brief encrypts data via AES
1150 * @param string $data The data that is to be encrypted
1151 * @param string $key The AES key
1153 * @return string encrypted data
1155 private static function aesEncrypt($data, $key)
1157 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1161 * @brief decrypts data via AES
1163 * @param string $encrypted The encrypted data
1164 * @param string $key The AES key
1166 * @return string decrypted data
1168 public static function aesDecrypt($encrypted, $key)
1170 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1174 * @brief Delivers the atom content to the contacts
1176 * @param array $owner Owner record
1177 * @param array $contact Contact record of the receiver
1178 * @param string $atom Content that will be transmitted
1179 * @param bool $dissolve (to be documented)
1181 * @return int Deliver status. Negative values mean an error.
1182 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1183 * @throws \ImagickException
1184 * @todo Add array type-hint for $owner, $contact
1186 public static function deliver($owner, $contact, $atom, $dissolve = false)
1188 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1190 if ($contact['duplex'] && $contact['dfrn-id']) {
1191 $idtosend = '0:' . $orig_id;
1193 if ($contact['duplex'] && $contact['issued-id']) {
1194 $idtosend = '1:' . $orig_id;
1197 $rino = Config::get('system', 'rino_encrypt');
1198 $rino = intval($rino);
1200 Logger::log("Local rino version: ". $rino, Logger::DEBUG);
1202 $ssl_val = intval(Config::get('system', 'ssl_policy'));
1205 case BaseURL::SSL_POLICY_FULL:
1206 $ssl_policy = 'full';
1208 case BaseURL::SSL_POLICY_SELFSIGN:
1209 $ssl_policy = 'self';
1211 case BaseURL::SSL_POLICY_NONE:
1213 $ssl_policy = 'none';
1217 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1219 Logger::log('dfrn_deliver: ' . $url);
1221 $curlResult = Network::curl($url);
1223 if ($curlResult->isTimeout()) {
1224 return -2; // timed out
1227 $xml = $curlResult->getBody();
1229 $curl_stat = $curlResult->getReturnCode();
1230 if (empty($curl_stat)) {
1231 return -3; // timed out
1234 Logger::log('dfrn_deliver: ' . $xml, Logger::DATA);
1240 if (strpos($xml, '<?xml') === false) {
1241 Logger::log('dfrn_deliver: no valid XML returned');
1242 Logger::log('dfrn_deliver: returned XML: ' . $xml, Logger::DATA);
1246 $res = XML::parseString($xml);
1248 if (!is_object($res) || (intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
1249 if (empty($res->status)) {
1252 $status = $res->status;
1259 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1260 $challenge = hex2bin((string) $res->challenge);
1261 $perm = (($res->perm) ? $res->perm : null);
1262 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1263 $rino_remote_version = intval($res->rino);
1264 $page = (($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? 1 : 0);
1266 Logger::log("Remote rino version: ".$rino_remote_version." for ".$contact["url"], Logger::DEBUG);
1268 if ($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
1272 $final_dfrn_id = '';
1275 if ((($perm == 'rw') && !intval($contact['writable']))
1276 || (($perm == 'r') && intval($contact['writable']))
1278 DBA::update('contact', ['writable' => ($perm == 'rw')], ['id' => $contact['id']]);
1280 $contact['writable'] = (string) 1 - intval($contact['writable']);
1284 if (($contact['duplex'] && strlen($contact['pubkey']))
1285 || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY && strlen($contact['pubkey']))
1286 || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
1288 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
1289 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
1291 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
1292 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
1295 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1297 if (strpos($final_dfrn_id, ':') == 1) {
1298 $final_dfrn_id = substr($final_dfrn_id, 2);
1301 if ($final_dfrn_id != $orig_id) {
1302 Logger::log('dfrn_deliver: wrong dfrn_id.');
1303 // did not decode properly - cannot trust this site
1307 $postvars['dfrn_id'] = $idtosend;
1308 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1310 $postvars['dissolve'] = '1';
1313 if ((($contact['rel']) && ($contact['rel'] != Contact::SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY)) {
1314 $postvars['data'] = $atom;
1315 $postvars['perm'] = 'rw';
1317 $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
1318 $postvars['perm'] = 'r';
1321 $postvars['ssl_policy'] = $ssl_policy;
1324 $postvars['page'] = $page;
1328 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1329 Logger::log('rino version: '. $rino_remote_version);
1331 switch ($rino_remote_version) {
1333 $key = openssl_random_pseudo_bytes(16);
1334 $data = self::aesEncrypt($postvars['data'], $key);
1338 Logger::log("rino: invalid requested version '$rino_remote_version'");
1342 $postvars['rino'] = $rino_remote_version;
1343 $postvars['data'] = bin2hex($data);
1345 if ($dfrn_version >= 2.1) {
1346 if (($contact['duplex'] && strlen($contact['pubkey']))
1347 || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY && strlen($contact['pubkey']))
1348 || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
1350 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1352 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1355 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY)) {
1356 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1358 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1362 Logger::log('md5 rawkey ' . md5($postvars['key']));
1364 $postvars['key'] = bin2hex($postvars['key']);
1368 Logger::log('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), Logger::DATA);
1370 $postResult = Network::post($contact['notify'], $postvars);
1372 $xml = $postResult->getBody();
1374 Logger::log('dfrn_deliver: ' . "RECEIVED: " . $xml, Logger::DATA);
1376 $curl_stat = $postResult->getReturnCode();
1377 if (empty($curl_stat) || empty($xml)) {
1378 return -9; // timed out
1381 if (($curl_stat == 503) && stristr($postResult->getHeader(), 'retry-after')) {
1385 if (strpos($xml, '<?xml') === false) {
1386 Logger::log('dfrn_deliver: phase 2: no valid XML returned');
1387 Logger::log('dfrn_deliver: phase 2: returned XML: ' . $xml, Logger::DATA);
1391 $res = XML::parseString($xml);
1393 if (!isset($res->status)) {
1397 // Possibly old servers had returned an empty value when everything was okay
1398 if (empty($res->status)) {
1402 if (!empty($res->message)) {
1403 Logger::log('Delivery returned status '.$res->status.' - '.$res->message, Logger::DEBUG);
1406 return intval($res->status);
1410 * @brief Transmits atom content to the contacts via the Diaspora transport layer
1412 * @param array $owner Owner record
1413 * @param array $contact Contact record of the receiver
1414 * @param string $atom Content that will be transmitted
1416 * @param bool $public_batch
1417 * @return int Deliver status. Negative values mean an error.
1418 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1419 * @throws \ImagickException
1421 public static function transmit($owner, $contact, $atom, $public_batch = false)
1423 if (!$public_batch) {
1424 if (empty($contact['addr'])) {
1425 Logger::log('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.');
1426 if (Contact::updateFromProbe($contact['id'])) {
1427 $new_contact = DBA::selectFirst('contact', ['addr'], ['id' => $contact['id']]);
1428 $contact['addr'] = $new_contact['addr'];
1431 if (empty($contact['addr'])) {
1432 Logger::log('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
1437 $fcontact = Diaspora::personByHandle($contact['addr']);
1438 if (empty($fcontact)) {
1439 Logger::log('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
1442 $pubkey = $fcontact['pubkey'];
1447 $envelope = Diaspora::buildMessage($atom, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
1449 // Create the endpoint for public posts. This is some WIP and should later be added to the probing
1450 if ($public_batch && empty($contact["batch"])) {
1451 $parts = parse_url($contact["notify"]);
1452 $path_parts = explode('/', $parts['path']);
1453 array_pop($path_parts);
1454 $parts['path'] = implode('/', $path_parts);
1455 $contact["batch"] = Network::unparseURL($parts);
1458 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
1460 if (empty($dest_url)) {
1461 Logger::info('Empty destination', ['public' => $public_batch, 'contact' => $contact]);
1465 $content_type = ($public_batch ? "application/magic-envelope+xml" : "application/json");
1467 $postResult = Network::post($dest_url, $envelope, ["Content-Type: ".$content_type]);
1468 $xml = $postResult->getBody();
1470 $curl_stat = $postResult->getReturnCode();
1471 if (empty($curl_stat) || empty($xml)) {
1472 Logger::log('Empty answer from ' . $contact['id'] . ' - ' . $dest_url);
1473 return -9; // timed out
1476 if (($curl_stat == 503) && (stristr($postResult->getHeader(), 'retry-after'))) {
1480 if (strpos($xml, '<?xml') === false) {
1481 Logger::log('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url);
1482 Logger::log('Returned XML: ' . $xml, Logger::DATA);
1486 $res = XML::parseString($xml);
1488 if (empty($res->status)) {
1492 if (!empty($res->message)) {
1493 Logger::log('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message, Logger::DEBUG);
1496 return intval($res->status);
1500 * @brief Fetch the author data from head or entry items
1502 * @param object $xpath XPath object
1503 * @param object $context In which context should the data be searched
1504 * @param array $importer Record of the importer user mixed with contact of the content
1505 * @param string $element Element name from which the data is fetched
1506 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1507 * @param string $xml optional, default empty
1509 * @return array Relevant data of the author
1510 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1511 * @throws \ImagickException
1512 * @todo Find good type-hints for all parameter
1514 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
1517 $author["name"] = XML::getFirstNodeValue($xpath, $element."/atom:name/text()", $context);
1518 $author["link"] = XML::getFirstNodeValue($xpath, $element."/atom:uri/text()", $context);
1520 $fields = ['id', 'uid', 'url', 'network', 'avatar-date', 'avatar', 'name-date', 'uri-date', 'addr',
1521 'name', 'nick', 'about', 'location', 'keywords', 'xmpp', 'bdyear', 'bd', 'hidden', 'contact-type'];
1522 $condition = ["`uid` = ? AND `nurl` = ? AND `network` != ?",
1523 $importer["importer_uid"], Strings::normaliseLink($author["link"]), Protocol::STATUSNET];
1524 $contact_old = DBA::selectFirst('contact', $fields, $condition);
1526 if (DBA::isResult($contact_old)) {
1527 $author["contact-id"] = $contact_old["id"];
1528 $author["network"] = $contact_old["network"];
1531 Logger::debug("Contact ".$author["link"]." wasn't found for user ".$importer["importer_uid"]." XML: ".$xml);
1534 $author["contact-unknown"] = true;
1535 $author["contact-id"] = $importer["id"];
1536 $author["network"] = $importer["network"];
1540 // Until now we aren't serving different sizes - but maybe later
1542 /// @todo check if "avatar" or "photo" would be the best field in the specification
1543 $avatars = $xpath->query($element . "/atom:link[@rel='avatar']", $context);
1544 foreach ($avatars as $avatar) {
1547 foreach ($avatar->attributes as $attributes) {
1548 /// @TODO Rewrite these similar if() to one switch
1549 if ($attributes->name == "href") {
1550 $href = $attributes->textContent;
1552 if ($attributes->name == "width") {
1553 $width = $attributes->textContent;
1555 if ($attributes->name == "updated") {
1556 $author["avatar-date"] = $attributes->textContent;
1559 if (($width > 0) && ($href != "")) {
1560 $avatarlist[$width] = $href;
1564 if (count($avatarlist) > 0) {
1565 krsort($avatarlist);
1566 $author["avatar"] = current($avatarlist);
1569 if (empty($author['avatar']) && !empty($author['link'])) {
1570 $cid = Contact::getIdForURL($author['link'], 0);
1572 $contact = DBA::selectFirst('contact', ['avatar'], ['id' => $cid]);
1573 if (DBA::isResult($contact)) {
1574 $author['avatar'] = $contact['avatar'];
1579 if (empty($author['avatar'])) {
1580 Logger::log('Empty author: ' . $xml);
1581 $author['avatar'] = '';
1584 if (DBA::isResult($contact_old) && !$onlyfetch) {
1585 Logger::log("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", Logger::DEBUG);
1587 $poco = ["url" => $contact_old["url"]];
1589 // When was the last change to name or uri?
1590 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1591 foreach ($name_element->attributes as $attributes) {
1592 if ($attributes->name == "updated") {
1593 $poco["name-date"] = $attributes->textContent;
1597 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1598 foreach ($link_element->attributes as $attributes) {
1599 if ($attributes->name == "updated") {
1600 $poco["uri-date"] = $attributes->textContent;
1604 // Update contact data
1605 $value = XML::getFirstNodeValue($xpath, $element . "/dfrn:handle/text()", $context);
1607 $poco["addr"] = $value;
1610 $value = XML::getFirstNodeValue($xpath, $element . "/poco:displayName/text()", $context);
1612 $poco["name"] = $value;
1615 $value = XML::getFirstNodeValue($xpath, $element . "/poco:preferredUsername/text()", $context);
1617 $poco["nick"] = $value;
1620 $value = XML::getFirstNodeValue($xpath, $element . "/poco:note/text()", $context);
1622 $poco["about"] = $value;
1625 $value = XML::getFirstNodeValue($xpath, $element . "/poco:address/poco:formatted/text()", $context);
1627 $poco["location"] = $value;
1630 /// @todo Only search for elements with "poco:type" = "xmpp"
1631 $value = XML::getFirstNodeValue($xpath, $element . "/poco:ims/poco:value/text()", $context);
1633 $poco["xmpp"] = $value;
1636 /// @todo Add support for the following fields that we don't support by now in the contact table:
1637 /// - poco:utcOffset
1643 // If the "hide" element is present then the profile isn't searchable.
1644 $hide = intval(XML::getFirstNodeValue($xpath, $element . "/dfrn:hide/text()", $context) == "true");
1646 Logger::log("Hidden status for contact " . $contact_old["url"] . ": " . $hide, Logger::DEBUG);
1648 // If the contact isn't searchable then set the contact to "hidden".
1649 // Problem: This can be manually overridden by the user.
1651 $contact_old["hidden"] = true;
1654 // Save the keywords into the contact table
1656 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1657 foreach ($tagelements as $tag) {
1658 $tags[$tag->nodeValue] = $tag->nodeValue;
1662 $poco["keywords"] = implode(", ", $tags);
1665 // "dfrn:birthday" contains the birthday converted to UTC
1666 $birthday = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1668 if (strtotime($birthday) > time()) {
1669 $bd_timestamp = strtotime($birthday);
1671 $poco["bdyear"] = date("Y", $bd_timestamp);
1674 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1675 $value = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1677 if (!in_array($value, ["", "0000-00-00", DBA::NULL_DATE])) {
1678 $bdyear = date("Y");
1679 $value = str_replace(["0000", "0001"], $bdyear, $value);
1681 if (strtotime($value) < time()) {
1682 $value = str_replace($bdyear, $bdyear + 1, $value);
1685 $poco["bd"] = $value;
1688 $contact = array_merge($contact_old, $poco);
1690 if ($contact_old["bdyear"] != $contact["bdyear"]) {
1691 Event::createBirthday($contact, $birthday);
1694 $fields = ['name' => $contact['name'], 'nick' => $contact['nick'], 'about' => $contact['about'],
1695 'location' => $contact['location'], 'addr' => $contact['addr'], 'keywords' => $contact['keywords'],
1696 'bdyear' => $contact['bdyear'], 'bd' => $contact['bd'], 'hidden' => $contact['hidden'],
1697 'xmpp' => $contact['xmpp'], 'name-date' => DateTimeFormat::utc($contact['name-date']),
1698 'unsearchable' => $contact['hidden'], 'uri-date' => DateTimeFormat::utc($contact['uri-date'])];
1700 DBA::update('contact', $fields, ['id' => $contact['id'], 'network' => $contact['network']], $contact_old);
1702 // Update the public contact. Don't set the "hidden" value, this is used differently for public contacts
1703 unset($fields['hidden']);
1704 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($contact_old['url'])];
1705 DBA::update('contact', $fields, $condition, true);
1707 Contact::updateAvatar($author['avatar'], $importer['importer_uid'], $contact['id']);
1709 $pcid = Contact::getIdForURL($contact_old['url']);
1710 if (!empty($pcid)) {
1711 Contact::updateAvatar($author['avatar'], 0, $pcid);
1715 * The generation is a sign for the reliability of the provided data.
1716 * It is used in the socgraph.php to prevent that old contact data
1717 * that was relayed over several servers can overwrite contact
1718 * data that we received directly.
1721 $poco["generation"] = 2;
1722 $poco["photo"] = $author["avatar"];
1723 $poco["hide"] = $hide;
1724 $poco["contact-type"] = $contact["contact-type"];
1725 $gcid = GContact::update($poco);
1727 GContact::link($gcid, $importer["importer_uid"], $contact["id"]);
1734 * @brief Transforms activity objects into an XML string
1736 * @param object $xpath XPath object
1737 * @param object $activity Activity object
1738 * @param string $element element name
1740 * @return string XML string
1741 * @todo Find good type-hints for all parameter
1743 private static function transformActivity($xpath, $activity, $element)
1745 if (!is_object($activity)) {
1749 $obj_doc = new DOMDocument("1.0", "utf-8");
1750 $obj_doc->formatOutput = true;
1752 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1754 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1755 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1757 $id = $xpath->query("atom:id", $activity)->item(0);
1758 if (is_object($id)) {
1759 $obj_element->appendChild($obj_doc->importNode($id, true));
1762 $title = $xpath->query("atom:title", $activity)->item(0);
1763 if (is_object($title)) {
1764 $obj_element->appendChild($obj_doc->importNode($title, true));
1767 $links = $xpath->query("atom:link", $activity);
1768 if (is_object($links)) {
1769 foreach ($links as $link) {
1770 $obj_element->appendChild($obj_doc->importNode($link, true));
1774 $content = $xpath->query("atom:content", $activity)->item(0);
1775 if (is_object($content)) {
1776 $obj_element->appendChild($obj_doc->importNode($content, true));
1779 $obj_doc->appendChild($obj_element);
1781 $objxml = $obj_doc->saveXML($obj_element);
1783 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1784 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1789 * @brief Processes the mail elements
1791 * @param object $xpath XPath object
1792 * @param object $mail mail elements
1793 * @param array $importer Record of the importer user mixed with contact of the content
1795 * @throws \Exception
1796 * @todo Find good type-hints for all parameter
1798 private static function processMail($xpath, $mail, $importer)
1800 Logger::log("Processing mails");
1803 $msg["uid"] = $importer["importer_uid"];
1804 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1805 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1806 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1807 $msg["contact-id"] = $importer["id"];
1808 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1809 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1810 $msg["created"] = DateTimeFormat::utc($xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue);
1811 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1812 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1818 * @brief Processes the suggestion elements
1820 * @param object $xpath XPath object
1821 * @param object $suggestion suggestion elements
1822 * @param array $importer Record of the importer user mixed with contact of the content
1824 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1825 * @todo Find good type-hints for all parameter
1827 private static function processSuggestion($xpath, $suggestion, $importer)
1829 Logger::log('Processing suggestions');
1831 /// @TODO Rewrite this to one statement
1833 $suggest['uid'] = $importer['importer_uid'];
1834 $suggest['cid'] = $importer['id'];
1835 $suggest['url'] = $xpath->query('dfrn:url/text()', $suggestion)->item(0)->nodeValue;
1836 $suggest['name'] = $xpath->query('dfrn:name/text()', $suggestion)->item(0)->nodeValue;
1837 $suggest['photo'] = $xpath->query('dfrn:photo/text()', $suggestion)->item(0)->nodeValue;
1838 $suggest['request'] = $xpath->query('dfrn:request/text()', $suggestion)->item(0)->nodeValue;
1839 $suggest['body'] = $xpath->query('dfrn:note/text()', $suggestion)->item(0)->nodeValue;
1841 // Does our member already have a friend matching this description?
1844 * The valid result means the friend we're about to send a friend
1845 * suggestion already has them in their contact, which means no further
1846 * action is required.
1848 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1850 $condition = ['nurl' => Strings::normaliseLink($suggest['url']), 'uid' => $suggest['uid']];
1851 if (DBA::exists('contact', $condition)) {
1854 // Do we already have an fcontact record for this person?
1857 $fcontact = DBA::selectFirst('fcontact', ['id'], ['url' => $suggest['url']]);
1858 if (DBA::isResult($fcontact)) {
1859 $fid = $fcontact['id'];
1861 // OK, we do. Do we already have an introduction for this person?
1862 if (DBA::exists('intro', ['uid' => $suggest['uid'], 'fid' => $fid])) {
1864 * The valid result means the friend we're about to send a friend
1865 * suggestion already has them in their contact, which means no further
1866 * action is required.
1868 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1875 $fields = ['name' => $suggest['name'], 'url' => $suggest['url'],
1876 'photo' => $suggest['photo'], 'request' => $suggest['request']];
1877 DBA::insert('fcontact', $fields);
1878 $fid = DBA::lastInsertId();
1882 * If no record in fcontact is found, below INSERT statement will not
1883 * link an introduction to it.
1886 // Database record did not get created. Quietly give up.
1890 $hash = Strings::getRandomHex();
1892 $fields = ['uid' => $suggest['uid'], 'fid' => $fid, 'contact-id' => $suggest['cid'],
1893 'note' => $suggest['body'], 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow(), 'blocked' => false];
1894 DBA::insert('intro', $fields);
1898 'type' => NOTIFY_SUGGEST,
1899 'notify_flags' => $importer['notify-flags'],
1900 'language' => $importer['language'],
1901 'to_name' => $importer['username'],
1902 'to_email' => $importer['email'],
1903 'uid' => $importer['importer_uid'],
1905 'link' => System::baseUrl().'/notifications/intros',
1906 'source_name' => $importer['name'],
1907 'source_link' => $importer['url'],
1908 'source_photo' => $importer['photo'],
1909 'verb' => ACTIVITY_REQ_FRIEND,
1917 * @brief Processes the relocation elements
1919 * @param object $xpath XPath object
1920 * @param object $relocation relocation elements
1921 * @param array $importer Record of the importer user mixed with contact of the content
1923 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1924 * @throws \ImagickException
1925 * @todo Find good type-hints for all parameter
1927 private static function processRelocation($xpath, $relocation, $importer)
1929 Logger::log("Processing relocations");
1931 /// @TODO Rewrite this to one statement
1933 $relocate["uid"] = $importer["importer_uid"];
1934 $relocate["cid"] = $importer["id"];
1935 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1936 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
1937 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1938 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
1939 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1940 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1941 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1942 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1943 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1944 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1945 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1946 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1948 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
1949 $relocate["avatar"] = $relocate["photo"];
1952 if ($relocate["addr"] == "") {
1953 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
1958 "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d",
1959 intval($importer["id"]),
1960 intval($importer["importer_uid"])
1963 if (!DBA::isResult($r)) {
1964 Logger::log("Query failed to execute, no result returned in " . __FUNCTION__);
1970 // Update the gcontact entry
1971 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
1973 $fields = ['name' => $relocate["name"], 'photo' => $relocate["avatar"],
1974 'url' => $relocate["url"], 'nurl' => Strings::normaliseLink($relocate["url"]),
1975 'addr' => $relocate["addr"], 'connect' => $relocate["addr"],
1976 'notify' => $relocate["notify"], 'server_url' => $relocate["server_url"]];
1977 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($old["url"])]);
1979 // Update the contact table. We try to find every entry.
1980 $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
1981 'url' => $relocate["url"], 'nurl' => Strings::normaliseLink($relocate["url"]),
1982 'addr' => $relocate["addr"], 'request' => $relocate["request"],
1983 'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
1984 'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
1985 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], Strings::normaliseLink($old["url"])];
1987 DBA::update('contact', $fields, $condition);
1989 Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
1991 Logger::log('Contacts are updated.');
1994 /// merge with current record, current contents have priority
1995 /// update record, set url-updated
1996 /// update profile photos
1997 /// schedule a scan?
2002 * @brief Updates an item
2004 * @param array $current the current item record
2005 * @param array $item the new item record
2006 * @param array $importer Record of the importer user mixed with contact of the content
2007 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2009 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2010 * @todo set proper type-hints (array?)
2012 private static function updateContent($current, $item, $importer, $entrytype)
2016 if (self::isEditedTimestampNewer($current, $item)) {
2017 // do not accept (ignore) an earlier edit than one we currently have.
2018 if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
2022 $fields = ['title' => defaults($item, 'title', ''), 'body' => defaults($item, 'body', ''),
2023 'tag' => defaults($item, 'tag', ''), 'changed' => DateTimeFormat::utcNow(),
2024 'edited' => DateTimeFormat::utc($item["edited"])];
2026 $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
2027 Item::update($fields, $condition);
2035 * @brief Detects the entry type of the item
2037 * @param array $importer Record of the importer user mixed with contact of the content
2038 * @param array $item the new item record
2040 * @return int Is it a toplevel entry, a comment or a relayed comment?
2041 * @throws \Exception
2042 * @todo set proper type-hints (array?)
2044 private static function getEntryType($importer, $item)
2046 if ($item["parent-uri"] != $item["uri"]) {
2049 if ($importer["page-flags"] == User::PAGE_FLAGS_COMMUNITY || $importer["page-flags"] == User::PAGE_FLAGS_PRVGROUP) {
2052 Logger::log("possible community action");
2054 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2057 // was the top-level post for this action written by somebody on this site?
2058 // Specifically, the recipient?
2060 $is_a_remote_action = false;
2062 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item["parent-uri"]]);
2063 if (DBA::isResult($parent)) {
2065 "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2066 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2067 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2068 AND `item`.`uid` = %d
2071 DBA::escape($parent["parent-uri"]),
2072 DBA::escape($parent["parent-uri"]),
2073 DBA::escape($parent["parent-uri"]),
2074 intval($importer["importer_uid"])
2076 if (DBA::isResult($r)) {
2077 $is_a_remote_action = true;
2082 * Does this have the characteristics of a community or private group action?
2083 * If it's an action to a wall post on a community/prvgroup page it's a
2084 * valid community action. Also forum_mode makes it valid for sure.
2085 * If neither, it's not.
2087 if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2088 $is_a_remote_action = false;
2089 Logger::log("not a community action");
2092 if ($is_a_remote_action) {
2093 return DFRN::REPLY_RC;
2098 return DFRN::TOP_LEVEL;
2103 * @brief Send a "poke"
2105 * @param array $item The new item record
2106 * @param array $importer Record of the importer user mixed with contact of the content
2108 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2109 * @todo set proper type-hints (array?)
2111 private static function doPoke(array $item, array $importer)
2113 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2117 $xo = XML::parseString($item["object"], false);
2119 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2120 // somebody was poked/prodded. Was it me?
2122 foreach ($xo->link as $l) {
2123 $atts = $l->attributes();
2124 switch ($atts["rel"]) {
2126 $Blink = $atts["href"];
2133 if ($Blink && Strings::compareLink($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2134 $author = DBA::selectFirst('contact', ['name', 'thumb', 'url'], ['id' => $item['author-id']]);
2136 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => $importer["importer_uid"]]);
2137 $item["parent"] = $parent['id'];
2139 // send a notification
2142 "type" => NOTIFY_POKE,
2143 "notify_flags" => $importer["notify-flags"],
2144 "language" => $importer["language"],
2145 "to_name" => $importer["username"],
2146 "to_email" => $importer["email"],
2147 "uid" => $importer["importer_uid"],
2149 "link" => System::baseUrl()."/display/".urlencode($item['guid']),
2150 "source_name" => $author["name"],
2151 "source_link" => $author["url"],
2152 "source_photo" => $author["thumb"],
2153 "verb" => $item["verb"],
2154 "otype" => "person",
2155 "activity" => $verb,
2156 "parent" => $item["parent"]]
2163 * @brief Processes several actions, depending on the verb
2165 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2166 * @param array $importer Record of the importer user mixed with contact of the content
2167 * @param array $item the new item record
2168 * @param bool $is_like Is the verb a "like"?
2170 * @return bool Should the processing of the entries be continued?
2171 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2172 * @todo set proper type-hints (array?)
2174 private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2176 Logger::log("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, Logger::DEBUG);
2178 if (($entrytype == DFRN::TOP_LEVEL) && !empty($importer['id'])) {
2179 // The filling of the the "contact" variable is done for legcy reasons
2180 // The functions below are partly used by ostatus.php as well - where we have this variable
2181 $contact = Contact::selectFirst([], ['id' => $importer['id']]);
2183 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2184 // This function once was responsible for DFRN and OStatus.
2185 if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2186 Logger::log("New follower");
2187 Contact::addRelationship($importer, $contact, $item);
2190 if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2191 Logger::log("Lost follower");
2192 Contact::removeFollower($importer, $contact, $item);
2195 if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2196 Logger::log("New friend request");
2197 Contact::addRelationship($importer, $contact, $item, true);
2200 if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2201 Logger::log("Lost sharer");
2202 Contact::removeSharer($importer, $contact, $item);
2206 if (($item["verb"] == ACTIVITY_LIKE)
2207 || ($item["verb"] == ACTIVITY_DISLIKE)
2208 || ($item["verb"] == ACTIVITY_ATTEND)
2209 || ($item["verb"] == ACTIVITY_ATTENDNO)
2210 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
2213 $item["gravity"] = GRAVITY_ACTIVITY;
2214 // only one like or dislike per person
2215 // splitted into two queries for performance issues
2216 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2217 'verb' => $item["verb"], 'parent-uri' => $item["parent-uri"]];
2218 if (Item::exists($condition)) {
2222 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2223 'verb' => $item["verb"], 'thr-parent' => $item["parent-uri"]];
2224 if (Item::exists($condition)) {
2228 // The owner of an activity must be the author
2229 $item["owner-name"] = $item["author-name"];
2230 $item["owner-link"] = $item["author-link"];
2231 $item["owner-avatar"] = $item["author-avatar"];
2232 $item["owner-id"] = $item["author-id"];
2237 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2238 $xo = XML::parseString($item["object"], false);
2239 $xt = XML::parseString($item["target"], false);
2241 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2242 $item_tag = Item::selectFirst(['id', 'tag'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]);
2244 if (!DBA::isResult($item_tag)) {
2245 Logger::log("Query failed to execute, no result returned in " . __FUNCTION__);
2249 // extract tag, if not duplicate, add to parent item
2251 if (!stristr($item_tag["tag"], trim($xo->content))) {
2252 $tag = $item_tag["tag"] . (strlen($item_tag["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2253 Item::update(['tag' => $tag], ['id' => $item_tag["id"]]);
2263 * @brief Processes the link elements
2265 * @param object $links link elements
2266 * @param array $item the item record
2268 * @todo set proper type-hints
2270 private static function parseLinks($links, &$item)
2277 foreach ($links as $link) {
2278 foreach ($link->attributes as $attributes) {
2279 switch ($attributes->name) {
2280 case "href" : $href = $attributes->textContent; break;
2281 case "rel" : $rel = $attributes->textContent; break;
2282 case "type" : $type = $attributes->textContent; break;
2283 case "length": $length = $attributes->textContent; break;
2284 case "title" : $title = $attributes->textContent; break;
2287 if (($rel != "") && ($href != "")) {
2290 $item["plink"] = $href;
2293 if (!empty($item["attach"])) {
2294 $item["attach"] .= ",";
2296 $item["attach"] = "";
2299 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2307 * @brief Processes the entry elements which contain the items and comments
2309 * @param array $header Array of the header elements that always stay the same
2310 * @param object $xpath XPath object
2311 * @param object $entry entry elements
2312 * @param array $importer Record of the importer user mixed with contact of the content
2313 * @param string $xml xml
2315 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2316 * @throws \ImagickException
2317 * @todo Add type-hints
2319 private static function processEntry($header, $xpath, $entry, $importer, $xml)
2321 Logger::log("Processing entries");
2325 $item["protocol"] = Conversation::PARCEL_DFRN;
2327 $item["source"] = $xml;
2330 $item["uri"] = XML::getFirstNodeValue($xpath, "atom:id/text()", $entry);
2332 $item["edited"] = XML::getFirstNodeValue($xpath, "atom:updated/text()", $entry);
2334 $current = Item::selectFirst(['id', 'uid', 'edited', 'body'],
2335 ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
2337 // Is there an existing item?
2338 if (DBA::isResult($current) && !self::isEditedTimestampNewer($current, $item)) {
2339 Logger::log("Item ".$item["uri"]." (".$item['edited'].") already existed.", Logger::DEBUG);
2344 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true, $xml);
2346 $owner_unknown = (isset($owner["contact-unknown"]) && $owner["contact-unknown"]);
2348 $item["owner-name"] = $owner["name"];
2349 $item["owner-link"] = $owner["link"];
2350 $item["owner-avatar"] = $owner["avatar"];
2351 $item["owner-id"] = Contact::getIdForURL($owner["link"], 0);
2354 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true, $xml);
2356 $item["author-name"] = $author["name"];
2357 $item["author-link"] = $author["link"];
2358 $item["author-avatar"] = $author["avatar"];
2359 $item["author-id"] = Contact::getIdForURL($author["link"], 0);
2361 $item["title"] = XML::getFirstNodeValue($xpath, "atom:title/text()", $entry);
2363 $item["created"] = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2365 $item["body"] = XML::getFirstNodeValue($xpath, "dfrn:env/text()", $entry);
2366 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2367 // make sure nobody is trying to sneak some html tags by us
2368 $item["body"] = Strings::escapeTags(Strings::base64UrlDecode($item["body"]));
2370 $item["body"] = BBCode::limitBodySize($item["body"]);
2372 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2373 if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
2374 $base_url = \get_app()->getBaseURL();
2375 $item['body'] = HTML::relToAbs($item['body'], $base_url);
2377 $item['body'] = HTML::toBBCodeVideo($item['body']);
2379 $item['body'] = OEmbed::HTML2BBCode($item['body']);
2381 $config = HTMLPurifier_Config::createDefault();
2382 $config->set('Cache.DefinitionImpl', null);
2384 // we shouldn't need a whitelist, because the bbcode converter
2385 // will strip out any unsupported tags.
2387 $purifier = new HTMLPurifier($config);
2388 $item['body'] = $purifier->purify($item['body']);
2390 $item['body'] = @HTML::toBBCode($item['body']);
2393 /// @todo We should check for a repeated post and if we know the repeated author.
2395 // We don't need the content element since "dfrn:env" is always present
2396 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2398 $item["location"] = XML::getFirstNodeValue($xpath, "dfrn:location/text()", $entry);
2400 $item["coord"] = XML::getFirstNodeValue($xpath, "georss:point", $entry);
2402 $item["private"] = XML::getFirstNodeValue($xpath, "dfrn:private/text()", $entry);
2404 $item["extid"] = XML::getFirstNodeValue($xpath, "dfrn:extid/text()", $entry);
2406 if (XML::getFirstNodeValue($xpath, "dfrn:bookmark/text()", $entry) == "true") {
2407 $item["post-type"] = Item::PT_PAGE;
2410 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2411 if ($notice_info && ($notice_info->length > 0)) {
2412 foreach ($notice_info->item(0)->attributes as $attributes) {
2413 if ($attributes->name == "source") {
2414 $item["app"] = strip_tags($attributes->textContent);
2419 $item["guid"] = XML::getFirstNodeValue($xpath, "dfrn:diaspora_guid/text()", $entry);
2421 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
2422 $dsprsig = XML::unescape(XML::getFirstNodeValue($xpath, "dfrn:diaspora_signature/text()", $entry));
2423 if ($dsprsig != "") {
2424 $item["dsprsig"] = $dsprsig;
2427 $item["verb"] = XML::getFirstNodeValue($xpath, "activity:verb/text()", $entry);
2429 if (XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry) != "") {
2430 $item["object-type"] = XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry);
2433 $object = $xpath->query("activity:object", $entry)->item(0);
2434 $item["object"] = self::transformActivity($xpath, $object, "object");
2436 if (trim($item["object"]) != "") {
2437 $r = XML::parseString($item["object"], false);
2438 if (isset($r->type)) {
2439 $item["object-type"] = $r->type;
2443 $target = $xpath->query("activity:target", $entry)->item(0);
2444 $item["target"] = self::transformActivity($xpath, $target, "target");
2446 $categories = $xpath->query("atom:category", $entry);
2448 foreach ($categories as $category) {
2451 foreach ($category->attributes as $attributes) {
2452 if ($attributes->name == "term") {
2453 $term = $attributes->textContent;
2456 if ($attributes->name == "scheme") {
2457 $scheme = $attributes->textContent;
2461 if (($term != "") && ($scheme != "")) {
2462 $parts = explode(":", $scheme);
2463 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2464 $termhash = array_shift($parts);
2465 $termurl = implode(":", $parts);
2467 if (!empty($item["tag"])) {
2468 $item["tag"] .= ",";
2473 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2479 $links = $xpath->query("atom:link", $entry);
2481 self::parseLinks($links, $item);
2484 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
2486 $conv = $xpath->query('ostatus:conversation', $entry);
2487 if (is_object($conv->item(0))) {
2488 foreach ($conv->item(0)->attributes as $attributes) {
2489 if ($attributes->name == "ref") {
2490 $item['conversation-uri'] = $attributes->textContent;
2492 if ($attributes->name == "href") {
2493 $item['conversation-href'] = $attributes->textContent;
2498 // Is it a reply or a top level posting?
2499 $item["parent-uri"] = $item["uri"];
2501 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2502 if (is_object($inreplyto->item(0))) {
2503 foreach ($inreplyto->item(0)->attributes as $attributes) {
2504 if ($attributes->name == "ref") {
2505 $item["parent-uri"] = $attributes->textContent;
2510 // Get the type of the item (Top level post, reply or remote reply)
2511 $entrytype = self::getEntryType($importer, $item);
2513 // Now assign the rest of the values that depend on the type of the message
2514 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2515 if (!isset($item["object-type"])) {
2516 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2519 if ($item["contact-id"] != $owner["contact-id"]) {
2520 $item["contact-id"] = $owner["contact-id"];
2523 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2524 $item["network"] = $owner["network"];
2527 if ($item["contact-id"] != $author["contact-id"]) {
2528 $item["contact-id"] = $author["contact-id"];
2531 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2532 $item["network"] = $author["network"];
2536 if ($entrytype == DFRN::REPLY_RC) {
2538 } elseif ($entrytype == DFRN::TOP_LEVEL) {
2539 if (!isset($item["object-type"])) {
2540 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2544 if (($item["object-type"] == ACTIVITY_OBJ_EVENT) && !$owner_unknown) {
2545 Logger::log("Item ".$item["uri"]." seems to contain an event.", Logger::DEBUG);
2546 $ev = Event::fromBBCode($item["body"]);
2547 if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
2548 Logger::log("Event in item ".$item["uri"]." was found.", Logger::DEBUG);
2549 $ev["cid"] = $importer["id"];
2550 $ev["uid"] = $importer["importer_uid"];
2551 $ev["uri"] = $item["uri"];
2552 $ev["edited"] = $item["edited"];
2553 $ev["private"] = $item["private"];
2554 $ev["guid"] = $item["guid"];
2555 $ev["plink"] = $item["plink"];
2557 $condition = ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]];
2558 $event = DBA::selectFirst('event', ['id'], $condition);
2559 if (DBA::isResult($event)) {
2560 $ev["id"] = $event["id"];
2563 $event_id = Event::store($ev);
2564 Logger::log("Event ".$event_id." was stored", Logger::DEBUG);
2570 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2571 Logger::log("Exiting because 'processVerbs' told us so", Logger::DEBUG);
2575 // This check is done here to be able to receive connection requests in "processVerbs"
2576 if (($entrytype == DFRN::TOP_LEVEL) && $owner_unknown) {
2577 Logger::log("Item won't be stored because user " . $importer["importer_uid"] . " doesn't follow " . $item["owner-link"] . ".", Logger::DEBUG);
2582 // Update content if 'updated' changes
2583 if (DBA::isResult($current)) {
2584 if (self::updateContent($current, $item, $importer, $entrytype)) {
2585 Logger::log("Item ".$item["uri"]." was updated.", Logger::DEBUG);
2587 Logger::log("Item " . $item["uri"] . " already existed.", Logger::DEBUG);
2592 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2593 $posted_id = Item::insert($item);
2595 Logger::log("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, Logger::DEBUG);
2597 if ($item['uid'] == 0) {
2598 Item::distribute($posted_id);
2603 } else { // $entrytype == DFRN::TOP_LEVEL
2604 if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
2605 Logger::log("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", Logger::DEBUG);
2608 if (!Strings::compareLink($item["owner-link"], $importer["url"])) {
2610 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2611 * but otherwise there's a possible data mixup on the sender's system.
2612 * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2613 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2615 Logger::log('Correcting item owner.', Logger::DEBUG);
2616 $item["owner-link"] = $importer["url"];
2617 $item["owner-id"] = Contact::getIdForURL($importer["url"], 0);
2620 if (($importer["rel"] == Contact::FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2621 Logger::log("Contact ".$importer["id"]." is only follower and tgroup check was negative.", Logger::DEBUG);
2625 // This is my contact on another system, but it's really me.
2626 // Turn this into a wall post.
2627 $notify = Item::isRemoteSelf($importer, $item);
2629 $posted_id = Item::insert($item, false, $notify);
2632 $posted_id = $notify;
2635 Logger::log("Item was stored with id ".$posted_id, Logger::DEBUG);
2637 if ($item['uid'] == 0) {
2638 Item::distribute($posted_id);
2641 if (stristr($item["verb"], ACTIVITY_POKE)) {
2642 $item['id'] = $posted_id;
2643 self::doPoke($item, $importer);
2649 * @brief Deletes items
2651 * @param object $xpath XPath object
2652 * @param object $deletion deletion elements
2653 * @param array $importer Record of the importer user mixed with contact of the content
2655 * @throws \Exception
2656 * @todo set proper type-hints
2658 private static function processDeletion($xpath, $deletion, $importer)
2660 Logger::log("Processing deletions");
2663 foreach ($deletion->attributes as $attributes) {
2664 if ($attributes->name == "ref") {
2665 $uri = $attributes->textContent;
2669 if (!$uri || !$importer["id"]) {
2673 $condition = ['uri' => $uri, 'uid' => $importer["importer_uid"]];
2674 $item = Item::selectFirst(['id', 'parent', 'contact-id', 'file', 'deleted'], $condition);
2675 if (!DBA::isResult($item)) {
2676 Logger::log("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", Logger::DEBUG);
2680 if (strstr($item['file'], '[')) {
2681 Logger::log("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " is filed. So it won't be deleted.", Logger::DEBUG);
2685 // When it is a starting post it has to belong to the person that wants to delete it
2686 if (($item['id'] == $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2687 Logger::log("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", Logger::DEBUG);
2691 // Comments can be deleted by the thread owner or comment owner
2692 if (($item['id'] != $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2693 $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2694 if (!Item::exists($condition)) {
2695 Logger::log("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", Logger::DEBUG);
2700 if ($item["deleted"]) {
2704 Logger::log('deleting item '.$item['id'].' uri='.$uri, Logger::DEBUG);
2706 Item::delete(['id' => $item['id']]);
2710 * @brief Imports a DFRN message
2712 * @param string $xml The DFRN message
2713 * @param array $importer Record of the importer user mixed with contact of the content
2714 * @param bool $sort_by_date Is used when feeds are polled
2715 * @return integer Import status
2716 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2717 * @throws \ImagickException
2718 * @todo set proper type-hints
2720 public static function import($xml, $importer, $sort_by_date = false)
2726 $doc = new DOMDocument();
2727 @$doc->loadXML($xml);
2729 $xpath = new DOMXPath($doc);
2730 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2731 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2732 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2733 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2734 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2735 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2736 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2737 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2738 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2739 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2742 $header["uid"] = $importer["importer_uid"];
2743 $header["network"] = Protocol::DFRN;
2744 $header["wall"] = 0;
2745 $header["origin"] = 0;
2746 $header["contact-id"] = $importer["id"];
2748 // Update the contact table if the data has changed
2750 // The "atom:author" is only present in feeds
2751 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2752 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2755 // Only the "dfrn:owner" in the head section contains all data
2756 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2757 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2760 Logger::log("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], Logger::DEBUG);
2762 // is it a public forum? Private forums aren't exposed with this method
2763 $forum = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:community/text()"));
2765 // The account type is new since 3.5.1
2766 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2767 // Hint: We are using separate update calls for uid=0 and uid!=0 since a combined call is bad for the database performance
2769 $accounttype = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:account_type/text()"));
2771 if ($accounttype != $importer["contact-type"]) {
2772 DBA::update('contact', ['contact-type' => $accounttype], ['id' => $importer['id']]);
2774 // Updating the public contact as well
2775 DBA::update('contact', ['contact-type' => $accounttype], ['uid' => 0, 'nurl' => $importer['nurl']]);
2777 // A forum contact can either have set "forum" or "prv" - but not both
2778 if ($accounttype == User::ACCOUNT_TYPE_COMMUNITY) {
2779 // It's a forum, so either set the public or private forum flag
2780 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer['id']];
2781 DBA::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2783 // Updating the public contact as well
2784 $condition = ['(`forum` != ? OR `prv` != ?) AND `uid` = 0 AND `nurl` = ?', $forum, !$forum, $importer['nurl']];
2785 DBA::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2787 // It's not a forum, so remove the flags
2788 $condition = ['(`forum` OR `prv`) AND `id` = ?', $importer['id']];
2789 DBA::update('contact', ['forum' => false, 'prv' => false], $condition);
2791 // Updating the public contact as well
2792 $condition = ['(`forum` OR `prv`) AND `uid` = 0 AND `nurl` = ?', $importer['nurl']];
2793 DBA::update('contact', ['forum' => false, 'prv' => false], $condition);
2795 } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
2796 $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2797 DBA::update('contact', ['forum' => $forum], $condition);
2799 // Updating the public contact as well
2800 $condition = ['`forum` != ? AND `uid` = 0 AND `nurl` = ?', $forum, $importer['nurl']];
2801 DBA::update('contact', ['forum' => $forum], $condition);
2805 // We are processing relocations even if we are ignoring a contact
2806 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2807 foreach ($relocations as $relocation) {
2808 self::processRelocation($xpath, $relocation, $importer);
2811 if (($importer["uid"] != 0) && !$importer["readonly"]) {
2812 $mails = $xpath->query("/atom:feed/dfrn:mail");
2813 foreach ($mails as $mail) {
2814 self::processMail($xpath, $mail, $importer);
2817 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2818 foreach ($suggestions as $suggestion) {
2819 self::processSuggestion($xpath, $suggestion, $importer);
2823 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2824 foreach ($deletions as $deletion) {
2825 self::processDeletion($xpath, $deletion, $importer);
2828 if (!$sort_by_date) {
2829 $entries = $xpath->query("/atom:feed/atom:entry");
2830 foreach ($entries as $entry) {
2831 self::processEntry($header, $xpath, $entry, $importer, $xml);
2835 $entries = $xpath->query("/atom:feed/atom:entry");
2836 foreach ($entries as $entry) {
2837 $created = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2838 $newentries[strtotime($created)] = $entry;
2841 // Now sort after the publishing date
2844 foreach ($newentries as $entry) {
2845 self::processEntry($header, $xpath, $entry, $importer, $xml);
2848 Logger::log("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], Logger::DEBUG);
2854 * @param string $contact_nick contact nickname
2855 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2857 public static function autoRedir(App $a, $contact_nick)
2860 if (!empty($_REQUEST['redir'])) {
2861 Logger::log('autoRedir might be looping because redirect has been redirected', Logger::DEBUG);
2862 // looping prevention also appears to sometimes prevent authentication for images
2863 // because browser may have multiple connections open and load an image on a connection
2864 // whose session wasn't updated when a previous redirect authenticated
2865 // Leaving commented in case looping reappears
2869 if ((! $contact_nick) || ($contact_nick === $a->user['nickname'])) {
2874 // We need to find out if $contact_nick is a user on this hub, and if so, if I
2875 // am a contact of that user. However, that user may have other contacts with the
2876 // same nickname as me on other hubs or other networks. Exclude these by requiring
2877 // that the contact have a local URL. I will be the only person with my nickname at
2878 // this URL, so if a result is found, then I am a contact of the $contact_nick user.
2880 // We also have to make sure that I'm a legitimate contact--I'm not blocked or pending.
2882 $baseurl = System::baseUrl();
2883 $domain_st = strpos($baseurl, "://");
2884 if ($domain_st === false) {
2887 $baseurl = substr($baseurl, $domain_st + 3);
2888 $nurl = Strings::normaliseLink($baseurl);
2890 $r = User::getByNickname($contact_nick, ["uid"]);
2891 $contact_uid = $r["uid"];
2893 /// @todo Why is there a query for "url" *and* "nurl"? Especially this normalising is strange.
2894 $r = q("SELECT `id` FROM `contact` WHERE `uid` = (SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1)
2895 AND `nick` = '%s' AND NOT `self` AND (`url` LIKE '%%%s%%' OR `nurl` LIKE '%%%s%%') AND NOT `blocked` AND NOT `pending` LIMIT 1",
2896 DBA::escape($contact_nick),
2897 DBA::escape($a->user['nickname']),
2898 DBA::escape($baseurl),
2901 if ((! DBA::isResult($r))) {
2904 // test if redirect authentication already succeeded
2905 // Note that "contact" in the sense used in the $contact_nick argument to this function
2906 // and the sense in the $remote[]["cid"] in the session are opposite.
2907 // In the session variable the user currently fetching is the contact
2908 // while $contact_nick is the nick of tho user who owns the stuff being fetched.
2909 if (Session::getVisitorContactIDForUserID($contact_uid) == $r[0]['id']) {
2913 $r = q("SELECT * FROM contact WHERE nick = '%s'
2914 AND network = '%s' AND uid = %d AND url LIKE '%%%s%%' LIMIT 1",
2915 DBA::escape($contact_nick),
2916 DBA::escape(Protocol::DFRN),
2917 intval(local_user()),
2918 DBA::escape($baseurl)
2920 if (! DBA::isResult($r)) {
2926 $dfrn_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2928 if ($r[0]['duplex'] && $r[0]['issued-id']) {
2929 $orig_id = $r[0]['issued-id'];
2930 $dfrn_id = '1:' . $orig_id;
2932 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
2933 $orig_id = $r[0]['dfrn-id'];
2934 $dfrn_id = '0:' . $orig_id;
2937 // ensure that we've got a valid ID. There may be some edge cases with forums and non-duplex mode
2938 // that may have triggered some of the "went to {profile/intro} and got an RSS feed" issues
2940 if (strlen($dfrn_id) < 3) {
2944 $sec = Strings::getRandomHex();
2946 DBA::insert('profile_check', ['uid' => local_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id, 'sec' => $sec, 'expire' => time() + 45]);
2948 $url = curPageURL();
2950 Logger::log('auto_redir: ' . $r[0]['name'] . ' ' . $sec, Logger::DEBUG);
2951 $dest = (($url) ? '&destination_url=' . $url : '');
2952 System::externalRedirect($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
2953 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest);
2960 * @brief Returns the activity verb
2962 * @param array $item Item array
2964 * @return string activity verb
2966 private static function constructVerb(array $item)
2968 if ($item['verb']) {
2969 return $item['verb'];
2971 return ACTIVITY_POST;
2974 private static function tgroupCheck($uid, $item)
2978 // check that the message originated elsewhere and is a top-level post
2980 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['parent-uri'])) {
2984 $user = DBA::selectFirst('user', ['page-flags', 'nickname'], ['uid' => $uid]);
2985 if (!DBA::isResult($user)) {
2989 $community_page = ($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY);
2990 $prvgroup = ($user['page-flags'] == User::PAGE_FLAGS_PRVGROUP);
2992 $link = Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']);
2995 * Diaspora uses their own hardwired link URL in @-tags
2996 * instead of the one we supply with webfinger
2998 $dlink = Strings::normaliseLink(System::baseUrl() . '/u/' . $user['nickname']);
3000 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
3002 foreach ($matches as $mtch) {
3003 if (Strings::compareLink($link, $mtch[1]) || Strings::compareLink($dlink, $mtch[1])) {
3005 Logger::log('mention found: ' . $mtch[2]);
3014 return $community_page || $prvgroup;
3018 * This function returns true if $update has an edited timestamp newer
3019 * than $existing, i.e. $update contains new data which should override
3020 * what's already there. If there is no timestamp yet, the update is
3021 * assumed to be newer. If the update has no timestamp, the existing
3022 * item is assumed to be up-to-date. If the timestamps are equal it
3023 * assumes the update has been seen before and should be ignored.
3028 * @throws \Exception
3030 private static function isEditedTimestampNewer($existing, $update)
3032 if (empty($existing['edited'])) {
3035 if (empty($update['edited'])) {
3039 $existing_edited = DateTimeFormat::utc($existing['edited']);
3040 $update_edited = DateTimeFormat::utc($update['edited']);
3042 return (strcmp($existing_edited, $update_edited) < 0);
3046 * Checks if the given contact url does support DFRN
3048 * @param string $url profile url
3049 * @param boolean $update Update the profile
3051 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3052 * @throws \ImagickException
3054 public static function isSupportedByContactUrl($url, $update = false)
3056 $probe = Probe::uri($url, Protocol::DFRN, 0, !$update);
3057 return $probe['network'] == Protocol::DFRN;