3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol;
26 use Friendica\App\BaseURL;
27 use Friendica\Content\Text\BBCode;
28 use Friendica\Core\Hook;
29 use Friendica\Core\Logger;
30 use Friendica\Core\Protocol;
31 use Friendica\Database\DBA;
33 use Friendica\Model\Contact;
34 use Friendica\Model\Conversation;
35 use Friendica\Model\Event;
36 use Friendica\Model\FContact;
37 use Friendica\Model\Item;
38 use Friendica\Model\ItemURI;
39 use Friendica\Model\Mail;
40 use Friendica\Model\Notification;
41 use Friendica\Model\PermissionSet;
42 use Friendica\Model\Post;
43 use Friendica\Model\Post\Category;
44 use Friendica\Model\Profile;
45 use Friendica\Model\Tag;
46 use Friendica\Model\User;
47 use Friendica\Model\Verb;
48 use Friendica\Network\Probe;
49 use Friendica\Util\Crypto;
50 use Friendica\Util\DateTimeFormat;
51 use Friendica\Util\Images;
52 use Friendica\Util\Network;
53 use Friendica\Util\Strings;
54 use Friendica\Util\XML;
57 * This class contain functions to create and send DFRN XML files
62 const TOP_LEVEL = 0; // Top level posting
63 const REPLY = 1; // Regular reply that is stored locally
64 const REPLY_RC = 2; // Reply that will be relayed
67 * Generates an array of contact and user for DFRN imports
69 * This array contains not only the receiver but also the sender of the message.
71 * @param integer $cid Contact id
72 * @param integer $uid User id
74 * @return array importer
77 public static function getImporter($cid, $uid = 0)
79 $condition = ['id' => $cid, 'blocked' => false, 'pending' => false];
80 $contact = DBA::selectFirst('contact', [], $condition);
81 if (!DBA::isResult($contact)) {
85 $contact['cpubkey'] = $contact['pubkey'];
86 $contact['cprvkey'] = $contact['prvkey'];
87 $contact['senderName'] = $contact['name'];
90 $condition = ['uid' => $uid, 'account_expired' => false, 'account_removed' => false];
91 $user = DBA::selectFirst('user', [], $condition);
92 if (!DBA::isResult($user)) {
96 $user['importer_uid'] = $user['uid'];
97 $user['uprvkey'] = $user['prvkey'];
99 $user = ['importer_uid' => 0, 'uprvkey' => '', 'timezone' => 'UTC',
100 'nickname' => '', 'sprvkey' => '', 'spubkey' => '',
101 'page-flags' => 0, 'account-type' => 0, 'prvnets' => 0];
104 return array_merge($contact, $user);
108 * Generates the atom entries for delivery.php
110 * This function is used whenever content is transmitted via DFRN.
112 * @param array $items Item elements
113 * @param array $owner Owner record
115 * @return string DFRN entries
116 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
117 * @throws \ImagickException
118 * @todo Find proper type-hints
120 public static function entries($items, $owner)
122 $doc = new DOMDocument('1.0', 'utf-8');
123 $doc->formatOutput = true;
125 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
127 if (! count($items)) {
128 return trim($doc->saveXML());
131 foreach ($items as $item) {
132 // These values aren't sent when sending from the queue.
133 /// @todo Check if we can set these values from the queue or if they are needed at all.
134 $item["entry:comment-allow"] = ($item["entry:comment-allow"] ?? '') ?: true;
135 $item["entry:cid"] = $item["entry:cid"] ?? 0;
137 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
139 $root->appendChild($entry);
143 return trim($doc->saveXML());
147 * Generate an atom feed for the given user
149 * This function is called when another server is pulling data from the user feed.
151 * @param string $dfrn_id DFRN ID from the requesting party
152 * @param string $owner_nick Owner nick name
153 * @param string $last_update Date of the last update
154 * @param int $direction Can be -1, 0 or 1.
155 * @param boolean $onlyheader Output only the header without content? (Default is "no")
157 * @return string DFRN feed entries
158 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
159 * @throws \ImagickException
161 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false)
165 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
166 $public_feed = (($dfrn_id) ? false : true);
167 $starred = false; // not yet implemented, possible security issues
170 if ($public_feed && $a->argc > 2) {
171 for ($x = 2; $x < $a->argc; $x++) {
172 if ($a->argv[$x] == 'converse') {
175 if ($a->argv[$x] == 'starred') {
178 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
179 $category = $a->argv[$x+1];
184 // default permissions - anonymous user
186 $sql_extra = sprintf(" AND `private` != %s ", Item::PRIVATE);
188 $owner = DBA::selectFirst('owner-view', [], ['nickname' => $owner_nick]);
189 if (!DBA::isResult($owner)) {
190 Logger::log(sprintf('No contact found for nickname=%d', $owner_nick), Logger::WARNING);
194 $owner_id = $owner['uid'];
197 switch ($direction) {
199 $sql_extra = sprintf(" AND `issued-id` = '%s' ", DBA::escape($dfrn_id));
202 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
205 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
212 $contact = DBA::selectFirst('contact', [], ["NOT `blocked` AND `contact`.`uid` = ?" . $sql_extra, $owner_id]);
213 if (!DBA::isResult($contact)) {
214 Logger::notice('No contact found', ['uid' => $owner_id]);
218 $set = PermissionSet::get($owner_id, $contact['id']);
221 $sql_extra = " AND `psid` IN (" . implode(',', $set) .")";
223 $sql_extra = sprintf(" AND `private` != %s", Item::PRIVATE);
227 if (!strlen($last_update)) {
228 $last_update = 'now -30 days';
231 if (isset($category)) {
232 $sql_extra .= sprintf(" AND `uri-id` IN (SELECT `uri-id` FROM `category-view` WHERE `name` = '%s' AND `type` = %d AND `uid` = %d)",
233 DBA::escape(Strings::protectSprintf($category)), intval(Category::CATEGORY), intval($owner_id));
236 if ($public_feed && ! $converse) {
237 $sql_extra .= " AND `self` ";
240 $check_date = DateTimeFormat::utc($last_update);
242 $condition = ["`uid` = ? AND `wall` AND `changed` > ? AND `vid` != ? AND `visible`" . $sql_extra,
243 $owner_id, $check_date, Verb::getID(Activity::ANNOUNCE)];
245 $params = ['sort' => ['parent' => $public_feed, 'received']];
246 $items = Post::selectToArray(Item::DELIVER_FIELDLIST, $condition, $params, ['limit' => 300]);
249 * Will check further below if this actually returned results.
250 * We will provide an empty feed if that is the case.
253 $doc = new DOMDocument('1.0', 'utf-8');
254 $doc->formatOutput = true;
256 $alternatelink = $owner['url'];
258 if (isset($category)) {
259 $alternatelink .= "/category/".$category;
263 $author = "dfrn:owner";
268 $root = self::addHeader($doc, $owner, $author, $alternatelink, true);
270 /// @TODO This hook can't work anymore
271 // \Friendica\Core\Hook::callAll('atom_feed', $atom);
273 if (!DBA::isResult($items) || $onlyheader) {
274 $atom = trim($doc->saveXML());
276 Hook::callAll('atom_feed_end', $atom);
281 foreach ($items as $item) {
282 // prevent private email from leaking.
283 if ($item['network'] == Protocol::MAIL) {
287 // public feeds get html, our own nodes use bbcode
291 // catch any email that's in a public conversation and make sure it doesn't leak
292 if ($item['private'] == Item::PRIVATE) {
299 $entry = self::entry($doc, $type, $item, $owner, true);
301 $root->appendChild($entry);
305 $atom = trim($doc->saveXML());
307 Hook::callAll('atom_feed_end', $atom);
313 * Generate an atom entry for a given item id
315 * @param int $item_id The item id
316 * @param boolean $conversation Show the conversation. If false show the single post.
318 * @return string DFRN feed entry
319 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
320 * @throws \ImagickException
322 public static function itemFeed($item_id, $conversation = false)
325 $condition = ['parent' => $item_id];
327 $condition = ['id' => $item_id];
330 $items = Post::selectToArray(Item::DELIVER_FIELDLIST, $condition);
331 if (!DBA::isResult($items)) {
337 if ($item['uid'] != 0) {
338 $owner = User::getOwnerDataById($item['uid']);
343 $owner = ['uid' => 0, 'nick' => 'feed-item'];
346 $doc = new DOMDocument('1.0', 'utf-8');
347 $doc->formatOutput = true;
351 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
352 $doc->appendChild($root);
354 $root->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
355 $root->setAttribute("xmlns:at", ActivityNamespace::TOMB);
356 $root->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
357 $root->setAttribute("xmlns:dfrn", ActivityNamespace::DFRN);
358 $root->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
359 $root->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
360 $root->setAttribute("xmlns:poco", ActivityNamespace::POCO);
361 $root->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
362 $root->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
364 //$root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
366 foreach ($items as $item) {
367 $entry = self::entry($doc, $type, $item, $owner, true, 0);
369 $root->appendChild($entry);
373 self::entry($doc, $type, $item, $owner, true, 0, true);
376 $atom = trim($doc->saveXML());
381 * Create XML text for DFRN mails
383 * @param array $mail Mail record
384 * @param array $owner Owner record
386 * @return string DFRN mail
387 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
388 * @todo Find proper type-hints
390 public static function mail(array $mail, array $owner)
392 $doc = new DOMDocument('1.0', 'utf-8');
393 $doc->formatOutput = true;
395 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
397 $mailElement = $doc->createElement("dfrn:mail");
398 $senderElement = $doc->createElement("dfrn:sender");
400 XML::addElement($doc, $senderElement, "dfrn:name", $owner['name']);
401 XML::addElement($doc, $senderElement, "dfrn:uri", $owner['url']);
402 XML::addElement($doc, $senderElement, "dfrn:avatar", $owner['thumb']);
404 $mailElement->appendChild($senderElement);
406 XML::addElement($doc, $mailElement, "dfrn:id", $mail['uri']);
407 XML::addElement($doc, $mailElement, "dfrn:in-reply-to", $mail['parent-uri']);
408 XML::addElement($doc, $mailElement, "dfrn:sentdate", DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM));
409 XML::addElement($doc, $mailElement, "dfrn:subject", $mail['title']);
410 XML::addElement($doc, $mailElement, "dfrn:content", $mail['body']);
412 $root->appendChild($mailElement);
414 return trim($doc->saveXML());
418 * Create XML text for DFRN friend suggestions
420 * @param array $item suggestion elements
421 * @param array $owner Owner record
423 * @return string DFRN suggestions
424 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
425 * @todo Find proper type-hints
427 public static function fsuggest($item, $owner)
429 $doc = new DOMDocument('1.0', 'utf-8');
430 $doc->formatOutput = true;
432 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
434 $suggest = $doc->createElement("dfrn:suggest");
436 XML::addElement($doc, $suggest, "dfrn:url", $item['url']);
437 XML::addElement($doc, $suggest, "dfrn:name", $item['name']);
438 XML::addElement($doc, $suggest, "dfrn:photo", $item['photo']);
439 XML::addElement($doc, $suggest, "dfrn:request", $item['request']);
440 XML::addElement($doc, $suggest, "dfrn:note", $item['note']);
442 $root->appendChild($suggest);
444 return trim($doc->saveXML());
448 * Create XML text for DFRN relocations
450 * @param array $owner Owner record
451 * @param int $uid User ID
453 * @return string DFRN relocations
454 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
455 * @todo Find proper type-hints
457 public static function relocate($owner, $uid)
460 /* get site pubkey. this could be a new installation with no site keys*/
461 $pubkey = DI::config()->get('system', 'site_pubkey');
463 $res = Crypto::newKeypair(1024);
464 DI::config()->set('system', 'site_prvkey', $res['prvkey']);
465 DI::config()->set('system', 'site_pubkey', $res['pubkey']);
469 "SELECT `resource-id` , `scale`, type FROM `photo`
470 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;",
474 $ext = Images::supportedTypes();
476 foreach ($rp as $p) {
477 $photos[$p['scale']] = DI::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
481 $doc = new DOMDocument('1.0', 'utf-8');
482 $doc->formatOutput = true;
484 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
486 $relocate = $doc->createElement("dfrn:relocate");
488 XML::addElement($doc, $relocate, "dfrn:url", $owner['url']);
489 XML::addElement($doc, $relocate, "dfrn:name", $owner['name']);
490 XML::addElement($doc, $relocate, "dfrn:addr", $owner['addr']);
491 XML::addElement($doc, $relocate, "dfrn:avatar", $owner['avatar']);
492 XML::addElement($doc, $relocate, "dfrn:photo", $photos[4]);
493 XML::addElement($doc, $relocate, "dfrn:thumb", $photos[5]);
494 XML::addElement($doc, $relocate, "dfrn:micro", $photos[6]);
495 XML::addElement($doc, $relocate, "dfrn:request", $owner['request']);
496 XML::addElement($doc, $relocate, "dfrn:confirm", $owner['confirm']);
497 XML::addElement($doc, $relocate, "dfrn:notify", $owner['notify']);
498 XML::addElement($doc, $relocate, "dfrn:poll", $owner['poll']);
499 XML::addElement($doc, $relocate, "dfrn:sitepubkey", DI::config()->get('system', 'site_pubkey'));
501 $root->appendChild($relocate);
503 return trim($doc->saveXML());
507 * Adds the header elements for the DFRN protocol
509 * @param DOMDocument $doc XML document
510 * @param array $owner Owner record
511 * @param string $authorelement Element name for the author
512 * @param string $alternatelink link to profile or category
513 * @param bool $public Is it a header for public posts?
515 * @return object XML root object
516 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
517 * @todo Find proper type-hints
519 private static function addHeader(DOMDocument $doc, $owner, $authorelement, $alternatelink = "", $public = false)
522 if ($alternatelink == "") {
523 $alternatelink = $owner['url'];
526 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
527 $doc->appendChild($root);
529 $root->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
530 $root->setAttribute("xmlns:at", ActivityNamespace::TOMB);
531 $root->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
532 $root->setAttribute("xmlns:dfrn", ActivityNamespace::DFRN);
533 $root->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
534 $root->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
535 $root->setAttribute("xmlns:poco", ActivityNamespace::POCO);
536 $root->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
537 $root->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
539 XML::addElement($doc, $root, "id", DI::baseUrl()."/profile/".$owner["nick"]);
540 XML::addElement($doc, $root, "title", $owner["name"]);
542 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION];
543 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
545 $attributes = ["rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/"];
546 XML::addElement($doc, $root, "link", "", $attributes);
548 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $alternatelink];
549 XML::addElement($doc, $root, "link", "", $attributes);
553 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
554 OStatus::hublinks($doc, $root, $owner["nick"]);
556 $attributes = ["rel" => "salmon", "href" => DI::baseUrl()."/salmon/".$owner["nick"]];
557 XML::addElement($doc, $root, "link", "", $attributes);
559 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => DI::baseUrl()."/salmon/".$owner["nick"]];
560 XML::addElement($doc, $root, "link", "", $attributes);
562 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => DI::baseUrl()."/salmon/".$owner["nick"]];
563 XML::addElement($doc, $root, "link", "", $attributes);
566 // For backward compatibility we keep this element
567 if ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY) {
568 XML::addElement($doc, $root, "dfrn:community", 1);
571 // The former element is replaced by this one
572 XML::addElement($doc, $root, "dfrn:account_type", $owner["account-type"]);
574 /// @todo We need a way to transmit the different page flags like "User::PAGE_FLAGS_PRVGROUP"
576 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
578 $author = self::addAuthor($doc, $owner, $authorelement, $public);
579 $root->appendChild($author);
585 * Adds the author element in the header for the DFRN protocol
587 * @param DOMDocument $doc XML document
588 * @param array $owner Owner record
589 * @param string $authorelement Element name for the author
590 * @param boolean $public boolean
592 * @return \DOMElement XML author object
593 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
594 * @todo Find proper type-hints
596 private static function addAuthor(DOMDocument $doc, array $owner, $authorelement, $public)
598 // Should the profile be "unsearchable" in the net? Then add the "hide" element
599 $hide = DBA::exists('profile', ['uid' => $owner['uid'], 'net-publish' => false]);
601 $author = $doc->createElement($authorelement);
603 $namdate = DateTimeFormat::utc($owner['name-date'].'+00:00', DateTimeFormat::ATOM);
604 $picdate = DateTimeFormat::utc($owner['avatar-date'].'+00:00', DateTimeFormat::ATOM);
608 if (!$public || !$hide) {
609 $attributes = ["dfrn:updated" => $namdate];
612 XML::addElement($doc, $author, "name", $owner["name"], $attributes);
613 XML::addElement($doc, $author, "uri", DI::baseUrl().'/profile/'.$owner["nickname"], $attributes);
614 XML::addElement($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
616 $attributes = ["rel" => "photo", "type" => "image/jpeg",
617 "media:width" => 300, "media:height" => 300, "href" => $owner['photo']];
619 if (!$public || !$hide) {
620 $attributes["dfrn:updated"] = $picdate;
623 XML::addElement($doc, $author, "link", "", $attributes);
625 $attributes["rel"] = "avatar";
626 XML::addElement($doc, $author, "link", "", $attributes);
629 XML::addElement($doc, $author, "dfrn:hide", "true");
632 // The following fields will only be generated if the data isn't meant for a public feed
637 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
640 XML::addElement($doc, $author, "dfrn:birthday", $birthday);
643 // Only show contact details when we are allowed to
644 $profile = DBA::selectFirst('owner-view',
645 ['about', 'name', 'homepage', 'nickname', 'timezone', 'locality', 'region', 'country-name', 'pub_keywords', 'xmpp', 'dob'],
646 ['uid' => $owner['uid'], 'hidewall' => false]);
647 if (DBA::isResult($profile)) {
648 XML::addElement($doc, $author, "poco:displayName", $profile["name"]);
649 XML::addElement($doc, $author, "poco:updated", $namdate);
651 if (trim($profile["dob"]) > DBA::NULL_DATE) {
652 XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
655 XML::addElement($doc, $author, "poco:note", $profile["about"]);
656 XML::addElement($doc, $author, "poco:preferredUsername", $profile["nickname"]);
658 $savetz = date_default_timezone_get();
659 date_default_timezone_set($profile["timezone"]);
660 XML::addElement($doc, $author, "poco:utcOffset", date("P"));
661 date_default_timezone_set($savetz);
663 if (trim($profile["homepage"]) != "") {
664 $urls = $doc->createElement("poco:urls");
665 XML::addElement($doc, $urls, "poco:type", "homepage");
666 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
667 XML::addElement($doc, $urls, "poco:primary", "true");
668 $author->appendChild($urls);
671 if (trim($profile["pub_keywords"]) != "") {
672 $keywords = explode(",", $profile["pub_keywords"]);
674 foreach ($keywords as $keyword) {
675 XML::addElement($doc, $author, "poco:tags", trim($keyword));
679 if (trim($profile["xmpp"]) != "") {
680 $ims = $doc->createElement("poco:ims");
681 XML::addElement($doc, $ims, "poco:type", "xmpp");
682 XML::addElement($doc, $ims, "poco:value", $profile["xmpp"]);
683 XML::addElement($doc, $ims, "poco:primary", "true");
684 $author->appendChild($ims);
687 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
688 $element = $doc->createElement("poco:address");
690 XML::addElement($doc, $element, "poco:formatted", Profile::formatLocation($profile));
692 if (trim($profile["locality"]) != "") {
693 XML::addElement($doc, $element, "poco:locality", $profile["locality"]);
696 if (trim($profile["region"]) != "") {
697 XML::addElement($doc, $element, "poco:region", $profile["region"]);
700 if (trim($profile["country-name"]) != "") {
701 XML::addElement($doc, $element, "poco:country", $profile["country-name"]);
704 $author->appendChild($element);
712 * Adds the author elements in the "entry" elements of the DFRN protocol
714 * @param DOMDocument $doc XML document
715 * @param string $element Element name for the author
716 * @param string $contact_url Link of the contact
717 * @param array $item Item elements
719 * @return \DOMElement XML author object
720 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
721 * @todo Find proper type-hints
723 private static function addEntryAuthor(DOMDocument $doc, $element, $contact_url, $item)
725 $author = $doc->createElement($element);
727 $contact = Contact::getByURLForUser($contact_url, $item["uid"], false, ['url', 'name', 'addr', 'photo']);
728 if (!empty($contact)) {
729 XML::addElement($doc, $author, "name", $contact["name"]);
730 XML::addElement($doc, $author, "uri", $contact["url"]);
731 XML::addElement($doc, $author, "dfrn:handle", $contact["addr"]);
734 /// - Check real image type and image size
735 /// - Check which of these boths elements we should use
738 "type" => "image/jpeg",
740 "media:height" => 80,
741 "href" => $contact["photo"]];
742 XML::addElement($doc, $author, "link", "", $attributes);
746 "type" => "image/jpeg",
748 "media:height" => 80,
749 "href" => $contact["photo"]];
750 XML::addElement($doc, $author, "link", "", $attributes);
757 * Adds the activity elements
759 * @param DOMDocument $doc XML document
760 * @param string $element Element name for the activity
761 * @param string $activity activity value
763 * @return \DOMElement XML activity object
764 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
765 * @todo Find proper type-hints
767 private static function createActivity(DOMDocument $doc, $element, $activity)
770 $entry = $doc->createElement($element);
772 $r = XML::parseString($activity);
778 XML::addElement($doc, $entry, "activity:object-type", $r->type);
782 XML::addElement($doc, $entry, "id", $r->id);
786 XML::addElement($doc, $entry, "title", $r->title);
790 if (substr($r->link, 0, 1) == '<') {
791 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
792 $r->link = str_replace('&', '&', $r->link);
795 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
797 // XML does need a single element as root element so we add a dummy element here
798 $data = XML::parseString("<dummy>" . $r->link . "</dummy>");
799 if (is_object($data)) {
800 foreach ($data->link as $link) {
802 foreach ($link->attributes() as $parameter => $value) {
803 $attributes[$parameter] = $value;
805 XML::addElement($doc, $entry, "link", "", $attributes);
809 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
810 XML::addElement($doc, $entry, "link", "", $attributes);
814 XML::addElement($doc, $entry, "content", BBCode::convert($r->content), ["type" => "html"]);
824 * Adds the elements for attachments
826 * @param object $doc XML document
827 * @param object $root XML root
828 * @param array $item Item element
830 * @return void XML attachment object
831 * @todo Find proper type-hints
833 private static function getAttachment($doc, $root, $item)
835 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]) as $attachment) {
836 $attributes = ['rel' => 'enclosure',
837 'href' => $attachment['url'],
838 'type' => $attachment['mimetype']];
840 if (!empty($attachment['size'])) {
841 $attributes['length'] = intval($attachment['size']);
843 if (!empty($attachment['description'])) {
844 $attributes['title'] = $attachment['description'];
847 XML::addElement($doc, $root, 'link', '', $attributes);
852 * Adds the "entry" elements for the DFRN protocol
854 * @param DOMDocument $doc XML document
855 * @param string $type "text" or "html"
856 * @param array $item Item element
857 * @param array $owner Owner record
858 * @param bool $comment Trigger the sending of the "comment" element
859 * @param int $cid Contact ID of the recipient
860 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
862 * @return null|\DOMElement XML entry object
863 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
864 * @throws \ImagickException
865 * @todo Find proper type-hints
867 private static function entry(DOMDocument $doc, $type, array $item, array $owner, $comment = false, $cid = 0, $single = false)
871 if (!$item['parent']) {
872 Logger::notice('Item without parent found.', ['type' => $type, 'item' => $item]);
876 if ($item['deleted']) {
877 $attributes = ["ref" => $item['uri'], "when" => DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM)];
878 return XML::createElement($doc, "at:deleted-entry", "", $attributes);
882 $entry = $doc->createElement("entry");
884 $entry = $doc->createElementNS(ActivityNamespace::ATOM1, 'entry');
885 $doc->appendChild($entry);
887 $entry->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
888 $entry->setAttribute("xmlns:at", ActivityNamespace::TOMB);
889 $entry->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
890 $entry->setAttribute("xmlns:dfrn", ActivityNamespace::DFRN);
891 $entry->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
892 $entry->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
893 $entry->setAttribute("xmlns:poco", ActivityNamespace::POCO);
894 $entry->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
895 $entry->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
898 if ($item['private'] == Item::PRIVATE) {
899 $body = Item::fixPrivatePhotos($item['body'], $owner['uid'], $item, $cid);
901 $body = $item['body'];
904 // Remove the abstract element. It is only locally important.
905 $body = BBCode::stripAbstract($body);
908 if ($type == 'html') {
911 if ($item['title'] != "") {
912 $htmlbody = "[b]" . $item['title'] . "[/b]\n\n" . $htmlbody;
915 $htmlbody = BBCode::convert($htmlbody, false, BBCode::OSTATUS);
918 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
919 $entry->appendChild($author);
921 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
922 $entry->appendChild($dfrnowner);
924 if ($item['gravity'] != GRAVITY_PARENT) {
925 $parent = Post::selectFirst(['guid', 'plink'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
926 if (DBA::isResult($parent)) {
927 $attributes = ["ref" => $item['thr-parent'], "type" => "text/html",
928 "href" => $parent['plink'],
929 "dfrn:diaspora_guid" => $parent['guid']];
930 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
934 // Add conversation data. This is used for OStatus
935 $conversation_href = DI::baseUrl()."/display/".$item["parent-guid"];
936 $conversation_uri = $conversation_href;
938 if (isset($parent_item)) {
939 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $item['thr-parent']]);
940 if (DBA::isResult($conversation)) {
941 if ($conversation['conversation-uri'] != '') {
942 $conversation_uri = $conversation['conversation-uri'];
944 if ($conversation['conversation-href'] != '') {
945 $conversation_href = $conversation['conversation-href'];
951 "href" => $conversation_href,
952 "ref" => $conversation_uri];
954 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
956 XML::addElement($doc, $entry, "id", $item["uri"]);
957 XML::addElement($doc, $entry, "title", $item["title"]);
959 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"] . "+00:00", DateTimeFormat::ATOM));
960 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"] . "+00:00", DateTimeFormat::ATOM));
962 // "dfrn:env" is used to read the content
963 XML::addElement($doc, $entry, "dfrn:env", Strings::base64UrlEncode($body, true));
965 // The "content" field is not read by the receiver. We could remove it when the type is "text"
966 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
967 XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
969 // We save this value in "plink". Maybe we should read it from there as well?
975 ["rel" => "alternate", "type" => "text/html",
976 "href" => DI::baseUrl() . "/display/" . $item["guid"]]
979 // "comment-allow" is some old fashioned stuff for old Friendica versions.
980 // It is included in the rewritten code for completeness
982 XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
985 if ($item['location']) {
986 XML::addElement($doc, $entry, "dfrn:location", $item['location']);
989 if ($item['coord']) {
990 XML::addElement($doc, $entry, "georss:point", $item['coord']);
993 if ($item['private']) {
994 // Friendica versions prior to 2020.3 can't handle "unlisted" properly. So we can only transmit public and private
995 XML::addElement($doc, $entry, "dfrn:private", ($item['private'] == Item::PRIVATE ? Item::PRIVATE : Item::PUBLIC));
996 XML::addElement($doc, $entry, "dfrn:unlisted", $item['private'] == Item::UNLISTED);
999 if ($item['extid']) {
1000 XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
1003 if ($item['post-type'] == Item::PT_PAGE) {
1004 XML::addElement($doc, $entry, "dfrn:bookmark", "true");
1008 XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
1011 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
1013 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
1014 // It is needed for relayed comments to Diaspora.
1015 if ($item['signed_text']) {
1016 $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => '','signer' => '']));
1017 XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
1020 XML::addElement($doc, $entry, "activity:verb", self::constructVerb($item));
1022 if ($item['object-type'] != "") {
1023 XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
1024 } elseif ($item['gravity'] == GRAVITY_PARENT) {
1025 XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::NOTE);
1027 XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::COMMENT);
1030 $actobj = self::createActivity($doc, "activity:object", $item['object']);
1032 $entry->appendChild($actobj);
1035 $actarg = self::createActivity($doc, "activity:target", $item['target']);
1037 $entry->appendChild($actarg);
1040 $tags = Tag::getByURIId($item['uri-id']);
1043 foreach ($tags as $tag) {
1044 if (($type != 'html') || ($tag['type'] == Tag::HASHTAG)) {
1045 XML::addElement($doc, $entry, "category", "", ["scheme" => "X-DFRN:" . Tag::TAG_CHARACTER[$tag['type']] . ":" . $tag['url'], "term" => $tag['name']]);
1047 if ($tag['type'] != Tag::HASHTAG) {
1048 $mentioned[$tag['url']] = $tag['url'];
1053 foreach ($mentioned as $mention) {
1054 $condition = ['uid' => $owner["uid"], 'nurl' => Strings::normaliseLink($mention)];
1055 $contact = DBA::selectFirst('contact', ['forum', 'prv'], $condition);
1057 if (DBA::isResult($contact) && ($contact["forum"] || $contact["prv"])) {
1063 ["rel" => "mentioned",
1064 "ostatus:object-type" => Activity\ObjectType::GROUP,
1073 ["rel" => "mentioned",
1074 "ostatus:object-type" => Activity\ObjectType::PERSON,
1080 self::getAttachment($doc, $entry, $item);
1086 * encrypts data via AES
1088 * @param string $data The data that is to be encrypted
1089 * @param string $key The AES key
1091 * @return string encrypted data
1093 private static function aesEncrypt($data, $key)
1095 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1099 * decrypts data via AES
1101 * @param string $encrypted The encrypted data
1102 * @param string $key The AES key
1104 * @return string decrypted data
1106 public static function aesDecrypt($encrypted, $key)
1108 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1112 * Delivers the atom content to the contacts
1114 * @param array $owner Owner record
1115 * @param array $contact Contact record of the receiver
1116 * @param string $atom Content that will be transmitted
1117 * @param bool $dissolve (to be documented)
1119 * @return int Deliver status. Negative values mean an error.
1120 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1121 * @throws \ImagickException
1122 * @todo Add array type-hint for $owner, $contact
1124 public static function deliver($owner, $contact, $atom, $dissolve = false)
1126 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1128 if ($contact['duplex'] && $contact['dfrn-id']) {
1129 $idtosend = '0:' . $orig_id;
1131 if ($contact['duplex'] && $contact['issued-id']) {
1132 $idtosend = '1:' . $orig_id;
1135 $rino = DI::config()->get('system', 'rino_encrypt');
1136 $rino = intval($rino);
1138 Logger::log("Local rino version: ". $rino, Logger::DEBUG);
1140 $ssl_val = intval(DI::config()->get('system', 'ssl_policy'));
1143 case BaseURL::SSL_POLICY_FULL:
1144 $ssl_policy = 'full';
1146 case BaseURL::SSL_POLICY_SELFSIGN:
1147 $ssl_policy = 'self';
1149 case BaseURL::SSL_POLICY_NONE:
1151 $ssl_policy = 'none';
1155 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1157 Logger::log('dfrn_deliver: ' . $url);
1159 $curlResult = DI::httpRequest()->get($url);
1161 if ($curlResult->isTimeout()) {
1162 return -2; // timed out
1165 $xml = $curlResult->getBody();
1167 $curl_stat = $curlResult->getReturnCode();
1168 if (empty($curl_stat)) {
1169 return -3; // timed out
1172 Logger::log('dfrn_deliver: ' . $xml, Logger::DATA);
1178 if (strpos($xml, '<?xml') === false) {
1179 Logger::log('dfrn_deliver: no valid XML returned');
1180 Logger::log('dfrn_deliver: returned XML: ' . $xml, Logger::DATA);
1184 $res = XML::parseString($xml);
1186 if (!is_object($res) || (intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
1187 if (empty($res->status)) {
1190 $status = $res->status;
1197 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1198 $challenge = hex2bin((string) $res->challenge);
1199 $perm = (($res->perm) ? $res->perm : null);
1200 $dfrn_version = floatval($res->dfrn_version ?: 2.0);
1201 $rino_remote_version = intval($res->rino);
1202 $page = (($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? 1 : 0);
1204 Logger::log("Remote rino version: ".$rino_remote_version." for ".$contact["url"], Logger::DEBUG);
1206 if ($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
1210 $final_dfrn_id = '';
1213 if ((($perm == 'rw') && !intval($contact['writable']))
1214 || (($perm == 'r') && intval($contact['writable']))
1216 DBA::update('contact', ['writable' => ($perm == 'rw')], ['id' => $contact['id']]);
1218 $contact['writable'] = (string) 1 - intval($contact['writable']);
1222 if (($contact['duplex'] && strlen($contact['pubkey']))
1223 || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY && strlen($contact['pubkey']))
1224 || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
1226 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
1227 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
1229 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
1230 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
1233 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1235 if (strpos($final_dfrn_id, ':') == 1) {
1236 $final_dfrn_id = substr($final_dfrn_id, 2);
1239 if ($final_dfrn_id != $orig_id) {
1240 Logger::log('dfrn_deliver: wrong dfrn_id.');
1241 // did not decode properly - cannot trust this site
1245 $postvars['dfrn_id'] = $idtosend;
1246 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1248 $postvars['dissolve'] = '1';
1251 if ((($contact['rel']) && ($contact['rel'] != Contact::SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY)) {
1252 $postvars['data'] = $atom;
1253 $postvars['perm'] = 'rw';
1255 $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
1256 $postvars['perm'] = 'r';
1259 $postvars['ssl_policy'] = $ssl_policy;
1262 $postvars['page'] = $page;
1266 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1267 Logger::log('rino version: '. $rino_remote_version);
1269 switch ($rino_remote_version) {
1271 $key = openssl_random_pseudo_bytes(16);
1272 $data = self::aesEncrypt($postvars['data'], $key);
1276 Logger::log("rino: invalid requested version '$rino_remote_version'");
1280 $postvars['rino'] = $rino_remote_version;
1281 $postvars['data'] = bin2hex($data);
1283 if ($dfrn_version >= 2.1) {
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_encrypt($key, $postvars['key'], $contact['pubkey']);
1290 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1293 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY)) {
1294 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1296 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1300 Logger::log('md5 rawkey ' . md5($postvars['key']));
1302 $postvars['key'] = bin2hex($postvars['key']);
1306 Logger::debug('dfrn_deliver', ['post' => $postvars]);
1308 $postResult = DI::httpRequest()->post($contact['notify'], $postvars);
1310 $xml = $postResult->getBody();
1312 Logger::log('dfrn_deliver: ' . "RECEIVED: " . $xml, Logger::DATA);
1314 $curl_stat = $postResult->getReturnCode();
1315 if (empty($curl_stat) || empty($xml)) {
1316 return -9; // timed out
1319 if (($curl_stat == 503) && stristr($postResult->getHeader(), 'retry-after')) {
1323 if (strpos($xml, '<?xml') === false) {
1324 Logger::log('dfrn_deliver: phase 2: no valid XML returned');
1325 Logger::log('dfrn_deliver: phase 2: returned XML: ' . $xml, Logger::DATA);
1329 $res = XML::parseString($xml);
1331 if (!isset($res->status)) {
1335 // Possibly old servers had returned an empty value when everything was okay
1336 if (empty($res->status)) {
1340 if (!empty($res->message)) {
1341 Logger::log('Delivery returned status '.$res->status.' - '.$res->message, Logger::DEBUG);
1344 return intval($res->status);
1348 * Transmits atom content to the contacts via the Diaspora transport layer
1350 * @param array $owner Owner record
1351 * @param array $contact Contact record of the receiver
1352 * @param string $atom Content that will be transmitted
1354 * @param bool $public_batch
1355 * @return int Deliver status. Negative values mean an error.
1356 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1357 * @throws \ImagickException
1359 public static function transmit($owner, $contact, $atom, $public_batch = false)
1361 if (!$public_batch) {
1362 if (empty($contact['addr'])) {
1363 Logger::log('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.');
1364 if (Contact::updateFromProbe($contact['id'])) {
1365 $new_contact = DBA::selectFirst('contact', ['addr'], ['id' => $contact['id']]);
1366 $contact['addr'] = $new_contact['addr'];
1369 if (empty($contact['addr'])) {
1370 Logger::log('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
1375 $fcontact = FContact::getByURL($contact['addr']);
1376 if (empty($fcontact)) {
1377 Logger::log('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
1380 $pubkey = $fcontact['pubkey'];
1385 $envelope = Diaspora::buildMessage($atom, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
1387 // Create the endpoint for public posts. This is some WIP and should later be added to the probing
1388 if ($public_batch && empty($contact["batch"])) {
1389 $parts = parse_url($contact["notify"]);
1390 $path_parts = explode('/', $parts['path']);
1391 array_pop($path_parts);
1392 $parts['path'] = implode('/', $path_parts);
1393 $contact["batch"] = Network::unparseURL($parts);
1396 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
1398 if (empty($dest_url)) {
1399 Logger::info('Empty destination', ['public' => $public_batch, 'contact' => $contact]);
1403 $content_type = ($public_batch ? "application/magic-envelope+xml" : "application/json");
1405 $postResult = DI::httpRequest()->post($dest_url, $envelope, ["Content-Type: " . $content_type]);
1406 $xml = $postResult->getBody();
1408 $curl_stat = $postResult->getReturnCode();
1409 if (empty($curl_stat) || empty($xml)) {
1410 Logger::log('Empty answer from ' . $contact['id'] . ' - ' . $dest_url);
1411 return -9; // timed out
1414 if (($curl_stat == 503) && (stristr($postResult->getHeader(), 'retry-after'))) {
1418 if (strpos($xml, '<?xml') === false) {
1419 Logger::log('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url);
1420 Logger::log('Returned XML: ' . $xml, Logger::DATA);
1424 $res = XML::parseString($xml);
1426 if (empty($res->status)) {
1430 if (!empty($res->message)) {
1431 Logger::log('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message, Logger::DEBUG);
1434 return intval($res->status);
1438 * Fetch the author data from head or entry items
1440 * @param object $xpath XPath object
1441 * @param object $context In which context should the data be searched
1442 * @param array $importer Record of the importer user mixed with contact of the content
1443 * @param string $element Element name from which the data is fetched
1444 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1445 * @param string $xml optional, default empty
1447 * @return array Relevant data of the author
1448 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1449 * @throws \ImagickException
1450 * @todo Find good type-hints for all parameter
1452 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
1455 $author["name"] = XML::getFirstNodeValue($xpath, $element."/atom:name/text()", $context);
1456 $author["link"] = XML::getFirstNodeValue($xpath, $element."/atom:uri/text()", $context);
1458 $fields = ['id', 'uid', 'url', 'network', 'avatar-date', 'avatar', 'name-date', 'uri-date', 'addr',
1459 'name', 'nick', 'about', 'location', 'keywords', 'xmpp', 'bdyear', 'bd', 'hidden', 'contact-type'];
1460 $condition = ["`uid` = ? AND `nurl` = ? AND `network` != ? AND NOT `pending` AND NOT `blocked`",
1461 $importer["importer_uid"], Strings::normaliseLink($author["link"]), Protocol::STATUSNET];
1463 if ($importer['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
1464 $condition = DBA::mergeConditions($condition, ['rel' => [Contact::SHARING, Contact::FRIEND]]);
1467 $contact_old = DBA::selectFirst('contact', $fields, $condition);
1469 if (DBA::isResult($contact_old)) {
1470 $author["contact-id"] = $contact_old["id"];
1471 $author["network"] = $contact_old["network"];
1473 Logger::info('Contact not found', ['condition' => $condition]);
1475 $author["contact-unknown"] = true;
1476 $contact = Contact::getByURL($author["link"], null, ["id", "network"]);
1477 $author["contact-id"] = $contact["id"] ?? $importer["id"];
1478 $author["network"] = $contact["network"] ?? $importer["network"];
1482 // Until now we aren't serving different sizes - but maybe later
1484 /// @todo check if "avatar" or "photo" would be the best field in the specification
1485 $avatars = $xpath->query($element . "/atom:link[@rel='avatar']", $context);
1486 foreach ($avatars as $avatar) {
1489 foreach ($avatar->attributes as $attributes) {
1490 /// @TODO Rewrite these similar if() to one switch
1491 if ($attributes->name == "href") {
1492 $href = $attributes->textContent;
1494 if ($attributes->name == "width") {
1495 $width = $attributes->textContent;
1497 if ($attributes->name == "updated") {
1498 $author["avatar-date"] = $attributes->textContent;
1501 if (($width > 0) && ($href != "")) {
1502 $avatarlist[$width] = $href;
1506 if (count($avatarlist) > 0) {
1507 krsort($avatarlist);
1508 $author["avatar"] = current($avatarlist);
1511 if (empty($author['avatar']) && !empty($author['link'])) {
1512 $cid = Contact::getIdForURL($author['link'], 0);
1514 $contact = DBA::selectFirst('contact', ['avatar'], ['id' => $cid]);
1515 if (DBA::isResult($contact)) {
1516 $author['avatar'] = $contact['avatar'];
1521 if (empty($author['avatar'])) {
1522 Logger::log('Empty author: ' . $xml);
1523 $author['avatar'] = '';
1526 if (DBA::isResult($contact_old) && !$onlyfetch) {
1527 Logger::log("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", Logger::DEBUG);
1529 $poco = ["url" => $contact_old["url"], "network" => $contact_old["network"]];
1531 // When was the last change to name or uri?
1532 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1533 foreach ($name_element->attributes as $attributes) {
1534 if ($attributes->name == "updated") {
1535 $poco["name-date"] = $attributes->textContent;
1539 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1540 foreach ($link_element->attributes as $attributes) {
1541 if ($attributes->name == "updated") {
1542 $poco["uri-date"] = $attributes->textContent;
1546 // Update contact data
1547 $value = XML::getFirstNodeValue($xpath, $element . "/dfrn:handle/text()", $context);
1549 $poco["addr"] = $value;
1552 $value = XML::getFirstNodeValue($xpath, $element . "/poco:displayName/text()", $context);
1554 $poco["name"] = $value;
1557 $value = XML::getFirstNodeValue($xpath, $element . "/poco:preferredUsername/text()", $context);
1559 $poco["nick"] = $value;
1562 $value = XML::getFirstNodeValue($xpath, $element . "/poco:note/text()", $context);
1564 $poco["about"] = $value;
1567 $value = XML::getFirstNodeValue($xpath, $element . "/poco:address/poco:formatted/text()", $context);
1569 $poco["location"] = $value;
1572 /// @todo Only search for elements with "poco:type" = "xmpp"
1573 $value = XML::getFirstNodeValue($xpath, $element . "/poco:ims/poco:value/text()", $context);
1575 $poco["xmpp"] = $value;
1578 /// @todo Add support for the following fields that we don't support by now in the contact table:
1579 /// - poco:utcOffset
1585 // If the "hide" element is present then the profile isn't searchable.
1586 $hide = intval(XML::getFirstNodeValue($xpath, $element . "/dfrn:hide/text()", $context) == "true");
1588 Logger::log("Hidden status for contact " . $contact_old["url"] . ": " . $hide, Logger::DEBUG);
1590 // If the contact isn't searchable then set the contact to "hidden".
1591 // Problem: This can be manually overridden by the user.
1593 $contact_old["hidden"] = true;
1596 // Save the keywords into the contact table
1598 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1599 foreach ($tagelements as $tag) {
1600 $tags[$tag->nodeValue] = $tag->nodeValue;
1604 $poco["keywords"] = implode(", ", $tags);
1607 // "dfrn:birthday" contains the birthday converted to UTC
1608 $birthday = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1610 if (strtotime($birthday) > time()) {
1611 $bd_timestamp = strtotime($birthday);
1613 $poco["bdyear"] = date("Y", $bd_timestamp);
1616 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1617 $value = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1619 if (!in_array($value, ["", "0000-00-00", DBA::NULL_DATE])) {
1620 $bdyear = date("Y");
1621 $value = str_replace(["0000", "0001"], $bdyear, $value);
1623 if (strtotime($value) < time()) {
1624 $value = str_replace($bdyear, $bdyear + 1, $value);
1627 $poco["bd"] = $value;
1630 $contact = array_merge($contact_old, $poco);
1632 if ($contact_old["bdyear"] != $contact["bdyear"]) {
1633 Event::createBirthday($contact, $birthday);
1636 $fields = ['name' => $contact['name'], 'nick' => $contact['nick'], 'about' => $contact['about'],
1637 'location' => $contact['location'], 'addr' => $contact['addr'], 'keywords' => $contact['keywords'],
1638 'bdyear' => $contact['bdyear'], 'bd' => $contact['bd'], 'hidden' => $contact['hidden'],
1639 'xmpp' => $contact['xmpp'], 'name-date' => DateTimeFormat::utc($contact['name-date']),
1640 'unsearchable' => $contact['hidden'], 'uri-date' => DateTimeFormat::utc($contact['uri-date'])];
1642 DBA::update('contact', $fields, ['id' => $contact['id'], 'network' => $contact['network']], $contact_old);
1644 // Update the public contact. Don't set the "hidden" value, this is used differently for public contacts
1645 unset($fields['hidden']);
1646 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($contact_old['url'])];
1647 DBA::update('contact', $fields, $condition, true);
1649 Contact::updateAvatar($contact['id'], $author['avatar']);
1651 $pcid = Contact::getIdForURL($contact_old['url']);
1652 if (!empty($pcid)) {
1653 Contact::updateAvatar($pcid, $author['avatar']);
1661 * Transforms activity objects into an XML string
1663 * @param object $xpath XPath object
1664 * @param object $activity Activity object
1665 * @param string $element element name
1667 * @return string XML string
1668 * @todo Find good type-hints for all parameter
1670 private static function transformActivity($xpath, $activity, $element)
1672 if (!is_object($activity)) {
1676 $obj_doc = new DOMDocument("1.0", "utf-8");
1677 $obj_doc->formatOutput = true;
1679 $obj_element = $obj_doc->createElementNS( ActivityNamespace::ATOM1, $element);
1681 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1682 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1684 $id = $xpath->query("atom:id", $activity)->item(0);
1685 if (is_object($id)) {
1686 $obj_element->appendChild($obj_doc->importNode($id, true));
1689 $title = $xpath->query("atom:title", $activity)->item(0);
1690 if (is_object($title)) {
1691 $obj_element->appendChild($obj_doc->importNode($title, true));
1694 $links = $xpath->query("atom:link", $activity);
1695 if (is_object($links)) {
1696 foreach ($links as $link) {
1697 $obj_element->appendChild($obj_doc->importNode($link, true));
1701 $content = $xpath->query("atom:content", $activity)->item(0);
1702 if (is_object($content)) {
1703 $obj_element->appendChild($obj_doc->importNode($content, true));
1706 $obj_doc->appendChild($obj_element);
1708 $objxml = $obj_doc->saveXML($obj_element);
1710 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1711 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1716 * Processes the mail elements
1718 * @param object $xpath XPath object
1719 * @param object $mail mail elements
1720 * @param array $importer Record of the importer user mixed with contact of the content
1722 * @throws \Exception
1723 * @todo Find good type-hints for all parameter
1725 private static function processMail($xpath, $mail, $importer)
1727 Logger::log("Processing mails");
1730 $msg["uid"] = $importer["importer_uid"];
1731 $msg["from-name"] = XML::getFirstValue($xpath, "dfrn:sender/dfrn:name/text()", $mail);
1732 $msg["from-url"] = XML::getFirstValue($xpath, "dfrn:sender/dfrn:uri/text()", $mail);
1733 $msg["from-photo"] = XML::getFirstValue($xpath, "dfrn:sender/dfrn:avatar/text()", $mail);
1734 $msg["contact-id"] = $importer["id"];
1735 $msg["uri"] = XML::getFirstValue($xpath, "dfrn:id/text()", $mail);
1736 $msg["parent-uri"] = XML::getFirstValue($xpath, "dfrn:in-reply-to/text()", $mail);
1737 $msg["created"] = DateTimeFormat::utc(XML::getFirstValue($xpath, "dfrn:sentdate/text()", $mail));
1738 $msg["title"] = XML::getFirstValue($xpath, "dfrn:subject/text()", $mail);
1739 $msg["body"] = XML::getFirstValue($xpath, "dfrn:content/text()", $mail);
1745 * Processes the suggestion elements
1747 * @param object $xpath XPath object
1748 * @param object $suggestion suggestion elements
1749 * @param array $importer Record of the importer user mixed with contact of the content
1751 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1752 * @todo Find good type-hints for all parameter
1754 private static function processSuggestion($xpath, $suggestion, $importer)
1756 Logger::notice('Processing suggestions');
1758 $url = $xpath->evaluate('string(dfrn:url[1]/text())', $suggestion);
1759 $cid = Contact::getIdForURL($url);
1760 $note = $xpath->evaluate('string(dfrn:note[1]/text())', $suggestion);
1762 return FContact::addSuggestion($importer['importer_uid'], $cid, $importer['id'], $note);
1766 * Processes the relocation elements
1768 * @param object $xpath XPath object
1769 * @param object $relocation relocation elements
1770 * @param array $importer Record of the importer user mixed with contact of the content
1772 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1773 * @throws \ImagickException
1774 * @todo Find good type-hints for all parameter
1776 private static function processRelocation($xpath, $relocation, $importer)
1778 Logger::log("Processing relocations");
1780 /// @TODO Rewrite this to one statement
1782 $relocate["uid"] = $importer["importer_uid"];
1783 $relocate["cid"] = $importer["id"];
1784 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1785 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
1786 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1787 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
1788 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1789 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1790 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1791 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1792 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1793 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1794 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1795 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1797 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
1798 $relocate["avatar"] = $relocate["photo"];
1801 if ($relocate["addr"] == "") {
1802 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
1807 "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d",
1808 intval($importer["id"]),
1809 intval($importer["importer_uid"])
1812 if (!DBA::isResult($r)) {
1813 Logger::log("Query failed to execute, no result returned in " . __FUNCTION__);
1819 // Update the contact table. We try to find every entry.
1820 $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
1821 'url' => $relocate["url"], 'nurl' => Strings::normaliseLink($relocate["url"]),
1822 'addr' => $relocate["addr"], 'request' => $relocate["request"],
1823 'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
1824 'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
1825 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], Strings::normaliseLink($old["url"])];
1827 DBA::update('contact', $fields, $condition);
1829 Contact::updateAvatar($importer["id"], $relocate["avatar"], true);
1831 Logger::log('Contacts are updated.');
1834 /// merge with current record, current contents have priority
1835 /// update record, set url-updated
1836 /// update profile photos
1837 /// schedule a scan?
1844 * @param array $current the current item record
1845 * @param array $item the new item record
1846 * @param array $importer Record of the importer user mixed with contact of the content
1847 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
1849 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1850 * @todo set proper type-hints (array?)
1852 private static function updateContent($current, $item, $importer, $entrytype)
1856 if (self::isEditedTimestampNewer($current, $item)) {
1857 // do not accept (ignore) an earlier edit than one we currently have.
1858 if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
1862 $fields = ['title' => $item['title'] ?? '', 'body' => $item['body'] ?? '',
1863 'changed' => DateTimeFormat::utcNow(),
1864 'edited' => DateTimeFormat::utc($item["edited"])];
1866 $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
1867 Item::update($fields, $condition);
1875 * Detects the entry type of the item
1877 * @param array $importer Record of the importer user mixed with contact of the content
1878 * @param array $item the new item record
1880 * @return int Is it a toplevel entry, a comment or a relayed comment?
1881 * @throws \Exception
1882 * @todo set proper type-hints (array?)
1884 private static function getEntryType($importer, $item)
1886 if ($item["thr-parent"] != $item["uri"]) {
1889 if ($importer["page-flags"] == User::PAGE_FLAGS_COMMUNITY || $importer["page-flags"] == User::PAGE_FLAGS_PRVGROUP) {
1892 Logger::log("possible community action");
1894 $sql_extra = " AND `self` AND `wall`";
1897 // was the top-level post for this action written by somebody on this site?
1898 // Specifically, the recipient?
1899 $parent = Post::selectFirst(['forum_mode', 'wall'],
1900 ["`uri` = ? AND `uid` = ?" . $sql_extra, $item["thr-parent"], $importer["importer_uid"]]);
1902 $is_a_remote_action = DBA::isResult($parent);
1905 * Does this have the characteristics of a community or private group action?
1906 * If it's an action to a wall post on a community/prvgroup page it's a
1907 * valid community action. Also forum_mode makes it valid for sure.
1908 * If neither, it's not.
1910 if ($is_a_remote_action && $community && (!$parent["forum_mode"]) && (!$parent["wall"])) {
1911 $is_a_remote_action = false;
1912 Logger::log("not a community action");
1915 if ($is_a_remote_action) {
1916 return DFRN::REPLY_RC;
1921 return DFRN::TOP_LEVEL;
1928 * @param array $item The new item record
1929 * @param array $importer Record of the importer user mixed with contact of the content
1931 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1932 * @todo set proper type-hints (array?)
1934 private static function doPoke(array $item, array $importer)
1936 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
1940 $xo = XML::parseString($item["object"]);
1942 if (($xo->type == Activity\ObjectType::PERSON) && ($xo->id)) {
1943 // somebody was poked/prodded. Was it me?
1945 foreach ($xo->link as $l) {
1946 $atts = $l->attributes();
1947 switch ($atts["rel"]) {
1949 $Blink = $atts["href"];
1956 if ($Blink && Strings::compareLink($Blink, DI::baseUrl() . "/profile/" . $importer["nickname"])) {
1957 $author = DBA::selectFirst('contact', ['id', 'name', 'thumb', 'url'], ['id' => $item['author-id']]);
1959 $parent = Post::selectFirst(['id'], ['uri' => $item['thr-parent'], 'uid' => $importer["importer_uid"]]);
1960 $item['parent'] = $parent['id'];
1962 // send a notification
1965 "type" => Notification\Type::POKE,
1966 "otype" => Notification\ObjectType::PERSON,
1967 "activity" => $verb,
1968 "verb" => $item["verb"],
1969 "uid" => $importer["importer_uid"],
1970 "cid" => $author["id"],
1972 "link" => DI::baseUrl() . "/display/" . urlencode($item['guid']),
1980 * Processes several actions, depending on the verb
1982 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
1983 * @param array $importer Record of the importer user mixed with contact of the content
1984 * @param array $item the new item record
1985 * @param bool $is_like Is the verb a "like"?
1987 * @return bool Should the processing of the entries be continued?
1988 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1989 * @todo set proper type-hints (array?)
1991 private static function processVerbs($entrytype, $importer, &$item, &$is_like)
1993 Logger::log("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, Logger::DEBUG);
1995 if (($entrytype == DFRN::TOP_LEVEL) && !empty($importer['id'])) {
1996 // The filling of the the "contact" variable is done for legcy reasons
1997 // The functions below are partly used by ostatus.php as well - where we have this variable
1998 $contact = Contact::selectFirst([], ['id' => $importer['id']]);
2000 $activity = DI::activity();
2002 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2003 // This function once was responsible for DFRN and OStatus.
2004 if ($activity->match($item["verb"], Activity::FOLLOW)) {
2005 Logger::log("New follower");
2006 Contact::addRelationship($importer, $contact, $item);
2009 if ($activity->match($item["verb"], Activity::UNFOLLOW)) {
2010 Logger::log("Lost follower");
2011 Contact::removeFollower($importer, $contact, $item);
2014 if ($activity->match($item["verb"], Activity::REQ_FRIEND)) {
2015 Logger::log("New friend request");
2016 Contact::addRelationship($importer, $contact, $item, true);
2019 if ($activity->match($item["verb"], Activity::UNFRIEND)) {
2020 Logger::log("Lost sharer");
2021 Contact::removeSharer($importer, $contact, $item);
2025 if (($item["verb"] == Activity::LIKE)
2026 || ($item["verb"] == Activity::DISLIKE)
2027 || ($item["verb"] == Activity::ATTEND)
2028 || ($item["verb"] == Activity::ATTENDNO)
2029 || ($item["verb"] == Activity::ATTENDMAYBE)
2030 || ($item["verb"] == Activity::ANNOUNCE)
2033 $item["gravity"] = GRAVITY_ACTIVITY;
2034 // only one like or dislike per person
2035 // split into two queries for performance issues
2036 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2037 'verb' => $item['verb'], 'parent-uri' => $item['thr-parent']];
2038 if (Post::exists($condition)) {
2042 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2043 'verb' => $item['verb'], 'thr-parent' => $item['thr-parent']];
2044 if (Post::exists($condition)) {
2048 // The owner of an activity must be the author
2049 $item["owner-name"] = $item["author-name"];
2050 $item["owner-link"] = $item["author-link"];
2051 $item["owner-avatar"] = $item["author-avatar"];
2052 $item["owner-id"] = $item["author-id"];
2057 if (($item["verb"] == Activity::TAG) && ($item["object-type"] == Activity\ObjectType::TAGTERM)) {
2058 $xo = XML::parseString($item["object"]);
2059 $xt = XML::parseString($item["target"]);
2061 if ($xt->type == Activity\ObjectType::NOTE) {
2062 $item_tag = Post::selectFirst(['id', 'uri-id'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]);
2064 if (!DBA::isResult($item_tag)) {
2065 Logger::log("Query failed to execute, no result returned in " . __FUNCTION__);
2069 // extract tag, if not duplicate, add to parent item
2071 Tag::store($item_tag['uri-id'], Tag::HASHTAG, $xo->content);
2080 * Processes the link elements
2082 * @param object $links link elements
2083 * @param array $item the item record
2085 * @todo set proper type-hints
2087 private static function parseLinks($links, &$item)
2094 foreach ($links as $link) {
2095 foreach ($link->attributes as $attributes) {
2096 switch ($attributes->name) {
2097 case "href" : $href = $attributes->textContent; break;
2098 case "rel" : $rel = $attributes->textContent; break;
2099 case "type" : $type = $attributes->textContent; break;
2100 case "length": $length = $attributes->textContent; break;
2101 case "title" : $title = $attributes->textContent; break;
2104 if (($rel != "") && ($href != "")) {
2107 $item["plink"] = $href;
2110 Post\Media::insert(['uri-id' => $item['uri-id'], 'type' => Post\Media::DOCUMENT,
2111 'url' => $href, 'mimetype' => $type, 'size' => $length, 'description' => $title]);
2119 * Checks if an incoming message is wanted
2121 * @param array $item
2122 * @return boolean Is the message wanted?
2124 private static function isSolicitedMessage(array $item)
2126 if (DBA::exists('contact', ["`nurl` = ? AND `uid` != ? AND `rel` IN (?, ?)",
2127 Strings::normaliseLink($item["author-link"]), 0, Contact::FRIEND, Contact::SHARING])) {
2128 Logger::info('Author has got followers - accepted', ['uri' => $item['uri'], 'author' => $item["author-link"]]);
2132 $taglist = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]);
2133 $tags = array_column($taglist, 'name');
2134 return Relay::isSolicitedPost($tags, $item['body'], $item['author-id'], $item['uri'], Protocol::DFRN);
2138 * Processes the entry elements which contain the items and comments
2140 * @param array $header Array of the header elements that always stay the same
2141 * @param object $xpath XPath object
2142 * @param object $entry entry elements
2143 * @param array $importer Record of the importer user mixed with contact of the content
2144 * @param string $xml xml
2146 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2147 * @throws \ImagickException
2148 * @todo Add type-hints
2150 private static function processEntry($header, $xpath, $entry, $importer, $xml, $protocol)
2152 Logger::log("Processing entries");
2156 $item["protocol"] = $protocol;
2158 $item["source"] = $xml;
2161 $item["uri"] = XML::getFirstNodeValue($xpath, "atom:id/text()", $entry);
2163 $item["edited"] = XML::getFirstNodeValue($xpath, "atom:updated/text()", $entry);
2165 $current = Post::selectFirst(['id', 'uid', 'edited', 'body'],
2166 ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
2168 // Is there an existing item?
2169 if (DBA::isResult($current) && !self::isEditedTimestampNewer($current, $item)) {
2170 Logger::log("Item ".$item["uri"]." (".$item['edited'].") already existed.", Logger::DEBUG);
2175 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true, $xml);
2177 $owner_unknown = (isset($owner["contact-unknown"]) && $owner["contact-unknown"]);
2179 $item["owner-name"] = $owner["name"];
2180 $item["owner-link"] = $owner["link"];
2181 $item["owner-avatar"] = $owner["avatar"];
2182 $item["owner-id"] = Contact::getIdForURL($owner["link"], 0);
2185 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true, $xml);
2187 $item["author-name"] = $author["name"];
2188 $item["author-link"] = $author["link"];
2189 $item["author-avatar"] = $author["avatar"];
2190 $item["author-id"] = Contact::getIdForURL($author["link"], 0);
2192 $item["title"] = XML::getFirstNodeValue($xpath, "atom:title/text()", $entry);
2194 $item["created"] = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2196 $item["body"] = XML::getFirstNodeValue($xpath, "dfrn:env/text()", $entry);
2197 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2199 $item["body"] = Strings::base64UrlDecode($item["body"]);
2201 $item["body"] = BBCode::limitBodySize($item["body"]);
2203 /// @todo We should check for a repeated post and if we know the repeated author.
2205 // We don't need the content element since "dfrn:env" is always present
2206 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2208 $item["location"] = XML::getFirstNodeValue($xpath, "dfrn:location/text()", $entry);
2210 $item["coord"] = XML::getFirstNodeValue($xpath, "georss:point", $entry);
2212 $item["private"] = XML::getFirstNodeValue($xpath, "dfrn:private/text()", $entry);
2214 $unlisted = XML::getFirstNodeValue($xpath, "dfrn:unlisted/text()", $entry);
2215 if (!empty($unlisted) && ($item['private'] != Item::PRIVATE)) {
2216 $item['private'] = Item::UNLISTED;
2219 $item["extid"] = XML::getFirstNodeValue($xpath, "dfrn:extid/text()", $entry);
2221 if (XML::getFirstNodeValue($xpath, "dfrn:bookmark/text()", $entry) == "true") {
2222 $item["post-type"] = Item::PT_PAGE;
2225 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2226 if ($notice_info && ($notice_info->length > 0)) {
2227 foreach ($notice_info->item(0)->attributes as $attributes) {
2228 if ($attributes->name == "source") {
2229 $item["app"] = strip_tags($attributes->textContent);
2234 $item["guid"] = XML::getFirstNodeValue($xpath, "dfrn:diaspora_guid/text()", $entry);
2236 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
2238 Tag::storeFromBody($item['uri-id'], $item["body"]);
2240 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
2241 $dsprsig = XML::unescape(XML::getFirstNodeValue($xpath, "dfrn:diaspora_signature/text()", $entry));
2242 if ($dsprsig != "") {
2243 $signature = json_decode(base64_decode($dsprsig));
2244 // We don't store the old style signatures anymore that also contained the "signature" and "signer"
2245 if (!empty($signature->signed_text) && empty($signature->signature) && empty($signature->signer)) {
2246 $item["diaspora_signed_text"] = $signature->signed_text;
2250 $item["verb"] = XML::getFirstNodeValue($xpath, "activity:verb/text()", $entry);
2252 if (XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry) != "") {
2253 $item["object-type"] = XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry);
2256 $object = $xpath->query("activity:object", $entry)->item(0);
2257 $item["object"] = self::transformActivity($xpath, $object, "object");
2259 if (trim($item["object"]) != "") {
2260 $r = XML::parseString($item["object"]);
2261 if (isset($r->type)) {
2262 $item["object-type"] = $r->type;
2266 $target = $xpath->query("activity:target", $entry)->item(0);
2267 $item["target"] = self::transformActivity($xpath, $target, "target");
2269 $categories = $xpath->query("atom:category", $entry);
2271 foreach ($categories as $category) {
2274 foreach ($category->attributes as $attributes) {
2275 if ($attributes->name == "term") {
2276 $term = $attributes->textContent;
2279 if ($attributes->name == "scheme") {
2280 $scheme = $attributes->textContent;
2284 if (($term != "") && ($scheme != "")) {
2285 $parts = explode(":", $scheme);
2286 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2287 $termurl = array_pop($parts);
2288 $termurl = array_pop($parts) . ':' . $termurl;
2289 Tag::store($item['uri-id'], Tag::IMPLICIT_MENTION, $term, $termurl);
2295 $links = $xpath->query("atom:link", $entry);
2297 self::parseLinks($links, $item);
2300 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
2302 $conv = $xpath->query('ostatus:conversation', $entry);
2303 if (is_object($conv->item(0))) {
2304 foreach ($conv->item(0)->attributes as $attributes) {
2305 if ($attributes->name == "ref") {
2306 $item['conversation-uri'] = $attributes->textContent;
2308 if ($attributes->name == "href") {
2309 $item['conversation-href'] = $attributes->textContent;
2314 // Is it a reply or a top level posting?
2315 $item['thr-parent'] = $item['uri'];
2317 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2318 if (is_object($inreplyto->item(0))) {
2319 foreach ($inreplyto->item(0)->attributes as $attributes) {
2320 if ($attributes->name == "ref") {
2321 $item['thr-parent'] = $attributes->textContent;
2326 // Check if the message is wanted
2327 if (($importer['importer_uid'] == 0) && ($item['uri'] == $item['thr-parent'])) {
2328 if (!self::isSolicitedMessage($item)) {
2329 DBA::delete('item-uri', ['uri' => $item['uri']]);
2334 // Get the type of the item (Top level post, reply or remote reply)
2335 $entrytype = self::getEntryType($importer, $item);
2337 // Now assign the rest of the values that depend on the type of the message
2338 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2339 if (!isset($item["object-type"])) {
2340 $item["object-type"] = Activity\ObjectType::COMMENT;
2343 if ($item["contact-id"] != $owner["contact-id"]) {
2344 $item["contact-id"] = $owner["contact-id"];
2347 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2348 $item["network"] = $owner["network"];
2351 if ($item["contact-id"] != $author["contact-id"]) {
2352 $item["contact-id"] = $author["contact-id"];
2355 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2356 $item["network"] = $author["network"];
2360 // Ensure to have the correct share data
2361 $item = Item::addShareDataFromOriginal($item);
2363 if ($entrytype == DFRN::REPLY_RC) {
2365 } elseif ($entrytype == DFRN::TOP_LEVEL) {
2366 if (!isset($item["object-type"])) {
2367 $item["object-type"] = Activity\ObjectType::NOTE;
2371 if (($item["object-type"] == Activity\ObjectType::EVENT) && !$owner_unknown) {
2372 Logger::log("Item ".$item["uri"]." seems to contain an event.", Logger::DEBUG);
2373 $ev = Event::fromBBCode($item["body"]);
2374 if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
2375 Logger::log("Event in item ".$item["uri"]." was found.", Logger::DEBUG);
2376 $ev["cid"] = $importer["id"];
2377 $ev["uid"] = $importer["importer_uid"];
2378 $ev["uri"] = $item["uri"];
2379 $ev["edited"] = $item["edited"];
2380 $ev["private"] = $item["private"];
2381 $ev["guid"] = $item["guid"];
2382 $ev["plink"] = $item["plink"];
2383 $ev["network"] = $item["network"];
2384 $ev["protocol"] = $item["protocol"];
2385 $ev["direction"] = $item["direction"];
2386 $ev["source"] = $item["source"];
2388 $condition = ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]];
2389 $event = DBA::selectFirst('event', ['id'], $condition);
2390 if (DBA::isResult($event)) {
2391 $ev["id"] = $event["id"];
2394 $event_id = Event::store($ev);
2395 Logger::log("Event ".$event_id." was stored", Logger::DEBUG);
2401 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2402 Logger::log("Exiting because 'processVerbs' told us so", Logger::DEBUG);
2406 // This check is done here to be able to receive connection requests in "processVerbs"
2407 if (($entrytype == DFRN::TOP_LEVEL) && $owner_unknown) {
2408 Logger::log("Item won't be stored because user " . $importer["importer_uid"] . " doesn't follow " . $item["owner-link"] . ".", Logger::DEBUG);
2413 // Update content if 'updated' changes
2414 if (DBA::isResult($current)) {
2415 if (self::updateContent($current, $item, $importer, $entrytype)) {
2416 Logger::log("Item ".$item["uri"]." was updated.", Logger::DEBUG);
2418 Logger::log("Item " . $item["uri"] . " already existed.", Logger::DEBUG);
2423 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2424 // Will be overwritten for sharing accounts in Item::insert
2425 if (empty($item['post-type']) && ($entrytype == DFRN::REPLY)) {
2426 $item['post-type'] = Item::PT_COMMENT;
2429 $posted_id = Item::insert($item);
2431 Logger::log("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, Logger::DEBUG);
2433 if ($item['uid'] == 0) {
2434 Item::distribute($posted_id);
2439 } else { // $entrytype == DFRN::TOP_LEVEL
2440 if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
2441 Logger::log("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", Logger::DEBUG);
2444 if (!Strings::compareLink($item["owner-link"], $importer["url"])) {
2446 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2447 * but otherwise there's a possible data mixup on the sender's system.
2448 * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2449 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2451 Logger::log('Correcting item owner.', Logger::DEBUG);
2452 $item["owner-link"] = $importer["url"];
2453 $item["owner-id"] = Contact::getIdForURL($importer["url"], 0);
2456 if (($importer["rel"] == Contact::FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2457 Logger::log("Contact ".$importer["id"]." is only follower and tgroup check was negative.", Logger::DEBUG);
2461 // This is my contact on another system, but it's really me.
2462 // Turn this into a wall post.
2463 $notify = Item::isRemoteSelf($importer, $item);
2465 $posted_id = Item::insert($item, $notify);
2468 $posted_id = $notify;
2471 Logger::log("Item was stored with id ".$posted_id, Logger::DEBUG);
2473 if ($item['uid'] == 0) {
2474 Item::distribute($posted_id);
2477 if (stristr($item["verb"], Activity::POKE)) {
2478 $item['id'] = $posted_id;
2479 self::doPoke($item, $importer);
2487 * @param object $xpath XPath object
2488 * @param object $deletion deletion elements
2489 * @param array $importer Record of the importer user mixed with contact of the content
2491 * @throws \Exception
2492 * @todo set proper type-hints
2494 private static function processDeletion($xpath, $deletion, $importer)
2496 Logger::log("Processing deletions");
2499 foreach ($deletion->attributes as $attributes) {
2500 if ($attributes->name == "ref") {
2501 $uri = $attributes->textContent;
2505 if (!$uri || !$importer["id"]) {
2509 $condition = ['uri' => $uri, 'uid' => $importer["importer_uid"]];
2510 $item = Post::selectFirst(['id', 'parent', 'contact-id', 'uri-id', 'deleted', 'gravity'], $condition);
2511 if (!DBA::isResult($item)) {
2512 Logger::log("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", Logger::DEBUG);
2516 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $importer['importer_uid'], 'type' => Post\Category::FILE])) {
2517 Logger::notice("Item is filed. It won't be deleted.", ['uri' => $uri, 'uri-id' => $item['uri_id'], 'uid' => $importer["importer_uid"]]);
2521 // When it is a starting post it has to belong to the person that wants to delete it
2522 if (($item['gravity'] == GRAVITY_PARENT) && ($item['contact-id'] != $importer["id"])) {
2523 Logger::log("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", Logger::DEBUG);
2527 // Comments can be deleted by the thread owner or comment owner
2528 if (($item['gravity'] != GRAVITY_PARENT) && ($item['contact-id'] != $importer["id"])) {
2529 $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2530 if (!Post::exists($condition)) {
2531 Logger::log("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", Logger::DEBUG);
2536 if ($item["deleted"]) {
2540 Logger::log('deleting item '.$item['id'].' uri='.$uri, Logger::DEBUG);
2542 Item::markForDeletion(['id' => $item['id']]);
2546 * Imports a DFRN message
2548 * @param string $xml The DFRN message
2549 * @param array $importer Record of the importer user mixed with contact of the content
2550 * @param int $protocol Transport protocol
2551 * @param int $direction Is the message pushed or pulled?
2552 * @return integer Import status
2553 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2554 * @throws \ImagickException
2555 * @todo set proper type-hints
2557 public static function import($xml, $importer, $protocol, $direction)
2563 $doc = new DOMDocument();
2564 @$doc->loadXML($xml);
2566 $xpath = new DOMXPath($doc);
2567 $xpath->registerNamespace("atom", ActivityNamespace::ATOM1);
2568 $xpath->registerNamespace("thr", ActivityNamespace::THREAD);
2569 $xpath->registerNamespace("at", ActivityNamespace::TOMB);
2570 $xpath->registerNamespace("media", ActivityNamespace::MEDIA);
2571 $xpath->registerNamespace("dfrn", ActivityNamespace::DFRN);
2572 $xpath->registerNamespace("activity", ActivityNamespace::ACTIVITY);
2573 $xpath->registerNamespace("georss", ActivityNamespace::GEORSS);
2574 $xpath->registerNamespace("poco", ActivityNamespace::POCO);
2575 $xpath->registerNamespace("ostatus", ActivityNamespace::OSTATUS);
2576 $xpath->registerNamespace("statusnet", ActivityNamespace::STATUSNET);
2579 $header["uid"] = $importer["importer_uid"];
2580 $header["network"] = Protocol::DFRN;
2581 $header["wall"] = 0;
2582 $header["origin"] = 0;
2583 $header["contact-id"] = $importer["id"];
2584 $header["direction"] = $direction;
2586 if ($direction === Conversation::RELAY) {
2587 $header['post-type'] = Item::PT_RELAY;
2590 // Update the contact table if the data has changed
2592 // The "atom:author" is only present in feeds
2593 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2594 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2597 // Only the "dfrn:owner" in the head section contains all data
2598 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2599 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2602 Logger::log("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], Logger::DEBUG);
2604 // is it a public forum? Private forums aren't exposed with this method
2605 $forum = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:community/text()"));
2607 // The account type is new since 3.5.1
2608 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2609 // Hint: We are using separate update calls for uid=0 and uid!=0 since a combined call is bad for the database performance
2611 $accounttype = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:account_type/text()"));
2613 if ($accounttype != $importer["contact-type"]) {
2614 DBA::update('contact', ['contact-type' => $accounttype], ['id' => $importer['id']]);
2616 // Updating the public contact as well
2617 DBA::update('contact', ['contact-type' => $accounttype], ['uid' => 0, 'nurl' => $importer['nurl']]);
2619 // A forum contact can either have set "forum" or "prv" - but not both
2620 if ($accounttype == User::ACCOUNT_TYPE_COMMUNITY) {
2621 // It's a forum, so either set the public or private forum flag
2622 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer['id']];
2623 DBA::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2625 // Updating the public contact as well
2626 $condition = ['(`forum` != ? OR `prv` != ?) AND `uid` = 0 AND `nurl` = ?', $forum, !$forum, $importer['nurl']];
2627 DBA::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2629 // It's not a forum, so remove the flags
2630 $condition = ['(`forum` OR `prv`) AND `id` = ?', $importer['id']];
2631 DBA::update('contact', ['forum' => false, 'prv' => false], $condition);
2633 // Updating the public contact as well
2634 $condition = ['(`forum` OR `prv`) AND `uid` = 0 AND `nurl` = ?', $importer['nurl']];
2635 DBA::update('contact', ['forum' => false, 'prv' => false], $condition);
2637 } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
2638 $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2639 DBA::update('contact', ['forum' => $forum], $condition);
2641 // Updating the public contact as well
2642 $condition = ['`forum` != ? AND `uid` = 0 AND `nurl` = ?', $forum, $importer['nurl']];
2643 DBA::update('contact', ['forum' => $forum], $condition);
2647 // We are processing relocations even if we are ignoring a contact
2648 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2649 foreach ($relocations as $relocation) {
2650 self::processRelocation($xpath, $relocation, $importer);
2653 if (($importer["uid"] != 0) && !$importer["readonly"]) {
2654 $mails = $xpath->query("/atom:feed/dfrn:mail");
2655 foreach ($mails as $mail) {
2656 self::processMail($xpath, $mail, $importer);
2659 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2660 foreach ($suggestions as $suggestion) {
2661 self::processSuggestion($xpath, $suggestion, $importer);
2665 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2666 if (!empty($deletions)) {
2667 foreach ($deletions as $deletion) {
2668 self::processDeletion($xpath, $deletion, $importer);
2670 if (count($deletions) > 0) {
2671 Logger::notice('Deletions had been processed');
2676 $entries = $xpath->query("/atom:feed/atom:entry");
2677 foreach ($entries as $entry) {
2678 self::processEntry($header, $xpath, $entry, $importer, $xml, $protocol);
2681 Logger::log("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], Logger::DEBUG);
2686 * Returns the activity verb
2688 * @param array $item Item array
2690 * @return string activity verb
2692 private static function constructVerb(array $item)
2694 if ($item['verb']) {
2695 return $item['verb'];
2697 return Activity::POST;
2700 private static function tgroupCheck($uid, $item)
2704 // check that the message originated elsewhere and is a top-level post
2706 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['thr-parent'])) {
2710 $user = DBA::selectFirst('user', ['page-flags', 'nickname'], ['uid' => $uid]);
2711 if (!DBA::isResult($user)) {
2715 $community_page = ($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY);
2716 $prvgroup = ($user['page-flags'] == User::PAGE_FLAGS_PRVGROUP);
2718 $link = Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']);
2721 * Diaspora uses their own hardwired link URL in @-tags
2722 * instead of the one we supply with webfinger
2724 $dlink = Strings::normaliseLink(DI::baseUrl() . '/u/' . $user['nickname']);
2726 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2728 foreach ($matches as $mtch) {
2729 if (Strings::compareLink($link, $mtch[1]) || Strings::compareLink($dlink, $mtch[1])) {
2731 Logger::log('mention found: ' . $mtch[2]);
2740 return $community_page || $prvgroup;
2744 * This function returns true if $update has an edited timestamp newer
2745 * than $existing, i.e. $update contains new data which should override
2746 * what's already there. If there is no timestamp yet, the update is
2747 * assumed to be newer. If the update has no timestamp, the existing
2748 * item is assumed to be up-to-date. If the timestamps are equal it
2749 * assumes the update has been seen before and should be ignored.
2754 * @throws \Exception
2756 private static function isEditedTimestampNewer($existing, $update)
2758 if (empty($existing['edited'])) {
2761 if (empty($update['edited'])) {
2765 $existing_edited = DateTimeFormat::utc($existing['edited']);
2766 $update_edited = DateTimeFormat::utc($update['edited']);
2768 return (strcmp($existing_edited, $update_edited) < 0);
2772 * Checks if the given contact url does support DFRN
2774 * @param string $url profile url
2776 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2777 * @throws \ImagickException
2779 public static function isSupportedByContactUrl($url)
2781 $probe = Probe::uri($url, Protocol::DFRN);
2782 return $probe['network'] == Protocol::DFRN;