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\GContact;
37 use Friendica\Model\Item;
38 use Friendica\Model\Mail;
39 use Friendica\Model\Notify\Type;
40 use Friendica\Model\PermissionSet;
41 use Friendica\Model\Profile;
42 use Friendica\Model\Term;
43 use Friendica\Model\User;
44 use Friendica\Network\Probe;
45 use Friendica\Util\Crypto;
46 use Friendica\Util\DateTimeFormat;
47 use Friendica\Util\Images;
48 use Friendica\Util\Network;
49 use Friendica\Util\Strings;
50 use Friendica\Util\XML;
53 * This class contain functions to create and send DFRN XML files
58 const TOP_LEVEL = 0; // Top level posting
59 const REPLY = 1; // Regular reply that is stored locally
60 const REPLY_RC = 2; // Reply that will be relayed
63 * Generates an array of contact and user for DFRN imports
65 * This array contains not only the receiver but also the sender of the message.
67 * @param integer $cid Contact id
68 * @param integer $uid User id
70 * @return array importer
73 public static function getImporter($cid, $uid = 0)
75 $condition = ['id' => $cid, 'blocked' => false, 'pending' => false];
76 $contact = DBA::selectFirst('contact', [], $condition);
77 if (!DBA::isResult($contact)) {
81 $contact['cpubkey'] = $contact['pubkey'];
82 $contact['cprvkey'] = $contact['prvkey'];
83 $contact['senderName'] = $contact['name'];
86 $condition = ['uid' => $uid, 'account_expired' => false, 'account_removed' => false];
87 $user = DBA::selectFirst('user', [], $condition);
88 if (!DBA::isResult($user)) {
92 $user['importer_uid'] = $user['uid'];
93 $user['uprvkey'] = $user['prvkey'];
95 $user = ['importer_uid' => 0, 'uprvkey' => '', 'timezone' => 'UTC',
96 'nickname' => '', 'sprvkey' => '', 'spubkey' => '',
97 'page-flags' => 0, 'account-type' => 0, 'prvnets' => 0];
100 return array_merge($contact, $user);
104 * Generates the atom entries for delivery.php
106 * This function is used whenever content is transmitted via DFRN.
108 * @param array $items Item elements
109 * @param array $owner Owner record
111 * @return string DFRN entries
112 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
113 * @throws \ImagickException
114 * @todo Find proper type-hints
116 public static function entries($items, $owner)
118 $doc = new DOMDocument('1.0', 'utf-8');
119 $doc->formatOutput = true;
121 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
123 if (! count($items)) {
124 return trim($doc->saveXML());
127 foreach ($items as $item) {
128 // These values aren't sent when sending from the queue.
129 /// @todo Check if we can set these values from the queue or if they are needed at all.
130 $item["entry:comment-allow"] = ($item["entry:comment-allow"] ?? '') ?: true;
131 $item["entry:cid"] = $item["entry:cid"] ?? 0;
133 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
135 $root->appendChild($entry);
139 return trim($doc->saveXML());
143 * Generate an atom feed for the given user
145 * This function is called when another server is pulling data from the user feed.
147 * @param string $dfrn_id DFRN ID from the requesting party
148 * @param string $owner_nick Owner nick name
149 * @param string $last_update Date of the last update
150 * @param int $direction Can be -1, 0 or 1.
151 * @param boolean $onlyheader Output only the header without content? (Default is "no")
153 * @return string DFRN feed entries
154 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
155 * @throws \ImagickException
157 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false)
161 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
162 $public_feed = (($dfrn_id) ? false : true);
163 $starred = false; // not yet implemented, possible security issues
166 if ($public_feed && $a->argc > 2) {
167 for ($x = 2; $x < $a->argc; $x++) {
168 if ($a->argv[$x] == 'converse') {
171 if ($a->argv[$x] == 'starred') {
174 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
175 $category = $a->argv[$x+1];
180 // default permissions - anonymous user
182 $sql_extra = sprintf(" AND `item`.`private` != %s ", Item::PRIVATE);
185 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
186 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
187 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
188 DBA::escape($owner_nick)
191 if (! DBA::isResult($r)) {
192 Logger::log(sprintf('No contact found for nickname=%d', $owner_nick), Logger::WARNING);
197 $owner_id = $owner['uid'];
199 $sql_post_table = "";
201 if (! $public_feed) {
202 switch ($direction) {
204 $sql_extra = sprintf(" AND `issued-id` = '%s' ", DBA::escape($dfrn_id));
207 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
210 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
218 "SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
222 if (! DBA::isResult($r)) {
223 Logger::log(sprintf('No contact found for uid=%d', $owner_id), Logger::WARNING);
229 $set = PermissionSet::get($owner_id, $contact['id']);
232 $sql_extra = " AND `item`.`psid` IN (" . implode(',', $set) .")";
234 $sql_extra = sprintf(" AND `item`.`private` != %s", Item::PRIVATE);
244 if (! strlen($last_update)) {
245 $last_update = 'now -30 days';
248 if (isset($category)) {
249 $sql_post_table = sprintf(
250 "INNER JOIN (SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d ORDER BY `tid` DESC) AS `term` ON `item`.`id` = `term`.`oid` ",
251 DBA::escape(Strings::protectSprintf($category)),
252 intval(Term::OBJECT_TYPE_POST),
253 intval(Term::CATEGORY),
258 if ($public_feed && ! $converse) {
259 $sql_extra .= " AND `contact`.`self` = 1 ";
262 $check_date = DateTimeFormat::utc($last_update);
266 FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
267 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
268 WHERE `item`.`uid` = %d AND `item`.`wall` AND `item`.`changed` > '%s'
269 AND `item`.`visible` $sql_extra
270 ORDER BY `item`.`parent` ".$sort.", `item`.`received` ASC LIMIT 0, 300",
272 DBA::escape($check_date),
277 foreach ($r as $item) {
278 $ids[] = $item['id'];
282 $ret = Item::select(Item::DELIVER_FIELDLIST, ['id' => $ids]);
283 $items = Item::inArray($ret);
289 * Will check further below if this actually returned results.
290 * We will provide an empty feed if that is the case.
293 $doc = new DOMDocument('1.0', 'utf-8');
294 $doc->formatOutput = true;
296 $alternatelink = $owner['url'];
298 if (isset($category)) {
299 $alternatelink .= "/category/".$category;
303 $author = "dfrn:owner";
308 $root = self::addHeader($doc, $owner, $author, $alternatelink, true);
310 /// @TODO This hook can't work anymore
311 // \Friendica\Core\Hook::callAll('atom_feed', $atom);
313 if (!DBA::isResult($items) || $onlyheader) {
314 $atom = trim($doc->saveXML());
316 Hook::callAll('atom_feed_end', $atom);
321 foreach ($items as $item) {
322 // prevent private email from leaking.
323 if ($item['network'] == Protocol::MAIL) {
327 // public feeds get html, our own nodes use bbcode
331 // catch any email that's in a public conversation and make sure it doesn't leak
332 if ($item['private'] == Item::PRIVATE) {
339 $entry = self::entry($doc, $type, $item, $owner, true);
341 $root->appendChild($entry);
345 $atom = trim($doc->saveXML());
347 Hook::callAll('atom_feed_end', $atom);
353 * Generate an atom entry for a given item id
355 * @param int $item_id The item id
356 * @param boolean $conversation Show the conversation. If false show the single post.
358 * @return string DFRN feed entry
359 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
360 * @throws \ImagickException
362 public static function itemFeed($item_id, $conversation = false)
365 $condition = ['parent' => $item_id];
367 $condition = ['id' => $item_id];
370 $ret = Item::select(Item::DELIVER_FIELDLIST, $condition);
371 $items = Item::inArray($ret);
372 if (!DBA::isResult($items)) {
378 if ($item['uid'] != 0) {
379 $owner = User::getOwnerDataById($item['uid']);
384 $owner = ['uid' => 0, 'nick' => 'feed-item'];
387 $doc = new DOMDocument('1.0', 'utf-8');
388 $doc->formatOutput = true;
392 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
393 $doc->appendChild($root);
395 $root->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
396 $root->setAttribute("xmlns:at", ActivityNamespace::TOMB);
397 $root->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
398 $root->setAttribute("xmlns:dfrn", ActivityNamespace::DFRN);
399 $root->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
400 $root->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
401 $root->setAttribute("xmlns:poco", ActivityNamespace::POCO);
402 $root->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
403 $root->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
405 //$root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
407 foreach ($items as $item) {
408 $entry = self::entry($doc, $type, $item, $owner, true, 0);
410 $root->appendChild($entry);
414 self::entry($doc, $type, $item, $owner, true, 0, true);
417 $atom = trim($doc->saveXML());
422 * Create XML text for DFRN mails
424 * @param array $item message elements
425 * @param array $owner Owner record
427 * @return string DFRN mail
428 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
429 * @todo Find proper type-hints
431 public static function mail($item, $owner)
433 $doc = new DOMDocument('1.0', 'utf-8');
434 $doc->formatOutput = true;
436 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
438 $mail = $doc->createElement("dfrn:mail");
439 $sender = $doc->createElement("dfrn:sender");
441 XML::addElement($doc, $sender, "dfrn:name", $owner['name']);
442 XML::addElement($doc, $sender, "dfrn:uri", $owner['url']);
443 XML::addElement($doc, $sender, "dfrn:avatar", $owner['thumb']);
445 $mail->appendChild($sender);
447 XML::addElement($doc, $mail, "dfrn:id", $item['uri']);
448 XML::addElement($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
449 XML::addElement($doc, $mail, "dfrn:sentdate", DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
450 XML::addElement($doc, $mail, "dfrn:subject", $item['title']);
451 XML::addElement($doc, $mail, "dfrn:content", $item['body']);
453 $root->appendChild($mail);
455 return trim($doc->saveXML());
459 * Create XML text for DFRN friend suggestions
461 * @param array $item suggestion elements
462 * @param array $owner Owner record
464 * @return string DFRN suggestions
465 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
466 * @todo Find proper type-hints
468 public static function fsuggest($item, $owner)
470 $doc = new DOMDocument('1.0', 'utf-8');
471 $doc->formatOutput = true;
473 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
475 $suggest = $doc->createElement("dfrn:suggest");
477 XML::addElement($doc, $suggest, "dfrn:url", $item['url']);
478 XML::addElement($doc, $suggest, "dfrn:name", $item['name']);
479 XML::addElement($doc, $suggest, "dfrn:photo", $item['photo']);
480 XML::addElement($doc, $suggest, "dfrn:request", $item['request']);
481 XML::addElement($doc, $suggest, "dfrn:note", $item['note']);
483 $root->appendChild($suggest);
485 return trim($doc->saveXML());
489 * Create XML text for DFRN relocations
491 * @param array $owner Owner record
492 * @param int $uid User ID
494 * @return string DFRN relocations
495 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
496 * @todo Find proper type-hints
498 public static function relocate($owner, $uid)
501 /* get site pubkey. this could be a new installation with no site keys*/
502 $pubkey = DI::config()->get('system', 'site_pubkey');
504 $res = Crypto::newKeypair(1024);
505 DI::config()->set('system', 'site_prvkey', $res['prvkey']);
506 DI::config()->set('system', 'site_pubkey', $res['pubkey']);
510 "SELECT `resource-id` , `scale`, type FROM `photo`
511 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;",
515 $ext = Images::supportedTypes();
517 foreach ($rp as $p) {
518 $photos[$p['scale']] = DI::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
522 $doc = new DOMDocument('1.0', 'utf-8');
523 $doc->formatOutput = true;
525 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
527 $relocate = $doc->createElement("dfrn:relocate");
529 XML::addElement($doc, $relocate, "dfrn:url", $owner['url']);
530 XML::addElement($doc, $relocate, "dfrn:name", $owner['name']);
531 XML::addElement($doc, $relocate, "dfrn:addr", $owner['addr']);
532 XML::addElement($doc, $relocate, "dfrn:avatar", $owner['avatar']);
533 XML::addElement($doc, $relocate, "dfrn:photo", $photos[4]);
534 XML::addElement($doc, $relocate, "dfrn:thumb", $photos[5]);
535 XML::addElement($doc, $relocate, "dfrn:micro", $photos[6]);
536 XML::addElement($doc, $relocate, "dfrn:request", $owner['request']);
537 XML::addElement($doc, $relocate, "dfrn:confirm", $owner['confirm']);
538 XML::addElement($doc, $relocate, "dfrn:notify", $owner['notify']);
539 XML::addElement($doc, $relocate, "dfrn:poll", $owner['poll']);
540 XML::addElement($doc, $relocate, "dfrn:sitepubkey", DI::config()->get('system', 'site_pubkey'));
542 $root->appendChild($relocate);
544 return trim($doc->saveXML());
548 * Adds the header elements for the DFRN protocol
550 * @param DOMDocument $doc XML document
551 * @param array $owner Owner record
552 * @param string $authorelement Element name for the author
553 * @param string $alternatelink link to profile or category
554 * @param bool $public Is it a header for public posts?
556 * @return object XML root object
557 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
558 * @todo Find proper type-hints
560 private static function addHeader(DOMDocument $doc, $owner, $authorelement, $alternatelink = "", $public = false)
563 if ($alternatelink == "") {
564 $alternatelink = $owner['url'];
567 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
568 $doc->appendChild($root);
570 $root->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
571 $root->setAttribute("xmlns:at", ActivityNamespace::TOMB);
572 $root->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
573 $root->setAttribute("xmlns:dfrn", ActivityNamespace::DFRN);
574 $root->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
575 $root->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
576 $root->setAttribute("xmlns:poco", ActivityNamespace::POCO);
577 $root->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
578 $root->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
580 XML::addElement($doc, $root, "id", DI::baseUrl()."/profile/".$owner["nick"]);
581 XML::addElement($doc, $root, "title", $owner["name"]);
583 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION];
584 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
586 $attributes = ["rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/"];
587 XML::addElement($doc, $root, "link", "", $attributes);
589 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $alternatelink];
590 XML::addElement($doc, $root, "link", "", $attributes);
594 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
595 OStatus::hublinks($doc, $root, $owner["nick"]);
597 $attributes = ["rel" => "salmon", "href" => DI::baseUrl()."/salmon/".$owner["nick"]];
598 XML::addElement($doc, $root, "link", "", $attributes);
600 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => DI::baseUrl()."/salmon/".$owner["nick"]];
601 XML::addElement($doc, $root, "link", "", $attributes);
603 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => DI::baseUrl()."/salmon/".$owner["nick"]];
604 XML::addElement($doc, $root, "link", "", $attributes);
607 // For backward compatibility we keep this element
608 if ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY) {
609 XML::addElement($doc, $root, "dfrn:community", 1);
612 // The former element is replaced by this one
613 XML::addElement($doc, $root, "dfrn:account_type", $owner["account-type"]);
615 /// @todo We need a way to transmit the different page flags like "User::PAGE_FLAGS_PRVGROUP"
617 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
619 $author = self::addAuthor($doc, $owner, $authorelement, $public);
620 $root->appendChild($author);
626 * Adds the author element in the header for the DFRN protocol
628 * @param DOMDocument $doc XML document
629 * @param array $owner Owner record
630 * @param string $authorelement Element name for the author
631 * @param boolean $public boolean
633 * @return \DOMElement XML author object
634 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
635 * @todo Find proper type-hints
637 private static function addAuthor(DOMDocument $doc, array $owner, $authorelement, $public)
639 // Should the profile be "unsearchable" in the net? Then add the "hide" element
640 $hide = DBA::exists('profile', ['uid' => $owner['uid'], 'net-publish' => false]);
642 $author = $doc->createElement($authorelement);
644 $namdate = DateTimeFormat::utc($owner['name-date'].'+00:00', DateTimeFormat::ATOM);
645 $picdate = DateTimeFormat::utc($owner['avatar-date'].'+00:00', DateTimeFormat::ATOM);
649 if (!$public || !$hide) {
650 $attributes = ["dfrn:updated" => $namdate];
653 XML::addElement($doc, $author, "name", $owner["name"], $attributes);
654 XML::addElement($doc, $author, "uri", DI::baseUrl().'/profile/'.$owner["nickname"], $attributes);
655 XML::addElement($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
657 $attributes = ["rel" => "photo", "type" => "image/jpeg",
658 "media:width" => 300, "media:height" => 300, "href" => $owner['photo']];
660 if (!$public || !$hide) {
661 $attributes["dfrn:updated"] = $picdate;
664 XML::addElement($doc, $author, "link", "", $attributes);
666 $attributes["rel"] = "avatar";
667 XML::addElement($doc, $author, "link", "", $attributes);
670 XML::addElement($doc, $author, "dfrn:hide", "true");
673 // The following fields will only be generated if the data isn't meant for a public feed
678 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
681 XML::addElement($doc, $author, "dfrn:birthday", $birthday);
684 // Only show contact details when we are allowed to
686 "SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
687 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
688 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
690 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
691 WHERE NOT `user`.`hidewall` AND `user`.`uid` = %d",
692 intval($owner['uid'])
694 if (DBA::isResult($r)) {
697 XML::addElement($doc, $author, "poco:displayName", $profile["name"]);
698 XML::addElement($doc, $author, "poco:updated", $namdate);
700 if (trim($profile["dob"]) > DBA::NULL_DATE) {
701 XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
704 XML::addElement($doc, $author, "poco:note", $profile["about"]);
705 XML::addElement($doc, $author, "poco:preferredUsername", $profile["nickname"]);
707 $savetz = date_default_timezone_get();
708 date_default_timezone_set($profile["timezone"]);
709 XML::addElement($doc, $author, "poco:utcOffset", date("P"));
710 date_default_timezone_set($savetz);
712 if (trim($profile["homepage"]) != "") {
713 $urls = $doc->createElement("poco:urls");
714 XML::addElement($doc, $urls, "poco:type", "homepage");
715 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
716 XML::addElement($doc, $urls, "poco:primary", "true");
717 $author->appendChild($urls);
720 if (trim($profile["pub_keywords"]) != "") {
721 $keywords = explode(",", $profile["pub_keywords"]);
723 foreach ($keywords as $keyword) {
724 XML::addElement($doc, $author, "poco:tags", trim($keyword));
728 if (trim($profile["xmpp"]) != "") {
729 $ims = $doc->createElement("poco:ims");
730 XML::addElement($doc, $ims, "poco:type", "xmpp");
731 XML::addElement($doc, $ims, "poco:value", $profile["xmpp"]);
732 XML::addElement($doc, $ims, "poco:primary", "true");
733 $author->appendChild($ims);
736 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
737 $element = $doc->createElement("poco:address");
739 XML::addElement($doc, $element, "poco:formatted", Profile::formatLocation($profile));
741 if (trim($profile["locality"]) != "") {
742 XML::addElement($doc, $element, "poco:locality", $profile["locality"]);
745 if (trim($profile["region"]) != "") {
746 XML::addElement($doc, $element, "poco:region", $profile["region"]);
749 if (trim($profile["country-name"]) != "") {
750 XML::addElement($doc, $element, "poco:country", $profile["country-name"]);
753 $author->appendChild($element);
761 * Adds the author elements in the "entry" elements of the DFRN protocol
763 * @param DOMDocument $doc XML document
764 * @param string $element Element name for the author
765 * @param string $contact_url Link of the contact
766 * @param array $item Item elements
768 * @return \DOMElement XML author object
769 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
770 * @todo Find proper type-hints
772 private static function addEntryAuthor(DOMDocument $doc, $element, $contact_url, $item)
774 $author = $doc->createElement($element);
776 $contact = Contact::getDetailsByURL($contact_url, $item["uid"]);
777 if (!empty($contact)) {
778 XML::addElement($doc, $author, "name", $contact["name"]);
779 XML::addElement($doc, $author, "uri", $contact["url"]);
780 XML::addElement($doc, $author, "dfrn:handle", $contact["addr"]);
783 /// - Check real image type and image size
784 /// - Check which of these boths elements we should use
787 "type" => "image/jpeg",
789 "media:height" => 80,
790 "href" => $contact["photo"]];
791 XML::addElement($doc, $author, "link", "", $attributes);
795 "type" => "image/jpeg",
797 "media:height" => 80,
798 "href" => $contact["photo"]];
799 XML::addElement($doc, $author, "link", "", $attributes);
806 * Adds the activity elements
808 * @param DOMDocument $doc XML document
809 * @param string $element Element name for the activity
810 * @param string $activity activity value
812 * @return \DOMElement XML activity object
813 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
814 * @todo Find proper type-hints
816 private static function createActivity(DOMDocument $doc, $element, $activity)
819 $entry = $doc->createElement($element);
821 $r = XML::parseString($activity, false);
827 XML::addElement($doc, $entry, "activity:object-type", $r->type);
831 XML::addElement($doc, $entry, "id", $r->id);
835 XML::addElement($doc, $entry, "title", $r->title);
839 if (substr($r->link, 0, 1) == '<') {
840 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
841 $r->link = str_replace('&', '&', $r->link);
844 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
846 // XML does need a single element as root element so we add a dummy element here
847 $data = XML::parseString("<dummy>" . $r->link . "</dummy>", false);
848 if (is_object($data)) {
849 foreach ($data->link as $link) {
851 foreach ($link->attributes() as $parameter => $value) {
852 $attributes[$parameter] = $value;
854 XML::addElement($doc, $entry, "link", "", $attributes);
858 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
859 XML::addElement($doc, $entry, "link", "", $attributes);
863 XML::addElement($doc, $entry, "content", BBCode::convert($r->content), ["type" => "html"]);
873 * Adds the elements for attachments
875 * @param object $doc XML document
876 * @param object $root XML root
877 * @param array $item Item element
879 * @return void XML attachment object
880 * @todo Find proper type-hints
882 private static function getAttachment($doc, $root, $item)
884 $arr = explode('[/attach],', $item['attach']);
886 foreach ($arr as $r) {
888 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
890 $attributes = ["rel" => "enclosure",
891 "href" => $matches[1],
892 "type" => $matches[3]];
894 if (intval($matches[2])) {
895 $attributes["length"] = intval($matches[2]);
898 if (trim($matches[4]) != "") {
899 $attributes["title"] = trim($matches[4]);
902 XML::addElement($doc, $root, "link", "", $attributes);
909 * Adds the "entry" elements for the DFRN protocol
911 * @param DOMDocument $doc XML document
912 * @param string $type "text" or "html"
913 * @param array $item Item element
914 * @param array $owner Owner record
915 * @param bool $comment Trigger the sending of the "comment" element
916 * @param int $cid Contact ID of the recipient
917 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
919 * @return null|\DOMElement XML entry object
920 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
921 * @throws \ImagickException
922 * @todo Find proper type-hints
924 private static function entry(DOMDocument $doc, $type, array $item, array $owner, $comment = false, $cid = 0, $single = false)
928 if (!$item['parent']) {
929 Logger::notice('Item without parent found.', ['type' => $type, 'item' => $item]);
933 if ($item['deleted']) {
934 $attributes = ["ref" => $item['uri'], "when" => DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM)];
935 return XML::createElement($doc, "at:deleted-entry", "", $attributes);
939 $entry = $doc->createElement("entry");
941 $entry = $doc->createElementNS(ActivityNamespace::ATOM1, 'entry');
942 $doc->appendChild($entry);
944 $entry->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
945 $entry->setAttribute("xmlns:at", ActivityNamespace::TOMB);
946 $entry->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
947 $entry->setAttribute("xmlns:dfrn", ActivityNamespace::DFRN);
948 $entry->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
949 $entry->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
950 $entry->setAttribute("xmlns:poco", ActivityNamespace::POCO);
951 $entry->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
952 $entry->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
955 if ($item['private'] == Item::PRIVATE) {
956 $body = Item::fixPrivatePhotos($item['body'], $owner['uid'], $item, $cid);
958 $body = $item['body'];
961 // Remove the abstract element. It is only locally important.
962 $body = BBCode::stripAbstract($body);
965 if ($type == 'html') {
968 if ($item['title'] != "") {
969 $htmlbody = "[b]" . $item['title'] . "[/b]\n\n" . $htmlbody;
972 $htmlbody = BBCode::convert($htmlbody, false, 7);
975 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
976 $entry->appendChild($author);
978 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
979 $entry->appendChild($dfrnowner);
981 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
982 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
983 $parent = Item::selectFirst(['guid', 'plink'], ['uri' => $parent_item, 'uid' => $item['uid']]);
984 $attributes = ["ref" => $parent_item, "type" => "text/html",
985 "href" => $parent['plink'],
986 "dfrn:diaspora_guid" => $parent['guid']];
987 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
990 // Add conversation data. This is used for OStatus
991 $conversation_href = DI::baseUrl()."/display/".$item["parent-guid"];
992 $conversation_uri = $conversation_href;
994 if (isset($parent_item)) {
995 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $item['parent-uri']]);
996 if (DBA::isResult($conversation)) {
997 if ($conversation['conversation-uri'] != '') {
998 $conversation_uri = $conversation['conversation-uri'];
1000 if ($conversation['conversation-href'] != '') {
1001 $conversation_href = $conversation['conversation-href'];
1007 "href" => $conversation_href,
1008 "ref" => $conversation_uri];
1010 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
1012 XML::addElement($doc, $entry, "id", $item["uri"]);
1013 XML::addElement($doc, $entry, "title", $item["title"]);
1015 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"] . "+00:00", DateTimeFormat::ATOM));
1016 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"] . "+00:00", DateTimeFormat::ATOM));
1018 // "dfrn:env" is used to read the content
1019 XML::addElement($doc, $entry, "dfrn:env", Strings::base64UrlEncode($body, true));
1021 // The "content" field is not read by the receiver. We could remove it when the type is "text"
1022 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
1023 XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
1025 // We save this value in "plink". Maybe we should read it from there as well?
1031 ["rel" => "alternate", "type" => "text/html",
1032 "href" => DI::baseUrl() . "/display/" . $item["guid"]]
1035 // "comment-allow" is some old fashioned stuff for old Friendica versions.
1036 // It is included in the rewritten code for completeness
1038 XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
1041 if ($item['location']) {
1042 XML::addElement($doc, $entry, "dfrn:location", $item['location']);
1045 if ($item['coord']) {
1046 XML::addElement($doc, $entry, "georss:point", $item['coord']);
1049 if ($item['private']) {
1050 // Friendica versions prior to 2020.3 can't handle "unlisted" properly. So we can only transmit public and private
1051 XML::addElement($doc, $entry, "dfrn:private", ($item['private'] == Item::PRIVATE ? Item::PRIVATE : Item::PUBLIC));
1052 XML::addElement($doc, $entry, "dfrn:unlisted", $item['private'] == Item::UNLISTED);
1055 if ($item['extid']) {
1056 XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
1059 if ($item['post-type'] == Item::PT_PAGE) {
1060 XML::addElement($doc, $entry, "dfrn:bookmark", "true");
1064 XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
1067 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
1069 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
1070 // It is needed for relayed comments to Diaspora.
1071 if ($item['signed_text']) {
1072 $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer']]));
1073 XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
1076 XML::addElement($doc, $entry, "activity:verb", self::constructVerb($item));
1078 if ($item['object-type'] != "") {
1079 XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
1080 } elseif ($item['id'] == $item['parent']) {
1081 XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::NOTE);
1083 XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::COMMENT);
1086 $actobj = self::createActivity($doc, "activity:object", $item['object']);
1088 $entry->appendChild($actobj);
1091 $actarg = self::createActivity($doc, "activity:target", $item['target']);
1093 $entry->appendChild($actarg);
1096 $tags = Item::getFeedTags($item);
1098 /// @TODO Combine this with similar below if() block?
1100 foreach ($tags as $t) {
1101 if (($type != 'html') || ($t[0] != "@")) {
1102 XML::addElement($doc, $entry, "category", "", ["scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]]);
1108 foreach ($tags as $t) {
1110 $mentioned[$t[1]] = $t[1];
1115 foreach ($mentioned as $mention) {
1116 $condition = ['uid' => $owner["uid"], 'nurl' => Strings::normaliseLink($mention)];
1117 $contact = DBA::selectFirst('contact', ['forum', 'prv'], $condition);
1119 if (DBA::isResult($contact) && ($contact["forum"] || $contact["prv"])) {
1125 ["rel" => "mentioned",
1126 "ostatus:object-type" => Activity\ObjectType::GROUP,
1135 ["rel" => "mentioned",
1136 "ostatus:object-type" => Activity\ObjectType::PERSON,
1142 self::getAttachment($doc, $entry, $item);
1148 * encrypts data via AES
1150 * @param string $data The data that is to be encrypted
1151 * @param string $key The AES key
1153 * @return string encrypted data
1155 private static function aesEncrypt($data, $key)
1157 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1161 * decrypts data via AES
1163 * @param string $encrypted The encrypted data
1164 * @param string $key The AES key
1166 * @return string decrypted data
1168 public static function aesDecrypt($encrypted, $key)
1170 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1174 * Delivers the atom content to the contacts
1176 * @param array $owner Owner record
1177 * @param array $contact Contact record of the receiver
1178 * @param string $atom Content that will be transmitted
1179 * @param bool $dissolve (to be documented)
1181 * @return int Deliver status. Negative values mean an error.
1182 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1183 * @throws \ImagickException
1184 * @todo Add array type-hint for $owner, $contact
1186 public static function deliver($owner, $contact, $atom, $dissolve = false)
1188 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1190 if ($contact['duplex'] && $contact['dfrn-id']) {
1191 $idtosend = '0:' . $orig_id;
1193 if ($contact['duplex'] && $contact['issued-id']) {
1194 $idtosend = '1:' . $orig_id;
1197 $rino = DI::config()->get('system', 'rino_encrypt');
1198 $rino = intval($rino);
1200 Logger::log("Local rino version: ". $rino, Logger::DEBUG);
1202 $ssl_val = intval(DI::config()->get('system', 'ssl_policy'));
1205 case BaseURL::SSL_POLICY_FULL:
1206 $ssl_policy = 'full';
1208 case BaseURL::SSL_POLICY_SELFSIGN:
1209 $ssl_policy = 'self';
1211 case BaseURL::SSL_POLICY_NONE:
1213 $ssl_policy = 'none';
1217 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1219 Logger::log('dfrn_deliver: ' . $url);
1221 $curlResult = Network::curl($url);
1223 if ($curlResult->isTimeout()) {
1224 return -2; // timed out
1227 $xml = $curlResult->getBody();
1229 $curl_stat = $curlResult->getReturnCode();
1230 if (empty($curl_stat)) {
1231 return -3; // timed out
1234 Logger::log('dfrn_deliver: ' . $xml, Logger::DATA);
1240 if (strpos($xml, '<?xml') === false) {
1241 Logger::log('dfrn_deliver: no valid XML returned');
1242 Logger::log('dfrn_deliver: returned XML: ' . $xml, Logger::DATA);
1246 $res = XML::parseString($xml);
1248 if (!is_object($res) || (intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
1249 if (empty($res->status)) {
1252 $status = $res->status;
1259 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1260 $challenge = hex2bin((string) $res->challenge);
1261 $perm = (($res->perm) ? $res->perm : null);
1262 $dfrn_version = floatval($res->dfrn_version ?: 2.0);
1263 $rino_remote_version = intval($res->rino);
1264 $page = (($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? 1 : 0);
1266 Logger::log("Remote rino version: ".$rino_remote_version." for ".$contact["url"], Logger::DEBUG);
1268 if ($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
1272 $final_dfrn_id = '';
1275 if ((($perm == 'rw') && !intval($contact['writable']))
1276 || (($perm == 'r') && intval($contact['writable']))
1278 DBA::update('contact', ['writable' => ($perm == 'rw')], ['id' => $contact['id']]);
1280 $contact['writable'] = (string) 1 - intval($contact['writable']);
1284 if (($contact['duplex'] && strlen($contact['pubkey']))
1285 || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY && strlen($contact['pubkey']))
1286 || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
1288 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
1289 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
1291 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
1292 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
1295 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1297 if (strpos($final_dfrn_id, ':') == 1) {
1298 $final_dfrn_id = substr($final_dfrn_id, 2);
1301 if ($final_dfrn_id != $orig_id) {
1302 Logger::log('dfrn_deliver: wrong dfrn_id.');
1303 // did not decode properly - cannot trust this site
1307 $postvars['dfrn_id'] = $idtosend;
1308 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1310 $postvars['dissolve'] = '1';
1313 if ((($contact['rel']) && ($contact['rel'] != Contact::SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY)) {
1314 $postvars['data'] = $atom;
1315 $postvars['perm'] = 'rw';
1317 $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
1318 $postvars['perm'] = 'r';
1321 $postvars['ssl_policy'] = $ssl_policy;
1324 $postvars['page'] = $page;
1328 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1329 Logger::log('rino version: '. $rino_remote_version);
1331 switch ($rino_remote_version) {
1333 $key = openssl_random_pseudo_bytes(16);
1334 $data = self::aesEncrypt($postvars['data'], $key);
1338 Logger::log("rino: invalid requested version '$rino_remote_version'");
1342 $postvars['rino'] = $rino_remote_version;
1343 $postvars['data'] = bin2hex($data);
1345 if ($dfrn_version >= 2.1) {
1346 if (($contact['duplex'] && strlen($contact['pubkey']))
1347 || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY && strlen($contact['pubkey']))
1348 || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
1350 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1352 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1355 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY)) {
1356 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1358 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1362 Logger::log('md5 rawkey ' . md5($postvars['key']));
1364 $postvars['key'] = bin2hex($postvars['key']);
1368 Logger::log('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), Logger::DATA);
1370 $postResult = Network::post($contact['notify'], $postvars);
1372 $xml = $postResult->getBody();
1374 Logger::log('dfrn_deliver: ' . "RECEIVED: " . $xml, Logger::DATA);
1376 $curl_stat = $postResult->getReturnCode();
1377 if (empty($curl_stat) || empty($xml)) {
1378 return -9; // timed out
1381 if (($curl_stat == 503) && stristr($postResult->getHeader(), 'retry-after')) {
1385 if (strpos($xml, '<?xml') === false) {
1386 Logger::log('dfrn_deliver: phase 2: no valid XML returned');
1387 Logger::log('dfrn_deliver: phase 2: returned XML: ' . $xml, Logger::DATA);
1391 $res = XML::parseString($xml);
1393 if (!isset($res->status)) {
1397 // Possibly old servers had returned an empty value when everything was okay
1398 if (empty($res->status)) {
1402 if (!empty($res->message)) {
1403 Logger::log('Delivery returned status '.$res->status.' - '.$res->message, Logger::DEBUG);
1406 return intval($res->status);
1410 * Transmits atom content to the contacts via the Diaspora transport layer
1412 * @param array $owner Owner record
1413 * @param array $contact Contact record of the receiver
1414 * @param string $atom Content that will be transmitted
1416 * @param bool $public_batch
1417 * @return int Deliver status. Negative values mean an error.
1418 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1419 * @throws \ImagickException
1421 public static function transmit($owner, $contact, $atom, $public_batch = false)
1423 if (!$public_batch) {
1424 if (empty($contact['addr'])) {
1425 Logger::log('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.');
1426 if (Contact::updateFromProbe($contact['id'])) {
1427 $new_contact = DBA::selectFirst('contact', ['addr'], ['id' => $contact['id']]);
1428 $contact['addr'] = $new_contact['addr'];
1431 if (empty($contact['addr'])) {
1432 Logger::log('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
1437 $fcontact = Diaspora::personByHandle($contact['addr']);
1438 if (empty($fcontact)) {
1439 Logger::log('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
1442 $pubkey = $fcontact['pubkey'];
1447 $envelope = Diaspora::buildMessage($atom, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
1449 // Create the endpoint for public posts. This is some WIP and should later be added to the probing
1450 if ($public_batch && empty($contact["batch"])) {
1451 $parts = parse_url($contact["notify"]);
1452 $path_parts = explode('/', $parts['path']);
1453 array_pop($path_parts);
1454 $parts['path'] = implode('/', $path_parts);
1455 $contact["batch"] = Network::unparseURL($parts);
1458 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
1460 if (empty($dest_url)) {
1461 Logger::info('Empty destination', ['public' => $public_batch, 'contact' => $contact]);
1465 $content_type = ($public_batch ? "application/magic-envelope+xml" : "application/json");
1467 $postResult = Network::post($dest_url, $envelope, ["Content-Type: ".$content_type]);
1468 $xml = $postResult->getBody();
1470 $curl_stat = $postResult->getReturnCode();
1471 if (empty($curl_stat) || empty($xml)) {
1472 Logger::log('Empty answer from ' . $contact['id'] . ' - ' . $dest_url);
1473 return -9; // timed out
1476 if (($curl_stat == 503) && (stristr($postResult->getHeader(), 'retry-after'))) {
1480 if (strpos($xml, '<?xml') === false) {
1481 Logger::log('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url);
1482 Logger::log('Returned XML: ' . $xml, Logger::DATA);
1486 $res = XML::parseString($xml);
1488 if (empty($res->status)) {
1492 if (!empty($res->message)) {
1493 Logger::log('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message, Logger::DEBUG);
1496 return intval($res->status);
1500 * Fetch the author data from head or entry items
1502 * @param object $xpath XPath object
1503 * @param object $context In which context should the data be searched
1504 * @param array $importer Record of the importer user mixed with contact of the content
1505 * @param string $element Element name from which the data is fetched
1506 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1507 * @param string $xml optional, default empty
1509 * @return array Relevant data of the author
1510 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1511 * @throws \ImagickException
1512 * @todo Find good type-hints for all parameter
1514 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
1517 $author["name"] = XML::getFirstNodeValue($xpath, $element."/atom:name/text()", $context);
1518 $author["link"] = XML::getFirstNodeValue($xpath, $element."/atom:uri/text()", $context);
1520 $fields = ['id', 'uid', 'url', 'network', 'avatar-date', 'avatar', 'name-date', 'uri-date', 'addr',
1521 'name', 'nick', 'about', 'location', 'keywords', 'xmpp', 'bdyear', 'bd', 'hidden', 'contact-type'];
1522 $condition = ["`uid` = ? AND `nurl` = ? AND `network` != ?",
1523 $importer["importer_uid"], Strings::normaliseLink($author["link"]), Protocol::STATUSNET];
1524 $contact_old = DBA::selectFirst('contact', $fields, $condition);
1526 if (DBA::isResult($contact_old)) {
1527 $author["contact-id"] = $contact_old["id"];
1528 $author["network"] = $contact_old["network"];
1531 Logger::debug("Contact ".$author["link"]." wasn't found for user ".$importer["importer_uid"]." XML: ".$xml);
1534 $author["contact-unknown"] = true;
1535 $author["contact-id"] = $importer["id"];
1536 $author["network"] = $importer["network"];
1540 // Until now we aren't serving different sizes - but maybe later
1542 /// @todo check if "avatar" or "photo" would be the best field in the specification
1543 $avatars = $xpath->query($element . "/atom:link[@rel='avatar']", $context);
1544 foreach ($avatars as $avatar) {
1547 foreach ($avatar->attributes as $attributes) {
1548 /// @TODO Rewrite these similar if() to one switch
1549 if ($attributes->name == "href") {
1550 $href = $attributes->textContent;
1552 if ($attributes->name == "width") {
1553 $width = $attributes->textContent;
1555 if ($attributes->name == "updated") {
1556 $author["avatar-date"] = $attributes->textContent;
1559 if (($width > 0) && ($href != "")) {
1560 $avatarlist[$width] = $href;
1564 if (count($avatarlist) > 0) {
1565 krsort($avatarlist);
1566 $author["avatar"] = current($avatarlist);
1569 if (empty($author['avatar']) && !empty($author['link'])) {
1570 $cid = Contact::getIdForURL($author['link'], 0);
1572 $contact = DBA::selectFirst('contact', ['avatar'], ['id' => $cid]);
1573 if (DBA::isResult($contact)) {
1574 $author['avatar'] = $contact['avatar'];
1579 if (empty($author['avatar'])) {
1580 Logger::log('Empty author: ' . $xml);
1581 $author['avatar'] = '';
1584 if (DBA::isResult($contact_old) && !$onlyfetch) {
1585 Logger::log("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", Logger::DEBUG);
1587 $poco = ["url" => $contact_old["url"]];
1589 // When was the last change to name or uri?
1590 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1591 foreach ($name_element->attributes as $attributes) {
1592 if ($attributes->name == "updated") {
1593 $poco["name-date"] = $attributes->textContent;
1597 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1598 foreach ($link_element->attributes as $attributes) {
1599 if ($attributes->name == "updated") {
1600 $poco["uri-date"] = $attributes->textContent;
1604 // Update contact data
1605 $value = XML::getFirstNodeValue($xpath, $element . "/dfrn:handle/text()", $context);
1607 $poco["addr"] = $value;
1610 $value = XML::getFirstNodeValue($xpath, $element . "/poco:displayName/text()", $context);
1612 $poco["name"] = $value;
1615 $value = XML::getFirstNodeValue($xpath, $element . "/poco:preferredUsername/text()", $context);
1617 $poco["nick"] = $value;
1620 $value = XML::getFirstNodeValue($xpath, $element . "/poco:note/text()", $context);
1622 $poco["about"] = $value;
1625 $value = XML::getFirstNodeValue($xpath, $element . "/poco:address/poco:formatted/text()", $context);
1627 $poco["location"] = $value;
1630 /// @todo Only search for elements with "poco:type" = "xmpp"
1631 $value = XML::getFirstNodeValue($xpath, $element . "/poco:ims/poco:value/text()", $context);
1633 $poco["xmpp"] = $value;
1636 /// @todo Add support for the following fields that we don't support by now in the contact table:
1637 /// - poco:utcOffset
1643 // If the "hide" element is present then the profile isn't searchable.
1644 $hide = intval(XML::getFirstNodeValue($xpath, $element . "/dfrn:hide/text()", $context) == "true");
1646 Logger::log("Hidden status for contact " . $contact_old["url"] . ": " . $hide, Logger::DEBUG);
1648 // If the contact isn't searchable then set the contact to "hidden".
1649 // Problem: This can be manually overridden by the user.
1651 $contact_old["hidden"] = true;
1654 // Save the keywords into the contact table
1656 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1657 foreach ($tagelements as $tag) {
1658 $tags[$tag->nodeValue] = $tag->nodeValue;
1662 $poco["keywords"] = implode(", ", $tags);
1665 // "dfrn:birthday" contains the birthday converted to UTC
1666 $birthday = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1668 if (strtotime($birthday) > time()) {
1669 $bd_timestamp = strtotime($birthday);
1671 $poco["bdyear"] = date("Y", $bd_timestamp);
1674 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1675 $value = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1677 if (!in_array($value, ["", "0000-00-00", DBA::NULL_DATE])) {
1678 $bdyear = date("Y");
1679 $value = str_replace(["0000", "0001"], $bdyear, $value);
1681 if (strtotime($value) < time()) {
1682 $value = str_replace($bdyear, $bdyear + 1, $value);
1685 $poco["bd"] = $value;
1688 $contact = array_merge($contact_old, $poco);
1690 if ($contact_old["bdyear"] != $contact["bdyear"]) {
1691 Event::createBirthday($contact, $birthday);
1694 $fields = ['name' => $contact['name'], 'nick' => $contact['nick'], 'about' => $contact['about'],
1695 'location' => $contact['location'], 'addr' => $contact['addr'], 'keywords' => $contact['keywords'],
1696 'bdyear' => $contact['bdyear'], 'bd' => $contact['bd'], 'hidden' => $contact['hidden'],
1697 'xmpp' => $contact['xmpp'], 'name-date' => DateTimeFormat::utc($contact['name-date']),
1698 'unsearchable' => $contact['hidden'], 'uri-date' => DateTimeFormat::utc($contact['uri-date'])];
1700 DBA::update('contact', $fields, ['id' => $contact['id'], 'network' => $contact['network']], $contact_old);
1702 // Update the public contact. Don't set the "hidden" value, this is used differently for public contacts
1703 unset($fields['hidden']);
1704 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($contact_old['url'])];
1705 DBA::update('contact', $fields, $condition, true);
1707 Contact::updateAvatar($author['avatar'], $importer['importer_uid'], $contact['id']);
1709 $pcid = Contact::getIdForURL($contact_old['url']);
1710 if (!empty($pcid)) {
1711 Contact::updateAvatar($author['avatar'], 0, $pcid);
1715 * The generation is a sign for the reliability of the provided data.
1716 * It is used in the socgraph.php to prevent that old contact data
1717 * that was relayed over several servers can overwrite contact
1718 * data that we received directly.
1721 $poco["generation"] = 2;
1722 $poco["photo"] = $author["avatar"];
1723 $poco["hide"] = $hide;
1724 $poco["contact-type"] = $contact["contact-type"];
1725 $gcid = GContact::update($poco);
1727 GContact::link($gcid, $importer["importer_uid"], $contact["id"]);
1734 * Transforms activity objects into an XML string
1736 * @param object $xpath XPath object
1737 * @param object $activity Activity object
1738 * @param string $element element name
1740 * @return string XML string
1741 * @todo Find good type-hints for all parameter
1743 private static function transformActivity($xpath, $activity, $element)
1745 if (!is_object($activity)) {
1749 $obj_doc = new DOMDocument("1.0", "utf-8");
1750 $obj_doc->formatOutput = true;
1752 $obj_element = $obj_doc->createElementNS( ActivityNamespace::ATOM1, $element);
1754 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1755 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1757 $id = $xpath->query("atom:id", $activity)->item(0);
1758 if (is_object($id)) {
1759 $obj_element->appendChild($obj_doc->importNode($id, true));
1762 $title = $xpath->query("atom:title", $activity)->item(0);
1763 if (is_object($title)) {
1764 $obj_element->appendChild($obj_doc->importNode($title, true));
1767 $links = $xpath->query("atom:link", $activity);
1768 if (is_object($links)) {
1769 foreach ($links as $link) {
1770 $obj_element->appendChild($obj_doc->importNode($link, true));
1774 $content = $xpath->query("atom:content", $activity)->item(0);
1775 if (is_object($content)) {
1776 $obj_element->appendChild($obj_doc->importNode($content, true));
1779 $obj_doc->appendChild($obj_element);
1781 $objxml = $obj_doc->saveXML($obj_element);
1783 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1784 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1789 * Processes the mail elements
1791 * @param object $xpath XPath object
1792 * @param object $mail mail elements
1793 * @param array $importer Record of the importer user mixed with contact of the content
1795 * @throws \Exception
1796 * @todo Find good type-hints for all parameter
1798 private static function processMail($xpath, $mail, $importer)
1800 Logger::log("Processing mails");
1803 $msg["uid"] = $importer["importer_uid"];
1804 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1805 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1806 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1807 $msg["contact-id"] = $importer["id"];
1808 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1809 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1810 $msg["created"] = DateTimeFormat::utc($xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue);
1811 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1812 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1818 * Processes the suggestion elements
1820 * @param object $xpath XPath object
1821 * @param object $suggestion suggestion elements
1822 * @param array $importer Record of the importer user mixed with contact of the content
1824 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1825 * @todo Find good type-hints for all parameter
1827 private static function processSuggestion($xpath, $suggestion, $importer)
1829 Logger::log('Processing suggestions');
1831 /// @TODO Rewrite this to one statement
1833 $suggest['uid'] = $importer['importer_uid'];
1834 $suggest['cid'] = $importer['id'];
1835 $suggest['url'] = $xpath->query('dfrn:url/text()', $suggestion)->item(0)->nodeValue;
1836 $suggest['name'] = $xpath->query('dfrn:name/text()', $suggestion)->item(0)->nodeValue;
1837 $suggest['photo'] = $xpath->query('dfrn:photo/text()', $suggestion)->item(0)->nodeValue;
1838 $suggest['request'] = $xpath->query('dfrn:request/text()', $suggestion)->item(0)->nodeValue;
1839 $suggest['body'] = $xpath->query('dfrn:note/text()', $suggestion)->item(0)->nodeValue;
1841 // Does our member already have a friend matching this description?
1844 * The valid result means the friend we're about to send a friend
1845 * suggestion already has them in their contact, which means no further
1846 * action is required.
1848 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1850 $condition = ['nurl' => Strings::normaliseLink($suggest['url']), 'uid' => $suggest['uid']];
1851 if (DBA::exists('contact', $condition)) {
1854 // Do we already have an fcontact record for this person?
1857 $fcontact = DBA::selectFirst('fcontact', ['id'], ['url' => $suggest['url']]);
1858 if (DBA::isResult($fcontact)) {
1859 $fid = $fcontact['id'];
1861 // OK, we do. Do we already have an introduction for this person?
1862 if (DBA::exists('intro', ['uid' => $suggest['uid'], 'fid' => $fid])) {
1864 * The valid result means the friend we're about to send a friend
1865 * suggestion already has them in their contact, which means no further
1866 * action is required.
1868 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1875 $fields = ['name' => $suggest['name'], 'url' => $suggest['url'],
1876 'photo' => $suggest['photo'], 'request' => $suggest['request']];
1877 DBA::insert('fcontact', $fields);
1878 $fid = DBA::lastInsertId();
1882 * If no record in fcontact is found, below INSERT statement will not
1883 * link an introduction to it.
1886 // Database record did not get created. Quietly give up.
1890 $hash = Strings::getRandomHex();
1892 $fields = ['uid' => $suggest['uid'], 'fid' => $fid, 'contact-id' => $suggest['cid'],
1893 'note' => $suggest['body'], 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow(), 'blocked' => false];
1894 DBA::insert('intro', $fields);
1898 'type' => Type::SUGGEST,
1899 'notify_flags' => $importer['notify-flags'],
1900 'language' => $importer['language'],
1901 'to_name' => $importer['username'],
1902 'to_email' => $importer['email'],
1903 'uid' => $importer['importer_uid'],
1905 'link' => DI::baseUrl().'/notifications/intros',
1906 'source_name' => $importer['name'],
1907 'source_link' => $importer['url'],
1908 'source_photo' => $importer['photo'],
1909 'verb' => Activity::REQ_FRIEND,
1917 * Processes the relocation elements
1919 * @param object $xpath XPath object
1920 * @param object $relocation relocation elements
1921 * @param array $importer Record of the importer user mixed with contact of the content
1923 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1924 * @throws \ImagickException
1925 * @todo Find good type-hints for all parameter
1927 private static function processRelocation($xpath, $relocation, $importer)
1929 Logger::log("Processing relocations");
1931 /// @TODO Rewrite this to one statement
1933 $relocate["uid"] = $importer["importer_uid"];
1934 $relocate["cid"] = $importer["id"];
1935 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1936 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
1937 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1938 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
1939 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1940 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1941 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1942 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1943 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1944 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1945 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1946 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1948 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
1949 $relocate["avatar"] = $relocate["photo"];
1952 if ($relocate["addr"] == "") {
1953 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
1958 "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d",
1959 intval($importer["id"]),
1960 intval($importer["importer_uid"])
1963 if (!DBA::isResult($r)) {
1964 Logger::log("Query failed to execute, no result returned in " . __FUNCTION__);
1970 // Update the gcontact entry
1971 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
1973 $fields = ['name' => $relocate["name"], 'photo' => $relocate["avatar"],
1974 'url' => $relocate["url"], 'nurl' => Strings::normaliseLink($relocate["url"]),
1975 'addr' => $relocate["addr"], 'connect' => $relocate["addr"],
1976 'notify' => $relocate["notify"], 'server_url' => $relocate["server_url"]];
1977 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($old["url"])]);
1979 // Update the contact table. We try to find every entry.
1980 $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
1981 'url' => $relocate["url"], 'nurl' => Strings::normaliseLink($relocate["url"]),
1982 'addr' => $relocate["addr"], 'request' => $relocate["request"],
1983 'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
1984 'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
1985 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], Strings::normaliseLink($old["url"])];
1987 DBA::update('contact', $fields, $condition);
1989 Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
1991 Logger::log('Contacts are updated.');
1994 /// merge with current record, current contents have priority
1995 /// update record, set url-updated
1996 /// update profile photos
1997 /// schedule a scan?
2004 * @param array $current the current item record
2005 * @param array $item the new item record
2006 * @param array $importer Record of the importer user mixed with contact of the content
2007 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2009 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2010 * @todo set proper type-hints (array?)
2012 private static function updateContent($current, $item, $importer, $entrytype)
2016 if (self::isEditedTimestampNewer($current, $item)) {
2017 // do not accept (ignore) an earlier edit than one we currently have.
2018 if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
2022 $fields = ['title' => $item['title'] ?? '', 'body' => $item['body'] ?? '',
2023 'tag' => $item['tag'] ?? '', 'changed' => DateTimeFormat::utcNow(),
2024 'edited' => DateTimeFormat::utc($item["edited"])];
2026 $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
2027 Item::update($fields, $condition);
2035 * Detects the entry type of the item
2037 * @param array $importer Record of the importer user mixed with contact of the content
2038 * @param array $item the new item record
2040 * @return int Is it a toplevel entry, a comment or a relayed comment?
2041 * @throws \Exception
2042 * @todo set proper type-hints (array?)
2044 private static function getEntryType($importer, $item)
2046 if ($item["parent-uri"] != $item["uri"]) {
2049 if ($importer["page-flags"] == User::PAGE_FLAGS_COMMUNITY || $importer["page-flags"] == User::PAGE_FLAGS_PRVGROUP) {
2052 Logger::log("possible community action");
2054 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2057 // was the top-level post for this action written by somebody on this site?
2058 // Specifically, the recipient?
2060 $is_a_remote_action = false;
2062 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item["parent-uri"]]);
2063 if (DBA::isResult($parent)) {
2065 "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2066 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2067 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2068 AND `item`.`uid` = %d
2071 DBA::escape($parent["parent-uri"]),
2072 DBA::escape($parent["parent-uri"]),
2073 DBA::escape($parent["parent-uri"]),
2074 intval($importer["importer_uid"])
2076 if (DBA::isResult($r)) {
2077 $is_a_remote_action = true;
2082 * Does this have the characteristics of a community or private group action?
2083 * If it's an action to a wall post on a community/prvgroup page it's a
2084 * valid community action. Also forum_mode makes it valid for sure.
2085 * If neither, it's not.
2087 if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2088 $is_a_remote_action = false;
2089 Logger::log("not a community action");
2092 if ($is_a_remote_action) {
2093 return DFRN::REPLY_RC;
2098 return DFRN::TOP_LEVEL;
2105 * @param array $item The new item record
2106 * @param array $importer Record of the importer user mixed with contact of the content
2108 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2109 * @todo set proper type-hints (array?)
2111 private static function doPoke(array $item, array $importer)
2113 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2117 $xo = XML::parseString($item["object"], false);
2119 if (($xo->type == Activity\ObjectType::PERSON) && ($xo->id)) {
2120 // somebody was poked/prodded. Was it me?
2122 foreach ($xo->link as $l) {
2123 $atts = $l->attributes();
2124 switch ($atts["rel"]) {
2126 $Blink = $atts["href"];
2133 if ($Blink && Strings::compareLink($Blink, DI::baseUrl() . "/profile/" . $importer["nickname"])) {
2134 $author = DBA::selectFirst('contact', ['name', 'thumb', 'url'], ['id' => $item['author-id']]);
2136 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => $importer["importer_uid"]]);
2137 $item["parent"] = $parent['id'];
2139 // send a notification
2142 "type" => Type::POKE,
2143 "notify_flags" => $importer["notify-flags"],
2144 "language" => $importer["language"],
2145 "to_name" => $importer["username"],
2146 "to_email" => $importer["email"],
2147 "uid" => $importer["importer_uid"],
2149 "link" => DI::baseUrl()."/display/".urlencode($item['guid']),
2150 "source_name" => $author["name"],
2151 "source_link" => $author["url"],
2152 "source_photo" => $author["thumb"],
2153 "verb" => $item["verb"],
2154 "otype" => "person",
2155 "activity" => $verb,
2156 "parent" => $item["parent"]]
2163 * Processes several actions, depending on the verb
2165 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2166 * @param array $importer Record of the importer user mixed with contact of the content
2167 * @param array $item the new item record
2168 * @param bool $is_like Is the verb a "like"?
2170 * @return bool Should the processing of the entries be continued?
2171 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2172 * @todo set proper type-hints (array?)
2174 private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2176 Logger::log("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, Logger::DEBUG);
2178 if (($entrytype == DFRN::TOP_LEVEL) && !empty($importer['id'])) {
2179 // The filling of the the "contact" variable is done for legcy reasons
2180 // The functions below are partly used by ostatus.php as well - where we have this variable
2181 $contact = Contact::selectFirst([], ['id' => $importer['id']]);
2183 $activity = DI::activity();
2185 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2186 // This function once was responsible for DFRN and OStatus.
2187 if ($activity->match($item["verb"], Activity::FOLLOW)) {
2188 Logger::log("New follower");
2189 Contact::addRelationship($importer, $contact, $item);
2192 if ($activity->match($item["verb"], Activity::UNFOLLOW)) {
2193 Logger::log("Lost follower");
2194 Contact::removeFollower($importer, $contact, $item);
2197 if ($activity->match($item["verb"], Activity::REQ_FRIEND)) {
2198 Logger::log("New friend request");
2199 Contact::addRelationship($importer, $contact, $item, true);
2202 if ($activity->match($item["verb"], Activity::UNFRIEND)) {
2203 Logger::log("Lost sharer");
2204 Contact::removeSharer($importer, $contact, $item);
2208 if (($item["verb"] == Activity::LIKE)
2209 || ($item["verb"] == Activity::DISLIKE)
2210 || ($item["verb"] == Activity::ATTEND)
2211 || ($item["verb"] == Activity::ATTENDNO)
2212 || ($item["verb"] == Activity::ATTENDMAYBE)
2215 $item["gravity"] = GRAVITY_ACTIVITY;
2216 // only one like or dislike per person
2217 // splitted into two queries for performance issues
2218 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2219 'verb' => $item["verb"], 'parent-uri' => $item["parent-uri"]];
2220 if (Item::exists($condition)) {
2224 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2225 'verb' => $item["verb"], 'thr-parent' => $item["parent-uri"]];
2226 if (Item::exists($condition)) {
2230 // The owner of an activity must be the author
2231 $item["owner-name"] = $item["author-name"];
2232 $item["owner-link"] = $item["author-link"];
2233 $item["owner-avatar"] = $item["author-avatar"];
2234 $item["owner-id"] = $item["author-id"];
2239 if (($item["verb"] == Activity::TAG) && ($item["object-type"] == Activity\ObjectType::TAGTERM)) {
2240 $xo = XML::parseString($item["object"], false);
2241 $xt = XML::parseString($item["target"], false);
2243 if ($xt->type == Activity\ObjectType::NOTE) {
2244 $item_tag = Item::selectFirst(['id', 'tag'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]);
2246 if (!DBA::isResult($item_tag)) {
2247 Logger::log("Query failed to execute, no result returned in " . __FUNCTION__);
2251 // extract tag, if not duplicate, add to parent item
2253 if (!stristr($item_tag["tag"], trim($xo->content))) {
2254 $tag = $item_tag["tag"] . (strlen($item_tag["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2255 Item::update(['tag' => $tag], ['id' => $item_tag["id"]]);
2265 * Processes the link elements
2267 * @param object $links link elements
2268 * @param array $item the item record
2270 * @todo set proper type-hints
2272 private static function parseLinks($links, &$item)
2279 foreach ($links as $link) {
2280 foreach ($link->attributes as $attributes) {
2281 switch ($attributes->name) {
2282 case "href" : $href = $attributes->textContent; break;
2283 case "rel" : $rel = $attributes->textContent; break;
2284 case "type" : $type = $attributes->textContent; break;
2285 case "length": $length = $attributes->textContent; break;
2286 case "title" : $title = $attributes->textContent; break;
2289 if (($rel != "") && ($href != "")) {
2292 $item["plink"] = $href;
2295 if (!empty($item["attach"])) {
2296 $item["attach"] .= ",";
2298 $item["attach"] = "";
2301 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2309 * Processes the entry elements which contain the items and comments
2311 * @param array $header Array of the header elements that always stay the same
2312 * @param object $xpath XPath object
2313 * @param object $entry entry elements
2314 * @param array $importer Record of the importer user mixed with contact of the content
2315 * @param string $xml xml
2317 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2318 * @throws \ImagickException
2319 * @todo Add type-hints
2321 private static function processEntry($header, $xpath, $entry, $importer, $xml)
2323 Logger::log("Processing entries");
2327 $item["protocol"] = Conversation::PARCEL_DFRN;
2329 $item["source"] = $xml;
2332 $item["uri"] = XML::getFirstNodeValue($xpath, "atom:id/text()", $entry);
2334 $item["edited"] = XML::getFirstNodeValue($xpath, "atom:updated/text()", $entry);
2336 $current = Item::selectFirst(['id', 'uid', 'edited', 'body'],
2337 ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
2339 // Is there an existing item?
2340 if (DBA::isResult($current) && !self::isEditedTimestampNewer($current, $item)) {
2341 Logger::log("Item ".$item["uri"]." (".$item['edited'].") already existed.", Logger::DEBUG);
2346 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true, $xml);
2348 $owner_unknown = (isset($owner["contact-unknown"]) && $owner["contact-unknown"]);
2350 $item["owner-name"] = $owner["name"];
2351 $item["owner-link"] = $owner["link"];
2352 $item["owner-avatar"] = $owner["avatar"];
2353 $item["owner-id"] = Contact::getIdForURL($owner["link"], 0);
2356 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true, $xml);
2358 $item["author-name"] = $author["name"];
2359 $item["author-link"] = $author["link"];
2360 $item["author-avatar"] = $author["avatar"];
2361 $item["author-id"] = Contact::getIdForURL($author["link"], 0);
2363 $item["title"] = XML::getFirstNodeValue($xpath, "atom:title/text()", $entry);
2365 $item["created"] = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2367 $item["body"] = XML::getFirstNodeValue($xpath, "dfrn:env/text()", $entry);
2368 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2370 $item["body"] = Strings::base64UrlDecode($item["body"]);
2372 $item["body"] = BBCode::limitBodySize($item["body"]);
2374 /// @todo We should check for a repeated post and if we know the repeated author.
2376 // We don't need the content element since "dfrn:env" is always present
2377 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2379 $item["location"] = XML::getFirstNodeValue($xpath, "dfrn:location/text()", $entry);
2381 $item["coord"] = XML::getFirstNodeValue($xpath, "georss:point", $entry);
2383 $item["private"] = XML::getFirstNodeValue($xpath, "dfrn:private/text()", $entry);
2385 $unlisted = XML::getFirstNodeValue($xpath, "dfrn:unlisted/text()", $entry);
2386 if (!empty($unlisted) && ($item['private'] != Item::PRIVATE)) {
2387 $item['private'] = Item::UNLISTED;
2390 $item["extid"] = XML::getFirstNodeValue($xpath, "dfrn:extid/text()", $entry);
2392 if (XML::getFirstNodeValue($xpath, "dfrn:bookmark/text()", $entry) == "true") {
2393 $item["post-type"] = Item::PT_PAGE;
2396 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2397 if ($notice_info && ($notice_info->length > 0)) {
2398 foreach ($notice_info->item(0)->attributes as $attributes) {
2399 if ($attributes->name == "source") {
2400 $item["app"] = strip_tags($attributes->textContent);
2405 $item["guid"] = XML::getFirstNodeValue($xpath, "dfrn:diaspora_guid/text()", $entry);
2407 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
2408 $dsprsig = XML::unescape(XML::getFirstNodeValue($xpath, "dfrn:diaspora_signature/text()", $entry));
2409 if ($dsprsig != "") {
2410 $item["dsprsig"] = $dsprsig;
2413 $item["verb"] = XML::getFirstNodeValue($xpath, "activity:verb/text()", $entry);
2415 if (XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry) != "") {
2416 $item["object-type"] = XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry);
2419 $object = $xpath->query("activity:object", $entry)->item(0);
2420 $item["object"] = self::transformActivity($xpath, $object, "object");
2422 if (trim($item["object"]) != "") {
2423 $r = XML::parseString($item["object"], false);
2424 if (isset($r->type)) {
2425 $item["object-type"] = $r->type;
2429 $target = $xpath->query("activity:target", $entry)->item(0);
2430 $item["target"] = self::transformActivity($xpath, $target, "target");
2432 $categories = $xpath->query("atom:category", $entry);
2434 foreach ($categories as $category) {
2437 foreach ($category->attributes as $attributes) {
2438 if ($attributes->name == "term") {
2439 $term = $attributes->textContent;
2442 if ($attributes->name == "scheme") {
2443 $scheme = $attributes->textContent;
2447 if (($term != "") && ($scheme != "")) {
2448 $parts = explode(":", $scheme);
2449 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2450 $termhash = array_shift($parts);
2451 $termurl = implode(":", $parts);
2453 if (!empty($item["tag"])) {
2454 $item["tag"] .= ",";
2459 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2465 $links = $xpath->query("atom:link", $entry);
2467 self::parseLinks($links, $item);
2470 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
2472 $conv = $xpath->query('ostatus:conversation', $entry);
2473 if (is_object($conv->item(0))) {
2474 foreach ($conv->item(0)->attributes as $attributes) {
2475 if ($attributes->name == "ref") {
2476 $item['conversation-uri'] = $attributes->textContent;
2478 if ($attributes->name == "href") {
2479 $item['conversation-href'] = $attributes->textContent;
2484 // Is it a reply or a top level posting?
2485 $item["parent-uri"] = $item["uri"];
2487 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2488 if (is_object($inreplyto->item(0))) {
2489 foreach ($inreplyto->item(0)->attributes as $attributes) {
2490 if ($attributes->name == "ref") {
2491 $item["parent-uri"] = $attributes->textContent;
2496 // Get the type of the item (Top level post, reply or remote reply)
2497 $entrytype = self::getEntryType($importer, $item);
2499 // Now assign the rest of the values that depend on the type of the message
2500 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2501 if (!isset($item["object-type"])) {
2502 $item["object-type"] = Activity\ObjectType::COMMENT;
2505 if ($item["contact-id"] != $owner["contact-id"]) {
2506 $item["contact-id"] = $owner["contact-id"];
2509 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2510 $item["network"] = $owner["network"];
2513 if ($item["contact-id"] != $author["contact-id"]) {
2514 $item["contact-id"] = $author["contact-id"];
2517 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2518 $item["network"] = $author["network"];
2522 // Ensure to have the correct share data
2523 $item = Item::addShareDataFromOriginal($item);
2525 if ($entrytype == DFRN::REPLY_RC) {
2527 } elseif ($entrytype == DFRN::TOP_LEVEL) {
2528 if (!isset($item["object-type"])) {
2529 $item["object-type"] = Activity\ObjectType::NOTE;
2533 if (($item["object-type"] == Activity\ObjectType::EVENT) && !$owner_unknown) {
2534 Logger::log("Item ".$item["uri"]." seems to contain an event.", Logger::DEBUG);
2535 $ev = Event::fromBBCode($item["body"]);
2536 if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
2537 Logger::log("Event in item ".$item["uri"]." was found.", Logger::DEBUG);
2538 $ev["cid"] = $importer["id"];
2539 $ev["uid"] = $importer["importer_uid"];
2540 $ev["uri"] = $item["uri"];
2541 $ev["edited"] = $item["edited"];
2542 $ev["private"] = $item["private"];
2543 $ev["guid"] = $item["guid"];
2544 $ev["plink"] = $item["plink"];
2546 $condition = ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]];
2547 $event = DBA::selectFirst('event', ['id'], $condition);
2548 if (DBA::isResult($event)) {
2549 $ev["id"] = $event["id"];
2552 $event_id = Event::store($ev);
2553 Logger::log("Event ".$event_id." was stored", Logger::DEBUG);
2559 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2560 Logger::log("Exiting because 'processVerbs' told us so", Logger::DEBUG);
2564 // This check is done here to be able to receive connection requests in "processVerbs"
2565 if (($entrytype == DFRN::TOP_LEVEL) && $owner_unknown) {
2566 Logger::log("Item won't be stored because user " . $importer["importer_uid"] . " doesn't follow " . $item["owner-link"] . ".", Logger::DEBUG);
2571 // Update content if 'updated' changes
2572 if (DBA::isResult($current)) {
2573 if (self::updateContent($current, $item, $importer, $entrytype)) {
2574 Logger::log("Item ".$item["uri"]." was updated.", Logger::DEBUG);
2576 Logger::log("Item " . $item["uri"] . " already existed.", Logger::DEBUG);
2581 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2582 $posted_id = Item::insert($item);
2584 Logger::log("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, Logger::DEBUG);
2586 if ($item['uid'] == 0) {
2587 Item::distribute($posted_id);
2592 } else { // $entrytype == DFRN::TOP_LEVEL
2593 if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
2594 Logger::log("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", Logger::DEBUG);
2597 if (!Strings::compareLink($item["owner-link"], $importer["url"])) {
2599 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2600 * but otherwise there's a possible data mixup on the sender's system.
2601 * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2602 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2604 Logger::log('Correcting item owner.', Logger::DEBUG);
2605 $item["owner-link"] = $importer["url"];
2606 $item["owner-id"] = Contact::getIdForURL($importer["url"], 0);
2609 if (($importer["rel"] == Contact::FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2610 Logger::log("Contact ".$importer["id"]." is only follower and tgroup check was negative.", Logger::DEBUG);
2614 // This is my contact on another system, but it's really me.
2615 // Turn this into a wall post.
2616 $notify = Item::isRemoteSelf($importer, $item);
2618 $posted_id = Item::insert($item, false, $notify);
2621 $posted_id = $notify;
2624 Logger::log("Item was stored with id ".$posted_id, Logger::DEBUG);
2626 if ($item['uid'] == 0) {
2627 Item::distribute($posted_id);
2630 if (stristr($item["verb"], Activity::POKE)) {
2631 $item['id'] = $posted_id;
2632 self::doPoke($item, $importer);
2640 * @param object $xpath XPath object
2641 * @param object $deletion deletion elements
2642 * @param array $importer Record of the importer user mixed with contact of the content
2644 * @throws \Exception
2645 * @todo set proper type-hints
2647 private static function processDeletion($xpath, $deletion, $importer)
2649 Logger::log("Processing deletions");
2652 foreach ($deletion->attributes as $attributes) {
2653 if ($attributes->name == "ref") {
2654 $uri = $attributes->textContent;
2658 if (!$uri || !$importer["id"]) {
2662 $condition = ['uri' => $uri, 'uid' => $importer["importer_uid"]];
2663 $item = Item::selectFirst(['id', 'parent', 'contact-id', 'file', 'deleted'], $condition);
2664 if (!DBA::isResult($item)) {
2665 Logger::log("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", Logger::DEBUG);
2669 if (strstr($item['file'], '[')) {
2670 Logger::log("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " is filed. So it won't be deleted.", Logger::DEBUG);
2674 // When it is a starting post it has to belong to the person that wants to delete it
2675 if (($item['id'] == $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2676 Logger::log("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", Logger::DEBUG);
2680 // Comments can be deleted by the thread owner or comment owner
2681 if (($item['id'] != $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2682 $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2683 if (!Item::exists($condition)) {
2684 Logger::log("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", Logger::DEBUG);
2689 if ($item["deleted"]) {
2693 Logger::log('deleting item '.$item['id'].' uri='.$uri, Logger::DEBUG);
2695 Item::markForDeletion(['id' => $item['id']]);
2699 * Imports a DFRN message
2701 * @param string $xml The DFRN message
2702 * @param array $importer Record of the importer user mixed with contact of the content
2703 * @param bool $sort_by_date Is used when feeds are polled
2704 * @return integer Import status
2705 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2706 * @throws \ImagickException
2707 * @todo set proper type-hints
2709 public static function import($xml, $importer, $sort_by_date = false)
2715 $doc = new DOMDocument();
2716 @$doc->loadXML($xml);
2718 $xpath = new DOMXPath($doc);
2719 $xpath->registerNamespace("atom", ActivityNamespace::ATOM1);
2720 $xpath->registerNamespace("thr", ActivityNamespace::THREAD);
2721 $xpath->registerNamespace("at", ActivityNamespace::TOMB);
2722 $xpath->registerNamespace("media", ActivityNamespace::MEDIA);
2723 $xpath->registerNamespace("dfrn", ActivityNamespace::DFRN);
2724 $xpath->registerNamespace("activity", ActivityNamespace::ACTIVITY);
2725 $xpath->registerNamespace("georss", ActivityNamespace::GEORSS);
2726 $xpath->registerNamespace("poco", ActivityNamespace::POCO);
2727 $xpath->registerNamespace("ostatus", ActivityNamespace::OSTATUS);
2728 $xpath->registerNamespace("statusnet", ActivityNamespace::STATUSNET);
2731 $header["uid"] = $importer["importer_uid"];
2732 $header["network"] = Protocol::DFRN;
2733 $header["wall"] = 0;
2734 $header["origin"] = 0;
2735 $header["contact-id"] = $importer["id"];
2737 // Update the contact table if the data has changed
2739 // The "atom:author" is only present in feeds
2740 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2741 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2744 // Only the "dfrn:owner" in the head section contains all data
2745 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2746 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2749 Logger::log("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], Logger::DEBUG);
2751 // is it a public forum? Private forums aren't exposed with this method
2752 $forum = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:community/text()"));
2754 // The account type is new since 3.5.1
2755 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2756 // Hint: We are using separate update calls for uid=0 and uid!=0 since a combined call is bad for the database performance
2758 $accounttype = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:account_type/text()"));
2760 if ($accounttype != $importer["contact-type"]) {
2761 DBA::update('contact', ['contact-type' => $accounttype], ['id' => $importer['id']]);
2763 // Updating the public contact as well
2764 DBA::update('contact', ['contact-type' => $accounttype], ['uid' => 0, 'nurl' => $importer['nurl']]);
2766 // A forum contact can either have set "forum" or "prv" - but not both
2767 if ($accounttype == User::ACCOUNT_TYPE_COMMUNITY) {
2768 // It's a forum, so either set the public or private forum flag
2769 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer['id']];
2770 DBA::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2772 // Updating the public contact as well
2773 $condition = ['(`forum` != ? OR `prv` != ?) AND `uid` = 0 AND `nurl` = ?', $forum, !$forum, $importer['nurl']];
2774 DBA::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2776 // It's not a forum, so remove the flags
2777 $condition = ['(`forum` OR `prv`) AND `id` = ?', $importer['id']];
2778 DBA::update('contact', ['forum' => false, 'prv' => false], $condition);
2780 // Updating the public contact as well
2781 $condition = ['(`forum` OR `prv`) AND `uid` = 0 AND `nurl` = ?', $importer['nurl']];
2782 DBA::update('contact', ['forum' => false, 'prv' => false], $condition);
2784 } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
2785 $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2786 DBA::update('contact', ['forum' => $forum], $condition);
2788 // Updating the public contact as well
2789 $condition = ['`forum` != ? AND `uid` = 0 AND `nurl` = ?', $forum, $importer['nurl']];
2790 DBA::update('contact', ['forum' => $forum], $condition);
2794 // We are processing relocations even if we are ignoring a contact
2795 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2796 foreach ($relocations as $relocation) {
2797 self::processRelocation($xpath, $relocation, $importer);
2800 if (($importer["uid"] != 0) && !$importer["readonly"]) {
2801 $mails = $xpath->query("/atom:feed/dfrn:mail");
2802 foreach ($mails as $mail) {
2803 self::processMail($xpath, $mail, $importer);
2806 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2807 foreach ($suggestions as $suggestion) {
2808 self::processSuggestion($xpath, $suggestion, $importer);
2812 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2813 foreach ($deletions as $deletion) {
2814 self::processDeletion($xpath, $deletion, $importer);
2817 if (!$sort_by_date) {
2818 $entries = $xpath->query("/atom:feed/atom:entry");
2819 foreach ($entries as $entry) {
2820 self::processEntry($header, $xpath, $entry, $importer, $xml);
2824 $entries = $xpath->query("/atom:feed/atom:entry");
2825 foreach ($entries as $entry) {
2826 $created = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2827 $newentries[strtotime($created)] = $entry;
2830 // Now sort after the publishing date
2833 foreach ($newentries as $entry) {
2834 self::processEntry($header, $xpath, $entry, $importer, $xml);
2837 Logger::log("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], Logger::DEBUG);
2842 * Returns the activity verb
2844 * @param array $item Item array
2846 * @return string activity verb
2848 private static function constructVerb(array $item)
2850 if ($item['verb']) {
2851 return $item['verb'];
2853 return Activity::POST;
2856 private static function tgroupCheck($uid, $item)
2860 // check that the message originated elsewhere and is a top-level post
2862 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['parent-uri'])) {
2866 $user = DBA::selectFirst('user', ['page-flags', 'nickname'], ['uid' => $uid]);
2867 if (!DBA::isResult($user)) {
2871 $community_page = ($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY);
2872 $prvgroup = ($user['page-flags'] == User::PAGE_FLAGS_PRVGROUP);
2874 $link = Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']);
2877 * Diaspora uses their own hardwired link URL in @-tags
2878 * instead of the one we supply with webfinger
2880 $dlink = Strings::normaliseLink(DI::baseUrl() . '/u/' . $user['nickname']);
2882 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2884 foreach ($matches as $mtch) {
2885 if (Strings::compareLink($link, $mtch[1]) || Strings::compareLink($dlink, $mtch[1])) {
2887 Logger::log('mention found: ' . $mtch[2]);
2896 return $community_page || $prvgroup;
2900 * This function returns true if $update has an edited timestamp newer
2901 * than $existing, i.e. $update contains new data which should override
2902 * what's already there. If there is no timestamp yet, the update is
2903 * assumed to be newer. If the update has no timestamp, the existing
2904 * item is assumed to be up-to-date. If the timestamps are equal it
2905 * assumes the update has been seen before and should be ignored.
2910 * @throws \Exception
2912 private static function isEditedTimestampNewer($existing, $update)
2914 if (empty($existing['edited'])) {
2917 if (empty($update['edited'])) {
2921 $existing_edited = DateTimeFormat::utc($existing['edited']);
2922 $update_edited = DateTimeFormat::utc($update['edited']);
2924 return (strcmp($existing_edited, $update_edited) < 0);
2928 * Checks if the given contact url does support DFRN
2930 * @param string $url profile url
2931 * @param boolean $update Update the profile
2933 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2934 * @throws \ImagickException
2936 public static function isSupportedByContactUrl($url, $update = false)
2938 $probe = Probe::uri($url, Protocol::DFRN, 0, !$update);
2939 return $probe['network'] == Protocol::DFRN;