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\Notify;
41 use Friendica\Model\Notify\Type;
42 use Friendica\Model\PermissionSet;
43 use Friendica\Model\Post;
44 use Friendica\Model\Post\Category;
45 use Friendica\Model\Profile;
46 use Friendica\Model\Tag;
47 use Friendica\Model\User;
48 use Friendica\Model\Verb;
49 use Friendica\Network\Probe;
50 use Friendica\Util\Crypto;
51 use Friendica\Util\DateTimeFormat;
52 use Friendica\Util\Images;
53 use Friendica\Util\Network;
54 use Friendica\Util\Strings;
55 use Friendica\Util\XML;
58 * This class contain functions to create and send DFRN XML files
63 const TOP_LEVEL = 0; // Top level posting
64 const REPLY = 1; // Regular reply that is stored locally
65 const REPLY_RC = 2; // Reply that will be relayed
68 * Generates an array of contact and user for DFRN imports
70 * This array contains not only the receiver but also the sender of the message.
72 * @param integer $cid Contact id
73 * @param integer $uid User id
75 * @return array importer
78 public static function getImporter($cid, $uid = 0)
80 $condition = ['id' => $cid, 'blocked' => false, 'pending' => false];
81 $contact = DBA::selectFirst('contact', [], $condition);
82 if (!DBA::isResult($contact)) {
86 $contact['cpubkey'] = $contact['pubkey'];
87 $contact['cprvkey'] = $contact['prvkey'];
88 $contact['senderName'] = $contact['name'];
91 $condition = ['uid' => $uid, 'account_expired' => false, 'account_removed' => false];
92 $user = DBA::selectFirst('user', [], $condition);
93 if (!DBA::isResult($user)) {
97 $user['importer_uid'] = $user['uid'];
98 $user['uprvkey'] = $user['prvkey'];
100 $user = ['importer_uid' => 0, 'uprvkey' => '', 'timezone' => 'UTC',
101 'nickname' => '', 'sprvkey' => '', 'spubkey' => '',
102 'page-flags' => 0, 'account-type' => 0, 'prvnets' => 0];
105 return array_merge($contact, $user);
109 * Generates the atom entries for delivery.php
111 * This function is used whenever content is transmitted via DFRN.
113 * @param array $items Item elements
114 * @param array $owner Owner record
116 * @return string DFRN entries
117 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
118 * @throws \ImagickException
119 * @todo Find proper type-hints
121 public static function entries($items, $owner)
123 $doc = new DOMDocument('1.0', 'utf-8');
124 $doc->formatOutput = true;
126 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
128 if (! count($items)) {
129 return trim($doc->saveXML());
132 foreach ($items as $item) {
133 // These values aren't sent when sending from the queue.
134 /// @todo Check if we can set these values from the queue or if they are needed at all.
135 $item["entry:comment-allow"] = ($item["entry:comment-allow"] ?? '') ?: true;
136 $item["entry:cid"] = $item["entry:cid"] ?? 0;
138 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
140 $root->appendChild($entry);
144 return trim($doc->saveXML());
148 * Generate an atom feed for the given user
150 * This function is called when another server is pulling data from the user feed.
152 * @param string $dfrn_id DFRN ID from the requesting party
153 * @param string $owner_nick Owner nick name
154 * @param string $last_update Date of the last update
155 * @param int $direction Can be -1, 0 or 1.
156 * @param boolean $onlyheader Output only the header without content? (Default is "no")
158 * @return string DFRN feed entries
159 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
160 * @throws \ImagickException
162 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false)
166 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
167 $public_feed = (($dfrn_id) ? false : true);
168 $starred = false; // not yet implemented, possible security issues
171 if ($public_feed && $a->argc > 2) {
172 for ($x = 2; $x < $a->argc; $x++) {
173 if ($a->argv[$x] == 'converse') {
176 if ($a->argv[$x] == 'starred') {
179 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
180 $category = $a->argv[$x+1];
185 // default permissions - anonymous user
187 $sql_extra = sprintf(" AND `private` != %s ", Item::PRIVATE);
189 $owner = DBA::selectFirst('owner-view', [], ['nickname' => $owner_nick]);
190 if (!DBA::isResult($owner)) {
191 Logger::log(sprintf('No contact found for nickname=%d', $owner_nick), Logger::WARNING);
195 $owner_id = $owner['uid'];
198 switch ($direction) {
200 $sql_extra = sprintf(" AND `issued-id` = '%s' ", DBA::escape($dfrn_id));
203 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
206 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
213 $contact = DBA::selectFirst('contact', [], ["NOT `blocked` AND `contact`.`uid` = ?" . $sql_extra, $owner_id]);
214 if (!DBA::isResult($contact)) {
215 Logger::notice('No contact found', ['uid' => $owner_id]);
219 $set = PermissionSet::get($owner_id, $contact['id']);
222 $sql_extra = " AND `psid` IN (" . implode(',', $set) .")";
224 $sql_extra = sprintf(" AND `private` != %s", Item::PRIVATE);
228 if (!strlen($last_update)) {
229 $last_update = 'now -30 days';
232 if (isset($category)) {
233 $sql_extra .= sprintf(" AND `uri-id` IN (SELECT `uri-id` FROM `category-view` WHERE `name` = '%s' AND `type` = %d AND `uid` = %d)",
234 DBA::escape(Strings::protectSprintf($category)), intval(Category::CATEGORY), intval($owner_id));
237 if ($public_feed && ! $converse) {
238 $sql_extra .= " AND `self` ";
241 $check_date = DateTimeFormat::utc($last_update);
243 $condition = ["`uid` = ? AND `wall` AND `changed` > ? AND `vid` != ? AND `visible`" . $sql_extra,
244 $owner_id, $check_date, Verb::getID(Activity::ANNOUNCE)];
246 $params = ['sort' => ['parent' => $public_feed, 'received']];
247 $items = Post::selectToArray(Item::DELIVER_FIELDLIST, $condition, $params, ['limit' => 300]);
250 * Will check further below if this actually returned results.
251 * We will provide an empty feed if that is the case.
254 $doc = new DOMDocument('1.0', 'utf-8');
255 $doc->formatOutput = true;
257 $alternatelink = $owner['url'];
259 if (isset($category)) {
260 $alternatelink .= "/category/".$category;
264 $author = "dfrn:owner";
269 $root = self::addHeader($doc, $owner, $author, $alternatelink, true);
271 /// @TODO This hook can't work anymore
272 // \Friendica\Core\Hook::callAll('atom_feed', $atom);
274 if (!DBA::isResult($items) || $onlyheader) {
275 $atom = trim($doc->saveXML());
277 Hook::callAll('atom_feed_end', $atom);
282 foreach ($items as $item) {
283 // prevent private email from leaking.
284 if ($item['network'] == Protocol::MAIL) {
288 // public feeds get html, our own nodes use bbcode
292 // catch any email that's in a public conversation and make sure it doesn't leak
293 if ($item['private'] == Item::PRIVATE) {
300 $entry = self::entry($doc, $type, $item, $owner, true);
302 $root->appendChild($entry);
306 $atom = trim($doc->saveXML());
308 Hook::callAll('atom_feed_end', $atom);
314 * Generate an atom entry for a given item id
316 * @param int $item_id The item id
317 * @param boolean $conversation Show the conversation. If false show the single post.
319 * @return string DFRN feed entry
320 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
321 * @throws \ImagickException
323 public static function itemFeed($item_id, $conversation = false)
326 $condition = ['parent' => $item_id];
328 $condition = ['id' => $item_id];
331 $items = Post::selectToArray(Item::DELIVER_FIELDLIST, $condition);
332 if (!DBA::isResult($items)) {
338 if ($item['uid'] != 0) {
339 $owner = User::getOwnerDataById($item['uid']);
344 $owner = ['uid' => 0, 'nick' => 'feed-item'];
347 $doc = new DOMDocument('1.0', 'utf-8');
348 $doc->formatOutput = true;
352 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
353 $doc->appendChild($root);
355 $root->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
356 $root->setAttribute("xmlns:at", ActivityNamespace::TOMB);
357 $root->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
358 $root->setAttribute("xmlns:dfrn", ActivityNamespace::DFRN);
359 $root->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
360 $root->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
361 $root->setAttribute("xmlns:poco", ActivityNamespace::POCO);
362 $root->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
363 $root->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
365 //$root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
367 foreach ($items as $item) {
368 $entry = self::entry($doc, $type, $item, $owner, true, 0);
370 $root->appendChild($entry);
374 self::entry($doc, $type, $item, $owner, true, 0, true);
377 $atom = trim($doc->saveXML());
382 * Create XML text for DFRN mails
384 * @param array $mail Mail record
385 * @param array $owner Owner record
387 * @return string DFRN mail
388 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
389 * @todo Find proper type-hints
391 public static function mail(array $mail, array $owner)
393 $doc = new DOMDocument('1.0', 'utf-8');
394 $doc->formatOutput = true;
396 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
398 $mailElement = $doc->createElement("dfrn:mail");
399 $senderElement = $doc->createElement("dfrn:sender");
401 XML::addElement($doc, $senderElement, "dfrn:name", $owner['name']);
402 XML::addElement($doc, $senderElement, "dfrn:uri", $owner['url']);
403 XML::addElement($doc, $senderElement, "dfrn:avatar", $owner['thumb']);
405 $mailElement->appendChild($senderElement);
407 XML::addElement($doc, $mailElement, "dfrn:id", $mail['uri']);
408 XML::addElement($doc, $mailElement, "dfrn:in-reply-to", $mail['parent-uri']);
409 XML::addElement($doc, $mailElement, "dfrn:sentdate", DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM));
410 XML::addElement($doc, $mailElement, "dfrn:subject", $mail['title']);
411 XML::addElement($doc, $mailElement, "dfrn:content", $mail['body']);
413 $root->appendChild($mailElement);
415 return trim($doc->saveXML());
419 * Create XML text for DFRN friend suggestions
421 * @param array $item suggestion elements
422 * @param array $owner Owner record
424 * @return string DFRN suggestions
425 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
426 * @todo Find proper type-hints
428 public static function fsuggest($item, $owner)
430 $doc = new DOMDocument('1.0', 'utf-8');
431 $doc->formatOutput = true;
433 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
435 $suggest = $doc->createElement("dfrn:suggest");
437 XML::addElement($doc, $suggest, "dfrn:url", $item['url']);
438 XML::addElement($doc, $suggest, "dfrn:name", $item['name']);
439 XML::addElement($doc, $suggest, "dfrn:photo", $item['photo']);
440 XML::addElement($doc, $suggest, "dfrn:request", $item['request']);
441 XML::addElement($doc, $suggest, "dfrn:note", $item['note']);
443 $root->appendChild($suggest);
445 return trim($doc->saveXML());
449 * Create XML text for DFRN relocations
451 * @param array $owner Owner record
452 * @param int $uid User ID
454 * @return string DFRN relocations
455 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
456 * @todo Find proper type-hints
458 public static function relocate($owner, $uid)
461 /* get site pubkey. this could be a new installation with no site keys*/
462 $pubkey = DI::config()->get('system', 'site_pubkey');
464 $res = Crypto::newKeypair(1024);
465 DI::config()->set('system', 'site_prvkey', $res['prvkey']);
466 DI::config()->set('system', 'site_pubkey', $res['pubkey']);
470 "SELECT `resource-id` , `scale`, type FROM `photo`
471 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;",
475 $ext = Images::supportedTypes();
477 foreach ($rp as $p) {
478 $photos[$p['scale']] = DI::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
482 $doc = new DOMDocument('1.0', 'utf-8');
483 $doc->formatOutput = true;
485 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
487 $relocate = $doc->createElement("dfrn:relocate");
489 XML::addElement($doc, $relocate, "dfrn:url", $owner['url']);
490 XML::addElement($doc, $relocate, "dfrn:name", $owner['name']);
491 XML::addElement($doc, $relocate, "dfrn:addr", $owner['addr']);
492 XML::addElement($doc, $relocate, "dfrn:avatar", $owner['avatar']);
493 XML::addElement($doc, $relocate, "dfrn:photo", $photos[4]);
494 XML::addElement($doc, $relocate, "dfrn:thumb", $photos[5]);
495 XML::addElement($doc, $relocate, "dfrn:micro", $photos[6]);
496 XML::addElement($doc, $relocate, "dfrn:request", $owner['request']);
497 XML::addElement($doc, $relocate, "dfrn:confirm", $owner['confirm']);
498 XML::addElement($doc, $relocate, "dfrn:notify", $owner['notify']);
499 XML::addElement($doc, $relocate, "dfrn:poll", $owner['poll']);
500 XML::addElement($doc, $relocate, "dfrn:sitepubkey", DI::config()->get('system', 'site_pubkey'));
502 $root->appendChild($relocate);
504 return trim($doc->saveXML());
508 * Adds the header elements for the DFRN protocol
510 * @param DOMDocument $doc XML document
511 * @param array $owner Owner record
512 * @param string $authorelement Element name for the author
513 * @param string $alternatelink link to profile or category
514 * @param bool $public Is it a header for public posts?
516 * @return object XML root object
517 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
518 * @todo Find proper type-hints
520 private static function addHeader(DOMDocument $doc, $owner, $authorelement, $alternatelink = "", $public = false)
523 if ($alternatelink == "") {
524 $alternatelink = $owner['url'];
527 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
528 $doc->appendChild($root);
530 $root->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
531 $root->setAttribute("xmlns:at", ActivityNamespace::TOMB);
532 $root->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
533 $root->setAttribute("xmlns:dfrn", ActivityNamespace::DFRN);
534 $root->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
535 $root->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
536 $root->setAttribute("xmlns:poco", ActivityNamespace::POCO);
537 $root->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
538 $root->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
540 XML::addElement($doc, $root, "id", DI::baseUrl()."/profile/".$owner["nick"]);
541 XML::addElement($doc, $root, "title", $owner["name"]);
543 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION];
544 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
546 $attributes = ["rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/"];
547 XML::addElement($doc, $root, "link", "", $attributes);
549 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $alternatelink];
550 XML::addElement($doc, $root, "link", "", $attributes);
554 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
555 OStatus::hublinks($doc, $root, $owner["nick"]);
557 $attributes = ["rel" => "salmon", "href" => DI::baseUrl()."/salmon/".$owner["nick"]];
558 XML::addElement($doc, $root, "link", "", $attributes);
560 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => DI::baseUrl()."/salmon/".$owner["nick"]];
561 XML::addElement($doc, $root, "link", "", $attributes);
563 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => DI::baseUrl()."/salmon/".$owner["nick"]];
564 XML::addElement($doc, $root, "link", "", $attributes);
567 // For backward compatibility we keep this element
568 if ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY) {
569 XML::addElement($doc, $root, "dfrn:community", 1);
572 // The former element is replaced by this one
573 XML::addElement($doc, $root, "dfrn:account_type", $owner["account-type"]);
575 /// @todo We need a way to transmit the different page flags like "User::PAGE_FLAGS_PRVGROUP"
577 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
579 $author = self::addAuthor($doc, $owner, $authorelement, $public);
580 $root->appendChild($author);
586 * Adds the author element in the header for the DFRN protocol
588 * @param DOMDocument $doc XML document
589 * @param array $owner Owner record
590 * @param string $authorelement Element name for the author
591 * @param boolean $public boolean
593 * @return \DOMElement XML author object
594 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
595 * @todo Find proper type-hints
597 private static function addAuthor(DOMDocument $doc, array $owner, $authorelement, $public)
599 // Should the profile be "unsearchable" in the net? Then add the "hide" element
600 $hide = DBA::exists('profile', ['uid' => $owner['uid'], 'net-publish' => false]);
602 $author = $doc->createElement($authorelement);
604 $namdate = DateTimeFormat::utc($owner['name-date'].'+00:00', DateTimeFormat::ATOM);
605 $picdate = DateTimeFormat::utc($owner['avatar-date'].'+00:00', DateTimeFormat::ATOM);
609 if (!$public || !$hide) {
610 $attributes = ["dfrn:updated" => $namdate];
613 XML::addElement($doc, $author, "name", $owner["name"], $attributes);
614 XML::addElement($doc, $author, "uri", DI::baseUrl().'/profile/'.$owner["nickname"], $attributes);
615 XML::addElement($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
617 $attributes = ["rel" => "photo", "type" => "image/jpeg",
618 "media:width" => 300, "media:height" => 300, "href" => $owner['photo']];
620 if (!$public || !$hide) {
621 $attributes["dfrn:updated"] = $picdate;
624 XML::addElement($doc, $author, "link", "", $attributes);
626 $attributes["rel"] = "avatar";
627 XML::addElement($doc, $author, "link", "", $attributes);
630 XML::addElement($doc, $author, "dfrn:hide", "true");
633 // The following fields will only be generated if the data isn't meant for a public feed
638 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
641 XML::addElement($doc, $author, "dfrn:birthday", $birthday);
644 // Only show contact details when we are allowed to
645 $profile = DBA::selectFirst('owner-view',
646 ['about', 'name', 'homepage', 'nickname', 'timezone', 'locality', 'region', 'country-name', 'pub_keywords', 'xmpp', 'dob'],
647 ['uid' => $owner['uid'], 'hidewall' => false]);
648 if (DBA::isResult($profile)) {
649 XML::addElement($doc, $author, "poco:displayName", $profile["name"]);
650 XML::addElement($doc, $author, "poco:updated", $namdate);
652 if (trim($profile["dob"]) > DBA::NULL_DATE) {
653 XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
656 XML::addElement($doc, $author, "poco:note", $profile["about"]);
657 XML::addElement($doc, $author, "poco:preferredUsername", $profile["nickname"]);
659 $savetz = date_default_timezone_get();
660 date_default_timezone_set($profile["timezone"]);
661 XML::addElement($doc, $author, "poco:utcOffset", date("P"));
662 date_default_timezone_set($savetz);
664 if (trim($profile["homepage"]) != "") {
665 $urls = $doc->createElement("poco:urls");
666 XML::addElement($doc, $urls, "poco:type", "homepage");
667 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
668 XML::addElement($doc, $urls, "poco:primary", "true");
669 $author->appendChild($urls);
672 if (trim($profile["pub_keywords"]) != "") {
673 $keywords = explode(",", $profile["pub_keywords"]);
675 foreach ($keywords as $keyword) {
676 XML::addElement($doc, $author, "poco:tags", trim($keyword));
680 if (trim($profile["xmpp"]) != "") {
681 $ims = $doc->createElement("poco:ims");
682 XML::addElement($doc, $ims, "poco:type", "xmpp");
683 XML::addElement($doc, $ims, "poco:value", $profile["xmpp"]);
684 XML::addElement($doc, $ims, "poco:primary", "true");
685 $author->appendChild($ims);
688 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
689 $element = $doc->createElement("poco:address");
691 XML::addElement($doc, $element, "poco:formatted", Profile::formatLocation($profile));
693 if (trim($profile["locality"]) != "") {
694 XML::addElement($doc, $element, "poco:locality", $profile["locality"]);
697 if (trim($profile["region"]) != "") {
698 XML::addElement($doc, $element, "poco:region", $profile["region"]);
701 if (trim($profile["country-name"]) != "") {
702 XML::addElement($doc, $element, "poco:country", $profile["country-name"]);
705 $author->appendChild($element);
713 * Adds the author elements in the "entry" elements of the DFRN protocol
715 * @param DOMDocument $doc XML document
716 * @param string $element Element name for the author
717 * @param string $contact_url Link of the contact
718 * @param array $item Item elements
720 * @return \DOMElement XML author object
721 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
722 * @todo Find proper type-hints
724 private static function addEntryAuthor(DOMDocument $doc, $element, $contact_url, $item)
726 $author = $doc->createElement($element);
728 $contact = Contact::getByURLForUser($contact_url, $item["uid"], false, ['url', 'name', 'addr', 'photo']);
729 if (!empty($contact)) {
730 XML::addElement($doc, $author, "name", $contact["name"]);
731 XML::addElement($doc, $author, "uri", $contact["url"]);
732 XML::addElement($doc, $author, "dfrn:handle", $contact["addr"]);
735 /// - Check real image type and image size
736 /// - Check which of these boths elements we should use
739 "type" => "image/jpeg",
741 "media:height" => 80,
742 "href" => $contact["photo"]];
743 XML::addElement($doc, $author, "link", "", $attributes);
747 "type" => "image/jpeg",
749 "media:height" => 80,
750 "href" => $contact["photo"]];
751 XML::addElement($doc, $author, "link", "", $attributes);
758 * Adds the activity elements
760 * @param DOMDocument $doc XML document
761 * @param string $element Element name for the activity
762 * @param string $activity activity value
764 * @return \DOMElement XML activity object
765 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
766 * @todo Find proper type-hints
768 private static function createActivity(DOMDocument $doc, $element, $activity)
771 $entry = $doc->createElement($element);
773 $r = XML::parseString($activity);
779 XML::addElement($doc, $entry, "activity:object-type", $r->type);
783 XML::addElement($doc, $entry, "id", $r->id);
787 XML::addElement($doc, $entry, "title", $r->title);
791 if (substr($r->link, 0, 1) == '<') {
792 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
793 $r->link = str_replace('&', '&', $r->link);
796 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
798 // XML does need a single element as root element so we add a dummy element here
799 $data = XML::parseString("<dummy>" . $r->link . "</dummy>");
800 if (is_object($data)) {
801 foreach ($data->link as $link) {
803 foreach ($link->attributes() as $parameter => $value) {
804 $attributes[$parameter] = $value;
806 XML::addElement($doc, $entry, "link", "", $attributes);
810 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
811 XML::addElement($doc, $entry, "link", "", $attributes);
815 XML::addElement($doc, $entry, "content", BBCode::convert($r->content), ["type" => "html"]);
825 * Adds the elements for attachments
827 * @param object $doc XML document
828 * @param object $root XML root
829 * @param array $item Item element
831 * @return void XML attachment object
832 * @todo Find proper type-hints
834 private static function getAttachment($doc, $root, $item)
836 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]) as $attachment) {
837 $attributes = ['rel' => 'enclosure',
838 'href' => $attachment['url'],
839 'type' => $attachment['mimetype']];
841 if (!empty($attachment['size'])) {
842 $attributes['length'] = intval($attachment['size']);
844 if (!empty($attachment['description'])) {
845 $attributes['title'] = $attachment['description'];
848 XML::addElement($doc, $root, 'link', '', $attributes);
853 * Adds the "entry" elements for the DFRN protocol
855 * @param DOMDocument $doc XML document
856 * @param string $type "text" or "html"
857 * @param array $item Item element
858 * @param array $owner Owner record
859 * @param bool $comment Trigger the sending of the "comment" element
860 * @param int $cid Contact ID of the recipient
861 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
863 * @return null|\DOMElement XML entry object
864 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
865 * @throws \ImagickException
866 * @todo Find proper type-hints
868 private static function entry(DOMDocument $doc, $type, array $item, array $owner, $comment = false, $cid = 0, $single = false)
872 if (!$item['parent']) {
873 Logger::notice('Item without parent found.', ['type' => $type, 'item' => $item]);
877 if ($item['deleted']) {
878 $attributes = ["ref" => $item['uri'], "when" => DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM)];
879 return XML::createElement($doc, "at:deleted-entry", "", $attributes);
883 $entry = $doc->createElement("entry");
885 $entry = $doc->createElementNS(ActivityNamespace::ATOM1, 'entry');
886 $doc->appendChild($entry);
888 $entry->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
889 $entry->setAttribute("xmlns:at", ActivityNamespace::TOMB);
890 $entry->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
891 $entry->setAttribute("xmlns:dfrn", ActivityNamespace::DFRN);
892 $entry->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
893 $entry->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
894 $entry->setAttribute("xmlns:poco", ActivityNamespace::POCO);
895 $entry->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
896 $entry->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
899 if ($item['private'] == Item::PRIVATE) {
900 $body = Item::fixPrivatePhotos($item['body'], $owner['uid'], $item, $cid);
902 $body = $item['body'];
905 // Remove the abstract element. It is only locally important.
906 $body = BBCode::stripAbstract($body);
909 if ($type == 'html') {
912 if ($item['title'] != "") {
913 $htmlbody = "[b]" . $item['title'] . "[/b]\n\n" . $htmlbody;
916 $htmlbody = BBCode::convert($htmlbody, false, BBCode::OSTATUS);
919 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
920 $entry->appendChild($author);
922 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
923 $entry->appendChild($dfrnowner);
925 if ($item['gravity'] != GRAVITY_PARENT) {
926 $parent = Post::selectFirst(['guid', 'plink'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
927 if (DBA::isResult($parent)) {
928 $attributes = ["ref" => $item['thr-parent'], "type" => "text/html",
929 "href" => $parent['plink'],
930 "dfrn:diaspora_guid" => $parent['guid']];
931 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
935 // Add conversation data. This is used for OStatus
936 $conversation_href = DI::baseUrl()."/display/".$item["parent-guid"];
937 $conversation_uri = $conversation_href;
939 if (isset($parent_item)) {
940 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $item['thr-parent']]);
941 if (DBA::isResult($conversation)) {
942 if ($conversation['conversation-uri'] != '') {
943 $conversation_uri = $conversation['conversation-uri'];
945 if ($conversation['conversation-href'] != '') {
946 $conversation_href = $conversation['conversation-href'];
952 "href" => $conversation_href,
953 "ref" => $conversation_uri];
955 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
957 XML::addElement($doc, $entry, "id", $item["uri"]);
958 XML::addElement($doc, $entry, "title", $item["title"]);
960 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"] . "+00:00", DateTimeFormat::ATOM));
961 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"] . "+00:00", DateTimeFormat::ATOM));
963 // "dfrn:env" is used to read the content
964 XML::addElement($doc, $entry, "dfrn:env", Strings::base64UrlEncode($body, true));
966 // The "content" field is not read by the receiver. We could remove it when the type is "text"
967 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
968 XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
970 // We save this value in "plink". Maybe we should read it from there as well?
976 ["rel" => "alternate", "type" => "text/html",
977 "href" => DI::baseUrl() . "/display/" . $item["guid"]]
980 // "comment-allow" is some old fashioned stuff for old Friendica versions.
981 // It is included in the rewritten code for completeness
983 XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
986 if ($item['location']) {
987 XML::addElement($doc, $entry, "dfrn:location", $item['location']);
990 if ($item['coord']) {
991 XML::addElement($doc, $entry, "georss:point", $item['coord']);
994 if ($item['private']) {
995 // Friendica versions prior to 2020.3 can't handle "unlisted" properly. So we can only transmit public and private
996 XML::addElement($doc, $entry, "dfrn:private", ($item['private'] == Item::PRIVATE ? Item::PRIVATE : Item::PUBLIC));
997 XML::addElement($doc, $entry, "dfrn:unlisted", $item['private'] == Item::UNLISTED);
1000 if ($item['extid']) {
1001 XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
1004 if ($item['post-type'] == Item::PT_PAGE) {
1005 XML::addElement($doc, $entry, "dfrn:bookmark", "true");
1009 XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
1012 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
1014 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
1015 // It is needed for relayed comments to Diaspora.
1016 if ($item['signed_text']) {
1017 $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => '','signer' => '']));
1018 XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
1021 XML::addElement($doc, $entry, "activity:verb", self::constructVerb($item));
1023 if ($item['object-type'] != "") {
1024 XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
1025 } elseif ($item['gravity'] == GRAVITY_PARENT) {
1026 XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::NOTE);
1028 XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::COMMENT);
1031 $actobj = self::createActivity($doc, "activity:object", $item['object']);
1033 $entry->appendChild($actobj);
1036 $actarg = self::createActivity($doc, "activity:target", $item['target']);
1038 $entry->appendChild($actarg);
1041 $tags = Tag::getByURIId($item['uri-id']);
1044 foreach ($tags as $tag) {
1045 if (($type != 'html') || ($tag['type'] == Tag::HASHTAG)) {
1046 XML::addElement($doc, $entry, "category", "", ["scheme" => "X-DFRN:" . Tag::TAG_CHARACTER[$tag['type']] . ":" . $tag['url'], "term" => $tag['name']]);
1048 if ($tag['type'] != Tag::HASHTAG) {
1049 $mentioned[$tag['url']] = $tag['url'];
1054 foreach ($mentioned as $mention) {
1055 $condition = ['uid' => $owner["uid"], 'nurl' => Strings::normaliseLink($mention)];
1056 $contact = DBA::selectFirst('contact', ['forum', 'prv'], $condition);
1058 if (DBA::isResult($contact) && ($contact["forum"] || $contact["prv"])) {
1064 ["rel" => "mentioned",
1065 "ostatus:object-type" => Activity\ObjectType::GROUP,
1074 ["rel" => "mentioned",
1075 "ostatus:object-type" => Activity\ObjectType::PERSON,
1081 self::getAttachment($doc, $entry, $item);
1087 * encrypts data via AES
1089 * @param string $data The data that is to be encrypted
1090 * @param string $key The AES key
1092 * @return string encrypted data
1094 private static function aesEncrypt($data, $key)
1096 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1100 * decrypts data via AES
1102 * @param string $encrypted The encrypted data
1103 * @param string $key The AES key
1105 * @return string decrypted data
1107 public static function aesDecrypt($encrypted, $key)
1109 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1113 * Delivers the atom content to the contacts
1115 * @param array $owner Owner record
1116 * @param array $contact Contact record of the receiver
1117 * @param string $atom Content that will be transmitted
1118 * @param bool $dissolve (to be documented)
1120 * @return int Deliver status. Negative values mean an error.
1121 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1122 * @throws \ImagickException
1123 * @todo Add array type-hint for $owner, $contact
1125 public static function deliver($owner, $contact, $atom, $dissolve = false)
1127 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1129 if ($contact['duplex'] && $contact['dfrn-id']) {
1130 $idtosend = '0:' . $orig_id;
1132 if ($contact['duplex'] && $contact['issued-id']) {
1133 $idtosend = '1:' . $orig_id;
1136 $rino = DI::config()->get('system', 'rino_encrypt');
1137 $rino = intval($rino);
1139 Logger::log("Local rino version: ". $rino, Logger::DEBUG);
1141 $ssl_val = intval(DI::config()->get('system', 'ssl_policy'));
1144 case BaseURL::SSL_POLICY_FULL:
1145 $ssl_policy = 'full';
1147 case BaseURL::SSL_POLICY_SELFSIGN:
1148 $ssl_policy = 'self';
1150 case BaseURL::SSL_POLICY_NONE:
1152 $ssl_policy = 'none';
1156 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1158 Logger::log('dfrn_deliver: ' . $url);
1160 $curlResult = DI::httpRequest()->get($url);
1162 if ($curlResult->isTimeout()) {
1163 return -2; // timed out
1166 $xml = $curlResult->getBody();
1168 $curl_stat = $curlResult->getReturnCode();
1169 if (empty($curl_stat)) {
1170 return -3; // timed out
1173 Logger::log('dfrn_deliver: ' . $xml, Logger::DATA);
1179 if (strpos($xml, '<?xml') === false) {
1180 Logger::log('dfrn_deliver: no valid XML returned');
1181 Logger::log('dfrn_deliver: returned XML: ' . $xml, Logger::DATA);
1185 $res = XML::parseString($xml);
1187 if (!is_object($res) || (intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
1188 if (empty($res->status)) {
1191 $status = $res->status;
1198 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1199 $challenge = hex2bin((string) $res->challenge);
1200 $perm = (($res->perm) ? $res->perm : null);
1201 $dfrn_version = floatval($res->dfrn_version ?: 2.0);
1202 $rino_remote_version = intval($res->rino);
1203 $page = (($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? 1 : 0);
1205 Logger::log("Remote rino version: ".$rino_remote_version." for ".$contact["url"], Logger::DEBUG);
1207 if ($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
1211 $final_dfrn_id = '';
1214 if ((($perm == 'rw') && !intval($contact['writable']))
1215 || (($perm == 'r') && intval($contact['writable']))
1217 DBA::update('contact', ['writable' => ($perm == 'rw')], ['id' => $contact['id']]);
1219 $contact['writable'] = (string) 1 - intval($contact['writable']);
1223 if (($contact['duplex'] && strlen($contact['pubkey']))
1224 || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY && strlen($contact['pubkey']))
1225 || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
1227 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
1228 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
1230 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
1231 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
1234 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1236 if (strpos($final_dfrn_id, ':') == 1) {
1237 $final_dfrn_id = substr($final_dfrn_id, 2);
1240 if ($final_dfrn_id != $orig_id) {
1241 Logger::log('dfrn_deliver: wrong dfrn_id.');
1242 // did not decode properly - cannot trust this site
1246 $postvars['dfrn_id'] = $idtosend;
1247 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1249 $postvars['dissolve'] = '1';
1252 if ((($contact['rel']) && ($contact['rel'] != Contact::SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY)) {
1253 $postvars['data'] = $atom;
1254 $postvars['perm'] = 'rw';
1256 $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
1257 $postvars['perm'] = 'r';
1260 $postvars['ssl_policy'] = $ssl_policy;
1263 $postvars['page'] = $page;
1267 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1268 Logger::log('rino version: '. $rino_remote_version);
1270 switch ($rino_remote_version) {
1272 $key = openssl_random_pseudo_bytes(16);
1273 $data = self::aesEncrypt($postvars['data'], $key);
1277 Logger::log("rino: invalid requested version '$rino_remote_version'");
1281 $postvars['rino'] = $rino_remote_version;
1282 $postvars['data'] = bin2hex($data);
1284 if ($dfrn_version >= 2.1) {
1285 if (($contact['duplex'] && strlen($contact['pubkey']))
1286 || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY && strlen($contact['pubkey']))
1287 || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
1289 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1291 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1294 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY)) {
1295 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1297 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1301 Logger::log('md5 rawkey ' . md5($postvars['key']));
1303 $postvars['key'] = bin2hex($postvars['key']);
1307 Logger::debug('dfrn_deliver', ['post' => $postvars]);
1309 $postResult = DI::httpRequest()->post($contact['notify'], $postvars);
1311 $xml = $postResult->getBody();
1313 Logger::log('dfrn_deliver: ' . "RECEIVED: " . $xml, Logger::DATA);
1315 $curl_stat = $postResult->getReturnCode();
1316 if (empty($curl_stat) || empty($xml)) {
1317 return -9; // timed out
1320 if (($curl_stat == 503) && stristr($postResult->getHeader(), 'retry-after')) {
1324 if (strpos($xml, '<?xml') === false) {
1325 Logger::log('dfrn_deliver: phase 2: no valid XML returned');
1326 Logger::log('dfrn_deliver: phase 2: returned XML: ' . $xml, Logger::DATA);
1330 $res = XML::parseString($xml);
1332 if (!isset($res->status)) {
1336 // Possibly old servers had returned an empty value when everything was okay
1337 if (empty($res->status)) {
1341 if (!empty($res->message)) {
1342 Logger::log('Delivery returned status '.$res->status.' - '.$res->message, Logger::DEBUG);
1345 return intval($res->status);
1349 * Transmits atom content to the contacts via the Diaspora transport layer
1351 * @param array $owner Owner record
1352 * @param array $contact Contact record of the receiver
1353 * @param string $atom Content that will be transmitted
1355 * @param bool $public_batch
1356 * @return int Deliver status. Negative values mean an error.
1357 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1358 * @throws \ImagickException
1360 public static function transmit($owner, $contact, $atom, $public_batch = false)
1362 if (!$public_batch) {
1363 if (empty($contact['addr'])) {
1364 Logger::log('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.');
1365 if (Contact::updateFromProbe($contact['id'])) {
1366 $new_contact = DBA::selectFirst('contact', ['addr'], ['id' => $contact['id']]);
1367 $contact['addr'] = $new_contact['addr'];
1370 if (empty($contact['addr'])) {
1371 Logger::log('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
1376 $fcontact = FContact::getByURL($contact['addr']);
1377 if (empty($fcontact)) {
1378 Logger::log('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
1381 $pubkey = $fcontact['pubkey'];
1386 $envelope = Diaspora::buildMessage($atom, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
1388 // Create the endpoint for public posts. This is some WIP and should later be added to the probing
1389 if ($public_batch && empty($contact["batch"])) {
1390 $parts = parse_url($contact["notify"]);
1391 $path_parts = explode('/', $parts['path']);
1392 array_pop($path_parts);
1393 $parts['path'] = implode('/', $path_parts);
1394 $contact["batch"] = Network::unparseURL($parts);
1397 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
1399 if (empty($dest_url)) {
1400 Logger::info('Empty destination', ['public' => $public_batch, 'contact' => $contact]);
1404 $content_type = ($public_batch ? "application/magic-envelope+xml" : "application/json");
1406 $postResult = DI::httpRequest()->post($dest_url, $envelope, ["Content-Type: " . $content_type]);
1407 $xml = $postResult->getBody();
1409 $curl_stat = $postResult->getReturnCode();
1410 if (empty($curl_stat) || empty($xml)) {
1411 Logger::log('Empty answer from ' . $contact['id'] . ' - ' . $dest_url);
1412 return -9; // timed out
1415 if (($curl_stat == 503) && (stristr($postResult->getHeader(), 'retry-after'))) {
1419 if (strpos($xml, '<?xml') === false) {
1420 Logger::log('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url);
1421 Logger::log('Returned XML: ' . $xml, Logger::DATA);
1425 $res = XML::parseString($xml);
1427 if (empty($res->status)) {
1431 if (!empty($res->message)) {
1432 Logger::log('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message, Logger::DEBUG);
1435 return intval($res->status);
1439 * Fetch the author data from head or entry items
1441 * @param object $xpath XPath object
1442 * @param object $context In which context should the data be searched
1443 * @param array $importer Record of the importer user mixed with contact of the content
1444 * @param string $element Element name from which the data is fetched
1445 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1446 * @param string $xml optional, default empty
1448 * @return array Relevant data of the author
1449 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1450 * @throws \ImagickException
1451 * @todo Find good type-hints for all parameter
1453 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
1456 $author["name"] = XML::getFirstNodeValue($xpath, $element."/atom:name/text()", $context);
1457 $author["link"] = XML::getFirstNodeValue($xpath, $element."/atom:uri/text()", $context);
1459 $fields = ['id', 'uid', 'url', 'network', 'avatar-date', 'avatar', 'name-date', 'uri-date', 'addr',
1460 'name', 'nick', 'about', 'location', 'keywords', 'xmpp', 'bdyear', 'bd', 'hidden', 'contact-type'];
1461 $condition = ["`uid` = ? AND `nurl` = ? AND `network` != ? AND NOT `pending` AND NOT `blocked`",
1462 $importer["importer_uid"], Strings::normaliseLink($author["link"]), Protocol::STATUSNET];
1464 if ($importer['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
1465 $condition = DBA::mergeConditions($condition, ['rel' => [Contact::SHARING, Contact::FRIEND]]);
1468 $contact_old = DBA::selectFirst('contact', $fields, $condition);
1470 if (DBA::isResult($contact_old)) {
1471 $author["contact-id"] = $contact_old["id"];
1472 $author["network"] = $contact_old["network"];
1474 Logger::info('Contact not found', ['condition' => $condition]);
1476 $author["contact-unknown"] = true;
1477 $contact = Contact::getByURL($author["link"], null, ["id", "network"]);
1478 $author["contact-id"] = $contact["id"] ?? $importer["id"];
1479 $author["network"] = $contact["network"] ?? $importer["network"];
1483 // Until now we aren't serving different sizes - but maybe later
1485 /// @todo check if "avatar" or "photo" would be the best field in the specification
1486 $avatars = $xpath->query($element . "/atom:link[@rel='avatar']", $context);
1487 foreach ($avatars as $avatar) {
1490 foreach ($avatar->attributes as $attributes) {
1491 /// @TODO Rewrite these similar if() to one switch
1492 if ($attributes->name == "href") {
1493 $href = $attributes->textContent;
1495 if ($attributes->name == "width") {
1496 $width = $attributes->textContent;
1498 if ($attributes->name == "updated") {
1499 $author["avatar-date"] = $attributes->textContent;
1502 if (($width > 0) && ($href != "")) {
1503 $avatarlist[$width] = $href;
1507 if (count($avatarlist) > 0) {
1508 krsort($avatarlist);
1509 $author["avatar"] = current($avatarlist);
1512 if (empty($author['avatar']) && !empty($author['link'])) {
1513 $cid = Contact::getIdForURL($author['link'], 0);
1515 $contact = DBA::selectFirst('contact', ['avatar'], ['id' => $cid]);
1516 if (DBA::isResult($contact)) {
1517 $author['avatar'] = $contact['avatar'];
1522 if (empty($author['avatar'])) {
1523 Logger::log('Empty author: ' . $xml);
1524 $author['avatar'] = '';
1527 if (DBA::isResult($contact_old) && !$onlyfetch) {
1528 Logger::log("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", Logger::DEBUG);
1530 $poco = ["url" => $contact_old["url"], "network" => $contact_old["network"]];
1532 // When was the last change to name or uri?
1533 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1534 foreach ($name_element->attributes as $attributes) {
1535 if ($attributes->name == "updated") {
1536 $poco["name-date"] = $attributes->textContent;
1540 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1541 foreach ($link_element->attributes as $attributes) {
1542 if ($attributes->name == "updated") {
1543 $poco["uri-date"] = $attributes->textContent;
1547 // Update contact data
1548 $value = XML::getFirstNodeValue($xpath, $element . "/dfrn:handle/text()", $context);
1550 $poco["addr"] = $value;
1553 $value = XML::getFirstNodeValue($xpath, $element . "/poco:displayName/text()", $context);
1555 $poco["name"] = $value;
1558 $value = XML::getFirstNodeValue($xpath, $element . "/poco:preferredUsername/text()", $context);
1560 $poco["nick"] = $value;
1563 $value = XML::getFirstNodeValue($xpath, $element . "/poco:note/text()", $context);
1565 $poco["about"] = $value;
1568 $value = XML::getFirstNodeValue($xpath, $element . "/poco:address/poco:formatted/text()", $context);
1570 $poco["location"] = $value;
1573 /// @todo Only search for elements with "poco:type" = "xmpp"
1574 $value = XML::getFirstNodeValue($xpath, $element . "/poco:ims/poco:value/text()", $context);
1576 $poco["xmpp"] = $value;
1579 /// @todo Add support for the following fields that we don't support by now in the contact table:
1580 /// - poco:utcOffset
1586 // If the "hide" element is present then the profile isn't searchable.
1587 $hide = intval(XML::getFirstNodeValue($xpath, $element . "/dfrn:hide/text()", $context) == "true");
1589 Logger::log("Hidden status for contact " . $contact_old["url"] . ": " . $hide, Logger::DEBUG);
1591 // If the contact isn't searchable then set the contact to "hidden".
1592 // Problem: This can be manually overridden by the user.
1594 $contact_old["hidden"] = true;
1597 // Save the keywords into the contact table
1599 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1600 foreach ($tagelements as $tag) {
1601 $tags[$tag->nodeValue] = $tag->nodeValue;
1605 $poco["keywords"] = implode(", ", $tags);
1608 // "dfrn:birthday" contains the birthday converted to UTC
1609 $birthday = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1611 if (strtotime($birthday) > time()) {
1612 $bd_timestamp = strtotime($birthday);
1614 $poco["bdyear"] = date("Y", $bd_timestamp);
1617 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1618 $value = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1620 if (!in_array($value, ["", "0000-00-00", DBA::NULL_DATE])) {
1621 $bdyear = date("Y");
1622 $value = str_replace(["0000", "0001"], $bdyear, $value);
1624 if (strtotime($value) < time()) {
1625 $value = str_replace($bdyear, $bdyear + 1, $value);
1628 $poco["bd"] = $value;
1631 $contact = array_merge($contact_old, $poco);
1633 if ($contact_old["bdyear"] != $contact["bdyear"]) {
1634 Event::createBirthday($contact, $birthday);
1637 $fields = ['name' => $contact['name'], 'nick' => $contact['nick'], 'about' => $contact['about'],
1638 'location' => $contact['location'], 'addr' => $contact['addr'], 'keywords' => $contact['keywords'],
1639 'bdyear' => $contact['bdyear'], 'bd' => $contact['bd'], 'hidden' => $contact['hidden'],
1640 'xmpp' => $contact['xmpp'], 'name-date' => DateTimeFormat::utc($contact['name-date']),
1641 'unsearchable' => $contact['hidden'], 'uri-date' => DateTimeFormat::utc($contact['uri-date'])];
1643 DBA::update('contact', $fields, ['id' => $contact['id'], 'network' => $contact['network']], $contact_old);
1645 // Update the public contact. Don't set the "hidden" value, this is used differently for public contacts
1646 unset($fields['hidden']);
1647 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($contact_old['url'])];
1648 DBA::update('contact', $fields, $condition, true);
1650 Contact::updateAvatar($contact['id'], $author['avatar']);
1652 $pcid = Contact::getIdForURL($contact_old['url']);
1653 if (!empty($pcid)) {
1654 Contact::updateAvatar($pcid, $author['avatar']);
1662 * Transforms activity objects into an XML string
1664 * @param object $xpath XPath object
1665 * @param object $activity Activity object
1666 * @param string $element element name
1668 * @return string XML string
1669 * @todo Find good type-hints for all parameter
1671 private static function transformActivity($xpath, $activity, $element)
1673 if (!is_object($activity)) {
1677 $obj_doc = new DOMDocument("1.0", "utf-8");
1678 $obj_doc->formatOutput = true;
1680 $obj_element = $obj_doc->createElementNS( ActivityNamespace::ATOM1, $element);
1682 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1683 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1685 $id = $xpath->query("atom:id", $activity)->item(0);
1686 if (is_object($id)) {
1687 $obj_element->appendChild($obj_doc->importNode($id, true));
1690 $title = $xpath->query("atom:title", $activity)->item(0);
1691 if (is_object($title)) {
1692 $obj_element->appendChild($obj_doc->importNode($title, true));
1695 $links = $xpath->query("atom:link", $activity);
1696 if (is_object($links)) {
1697 foreach ($links as $link) {
1698 $obj_element->appendChild($obj_doc->importNode($link, true));
1702 $content = $xpath->query("atom:content", $activity)->item(0);
1703 if (is_object($content)) {
1704 $obj_element->appendChild($obj_doc->importNode($content, true));
1707 $obj_doc->appendChild($obj_element);
1709 $objxml = $obj_doc->saveXML($obj_element);
1711 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1712 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1717 * Processes the mail elements
1719 * @param object $xpath XPath object
1720 * @param object $mail mail elements
1721 * @param array $importer Record of the importer user mixed with contact of the content
1723 * @throws \Exception
1724 * @todo Find good type-hints for all parameter
1726 private static function processMail($xpath, $mail, $importer)
1728 Logger::log("Processing mails");
1731 $msg["uid"] = $importer["importer_uid"];
1732 $msg["from-name"] = XML::getFirstValue($xpath, "dfrn:sender/dfrn:name/text()", $mail);
1733 $msg["from-url"] = XML::getFirstValue($xpath, "dfrn:sender/dfrn:uri/text()", $mail);
1734 $msg["from-photo"] = XML::getFirstValue($xpath, "dfrn:sender/dfrn:avatar/text()", $mail);
1735 $msg["contact-id"] = $importer["id"];
1736 $msg["uri"] = XML::getFirstValue($xpath, "dfrn:id/text()", $mail);
1737 $msg["parent-uri"] = XML::getFirstValue($xpath, "dfrn:in-reply-to/text()", $mail);
1738 $msg["created"] = DateTimeFormat::utc(XML::getFirstValue($xpath, "dfrn:sentdate/text()", $mail));
1739 $msg["title"] = XML::getFirstValue($xpath, "dfrn:subject/text()", $mail);
1740 $msg["body"] = XML::getFirstValue($xpath, "dfrn:content/text()", $mail);
1746 * Processes the suggestion elements
1748 * @param object $xpath XPath object
1749 * @param object $suggestion suggestion elements
1750 * @param array $importer Record of the importer user mixed with contact of the content
1752 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1753 * @todo Find good type-hints for all parameter
1755 private static function processSuggestion($xpath, $suggestion, $importer)
1757 Logger::notice('Processing suggestions');
1759 $url = $xpath->evaluate('string(dfrn:url[1]/text())', $suggestion);
1760 $cid = Contact::getIdForURL($url);
1761 $note = $xpath->evaluate('string(dfrn:note[1]/text())', $suggestion);
1763 return FContact::addSuggestion($importer['importer_uid'], $cid, $importer['id'], $note);
1767 * Processes the relocation elements
1769 * @param object $xpath XPath object
1770 * @param object $relocation relocation elements
1771 * @param array $importer Record of the importer user mixed with contact of the content
1773 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1774 * @throws \ImagickException
1775 * @todo Find good type-hints for all parameter
1777 private static function processRelocation($xpath, $relocation, $importer)
1779 Logger::log("Processing relocations");
1781 /// @TODO Rewrite this to one statement
1783 $relocate["uid"] = $importer["importer_uid"];
1784 $relocate["cid"] = $importer["id"];
1785 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1786 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
1787 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1788 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
1789 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1790 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1791 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1792 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1793 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1794 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1795 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1796 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1798 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
1799 $relocate["avatar"] = $relocate["photo"];
1802 if ($relocate["addr"] == "") {
1803 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
1808 "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d",
1809 intval($importer["id"]),
1810 intval($importer["importer_uid"])
1813 if (!DBA::isResult($r)) {
1814 Logger::log("Query failed to execute, no result returned in " . __FUNCTION__);
1820 // Update the contact table. We try to find every entry.
1821 $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
1822 'url' => $relocate["url"], 'nurl' => Strings::normaliseLink($relocate["url"]),
1823 'addr' => $relocate["addr"], 'request' => $relocate["request"],
1824 'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
1825 'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
1826 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], Strings::normaliseLink($old["url"])];
1828 DBA::update('contact', $fields, $condition);
1830 Contact::updateAvatar($importer["id"], $relocate["avatar"], true);
1832 Logger::log('Contacts are updated.');
1835 /// merge with current record, current contents have priority
1836 /// update record, set url-updated
1837 /// update profile photos
1838 /// schedule a scan?
1845 * @param array $current the current item record
1846 * @param array $item the new item record
1847 * @param array $importer Record of the importer user mixed with contact of the content
1848 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
1850 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1851 * @todo set proper type-hints (array?)
1853 private static function updateContent($current, $item, $importer, $entrytype)
1857 if (self::isEditedTimestampNewer($current, $item)) {
1858 // do not accept (ignore) an earlier edit than one we currently have.
1859 if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
1863 $fields = ['title' => $item['title'] ?? '', 'body' => $item['body'] ?? '',
1864 'changed' => DateTimeFormat::utcNow(),
1865 'edited' => DateTimeFormat::utc($item["edited"])];
1867 $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
1868 Item::update($fields, $condition);
1876 * Detects the entry type of the item
1878 * @param array $importer Record of the importer user mixed with contact of the content
1879 * @param array $item the new item record
1881 * @return int Is it a toplevel entry, a comment or a relayed comment?
1882 * @throws \Exception
1883 * @todo set proper type-hints (array?)
1885 private static function getEntryType($importer, $item)
1887 if ($item["thr-parent"] != $item["uri"]) {
1890 if ($importer["page-flags"] == User::PAGE_FLAGS_COMMUNITY || $importer["page-flags"] == User::PAGE_FLAGS_PRVGROUP) {
1893 Logger::log("possible community action");
1895 $sql_extra = " AND `self` AND `wall`";
1898 // was the top-level post for this action written by somebody on this site?
1899 // Specifically, the recipient?
1900 $parent = Post::selectFirst(['forum_mode', 'wall'],
1901 ["`uri` = ? AND `uid` = ?" . $sql_extra, $item["thr-parent"], $importer["importer_uid"]]);
1903 $is_a_remote_action = DBA::isResult($parent);
1906 * Does this have the characteristics of a community or private group action?
1907 * If it's an action to a wall post on a community/prvgroup page it's a
1908 * valid community action. Also forum_mode makes it valid for sure.
1909 * If neither, it's not.
1911 if ($is_a_remote_action && $community && (!$parent["forum_mode"]) && (!$parent["wall"])) {
1912 $is_a_remote_action = false;
1913 Logger::log("not a community action");
1916 if ($is_a_remote_action) {
1917 return DFRN::REPLY_RC;
1922 return DFRN::TOP_LEVEL;
1929 * @param array $item The new item record
1930 * @param array $importer Record of the importer user mixed with contact of the content
1932 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1933 * @todo set proper type-hints (array?)
1935 private static function doPoke(array $item, array $importer)
1937 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
1941 $xo = XML::parseString($item["object"]);
1943 if (($xo->type == Activity\ObjectType::PERSON) && ($xo->id)) {
1944 // somebody was poked/prodded. Was it me?
1946 foreach ($xo->link as $l) {
1947 $atts = $l->attributes();
1948 switch ($atts["rel"]) {
1950 $Blink = $atts["href"];
1957 if ($Blink && Strings::compareLink($Blink, DI::baseUrl() . "/profile/" . $importer["nickname"])) {
1958 $author = DBA::selectFirst('contact', ['id', 'name', 'thumb', 'url'], ['id' => $item['author-id']]);
1960 $parent = Post::selectFirst(['id'], ['uri' => $item['thr-parent'], 'uid' => $importer["importer_uid"]]);
1961 $item['parent'] = $parent['id'];
1963 // send a notification
1966 "type" => Type::POKE,
1967 "otype" => Notify\ObjectType::PERSON,
1968 "activity" => $verb,
1969 "verb" => $item["verb"],
1970 "uid" => $importer["importer_uid"],
1971 "cid" => $author["id"],
1973 "link" => DI::baseUrl() . "/display/" . urlencode($item['guid']),
1981 * Processes several actions, depending on the verb
1983 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
1984 * @param array $importer Record of the importer user mixed with contact of the content
1985 * @param array $item the new item record
1986 * @param bool $is_like Is the verb a "like"?
1988 * @return bool Should the processing of the entries be continued?
1989 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1990 * @todo set proper type-hints (array?)
1992 private static function processVerbs($entrytype, $importer, &$item, &$is_like)
1994 Logger::log("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, Logger::DEBUG);
1996 if (($entrytype == DFRN::TOP_LEVEL) && !empty($importer['id'])) {
1997 // The filling of the the "contact" variable is done for legcy reasons
1998 // The functions below are partly used by ostatus.php as well - where we have this variable
1999 $contact = Contact::selectFirst([], ['id' => $importer['id']]);
2001 $activity = DI::activity();
2003 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2004 // This function once was responsible for DFRN and OStatus.
2005 if ($activity->match($item["verb"], Activity::FOLLOW)) {
2006 Logger::log("New follower");
2007 Contact::addRelationship($importer, $contact, $item);
2010 if ($activity->match($item["verb"], Activity::UNFOLLOW)) {
2011 Logger::log("Lost follower");
2012 Contact::removeFollower($importer, $contact, $item);
2015 if ($activity->match($item["verb"], Activity::REQ_FRIEND)) {
2016 Logger::log("New friend request");
2017 Contact::addRelationship($importer, $contact, $item, true);
2020 if ($activity->match($item["verb"], Activity::UNFRIEND)) {
2021 Logger::log("Lost sharer");
2022 Contact::removeSharer($importer, $contact, $item);
2026 if (($item["verb"] == Activity::LIKE)
2027 || ($item["verb"] == Activity::DISLIKE)
2028 || ($item["verb"] == Activity::ATTEND)
2029 || ($item["verb"] == Activity::ATTENDNO)
2030 || ($item["verb"] == Activity::ATTENDMAYBE)
2031 || ($item["verb"] == Activity::ANNOUNCE)
2034 $item["gravity"] = GRAVITY_ACTIVITY;
2035 // only one like or dislike per person
2036 // split into two queries for performance issues
2037 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2038 'verb' => $item['verb'], 'parent-uri' => $item['thr-parent']];
2039 if (Post::exists($condition)) {
2043 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2044 'verb' => $item['verb'], 'thr-parent' => $item['thr-parent']];
2045 if (Post::exists($condition)) {
2049 // The owner of an activity must be the author
2050 $item["owner-name"] = $item["author-name"];
2051 $item["owner-link"] = $item["author-link"];
2052 $item["owner-avatar"] = $item["author-avatar"];
2053 $item["owner-id"] = $item["author-id"];
2058 if (($item["verb"] == Activity::TAG) && ($item["object-type"] == Activity\ObjectType::TAGTERM)) {
2059 $xo = XML::parseString($item["object"]);
2060 $xt = XML::parseString($item["target"]);
2062 if ($xt->type == Activity\ObjectType::NOTE) {
2063 $item_tag = Post::selectFirst(['id', 'uri-id'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]);
2065 if (!DBA::isResult($item_tag)) {
2066 Logger::log("Query failed to execute, no result returned in " . __FUNCTION__);
2070 // extract tag, if not duplicate, add to parent item
2072 Tag::store($item_tag['uri-id'], Tag::HASHTAG, $xo->content);
2081 * Processes the link elements
2083 * @param object $links link elements
2084 * @param array $item the item record
2086 * @todo set proper type-hints
2088 private static function parseLinks($links, &$item)
2095 foreach ($links as $link) {
2096 foreach ($link->attributes as $attributes) {
2097 switch ($attributes->name) {
2098 case "href" : $href = $attributes->textContent; break;
2099 case "rel" : $rel = $attributes->textContent; break;
2100 case "type" : $type = $attributes->textContent; break;
2101 case "length": $length = $attributes->textContent; break;
2102 case "title" : $title = $attributes->textContent; break;
2105 if (($rel != "") && ($href != "")) {
2108 $item["plink"] = $href;
2111 Post\Media::insert(['uri-id' => $item['uri-id'], 'type' => Post\Media::DOCUMENT,
2112 'url' => $href, 'mimetype' => $type, 'size' => $length, 'description' => $title]);
2120 * Checks if an incoming message is wanted
2122 * @param array $item
2123 * @return boolean Is the message wanted?
2125 private static function isSolicitedMessage(array $item)
2127 if (DBA::exists('contact', ["`nurl` = ? AND `uid` != ? AND `rel` IN (?, ?)",
2128 Strings::normaliseLink($item["author-link"]), 0, Contact::FRIEND, Contact::SHARING])) {
2129 Logger::info('Author has got followers - accepted', ['uri' => $item['uri'], 'author' => $item["author-link"]]);
2133 $taglist = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]);
2134 $tags = array_column($taglist, 'name');
2135 return Relay::isSolicitedPost($tags, $item['body'], $item['author-id'], $item['uri'], Protocol::DFRN);
2139 * Processes the entry elements which contain the items and comments
2141 * @param array $header Array of the header elements that always stay the same
2142 * @param object $xpath XPath object
2143 * @param object $entry entry elements
2144 * @param array $importer Record of the importer user mixed with contact of the content
2145 * @param string $xml xml
2147 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2148 * @throws \ImagickException
2149 * @todo Add type-hints
2151 private static function processEntry($header, $xpath, $entry, $importer, $xml, $protocol)
2153 Logger::log("Processing entries");
2157 $item["protocol"] = $protocol;
2159 $item["source"] = $xml;
2162 $item["uri"] = XML::getFirstNodeValue($xpath, "atom:id/text()", $entry);
2164 $item["edited"] = XML::getFirstNodeValue($xpath, "atom:updated/text()", $entry);
2166 $current = Post::selectFirst(['id', 'uid', 'edited', 'body'],
2167 ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
2169 // Is there an existing item?
2170 if (DBA::isResult($current) && !self::isEditedTimestampNewer($current, $item)) {
2171 Logger::log("Item ".$item["uri"]." (".$item['edited'].") already existed.", Logger::DEBUG);
2176 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true, $xml);
2178 $owner_unknown = (isset($owner["contact-unknown"]) && $owner["contact-unknown"]);
2180 $item["owner-name"] = $owner["name"];
2181 $item["owner-link"] = $owner["link"];
2182 $item["owner-avatar"] = $owner["avatar"];
2183 $item["owner-id"] = Contact::getIdForURL($owner["link"], 0);
2186 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true, $xml);
2188 $item["author-name"] = $author["name"];
2189 $item["author-link"] = $author["link"];
2190 $item["author-avatar"] = $author["avatar"];
2191 $item["author-id"] = Contact::getIdForURL($author["link"], 0);
2193 $item["title"] = XML::getFirstNodeValue($xpath, "atom:title/text()", $entry);
2195 $item["created"] = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2197 $item["body"] = XML::getFirstNodeValue($xpath, "dfrn:env/text()", $entry);
2198 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2200 $item["body"] = Strings::base64UrlDecode($item["body"]);
2202 $item["body"] = BBCode::limitBodySize($item["body"]);
2204 /// @todo We should check for a repeated post and if we know the repeated author.
2206 // We don't need the content element since "dfrn:env" is always present
2207 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2209 $item["location"] = XML::getFirstNodeValue($xpath, "dfrn:location/text()", $entry);
2211 $item["coord"] = XML::getFirstNodeValue($xpath, "georss:point", $entry);
2213 $item["private"] = XML::getFirstNodeValue($xpath, "dfrn:private/text()", $entry);
2215 $unlisted = XML::getFirstNodeValue($xpath, "dfrn:unlisted/text()", $entry);
2216 if (!empty($unlisted) && ($item['private'] != Item::PRIVATE)) {
2217 $item['private'] = Item::UNLISTED;
2220 $item["extid"] = XML::getFirstNodeValue($xpath, "dfrn:extid/text()", $entry);
2222 if (XML::getFirstNodeValue($xpath, "dfrn:bookmark/text()", $entry) == "true") {
2223 $item["post-type"] = Item::PT_PAGE;
2226 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2227 if ($notice_info && ($notice_info->length > 0)) {
2228 foreach ($notice_info->item(0)->attributes as $attributes) {
2229 if ($attributes->name == "source") {
2230 $item["app"] = strip_tags($attributes->textContent);
2235 $item["guid"] = XML::getFirstNodeValue($xpath, "dfrn:diaspora_guid/text()", $entry);
2237 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
2239 Tag::storeFromBody($item['uri-id'], $item["body"]);
2241 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
2242 $dsprsig = XML::unescape(XML::getFirstNodeValue($xpath, "dfrn:diaspora_signature/text()", $entry));
2243 if ($dsprsig != "") {
2244 $signature = json_decode(base64_decode($dsprsig));
2245 // We don't store the old style signatures anymore that also contained the "signature" and "signer"
2246 if (!empty($signature->signed_text) && empty($signature->signature) && empty($signature->signer)) {
2247 $item["diaspora_signed_text"] = $signature->signed_text;
2251 $item["verb"] = XML::getFirstNodeValue($xpath, "activity:verb/text()", $entry);
2253 if (XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry) != "") {
2254 $item["object-type"] = XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry);
2257 $object = $xpath->query("activity:object", $entry)->item(0);
2258 $item["object"] = self::transformActivity($xpath, $object, "object");
2260 if (trim($item["object"]) != "") {
2261 $r = XML::parseString($item["object"]);
2262 if (isset($r->type)) {
2263 $item["object-type"] = $r->type;
2267 $target = $xpath->query("activity:target", $entry)->item(0);
2268 $item["target"] = self::transformActivity($xpath, $target, "target");
2270 $categories = $xpath->query("atom:category", $entry);
2272 foreach ($categories as $category) {
2275 foreach ($category->attributes as $attributes) {
2276 if ($attributes->name == "term") {
2277 $term = $attributes->textContent;
2280 if ($attributes->name == "scheme") {
2281 $scheme = $attributes->textContent;
2285 if (($term != "") && ($scheme != "")) {
2286 $parts = explode(":", $scheme);
2287 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2288 $termurl = array_pop($parts);
2289 $termurl = array_pop($parts) . ':' . $termurl;
2290 Tag::store($item['uri-id'], Tag::IMPLICIT_MENTION, $term, $termurl);
2296 $links = $xpath->query("atom:link", $entry);
2298 self::parseLinks($links, $item);
2301 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
2303 $conv = $xpath->query('ostatus:conversation', $entry);
2304 if (is_object($conv->item(0))) {
2305 foreach ($conv->item(0)->attributes as $attributes) {
2306 if ($attributes->name == "ref") {
2307 $item['conversation-uri'] = $attributes->textContent;
2309 if ($attributes->name == "href") {
2310 $item['conversation-href'] = $attributes->textContent;
2315 // Is it a reply or a top level posting?
2316 $item['thr-parent'] = $item['uri'];
2318 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2319 if (is_object($inreplyto->item(0))) {
2320 foreach ($inreplyto->item(0)->attributes as $attributes) {
2321 if ($attributes->name == "ref") {
2322 $item['thr-parent'] = $attributes->textContent;
2327 // Check if the message is wanted
2328 if (($importer['importer_uid'] == 0) && ($item['uri'] == $item['thr-parent'])) {
2329 if (!self::isSolicitedMessage($item)) {
2330 DBA::delete('item-uri', ['uri' => $item['uri']]);
2335 // Get the type of the item (Top level post, reply or remote reply)
2336 $entrytype = self::getEntryType($importer, $item);
2338 // Now assign the rest of the values that depend on the type of the message
2339 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2340 if (!isset($item["object-type"])) {
2341 $item["object-type"] = Activity\ObjectType::COMMENT;
2344 if ($item["contact-id"] != $owner["contact-id"]) {
2345 $item["contact-id"] = $owner["contact-id"];
2348 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2349 $item["network"] = $owner["network"];
2352 if ($item["contact-id"] != $author["contact-id"]) {
2353 $item["contact-id"] = $author["contact-id"];
2356 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2357 $item["network"] = $author["network"];
2361 // Ensure to have the correct share data
2362 $item = Item::addShareDataFromOriginal($item);
2364 if ($entrytype == DFRN::REPLY_RC) {
2366 } elseif ($entrytype == DFRN::TOP_LEVEL) {
2367 if (!isset($item["object-type"])) {
2368 $item["object-type"] = Activity\ObjectType::NOTE;
2372 if (($item["object-type"] == Activity\ObjectType::EVENT) && !$owner_unknown) {
2373 Logger::log("Item ".$item["uri"]." seems to contain an event.", Logger::DEBUG);
2374 $ev = Event::fromBBCode($item["body"]);
2375 if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
2376 Logger::log("Event in item ".$item["uri"]." was found.", Logger::DEBUG);
2377 $ev["cid"] = $importer["id"];
2378 $ev["uid"] = $importer["importer_uid"];
2379 $ev["uri"] = $item["uri"];
2380 $ev["edited"] = $item["edited"];
2381 $ev["private"] = $item["private"];
2382 $ev["guid"] = $item["guid"];
2383 $ev["plink"] = $item["plink"];
2384 $ev["network"] = $item["network"];
2385 $ev["protocol"] = $item["protocol"];
2386 $ev["direction"] = $item["direction"];
2387 $ev["source"] = $item["source"];
2389 $condition = ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]];
2390 $event = DBA::selectFirst('event', ['id'], $condition);
2391 if (DBA::isResult($event)) {
2392 $ev["id"] = $event["id"];
2395 $event_id = Event::store($ev);
2396 Logger::log("Event ".$event_id." was stored", Logger::DEBUG);
2402 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2403 Logger::log("Exiting because 'processVerbs' told us so", Logger::DEBUG);
2407 // This check is done here to be able to receive connection requests in "processVerbs"
2408 if (($entrytype == DFRN::TOP_LEVEL) && $owner_unknown) {
2409 Logger::log("Item won't be stored because user " . $importer["importer_uid"] . " doesn't follow " . $item["owner-link"] . ".", Logger::DEBUG);
2414 // Update content if 'updated' changes
2415 if (DBA::isResult($current)) {
2416 if (self::updateContent($current, $item, $importer, $entrytype)) {
2417 Logger::log("Item ".$item["uri"]." was updated.", Logger::DEBUG);
2419 Logger::log("Item " . $item["uri"] . " already existed.", Logger::DEBUG);
2424 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2425 // Will be overwritten for sharing accounts in Item::insert
2426 if (empty($item['post-type']) && ($entrytype == DFRN::REPLY)) {
2427 $item['post-type'] = Item::PT_COMMENT;
2430 $posted_id = Item::insert($item);
2432 Logger::log("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, Logger::DEBUG);
2434 if ($item['uid'] == 0) {
2435 Item::distribute($posted_id);
2440 } else { // $entrytype == DFRN::TOP_LEVEL
2441 if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
2442 Logger::log("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", Logger::DEBUG);
2445 if (!Strings::compareLink($item["owner-link"], $importer["url"])) {
2447 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2448 * but otherwise there's a possible data mixup on the sender's system.
2449 * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2450 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2452 Logger::log('Correcting item owner.', Logger::DEBUG);
2453 $item["owner-link"] = $importer["url"];
2454 $item["owner-id"] = Contact::getIdForURL($importer["url"], 0);
2457 if (($importer["rel"] == Contact::FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2458 Logger::log("Contact ".$importer["id"]." is only follower and tgroup check was negative.", Logger::DEBUG);
2462 // This is my contact on another system, but it's really me.
2463 // Turn this into a wall post.
2464 $notify = Item::isRemoteSelf($importer, $item);
2466 $posted_id = Item::insert($item, $notify);
2469 $posted_id = $notify;
2472 Logger::log("Item was stored with id ".$posted_id, Logger::DEBUG);
2474 if ($item['uid'] == 0) {
2475 Item::distribute($posted_id);
2478 if (stristr($item["verb"], Activity::POKE)) {
2479 $item['id'] = $posted_id;
2480 self::doPoke($item, $importer);
2488 * @param object $xpath XPath object
2489 * @param object $deletion deletion elements
2490 * @param array $importer Record of the importer user mixed with contact of the content
2492 * @throws \Exception
2493 * @todo set proper type-hints
2495 private static function processDeletion($xpath, $deletion, $importer)
2497 Logger::log("Processing deletions");
2500 foreach ($deletion->attributes as $attributes) {
2501 if ($attributes->name == "ref") {
2502 $uri = $attributes->textContent;
2506 if (!$uri || !$importer["id"]) {
2510 $condition = ['uri' => $uri, 'uid' => $importer["importer_uid"]];
2511 $item = Post::selectFirst(['id', 'parent', 'contact-id', 'uri-id', 'deleted', 'gravity'], $condition);
2512 if (!DBA::isResult($item)) {
2513 Logger::log("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", Logger::DEBUG);
2517 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $importer['importer_uid'], 'type' => Post\Category::FILE])) {
2518 Logger::notice("Item is filed. It won't be deleted.", ['uri' => $uri, 'uri-id' => $item['uri_id'], 'uid' => $importer["importer_uid"]]);
2522 // When it is a starting post it has to belong to the person that wants to delete it
2523 if (($item['gravity'] == GRAVITY_PARENT) && ($item['contact-id'] != $importer["id"])) {
2524 Logger::log("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", Logger::DEBUG);
2528 // Comments can be deleted by the thread owner or comment owner
2529 if (($item['gravity'] != GRAVITY_PARENT) && ($item['contact-id'] != $importer["id"])) {
2530 $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2531 if (!Post::exists($condition)) {
2532 Logger::log("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", Logger::DEBUG);
2537 if ($item["deleted"]) {
2541 Logger::log('deleting item '.$item['id'].' uri='.$uri, Logger::DEBUG);
2543 Item::markForDeletion(['id' => $item['id']]);
2547 * Imports a DFRN message
2549 * @param string $xml The DFRN message
2550 * @param array $importer Record of the importer user mixed with contact of the content
2551 * @param int $protocol Transport protocol
2552 * @param int $direction Is the message pushed or pulled?
2553 * @return integer Import status
2554 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2555 * @throws \ImagickException
2556 * @todo set proper type-hints
2558 public static function import($xml, $importer, $protocol, $direction)
2564 $doc = new DOMDocument();
2565 @$doc->loadXML($xml);
2567 $xpath = new DOMXPath($doc);
2568 $xpath->registerNamespace("atom", ActivityNamespace::ATOM1);
2569 $xpath->registerNamespace("thr", ActivityNamespace::THREAD);
2570 $xpath->registerNamespace("at", ActivityNamespace::TOMB);
2571 $xpath->registerNamespace("media", ActivityNamespace::MEDIA);
2572 $xpath->registerNamespace("dfrn", ActivityNamespace::DFRN);
2573 $xpath->registerNamespace("activity", ActivityNamespace::ACTIVITY);
2574 $xpath->registerNamespace("georss", ActivityNamespace::GEORSS);
2575 $xpath->registerNamespace("poco", ActivityNamespace::POCO);
2576 $xpath->registerNamespace("ostatus", ActivityNamespace::OSTATUS);
2577 $xpath->registerNamespace("statusnet", ActivityNamespace::STATUSNET);
2580 $header["uid"] = $importer["importer_uid"];
2581 $header["network"] = Protocol::DFRN;
2582 $header["wall"] = 0;
2583 $header["origin"] = 0;
2584 $header["contact-id"] = $importer["id"];
2585 $header["direction"] = $direction;
2587 if ($direction === Conversation::RELAY) {
2588 $header['post-type'] = Item::PT_RELAY;
2591 // Update the contact table if the data has changed
2593 // The "atom:author" is only present in feeds
2594 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2595 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2598 // Only the "dfrn:owner" in the head section contains all data
2599 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2600 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2603 Logger::log("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], Logger::DEBUG);
2605 // is it a public forum? Private forums aren't exposed with this method
2606 $forum = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:community/text()"));
2608 // The account type is new since 3.5.1
2609 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2610 // Hint: We are using separate update calls for uid=0 and uid!=0 since a combined call is bad for the database performance
2612 $accounttype = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:account_type/text()"));
2614 if ($accounttype != $importer["contact-type"]) {
2615 DBA::update('contact', ['contact-type' => $accounttype], ['id' => $importer['id']]);
2617 // Updating the public contact as well
2618 DBA::update('contact', ['contact-type' => $accounttype], ['uid' => 0, 'nurl' => $importer['nurl']]);
2620 // A forum contact can either have set "forum" or "prv" - but not both
2621 if ($accounttype == User::ACCOUNT_TYPE_COMMUNITY) {
2622 // It's a forum, so either set the public or private forum flag
2623 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer['id']];
2624 DBA::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2626 // Updating the public contact as well
2627 $condition = ['(`forum` != ? OR `prv` != ?) AND `uid` = 0 AND `nurl` = ?', $forum, !$forum, $importer['nurl']];
2628 DBA::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2630 // It's not a forum, so remove the flags
2631 $condition = ['(`forum` OR `prv`) AND `id` = ?', $importer['id']];
2632 DBA::update('contact', ['forum' => false, 'prv' => false], $condition);
2634 // Updating the public contact as well
2635 $condition = ['(`forum` OR `prv`) AND `uid` = 0 AND `nurl` = ?', $importer['nurl']];
2636 DBA::update('contact', ['forum' => false, 'prv' => false], $condition);
2638 } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
2639 $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2640 DBA::update('contact', ['forum' => $forum], $condition);
2642 // Updating the public contact as well
2643 $condition = ['`forum` != ? AND `uid` = 0 AND `nurl` = ?', $forum, $importer['nurl']];
2644 DBA::update('contact', ['forum' => $forum], $condition);
2648 // We are processing relocations even if we are ignoring a contact
2649 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2650 foreach ($relocations as $relocation) {
2651 self::processRelocation($xpath, $relocation, $importer);
2654 if (($importer["uid"] != 0) && !$importer["readonly"]) {
2655 $mails = $xpath->query("/atom:feed/dfrn:mail");
2656 foreach ($mails as $mail) {
2657 self::processMail($xpath, $mail, $importer);
2660 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2661 foreach ($suggestions as $suggestion) {
2662 self::processSuggestion($xpath, $suggestion, $importer);
2666 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2667 if (!empty($deletions)) {
2668 foreach ($deletions as $deletion) {
2669 self::processDeletion($xpath, $deletion, $importer);
2671 if (count($deletions) > 0) {
2672 Logger::notice('Deletions had been processed');
2677 $entries = $xpath->query("/atom:feed/atom:entry");
2678 foreach ($entries as $entry) {
2679 self::processEntry($header, $xpath, $entry, $importer, $xml, $protocol);
2682 Logger::log("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], Logger::DEBUG);
2687 * Returns the activity verb
2689 * @param array $item Item array
2691 * @return string activity verb
2693 private static function constructVerb(array $item)
2695 if ($item['verb']) {
2696 return $item['verb'];
2698 return Activity::POST;
2701 private static function tgroupCheck($uid, $item)
2705 // check that the message originated elsewhere and is a top-level post
2707 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['thr-parent'])) {
2711 $user = DBA::selectFirst('user', ['page-flags', 'nickname'], ['uid' => $uid]);
2712 if (!DBA::isResult($user)) {
2716 $community_page = ($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY);
2717 $prvgroup = ($user['page-flags'] == User::PAGE_FLAGS_PRVGROUP);
2719 $link = Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']);
2722 * Diaspora uses their own hardwired link URL in @-tags
2723 * instead of the one we supply with webfinger
2725 $dlink = Strings::normaliseLink(DI::baseUrl() . '/u/' . $user['nickname']);
2727 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2729 foreach ($matches as $mtch) {
2730 if (Strings::compareLink($link, $mtch[1]) || Strings::compareLink($dlink, $mtch[1])) {
2732 Logger::log('mention found: ' . $mtch[2]);
2741 return $community_page || $prvgroup;
2745 * This function returns true if $update has an edited timestamp newer
2746 * than $existing, i.e. $update contains new data which should override
2747 * what's already there. If there is no timestamp yet, the update is
2748 * assumed to be newer. If the update has no timestamp, the existing
2749 * item is assumed to be up-to-date. If the timestamps are equal it
2750 * assumes the update has been seen before and should be ignored.
2755 * @throws \Exception
2757 private static function isEditedTimestampNewer($existing, $update)
2759 if (empty($existing['edited'])) {
2762 if (empty($update['edited'])) {
2766 $existing_edited = DateTimeFormat::utc($existing['edited']);
2767 $update_edited = DateTimeFormat::utc($update['edited']);
2769 return (strcmp($existing_edited, $update_edited) < 0);
2773 * Checks if the given contact url does support DFRN
2775 * @param string $url profile url
2777 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2778 * @throws \ImagickException
2780 public static function isSupportedByContactUrl($url)
2782 $probe = Probe::uri($url, Protocol::DFRN);
2783 return $probe['network'] == Protocol::DFRN;