3 * @file include/dfrn.php
4 * The implementation of the dfrn protocol
6 * @see https://github.com/friendica/friendica/wiki/Protocol and
7 * https://github.com/friendica/friendica/blob/master/spec/dfrn2.pdf
9 namespace Friendica\Protocol;
13 use Friendica\App\BaseURL;
14 use Friendica\Content\OEmbed;
15 use Friendica\Content\Text\BBCode;
16 use Friendica\Content\Text\HTML;
17 use Friendica\Core\Hook;
18 use Friendica\Core\Logger;
19 use Friendica\Core\Protocol;
20 use Friendica\Database\DBA;
22 use Friendica\Model\Contact;
23 use Friendica\Model\Conversation;
24 use Friendica\Model\Event;
25 use Friendica\Model\GContact;
26 use Friendica\Model\Item;
27 use Friendica\Model\Mail;
28 use Friendica\Model\PermissionSet;
29 use Friendica\Model\Profile;
30 use Friendica\Model\User;
31 use Friendica\Network\Probe;
32 use Friendica\Util\Crypto;
33 use Friendica\Util\DateTimeFormat;
34 use Friendica\Util\Images;
35 use Friendica\Util\Network;
36 use Friendica\Util\Strings;
37 use Friendica\Util\XML;
39 use HTMLPurifier_Config;
42 * This class contain functions to create and send DFRN XML files
47 const TOP_LEVEL = 0; // Top level posting
48 const REPLY = 1; // Regular reply that is stored locally
49 const REPLY_RC = 2; // Reply that will be relayed
52 * Generates an array of contact and user for DFRN imports
54 * This array contains not only the receiver but also the sender of the message.
56 * @param integer $cid Contact id
57 * @param integer $uid User id
59 * @return array importer
62 public static function getImporter($cid, $uid = 0)
64 $condition = ['id' => $cid, 'blocked' => false, 'pending' => false];
65 $contact = DBA::selectFirst('contact', [], $condition);
66 if (!DBA::isResult($contact)) {
70 $contact['cpubkey'] = $contact['pubkey'];
71 $contact['cprvkey'] = $contact['prvkey'];
72 $contact['senderName'] = $contact['name'];
75 $condition = ['uid' => $uid, 'account_expired' => false, 'account_removed' => false];
76 $user = DBA::selectFirst('user', [], $condition);
77 if (!DBA::isResult($user)) {
81 $user['importer_uid'] = $user['uid'];
82 $user['uprvkey'] = $user['prvkey'];
84 $user = ['importer_uid' => 0, 'uprvkey' => '', 'timezone' => 'UTC',
85 'nickname' => '', 'sprvkey' => '', 'spubkey' => '',
86 'page-flags' => 0, 'account-type' => 0, 'prvnets' => 0];
89 return array_merge($contact, $user);
93 * Generates the atom entries for delivery.php
95 * This function is used whenever content is transmitted via DFRN.
97 * @param array $items Item elements
98 * @param array $owner Owner record
100 * @return string DFRN entries
101 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
102 * @throws \ImagickException
103 * @todo Find proper type-hints
105 public static function entries($items, $owner)
107 $doc = new DOMDocument('1.0', 'utf-8');
108 $doc->formatOutput = true;
110 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
112 if (! count($items)) {
113 return trim($doc->saveXML());
116 foreach ($items as $item) {
117 // These values aren't sent when sending from the queue.
118 /// @todo Check if we can set these values from the queue or if they are needed at all.
119 $item["entry:comment-allow"] = ($item["entry:comment-allow"] ?? '') ?: true;
120 $item["entry:cid"] = $item["entry:cid"] ?? 0;
122 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
124 $root->appendChild($entry);
128 return trim($doc->saveXML());
132 * Generate an atom feed for the given user
134 * This function is called when another server is pulling data from the user feed.
136 * @param string $dfrn_id DFRN ID from the requesting party
137 * @param string $owner_nick Owner nick name
138 * @param string $last_update Date of the last update
139 * @param int $direction Can be -1, 0 or 1.
140 * @param boolean $onlyheader Output only the header without content? (Default is "no")
142 * @return string DFRN feed entries
143 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
144 * @throws \ImagickException
146 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false)
150 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
151 $public_feed = (($dfrn_id) ? false : true);
152 $starred = false; // not yet implemented, possible security issues
155 if ($public_feed && $a->argc > 2) {
156 for ($x = 2; $x < $a->argc; $x++) {
157 if ($a->argv[$x] == 'converse') {
160 if ($a->argv[$x] == 'starred') {
163 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
164 $category = $a->argv[$x+1];
169 // default permissions - anonymous user
171 $sql_extra = " AND NOT `item`.`private` ";
174 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
175 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
176 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
177 DBA::escape($owner_nick)
180 if (! DBA::isResult($r)) {
181 Logger::log(sprintf('No contact found for nickname=%d', $owner_nick), Logger::WARNING);
186 $owner_id = $owner['uid'];
188 $sql_post_table = "";
190 if (! $public_feed) {
191 switch ($direction) {
193 $sql_extra = sprintf(" AND `issued-id` = '%s' ", DBA::escape($dfrn_id));
196 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
199 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
207 "SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
211 if (! DBA::isResult($r)) {
212 Logger::log(sprintf('No contact found for uid=%d', $owner_id), Logger::WARNING);
218 $set = PermissionSet::get($owner_id, $contact['id']);
221 $sql_extra = " AND `item`.`psid` IN (" . implode(',', $set) .")";
223 $sql_extra = " AND NOT `item`.`private`";
233 if (! strlen($last_update)) {
234 $last_update = 'now -30 days';
237 if (isset($category)) {
238 $sql_post_table = sprintf(
239 "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` ",
240 DBA::escape(Strings::protectSprintf($category)),
241 intval(TERM_OBJ_POST),
242 intval(TERM_CATEGORY),
247 if ($public_feed && ! $converse) {
248 $sql_extra .= " AND `contact`.`self` = 1 ";
251 $check_date = DateTimeFormat::utc($last_update);
255 FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
256 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
257 WHERE `item`.`uid` = %d AND `item`.`wall` AND `item`.`changed` > '%s'
258 AND `item`.`visible` $sql_extra
259 ORDER BY `item`.`parent` ".$sort.", `item`.`received` ASC LIMIT 0, 300",
261 DBA::escape($check_date),
266 foreach ($r as $item) {
267 $ids[] = $item['id'];
271 $ret = Item::select(Item::DELIVER_FIELDLIST, ['id' => $ids]);
272 $items = Item::inArray($ret);
278 * Will check further below if this actually returned results.
279 * We will provide an empty feed if that is the case.
282 $doc = new DOMDocument('1.0', 'utf-8');
283 $doc->formatOutput = true;
285 $alternatelink = $owner['url'];
287 if (isset($category)) {
288 $alternatelink .= "/category/".$category;
292 $author = "dfrn:owner";
297 $root = self::addHeader($doc, $owner, $author, $alternatelink, true);
299 /// @TODO This hook can't work anymore
300 // \Friendica\Core\Hook::callAll('atom_feed', $atom);
302 if (!DBA::isResult($items) || $onlyheader) {
303 $atom = trim($doc->saveXML());
305 Hook::callAll('atom_feed_end', $atom);
310 foreach ($items as $item) {
311 // prevent private email from leaking.
312 if ($item['network'] == Protocol::MAIL) {
316 // public feeds get html, our own nodes use bbcode
320 // catch any email that's in a public conversation and make sure it doesn't leak
321 if ($item['private']) {
328 $entry = self::entry($doc, $type, $item, $owner, true);
330 $root->appendChild($entry);
334 $atom = trim($doc->saveXML());
336 Hook::callAll('atom_feed_end', $atom);
342 * Generate an atom entry for a given item id
344 * @param int $item_id The item id
345 * @param boolean $conversation Show the conversation. If false show the single post.
347 * @return string DFRN feed entry
348 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
349 * @throws \ImagickException
351 public static function itemFeed($item_id, $conversation = false)
354 $condition = ['parent' => $item_id];
356 $condition = ['id' => $item_id];
359 $ret = Item::select(Item::DELIVER_FIELDLIST, $condition);
360 $items = Item::inArray($ret);
361 if (!DBA::isResult($items)) {
367 if ($item['uid'] != 0) {
368 $owner = User::getOwnerDataById($item['uid']);
373 $owner = ['uid' => 0, 'nick' => 'feed-item'];
376 $doc = new DOMDocument('1.0', 'utf-8');
377 $doc->formatOutput = true;
381 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
382 $doc->appendChild($root);
384 $root->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
385 $root->setAttribute("xmlns:at", ActivityNamespace::TOMB);
386 $root->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
387 $root->setAttribute("xmlns:dfrn", ActivityNamespace::DFRN);
388 $root->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
389 $root->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
390 $root->setAttribute("xmlns:poco", ActivityNamespace::POCO);
391 $root->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
392 $root->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
394 //$root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
396 foreach ($items as $item) {
397 $entry = self::entry($doc, $type, $item, $owner, true, 0);
399 $root->appendChild($entry);
403 self::entry($doc, $type, $item, $owner, true, 0, true);
406 $atom = trim($doc->saveXML());
411 * Create XML text for DFRN mails
413 * @param array $item message elements
414 * @param array $owner Owner record
416 * @return string DFRN mail
417 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
418 * @todo Find proper type-hints
420 public static function mail($item, $owner)
422 $doc = new DOMDocument('1.0', 'utf-8');
423 $doc->formatOutput = true;
425 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
427 $mail = $doc->createElement("dfrn:mail");
428 $sender = $doc->createElement("dfrn:sender");
430 XML::addElement($doc, $sender, "dfrn:name", $owner['name']);
431 XML::addElement($doc, $sender, "dfrn:uri", $owner['url']);
432 XML::addElement($doc, $sender, "dfrn:avatar", $owner['thumb']);
434 $mail->appendChild($sender);
436 XML::addElement($doc, $mail, "dfrn:id", $item['uri']);
437 XML::addElement($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
438 XML::addElement($doc, $mail, "dfrn:sentdate", DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
439 XML::addElement($doc, $mail, "dfrn:subject", $item['title']);
440 XML::addElement($doc, $mail, "dfrn:content", $item['body']);
442 $root->appendChild($mail);
444 return trim($doc->saveXML());
448 * Create XML text for DFRN friend suggestions
450 * @param array $item suggestion elements
451 * @param array $owner Owner record
453 * @return string DFRN suggestions
454 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
455 * @todo Find proper type-hints
457 public static function fsuggest($item, $owner)
459 $doc = new DOMDocument('1.0', 'utf-8');
460 $doc->formatOutput = true;
462 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
464 $suggest = $doc->createElement("dfrn:suggest");
466 XML::addElement($doc, $suggest, "dfrn:url", $item['url']);
467 XML::addElement($doc, $suggest, "dfrn:name", $item['name']);
468 XML::addElement($doc, $suggest, "dfrn:photo", $item['photo']);
469 XML::addElement($doc, $suggest, "dfrn:request", $item['request']);
470 XML::addElement($doc, $suggest, "dfrn:note", $item['note']);
472 $root->appendChild($suggest);
474 return trim($doc->saveXML());
478 * Create XML text for DFRN relocations
480 * @param array $owner Owner record
481 * @param int $uid User ID
483 * @return string DFRN relocations
484 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
485 * @todo Find proper type-hints
487 public static function relocate($owner, $uid)
490 /* get site pubkey. this could be a new installation with no site keys*/
491 $pubkey = DI::config()->get('system', 'site_pubkey');
493 $res = Crypto::newKeypair(1024);
494 DI::config()->set('system', 'site_prvkey', $res['prvkey']);
495 DI::config()->set('system', 'site_pubkey', $res['pubkey']);
499 "SELECT `resource-id` , `scale`, type FROM `photo`
500 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;",
504 $ext = Images::supportedTypes();
506 foreach ($rp as $p) {
507 $photos[$p['scale']] = DI::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
511 $doc = new DOMDocument('1.0', 'utf-8');
512 $doc->formatOutput = true;
514 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
516 $relocate = $doc->createElement("dfrn:relocate");
518 XML::addElement($doc, $relocate, "dfrn:url", $owner['url']);
519 XML::addElement($doc, $relocate, "dfrn:name", $owner['name']);
520 XML::addElement($doc, $relocate, "dfrn:addr", $owner['addr']);
521 XML::addElement($doc, $relocate, "dfrn:avatar", $owner['avatar']);
522 XML::addElement($doc, $relocate, "dfrn:photo", $photos[4]);
523 XML::addElement($doc, $relocate, "dfrn:thumb", $photos[5]);
524 XML::addElement($doc, $relocate, "dfrn:micro", $photos[6]);
525 XML::addElement($doc, $relocate, "dfrn:request", $owner['request']);
526 XML::addElement($doc, $relocate, "dfrn:confirm", $owner['confirm']);
527 XML::addElement($doc, $relocate, "dfrn:notify", $owner['notify']);
528 XML::addElement($doc, $relocate, "dfrn:poll", $owner['poll']);
529 XML::addElement($doc, $relocate, "dfrn:sitepubkey", DI::config()->get('system', 'site_pubkey'));
531 $root->appendChild($relocate);
533 return trim($doc->saveXML());
537 * Adds the header elements for the DFRN protocol
539 * @param DOMDocument $doc XML document
540 * @param array $owner Owner record
541 * @param string $authorelement Element name for the author
542 * @param string $alternatelink link to profile or category
543 * @param bool $public Is it a header for public posts?
545 * @return object XML root object
546 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
547 * @todo Find proper type-hints
549 private static function addHeader(DOMDocument $doc, $owner, $authorelement, $alternatelink = "", $public = false)
552 if ($alternatelink == "") {
553 $alternatelink = $owner['url'];
556 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
557 $doc->appendChild($root);
559 $root->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
560 $root->setAttribute("xmlns:at", ActivityNamespace::TOMB);
561 $root->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
562 $root->setAttribute("xmlns:dfrn", ActivityNamespace::DFRN);
563 $root->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
564 $root->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
565 $root->setAttribute("xmlns:poco", ActivityNamespace::POCO);
566 $root->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
567 $root->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
569 XML::addElement($doc, $root, "id", DI::baseUrl()."/profile/".$owner["nick"]);
570 XML::addElement($doc, $root, "title", $owner["name"]);
572 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION];
573 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
575 $attributes = ["rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/"];
576 XML::addElement($doc, $root, "link", "", $attributes);
578 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $alternatelink];
579 XML::addElement($doc, $root, "link", "", $attributes);
583 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
584 OStatus::hublinks($doc, $root, $owner["nick"]);
586 $attributes = ["rel" => "salmon", "href" => DI::baseUrl()."/salmon/".$owner["nick"]];
587 XML::addElement($doc, $root, "link", "", $attributes);
589 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => DI::baseUrl()."/salmon/".$owner["nick"]];
590 XML::addElement($doc, $root, "link", "", $attributes);
592 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => DI::baseUrl()."/salmon/".$owner["nick"]];
593 XML::addElement($doc, $root, "link", "", $attributes);
596 // For backward compatibility we keep this element
597 if ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY) {
598 XML::addElement($doc, $root, "dfrn:community", 1);
601 // The former element is replaced by this one
602 XML::addElement($doc, $root, "dfrn:account_type", $owner["account-type"]);
604 /// @todo We need a way to transmit the different page flags like "User::PAGE_FLAGS_PRVGROUP"
606 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
608 $author = self::addAuthor($doc, $owner, $authorelement, $public);
609 $root->appendChild($author);
615 * Adds the author element in the header for the DFRN protocol
617 * @param DOMDocument $doc XML document
618 * @param array $owner Owner record
619 * @param string $authorelement Element name for the author
620 * @param boolean $public boolean
622 * @return \DOMElement XML author object
623 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
624 * @todo Find proper type-hints
626 private static function addAuthor(DOMDocument $doc, array $owner, $authorelement, $public)
628 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
630 "SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
631 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
632 intval($owner['uid'])
634 if (DBA::isResult($r)) {
640 $author = $doc->createElement($authorelement);
642 $namdate = DateTimeFormat::utc($owner['name-date'].'+00:00', DateTimeFormat::ATOM);
643 $uridate = DateTimeFormat::utc($owner['uri-date'].'+00:00', DateTimeFormat::ATOM);
644 $picdate = DateTimeFormat::utc($owner['avatar-date'].'+00:00', DateTimeFormat::ATOM);
648 if (!$public || !$hidewall) {
649 $attributes = ["dfrn:updated" => $namdate];
652 XML::addElement($doc, $author, "name", $owner["name"], $attributes);
653 XML::addElement($doc, $author, "uri", DI::baseUrl().'/profile/'.$owner["nickname"], $attributes);
654 XML::addElement($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
656 $attributes = ["rel" => "photo", "type" => "image/jpeg",
657 "media:width" => 300, "media:height" => 300, "href" => $owner['photo']];
659 if (!$public || !$hidewall) {
660 $attributes["dfrn:updated"] = $picdate;
663 XML::addElement($doc, $author, "link", "", $attributes);
665 $attributes["rel"] = "avatar";
666 XML::addElement($doc, $author, "link", "", $attributes);
669 XML::addElement($doc, $author, "dfrn:hide", "true");
672 // The following fields will only be generated if the data isn't meant for a public feed
677 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
680 XML::addElement($doc, $author, "dfrn:birthday", $birthday);
683 // Only show contact details when we are allowed to
685 "SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
686 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
687 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
689 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
690 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
691 intval($owner['uid'])
693 if (DBA::isResult($r)) {
696 XML::addElement($doc, $author, "poco:displayName", $profile["name"]);
697 XML::addElement($doc, $author, "poco:updated", $namdate);
699 if (trim($profile["dob"]) > DBA::NULL_DATE) {
700 XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
703 XML::addElement($doc, $author, "poco:note", $profile["about"]);
704 XML::addElement($doc, $author, "poco:preferredUsername", $profile["nickname"]);
706 $savetz = date_default_timezone_get();
707 date_default_timezone_set($profile["timezone"]);
708 XML::addElement($doc, $author, "poco:utcOffset", date("P"));
709 date_default_timezone_set($savetz);
711 if (trim($profile["homepage"]) != "") {
712 $urls = $doc->createElement("poco:urls");
713 XML::addElement($doc, $urls, "poco:type", "homepage");
714 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
715 XML::addElement($doc, $urls, "poco:primary", "true");
716 $author->appendChild($urls);
719 if (trim($profile["pub_keywords"]) != "") {
720 $keywords = explode(",", $profile["pub_keywords"]);
722 foreach ($keywords as $keyword) {
723 XML::addElement($doc, $author, "poco:tags", trim($keyword));
727 if (trim($profile["xmpp"]) != "") {
728 $ims = $doc->createElement("poco:ims");
729 XML::addElement($doc, $ims, "poco:type", "xmpp");
730 XML::addElement($doc, $ims, "poco:value", $profile["xmpp"]);
731 XML::addElement($doc, $ims, "poco:primary", "true");
732 $author->appendChild($ims);
735 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
736 $element = $doc->createElement("poco:address");
738 XML::addElement($doc, $element, "poco:formatted", Profile::formatLocation($profile));
740 if (trim($profile["locality"]) != "") {
741 XML::addElement($doc, $element, "poco:locality", $profile["locality"]);
744 if (trim($profile["region"]) != "") {
745 XML::addElement($doc, $element, "poco:region", $profile["region"]);
748 if (trim($profile["country-name"]) != "") {
749 XML::addElement($doc, $element, "poco:country", $profile["country-name"]);
752 $author->appendChild($element);
760 * Adds the author elements in the "entry" elements of the DFRN protocol
762 * @param DOMDocument $doc XML document
763 * @param string $element Element name for the author
764 * @param string $contact_url Link of the contact
765 * @param array $item Item elements
767 * @return \DOMElement XML author object
768 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
769 * @todo Find proper type-hints
771 private static function addEntryAuthor(DOMDocument $doc, $element, $contact_url, $item)
773 $author = $doc->createElement($element);
775 $contact = Contact::getDetailsByURL($contact_url, $item["uid"]);
776 if (!empty($contact)) {
777 XML::addElement($doc, $author, "name", $contact["name"]);
778 XML::addElement($doc, $author, "uri", $contact["url"]);
779 XML::addElement($doc, $author, "dfrn:handle", $contact["addr"]);
782 /// - Check real image type and image size
783 /// - Check which of these boths elements we should use
786 "type" => "image/jpeg",
788 "media:height" => 80,
789 "href" => $contact["photo"]];
790 XML::addElement($doc, $author, "link", "", $attributes);
794 "type" => "image/jpeg",
796 "media:height" => 80,
797 "href" => $contact["photo"]];
798 XML::addElement($doc, $author, "link", "", $attributes);
805 * Adds the activity elements
807 * @param DOMDocument $doc XML document
808 * @param string $element Element name for the activity
809 * @param string $activity activity value
811 * @return \DOMElement XML activity object
812 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
813 * @todo Find proper type-hints
815 private static function createActivity(DOMDocument $doc, $element, $activity)
818 $entry = $doc->createElement($element);
820 $r = XML::parseString($activity, false);
826 XML::addElement($doc, $entry, "activity:object-type", $r->type);
830 XML::addElement($doc, $entry, "id", $r->id);
834 XML::addElement($doc, $entry, "title", $r->title);
838 if (substr($r->link, 0, 1) == '<') {
839 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
840 $r->link = str_replace('&', '&', $r->link);
843 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
845 // XML does need a single element as root element so we add a dummy element here
846 $data = XML::parseString("<dummy>" . $r->link . "</dummy>", false);
847 if (is_object($data)) {
848 foreach ($data->link as $link) {
850 foreach ($link->attributes() as $parameter => $value) {
851 $attributes[$parameter] = $value;
853 XML::addElement($doc, $entry, "link", "", $attributes);
857 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
858 XML::addElement($doc, $entry, "link", "", $attributes);
862 XML::addElement($doc, $entry, "content", BBCode::convert($r->content), ["type" => "html"]);
872 * Adds the elements for attachments
874 * @param object $doc XML document
875 * @param object $root XML root
876 * @param array $item Item element
878 * @return void XML attachment object
879 * @todo Find proper type-hints
881 private static function getAttachment($doc, $root, $item)
883 $arr = explode('[/attach],', $item['attach']);
885 foreach ($arr as $r) {
887 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
889 $attributes = ["rel" => "enclosure",
890 "href" => $matches[1],
891 "type" => $matches[3]];
893 if (intval($matches[2])) {
894 $attributes["length"] = intval($matches[2]);
897 if (trim($matches[4]) != "") {
898 $attributes["title"] = trim($matches[4]);
901 XML::addElement($doc, $root, "link", "", $attributes);
908 * Adds the "entry" elements for the DFRN protocol
910 * @param DOMDocument $doc XML document
911 * @param string $type "text" or "html"
912 * @param array $item Item element
913 * @param array $owner Owner record
914 * @param bool $comment Trigger the sending of the "comment" element
915 * @param int $cid Contact ID of the recipient
916 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
918 * @return null|\DOMElement XML entry object
919 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
920 * @throws \ImagickException
921 * @todo Find proper type-hints
923 private static function entry(DOMDocument $doc, $type, array $item, array $owner, $comment = false, $cid = 0, $single = false)
927 if (!$item['parent']) {
928 Logger::notice('Item without parent found.', ['type' => $type, 'item' => $item]);
932 if ($item['deleted']) {
933 $attributes = ["ref" => $item['uri'], "when" => DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM)];
934 return XML::createElement($doc, "at:deleted-entry", "", $attributes);
938 $entry = $doc->createElement("entry");
940 $entry = $doc->createElementNS(ActivityNamespace::ATOM1, 'entry');
941 $doc->appendChild($entry);
943 $entry->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
944 $entry->setAttribute("xmlns:at", ActivityNamespace::TOMB);
945 $entry->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
946 $entry->setAttribute("xmlns:dfrn", ActivityNamespace::DFRN);
947 $entry->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
948 $entry->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
949 $entry->setAttribute("xmlns:poco", ActivityNamespace::POCO);
950 $entry->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
951 $entry->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
954 if ($item['private']) {
955 $body = Item::fixPrivatePhotos($item['body'], $owner['uid'], $item, $cid);
957 $body = $item['body'];
960 // Remove the abstract element. It is only locally important.
961 $body = BBCode::stripAbstract($body);
964 if ($type == 'html') {
967 if ($item['title'] != "") {
968 $htmlbody = "[b]" . $item['title'] . "[/b]\n\n" . $htmlbody;
971 $htmlbody = BBCode::convert($htmlbody, false, 7);
974 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
975 $entry->appendChild($author);
977 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
978 $entry->appendChild($dfrnowner);
980 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
981 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
982 $parent = Item::selectFirst(['guid', 'plink'], ['uri' => $parent_item, 'uid' => $item['uid']]);
983 $attributes = ["ref" => $parent_item, "type" => "text/html",
984 "href" => $parent['plink'],
985 "dfrn:diaspora_guid" => $parent['guid']];
986 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
989 // Add conversation data. This is used for OStatus
990 $conversation_href = DI::baseUrl()."/display/".$item["parent-guid"];
991 $conversation_uri = $conversation_href;
993 if (isset($parent_item)) {
994 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $item['parent-uri']]);
995 if (DBA::isResult($conversation)) {
996 if ($conversation['conversation-uri'] != '') {
997 $conversation_uri = $conversation['conversation-uri'];
999 if ($conversation['conversation-href'] != '') {
1000 $conversation_href = $conversation['conversation-href'];
1006 "href" => $conversation_href,
1007 "ref" => $conversation_uri];
1009 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
1011 XML::addElement($doc, $entry, "id", $item["uri"]);
1012 XML::addElement($doc, $entry, "title", $item["title"]);
1014 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"] . "+00:00", DateTimeFormat::ATOM));
1015 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"] . "+00:00", DateTimeFormat::ATOM));
1017 // "dfrn:env" is used to read the content
1018 XML::addElement($doc, $entry, "dfrn:env", Strings::base64UrlEncode($body, true));
1020 // The "content" field is not read by the receiver. We could remove it when the type is "text"
1021 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
1022 XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
1024 // We save this value in "plink". Maybe we should read it from there as well?
1030 ["rel" => "alternate", "type" => "text/html",
1031 "href" => DI::baseUrl() . "/display/" . $item["guid"]]
1034 // "comment-allow" is some old fashioned stuff for old Friendica versions.
1035 // It is included in the rewritten code for completeness
1037 XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
1040 if ($item['location']) {
1041 XML::addElement($doc, $entry, "dfrn:location", $item['location']);
1044 if ($item['coord']) {
1045 XML::addElement($doc, $entry, "georss:point", $item['coord']);
1048 if ($item['private']) {
1049 XML::addElement($doc, $entry, "dfrn:private", ($item['private'] ? $item['private'] : 1));
1052 if ($item['extid']) {
1053 XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
1056 if ($item['post-type'] == Item::PT_PAGE) {
1057 XML::addElement($doc, $entry, "dfrn:bookmark", "true");
1061 XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
1064 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
1066 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
1067 // It is needed for relayed comments to Diaspora.
1068 if ($item['signed_text']) {
1069 $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer']]));
1070 XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
1073 XML::addElement($doc, $entry, "activity:verb", self::constructVerb($item));
1075 if ($item['object-type'] != "") {
1076 XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
1077 } elseif ($item['id'] == $item['parent']) {
1078 XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::NOTE);
1080 XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::COMMENT);
1083 $actobj = self::createActivity($doc, "activity:object", $item['object']);
1085 $entry->appendChild($actobj);
1088 $actarg = self::createActivity($doc, "activity:target", $item['target']);
1090 $entry->appendChild($actarg);
1093 $tags = Item::getFeedTags($item);
1095 /// @TODO Combine this with similar below if() block?
1097 foreach ($tags as $t) {
1098 if (($type != 'html') || ($t[0] != "@")) {
1099 XML::addElement($doc, $entry, "category", "", ["scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]]);
1105 foreach ($tags as $t) {
1107 $mentioned[$t[1]] = $t[1];
1112 foreach ($mentioned as $mention) {
1113 $condition = ['uid' => $owner["uid"], 'nurl' => Strings::normaliseLink($mention)];
1114 $contact = DBA::selectFirst('contact', ['forum', 'prv'], $condition);
1116 if (DBA::isResult($contact) && ($contact["forum"] || $contact["prv"])) {
1122 ["rel" => "mentioned",
1123 "ostatus:object-type" => Activity\ObjectType::GROUP,
1132 ["rel" => "mentioned",
1133 "ostatus:object-type" => Activity\ObjectType::PERSON,
1139 self::getAttachment($doc, $entry, $item);
1145 * encrypts data via AES
1147 * @param string $data The data that is to be encrypted
1148 * @param string $key The AES key
1150 * @return string encrypted data
1152 private static function aesEncrypt($data, $key)
1154 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1158 * decrypts data via AES
1160 * @param string $encrypted The encrypted data
1161 * @param string $key The AES key
1163 * @return string decrypted data
1165 public static function aesDecrypt($encrypted, $key)
1167 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1171 * Delivers the atom content to the contacts
1173 * @param array $owner Owner record
1174 * @param array $contact Contact record of the receiver
1175 * @param string $atom Content that will be transmitted
1176 * @param bool $dissolve (to be documented)
1178 * @return int Deliver status. Negative values mean an error.
1179 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1180 * @throws \ImagickException
1181 * @todo Add array type-hint for $owner, $contact
1183 public static function deliver($owner, $contact, $atom, $dissolve = false)
1185 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1187 if ($contact['duplex'] && $contact['dfrn-id']) {
1188 $idtosend = '0:' . $orig_id;
1190 if ($contact['duplex'] && $contact['issued-id']) {
1191 $idtosend = '1:' . $orig_id;
1194 $rino = DI::config()->get('system', 'rino_encrypt');
1195 $rino = intval($rino);
1197 Logger::log("Local rino version: ". $rino, Logger::DEBUG);
1199 $ssl_val = intval(DI::config()->get('system', 'ssl_policy'));
1202 case BaseURL::SSL_POLICY_FULL:
1203 $ssl_policy = 'full';
1205 case BaseURL::SSL_POLICY_SELFSIGN:
1206 $ssl_policy = 'self';
1208 case BaseURL::SSL_POLICY_NONE:
1210 $ssl_policy = 'none';
1214 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1216 Logger::log('dfrn_deliver: ' . $url);
1218 $curlResult = Network::curl($url);
1220 if ($curlResult->isTimeout()) {
1221 return -2; // timed out
1224 $xml = $curlResult->getBody();
1226 $curl_stat = $curlResult->getReturnCode();
1227 if (empty($curl_stat)) {
1228 return -3; // timed out
1231 Logger::log('dfrn_deliver: ' . $xml, Logger::DATA);
1237 if (strpos($xml, '<?xml') === false) {
1238 Logger::log('dfrn_deliver: no valid XML returned');
1239 Logger::log('dfrn_deliver: returned XML: ' . $xml, Logger::DATA);
1243 $res = XML::parseString($xml);
1245 if (!is_object($res) || (intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
1246 if (empty($res->status)) {
1249 $status = $res->status;
1256 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1257 $challenge = hex2bin((string) $res->challenge);
1258 $perm = (($res->perm) ? $res->perm : null);
1259 $dfrn_version = floatval($res->dfrn_version ?: 2.0);
1260 $rino_remote_version = intval($res->rino);
1261 $page = (($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? 1 : 0);
1263 Logger::log("Remote rino version: ".$rino_remote_version." for ".$contact["url"], Logger::DEBUG);
1265 if ($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
1269 $final_dfrn_id = '';
1272 if ((($perm == 'rw') && !intval($contact['writable']))
1273 || (($perm == 'r') && intval($contact['writable']))
1275 DBA::update('contact', ['writable' => ($perm == 'rw')], ['id' => $contact['id']]);
1277 $contact['writable'] = (string) 1 - intval($contact['writable']);
1281 if (($contact['duplex'] && strlen($contact['pubkey']))
1282 || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY && strlen($contact['pubkey']))
1283 || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
1285 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
1286 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
1288 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
1289 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
1292 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1294 if (strpos($final_dfrn_id, ':') == 1) {
1295 $final_dfrn_id = substr($final_dfrn_id, 2);
1298 if ($final_dfrn_id != $orig_id) {
1299 Logger::log('dfrn_deliver: wrong dfrn_id.');
1300 // did not decode properly - cannot trust this site
1304 $postvars['dfrn_id'] = $idtosend;
1305 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1307 $postvars['dissolve'] = '1';
1310 if ((($contact['rel']) && ($contact['rel'] != Contact::SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY)) {
1311 $postvars['data'] = $atom;
1312 $postvars['perm'] = 'rw';
1314 $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
1315 $postvars['perm'] = 'r';
1318 $postvars['ssl_policy'] = $ssl_policy;
1321 $postvars['page'] = $page;
1325 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1326 Logger::log('rino version: '. $rino_remote_version);
1328 switch ($rino_remote_version) {
1330 $key = openssl_random_pseudo_bytes(16);
1331 $data = self::aesEncrypt($postvars['data'], $key);
1335 Logger::log("rino: invalid requested version '$rino_remote_version'");
1339 $postvars['rino'] = $rino_remote_version;
1340 $postvars['data'] = bin2hex($data);
1342 if ($dfrn_version >= 2.1) {
1343 if (($contact['duplex'] && strlen($contact['pubkey']))
1344 || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY && strlen($contact['pubkey']))
1345 || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
1347 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1349 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1352 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY)) {
1353 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1355 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1359 Logger::log('md5 rawkey ' . md5($postvars['key']));
1361 $postvars['key'] = bin2hex($postvars['key']);
1365 Logger::log('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), Logger::DATA);
1367 $postResult = Network::post($contact['notify'], $postvars);
1369 $xml = $postResult->getBody();
1371 Logger::log('dfrn_deliver: ' . "RECEIVED: " . $xml, Logger::DATA);
1373 $curl_stat = $postResult->getReturnCode();
1374 if (empty($curl_stat) || empty($xml)) {
1375 return -9; // timed out
1378 if (($curl_stat == 503) && stristr($postResult->getHeader(), 'retry-after')) {
1382 if (strpos($xml, '<?xml') === false) {
1383 Logger::log('dfrn_deliver: phase 2: no valid XML returned');
1384 Logger::log('dfrn_deliver: phase 2: returned XML: ' . $xml, Logger::DATA);
1388 $res = XML::parseString($xml);
1390 if (!isset($res->status)) {
1394 // Possibly old servers had returned an empty value when everything was okay
1395 if (empty($res->status)) {
1399 if (!empty($res->message)) {
1400 Logger::log('Delivery returned status '.$res->status.' - '.$res->message, Logger::DEBUG);
1403 return intval($res->status);
1407 * Transmits atom content to the contacts via the Diaspora transport layer
1409 * @param array $owner Owner record
1410 * @param array $contact Contact record of the receiver
1411 * @param string $atom Content that will be transmitted
1413 * @param bool $public_batch
1414 * @return int Deliver status. Negative values mean an error.
1415 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1416 * @throws \ImagickException
1418 public static function transmit($owner, $contact, $atom, $public_batch = false)
1420 if (!$public_batch) {
1421 if (empty($contact['addr'])) {
1422 Logger::log('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.');
1423 if (Contact::updateFromProbe($contact['id'])) {
1424 $new_contact = DBA::selectFirst('contact', ['addr'], ['id' => $contact['id']]);
1425 $contact['addr'] = $new_contact['addr'];
1428 if (empty($contact['addr'])) {
1429 Logger::log('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
1434 $fcontact = Diaspora::personByHandle($contact['addr']);
1435 if (empty($fcontact)) {
1436 Logger::log('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
1439 $pubkey = $fcontact['pubkey'];
1444 $envelope = Diaspora::buildMessage($atom, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
1446 // Create the endpoint for public posts. This is some WIP and should later be added to the probing
1447 if ($public_batch && empty($contact["batch"])) {
1448 $parts = parse_url($contact["notify"]);
1449 $path_parts = explode('/', $parts['path']);
1450 array_pop($path_parts);
1451 $parts['path'] = implode('/', $path_parts);
1452 $contact["batch"] = Network::unparseURL($parts);
1455 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
1457 if (empty($dest_url)) {
1458 Logger::info('Empty destination', ['public' => $public_batch, 'contact' => $contact]);
1462 $content_type = ($public_batch ? "application/magic-envelope+xml" : "application/json");
1464 $postResult = Network::post($dest_url, $envelope, ["Content-Type: ".$content_type]);
1465 $xml = $postResult->getBody();
1467 $curl_stat = $postResult->getReturnCode();
1468 if (empty($curl_stat) || empty($xml)) {
1469 Logger::log('Empty answer from ' . $contact['id'] . ' - ' . $dest_url);
1470 return -9; // timed out
1473 if (($curl_stat == 503) && (stristr($postResult->getHeader(), 'retry-after'))) {
1477 if (strpos($xml, '<?xml') === false) {
1478 Logger::log('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url);
1479 Logger::log('Returned XML: ' . $xml, Logger::DATA);
1483 $res = XML::parseString($xml);
1485 if (empty($res->status)) {
1489 if (!empty($res->message)) {
1490 Logger::log('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message, Logger::DEBUG);
1493 return intval($res->status);
1497 * Fetch the author data from head or entry items
1499 * @param object $xpath XPath object
1500 * @param object $context In which context should the data be searched
1501 * @param array $importer Record of the importer user mixed with contact of the content
1502 * @param string $element Element name from which the data is fetched
1503 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1504 * @param string $xml optional, default empty
1506 * @return array Relevant data of the author
1507 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1508 * @throws \ImagickException
1509 * @todo Find good type-hints for all parameter
1511 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
1514 $author["name"] = XML::getFirstNodeValue($xpath, $element."/atom:name/text()", $context);
1515 $author["link"] = XML::getFirstNodeValue($xpath, $element."/atom:uri/text()", $context);
1517 $fields = ['id', 'uid', 'url', 'network', 'avatar-date', 'avatar', 'name-date', 'uri-date', 'addr',
1518 'name', 'nick', 'about', 'location', 'keywords', 'xmpp', 'bdyear', 'bd', 'hidden', 'contact-type'];
1519 $condition = ["`uid` = ? AND `nurl` = ? AND `network` != ?",
1520 $importer["importer_uid"], Strings::normaliseLink($author["link"]), Protocol::STATUSNET];
1521 $contact_old = DBA::selectFirst('contact', $fields, $condition);
1523 if (DBA::isResult($contact_old)) {
1524 $author["contact-id"] = $contact_old["id"];
1525 $author["network"] = $contact_old["network"];
1528 Logger::debug("Contact ".$author["link"]." wasn't found for user ".$importer["importer_uid"]." XML: ".$xml);
1531 $author["contact-unknown"] = true;
1532 $author["contact-id"] = $importer["id"];
1533 $author["network"] = $importer["network"];
1537 // Until now we aren't serving different sizes - but maybe later
1539 /// @todo check if "avatar" or "photo" would be the best field in the specification
1540 $avatars = $xpath->query($element . "/atom:link[@rel='avatar']", $context);
1541 foreach ($avatars as $avatar) {
1544 foreach ($avatar->attributes as $attributes) {
1545 /// @TODO Rewrite these similar if() to one switch
1546 if ($attributes->name == "href") {
1547 $href = $attributes->textContent;
1549 if ($attributes->name == "width") {
1550 $width = $attributes->textContent;
1552 if ($attributes->name == "updated") {
1553 $author["avatar-date"] = $attributes->textContent;
1556 if (($width > 0) && ($href != "")) {
1557 $avatarlist[$width] = $href;
1561 if (count($avatarlist) > 0) {
1562 krsort($avatarlist);
1563 $author["avatar"] = current($avatarlist);
1566 if (empty($author['avatar']) && !empty($author['link'])) {
1567 $cid = Contact::getIdForURL($author['link'], 0);
1569 $contact = DBA::selectFirst('contact', ['avatar'], ['id' => $cid]);
1570 if (DBA::isResult($contact)) {
1571 $author['avatar'] = $contact['avatar'];
1576 if (empty($author['avatar'])) {
1577 Logger::log('Empty author: ' . $xml);
1578 $author['avatar'] = '';
1581 if (DBA::isResult($contact_old) && !$onlyfetch) {
1582 Logger::log("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", Logger::DEBUG);
1584 $poco = ["url" => $contact_old["url"]];
1586 // When was the last change to name or uri?
1587 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1588 foreach ($name_element->attributes as $attributes) {
1589 if ($attributes->name == "updated") {
1590 $poco["name-date"] = $attributes->textContent;
1594 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1595 foreach ($link_element->attributes as $attributes) {
1596 if ($attributes->name == "updated") {
1597 $poco["uri-date"] = $attributes->textContent;
1601 // Update contact data
1602 $value = XML::getFirstNodeValue($xpath, $element . "/dfrn:handle/text()", $context);
1604 $poco["addr"] = $value;
1607 $value = XML::getFirstNodeValue($xpath, $element . "/poco:displayName/text()", $context);
1609 $poco["name"] = $value;
1612 $value = XML::getFirstNodeValue($xpath, $element . "/poco:preferredUsername/text()", $context);
1614 $poco["nick"] = $value;
1617 $value = XML::getFirstNodeValue($xpath, $element . "/poco:note/text()", $context);
1619 $poco["about"] = $value;
1622 $value = XML::getFirstNodeValue($xpath, $element . "/poco:address/poco:formatted/text()", $context);
1624 $poco["location"] = $value;
1627 /// @todo Only search for elements with "poco:type" = "xmpp"
1628 $value = XML::getFirstNodeValue($xpath, $element . "/poco:ims/poco:value/text()", $context);
1630 $poco["xmpp"] = $value;
1633 /// @todo Add support for the following fields that we don't support by now in the contact table:
1634 /// - poco:utcOffset
1640 // If the "hide" element is present then the profile isn't searchable.
1641 $hide = intval(XML::getFirstNodeValue($xpath, $element . "/dfrn:hide/text()", $context) == "true");
1643 Logger::log("Hidden status for contact " . $contact_old["url"] . ": " . $hide, Logger::DEBUG);
1645 // If the contact isn't searchable then set the contact to "hidden".
1646 // Problem: This can be manually overridden by the user.
1648 $contact_old["hidden"] = true;
1651 // Save the keywords into the contact table
1653 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1654 foreach ($tagelements as $tag) {
1655 $tags[$tag->nodeValue] = $tag->nodeValue;
1659 $poco["keywords"] = implode(", ", $tags);
1662 // "dfrn:birthday" contains the birthday converted to UTC
1663 $birthday = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1665 if (strtotime($birthday) > time()) {
1666 $bd_timestamp = strtotime($birthday);
1668 $poco["bdyear"] = date("Y", $bd_timestamp);
1671 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1672 $value = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1674 if (!in_array($value, ["", "0000-00-00", DBA::NULL_DATE])) {
1675 $bdyear = date("Y");
1676 $value = str_replace(["0000", "0001"], $bdyear, $value);
1678 if (strtotime($value) < time()) {
1679 $value = str_replace($bdyear, $bdyear + 1, $value);
1682 $poco["bd"] = $value;
1685 $contact = array_merge($contact_old, $poco);
1687 if ($contact_old["bdyear"] != $contact["bdyear"]) {
1688 Event::createBirthday($contact, $birthday);
1691 $fields = ['name' => $contact['name'], 'nick' => $contact['nick'], 'about' => $contact['about'],
1692 'location' => $contact['location'], 'addr' => $contact['addr'], 'keywords' => $contact['keywords'],
1693 'bdyear' => $contact['bdyear'], 'bd' => $contact['bd'], 'hidden' => $contact['hidden'],
1694 'xmpp' => $contact['xmpp'], 'name-date' => DateTimeFormat::utc($contact['name-date']),
1695 'unsearchable' => $contact['hidden'], 'uri-date' => DateTimeFormat::utc($contact['uri-date'])];
1697 DBA::update('contact', $fields, ['id' => $contact['id'], 'network' => $contact['network']], $contact_old);
1699 // Update the public contact. Don't set the "hidden" value, this is used differently for public contacts
1700 unset($fields['hidden']);
1701 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($contact_old['url'])];
1702 DBA::update('contact', $fields, $condition, true);
1704 Contact::updateAvatar($author['avatar'], $importer['importer_uid'], $contact['id']);
1706 $pcid = Contact::getIdForURL($contact_old['url']);
1707 if (!empty($pcid)) {
1708 Contact::updateAvatar($author['avatar'], 0, $pcid);
1712 * The generation is a sign for the reliability of the provided data.
1713 * It is used in the socgraph.php to prevent that old contact data
1714 * that was relayed over several servers can overwrite contact
1715 * data that we received directly.
1718 $poco["generation"] = 2;
1719 $poco["photo"] = $author["avatar"];
1720 $poco["hide"] = $hide;
1721 $poco["contact-type"] = $contact["contact-type"];
1722 $gcid = GContact::update($poco);
1724 GContact::link($gcid, $importer["importer_uid"], $contact["id"]);
1731 * Transforms activity objects into an XML string
1733 * @param object $xpath XPath object
1734 * @param object $activity Activity object
1735 * @param string $element element name
1737 * @return string XML string
1738 * @todo Find good type-hints for all parameter
1740 private static function transformActivity($xpath, $activity, $element)
1742 if (!is_object($activity)) {
1746 $obj_doc = new DOMDocument("1.0", "utf-8");
1747 $obj_doc->formatOutput = true;
1749 $obj_element = $obj_doc->createElementNS( ActivityNamespace::ATOM1, $element);
1751 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1752 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1754 $id = $xpath->query("atom:id", $activity)->item(0);
1755 if (is_object($id)) {
1756 $obj_element->appendChild($obj_doc->importNode($id, true));
1759 $title = $xpath->query("atom:title", $activity)->item(0);
1760 if (is_object($title)) {
1761 $obj_element->appendChild($obj_doc->importNode($title, true));
1764 $links = $xpath->query("atom:link", $activity);
1765 if (is_object($links)) {
1766 foreach ($links as $link) {
1767 $obj_element->appendChild($obj_doc->importNode($link, true));
1771 $content = $xpath->query("atom:content", $activity)->item(0);
1772 if (is_object($content)) {
1773 $obj_element->appendChild($obj_doc->importNode($content, true));
1776 $obj_doc->appendChild($obj_element);
1778 $objxml = $obj_doc->saveXML($obj_element);
1780 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1781 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1786 * Processes the mail elements
1788 * @param object $xpath XPath object
1789 * @param object $mail mail elements
1790 * @param array $importer Record of the importer user mixed with contact of the content
1792 * @throws \Exception
1793 * @todo Find good type-hints for all parameter
1795 private static function processMail($xpath, $mail, $importer)
1797 Logger::log("Processing mails");
1800 $msg["uid"] = $importer["importer_uid"];
1801 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1802 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1803 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1804 $msg["contact-id"] = $importer["id"];
1805 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1806 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1807 $msg["created"] = DateTimeFormat::utc($xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue);
1808 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1809 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1815 * Processes the suggestion elements
1817 * @param object $xpath XPath object
1818 * @param object $suggestion suggestion elements
1819 * @param array $importer Record of the importer user mixed with contact of the content
1821 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1822 * @todo Find good type-hints for all parameter
1824 private static function processSuggestion($xpath, $suggestion, $importer)
1826 Logger::log('Processing suggestions');
1828 /// @TODO Rewrite this to one statement
1830 $suggest['uid'] = $importer['importer_uid'];
1831 $suggest['cid'] = $importer['id'];
1832 $suggest['url'] = $xpath->query('dfrn:url/text()', $suggestion)->item(0)->nodeValue;
1833 $suggest['name'] = $xpath->query('dfrn:name/text()', $suggestion)->item(0)->nodeValue;
1834 $suggest['photo'] = $xpath->query('dfrn:photo/text()', $suggestion)->item(0)->nodeValue;
1835 $suggest['request'] = $xpath->query('dfrn:request/text()', $suggestion)->item(0)->nodeValue;
1836 $suggest['body'] = $xpath->query('dfrn:note/text()', $suggestion)->item(0)->nodeValue;
1838 // Does our member already have a friend matching this description?
1841 * The valid result means the friend we're about to send a friend
1842 * suggestion already has them in their contact, which means no further
1843 * action is required.
1845 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1847 $condition = ['nurl' => Strings::normaliseLink($suggest['url']), 'uid' => $suggest['uid']];
1848 if (DBA::exists('contact', $condition)) {
1851 // Do we already have an fcontact record for this person?
1854 $fcontact = DBA::selectFirst('fcontact', ['id'], ['url' => $suggest['url']]);
1855 if (DBA::isResult($fcontact)) {
1856 $fid = $fcontact['id'];
1858 // OK, we do. Do we already have an introduction for this person?
1859 if (DBA::exists('intro', ['uid' => $suggest['uid'], 'fid' => $fid])) {
1861 * The valid result means the friend we're about to send a friend
1862 * suggestion already has them in their contact, which means no further
1863 * action is required.
1865 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1872 $fields = ['name' => $suggest['name'], 'url' => $suggest['url'],
1873 'photo' => $suggest['photo'], 'request' => $suggest['request']];
1874 DBA::insert('fcontact', $fields);
1875 $fid = DBA::lastInsertId();
1879 * If no record in fcontact is found, below INSERT statement will not
1880 * link an introduction to it.
1883 // Database record did not get created. Quietly give up.
1887 $hash = Strings::getRandomHex();
1889 $fields = ['uid' => $suggest['uid'], 'fid' => $fid, 'contact-id' => $suggest['cid'],
1890 'note' => $suggest['body'], 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow(), 'blocked' => false];
1891 DBA::insert('intro', $fields);
1895 'type' => NOTIFY_SUGGEST,
1896 'notify_flags' => $importer['notify-flags'],
1897 'language' => $importer['language'],
1898 'to_name' => $importer['username'],
1899 'to_email' => $importer['email'],
1900 'uid' => $importer['importer_uid'],
1902 'link' => DI::baseUrl().'/notifications/intros',
1903 'source_name' => $importer['name'],
1904 'source_link' => $importer['url'],
1905 'source_photo' => $importer['photo'],
1906 'verb' => Activity::REQ_FRIEND,
1914 * Processes the relocation elements
1916 * @param object $xpath XPath object
1917 * @param object $relocation relocation elements
1918 * @param array $importer Record of the importer user mixed with contact of the content
1920 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1921 * @throws \ImagickException
1922 * @todo Find good type-hints for all parameter
1924 private static function processRelocation($xpath, $relocation, $importer)
1926 Logger::log("Processing relocations");
1928 /// @TODO Rewrite this to one statement
1930 $relocate["uid"] = $importer["importer_uid"];
1931 $relocate["cid"] = $importer["id"];
1932 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1933 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
1934 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1935 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
1936 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1937 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1938 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1939 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1940 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1941 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1942 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1943 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1945 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
1946 $relocate["avatar"] = $relocate["photo"];
1949 if ($relocate["addr"] == "") {
1950 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
1955 "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d",
1956 intval($importer["id"]),
1957 intval($importer["importer_uid"])
1960 if (!DBA::isResult($r)) {
1961 Logger::log("Query failed to execute, no result returned in " . __FUNCTION__);
1967 // Update the gcontact entry
1968 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
1970 $fields = ['name' => $relocate["name"], 'photo' => $relocate["avatar"],
1971 'url' => $relocate["url"], 'nurl' => Strings::normaliseLink($relocate["url"]),
1972 'addr' => $relocate["addr"], 'connect' => $relocate["addr"],
1973 'notify' => $relocate["notify"], 'server_url' => $relocate["server_url"]];
1974 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($old["url"])]);
1976 // Update the contact table. We try to find every entry.
1977 $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
1978 'url' => $relocate["url"], 'nurl' => Strings::normaliseLink($relocate["url"]),
1979 'addr' => $relocate["addr"], 'request' => $relocate["request"],
1980 'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
1981 'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
1982 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], Strings::normaliseLink($old["url"])];
1984 DBA::update('contact', $fields, $condition);
1986 Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
1988 Logger::log('Contacts are updated.');
1991 /// merge with current record, current contents have priority
1992 /// update record, set url-updated
1993 /// update profile photos
1994 /// schedule a scan?
2001 * @param array $current the current item record
2002 * @param array $item the new item record
2003 * @param array $importer Record of the importer user mixed with contact of the content
2004 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2006 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2007 * @todo set proper type-hints (array?)
2009 private static function updateContent($current, $item, $importer, $entrytype)
2013 if (self::isEditedTimestampNewer($current, $item)) {
2014 // do not accept (ignore) an earlier edit than one we currently have.
2015 if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
2019 $fields = ['title' => $item['title'] ?? '', 'body' => $item['body'] ?? '',
2020 'tag' => $item['tag'] ?? '', 'changed' => DateTimeFormat::utcNow(),
2021 'edited' => DateTimeFormat::utc($item["edited"])];
2023 $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
2024 Item::update($fields, $condition);
2032 * Detects the entry type of the item
2034 * @param array $importer Record of the importer user mixed with contact of the content
2035 * @param array $item the new item record
2037 * @return int Is it a toplevel entry, a comment or a relayed comment?
2038 * @throws \Exception
2039 * @todo set proper type-hints (array?)
2041 private static function getEntryType($importer, $item)
2043 if ($item["parent-uri"] != $item["uri"]) {
2046 if ($importer["page-flags"] == User::PAGE_FLAGS_COMMUNITY || $importer["page-flags"] == User::PAGE_FLAGS_PRVGROUP) {
2049 Logger::log("possible community action");
2051 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2054 // was the top-level post for this action written by somebody on this site?
2055 // Specifically, the recipient?
2057 $is_a_remote_action = false;
2059 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item["parent-uri"]]);
2060 if (DBA::isResult($parent)) {
2062 "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2063 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2064 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2065 AND `item`.`uid` = %d
2068 DBA::escape($parent["parent-uri"]),
2069 DBA::escape($parent["parent-uri"]),
2070 DBA::escape($parent["parent-uri"]),
2071 intval($importer["importer_uid"])
2073 if (DBA::isResult($r)) {
2074 $is_a_remote_action = true;
2079 * Does this have the characteristics of a community or private group action?
2080 * If it's an action to a wall post on a community/prvgroup page it's a
2081 * valid community action. Also forum_mode makes it valid for sure.
2082 * If neither, it's not.
2084 if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2085 $is_a_remote_action = false;
2086 Logger::log("not a community action");
2089 if ($is_a_remote_action) {
2090 return DFRN::REPLY_RC;
2095 return DFRN::TOP_LEVEL;
2102 * @param array $item The new item record
2103 * @param array $importer Record of the importer user mixed with contact of the content
2105 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2106 * @todo set proper type-hints (array?)
2108 private static function doPoke(array $item, array $importer)
2110 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2114 $xo = XML::parseString($item["object"], false);
2116 if (($xo->type == Activity\ObjectType::PERSON) && ($xo->id)) {
2117 // somebody was poked/prodded. Was it me?
2119 foreach ($xo->link as $l) {
2120 $atts = $l->attributes();
2121 switch ($atts["rel"]) {
2123 $Blink = $atts["href"];
2130 if ($Blink && Strings::compareLink($Blink, DI::baseUrl() . "/profile/" . $importer["nickname"])) {
2131 $author = DBA::selectFirst('contact', ['name', 'thumb', 'url'], ['id' => $item['author-id']]);
2133 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => $importer["importer_uid"]]);
2134 $item["parent"] = $parent['id'];
2136 // send a notification
2139 "type" => NOTIFY_POKE,
2140 "notify_flags" => $importer["notify-flags"],
2141 "language" => $importer["language"],
2142 "to_name" => $importer["username"],
2143 "to_email" => $importer["email"],
2144 "uid" => $importer["importer_uid"],
2146 "link" => DI::baseUrl()."/display/".urlencode($item['guid']),
2147 "source_name" => $author["name"],
2148 "source_link" => $author["url"],
2149 "source_photo" => $author["thumb"],
2150 "verb" => $item["verb"],
2151 "otype" => "person",
2152 "activity" => $verb,
2153 "parent" => $item["parent"]]
2160 * Processes several actions, depending on the verb
2162 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2163 * @param array $importer Record of the importer user mixed with contact of the content
2164 * @param array $item the new item record
2165 * @param bool $is_like Is the verb a "like"?
2167 * @return bool Should the processing of the entries be continued?
2168 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2169 * @todo set proper type-hints (array?)
2171 private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2173 Logger::log("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, Logger::DEBUG);
2175 if (($entrytype == DFRN::TOP_LEVEL) && !empty($importer['id'])) {
2176 // The filling of the the "contact" variable is done for legcy reasons
2177 // The functions below are partly used by ostatus.php as well - where we have this variable
2178 $contact = Contact::selectFirst([], ['id' => $importer['id']]);
2180 $activity = DI::activity();
2182 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2183 // This function once was responsible for DFRN and OStatus.
2184 if ($activity->match($item["verb"], Activity::FOLLOW)) {
2185 Logger::log("New follower");
2186 Contact::addRelationship($importer, $contact, $item);
2189 if ($activity->match($item["verb"], Activity::UNFOLLOW)) {
2190 Logger::log("Lost follower");
2191 Contact::removeFollower($importer, $contact, $item);
2194 if ($activity->match($item["verb"], Activity::REQ_FRIEND)) {
2195 Logger::log("New friend request");
2196 Contact::addRelationship($importer, $contact, $item, true);
2199 if ($activity->match($item["verb"], Activity::UNFRIEND)) {
2200 Logger::log("Lost sharer");
2201 Contact::removeSharer($importer, $contact, $item);
2205 if (($item["verb"] == Activity::LIKE)
2206 || ($item["verb"] == Activity::DISLIKE)
2207 || ($item["verb"] == Activity::ATTEND)
2208 || ($item["verb"] == Activity::ATTENDNO)
2209 || ($item["verb"] == Activity::ATTENDMAYBE)
2212 $item["gravity"] = GRAVITY_ACTIVITY;
2213 // only one like or dislike per person
2214 // splitted into two queries for performance issues
2215 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2216 'verb' => $item["verb"], 'parent-uri' => $item["parent-uri"]];
2217 if (Item::exists($condition)) {
2221 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2222 'verb' => $item["verb"], 'thr-parent' => $item["parent-uri"]];
2223 if (Item::exists($condition)) {
2227 // The owner of an activity must be the author
2228 $item["owner-name"] = $item["author-name"];
2229 $item["owner-link"] = $item["author-link"];
2230 $item["owner-avatar"] = $item["author-avatar"];
2231 $item["owner-id"] = $item["author-id"];
2236 if (($item["verb"] == Activity::TAG) && ($item["object-type"] == Activity\ObjectType::TAGTERM)) {
2237 $xo = XML::parseString($item["object"], false);
2238 $xt = XML::parseString($item["target"], false);
2240 if ($xt->type == Activity\ObjectType::NOTE) {
2241 $item_tag = Item::selectFirst(['id', 'tag'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]);
2243 if (!DBA::isResult($item_tag)) {
2244 Logger::log("Query failed to execute, no result returned in " . __FUNCTION__);
2248 // extract tag, if not duplicate, add to parent item
2250 if (!stristr($item_tag["tag"], trim($xo->content))) {
2251 $tag = $item_tag["tag"] . (strlen($item_tag["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2252 Item::update(['tag' => $tag], ['id' => $item_tag["id"]]);
2262 * Processes the link elements
2264 * @param object $links link elements
2265 * @param array $item the item record
2267 * @todo set proper type-hints
2269 private static function parseLinks($links, &$item)
2276 foreach ($links as $link) {
2277 foreach ($link->attributes as $attributes) {
2278 switch ($attributes->name) {
2279 case "href" : $href = $attributes->textContent; break;
2280 case "rel" : $rel = $attributes->textContent; break;
2281 case "type" : $type = $attributes->textContent; break;
2282 case "length": $length = $attributes->textContent; break;
2283 case "title" : $title = $attributes->textContent; break;
2286 if (($rel != "") && ($href != "")) {
2289 $item["plink"] = $href;
2292 if (!empty($item["attach"])) {
2293 $item["attach"] .= ",";
2295 $item["attach"] = "";
2298 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2306 * Processes the entry elements which contain the items and comments
2308 * @param array $header Array of the header elements that always stay the same
2309 * @param object $xpath XPath object
2310 * @param object $entry entry elements
2311 * @param array $importer Record of the importer user mixed with contact of the content
2312 * @param string $xml xml
2314 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2315 * @throws \ImagickException
2316 * @todo Add type-hints
2318 private static function processEntry($header, $xpath, $entry, $importer, $xml)
2320 Logger::log("Processing entries");
2324 $item["protocol"] = Conversation::PARCEL_DFRN;
2326 $item["source"] = $xml;
2329 $item["uri"] = XML::getFirstNodeValue($xpath, "atom:id/text()", $entry);
2331 $item["edited"] = XML::getFirstNodeValue($xpath, "atom:updated/text()", $entry);
2333 $current = Item::selectFirst(['id', 'uid', 'edited', 'body'],
2334 ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
2336 // Is there an existing item?
2337 if (DBA::isResult($current) && !self::isEditedTimestampNewer($current, $item)) {
2338 Logger::log("Item ".$item["uri"]." (".$item['edited'].") already existed.", Logger::DEBUG);
2343 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true, $xml);
2345 $owner_unknown = (isset($owner["contact-unknown"]) && $owner["contact-unknown"]);
2347 $item["owner-name"] = $owner["name"];
2348 $item["owner-link"] = $owner["link"];
2349 $item["owner-avatar"] = $owner["avatar"];
2350 $item["owner-id"] = Contact::getIdForURL($owner["link"], 0);
2353 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true, $xml);
2355 $item["author-name"] = $author["name"];
2356 $item["author-link"] = $author["link"];
2357 $item["author-avatar"] = $author["avatar"];
2358 $item["author-id"] = Contact::getIdForURL($author["link"], 0);
2360 $item["title"] = XML::getFirstNodeValue($xpath, "atom:title/text()", $entry);
2362 $item["created"] = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2364 $item["body"] = XML::getFirstNodeValue($xpath, "dfrn:env/text()", $entry);
2365 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2366 // make sure nobody is trying to sneak some html tags by us
2367 $item["body"] = Strings::base64UrlDecode($item["body"]);
2369 $item["body"] = BBCode::limitBodySize($item["body"]);
2371 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2372 if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
2373 $base_url = DI::baseUrl()->get();
2374 $item['body'] = HTML::relToAbs($item['body'], $base_url);
2376 $item['body'] = HTML::toBBCodeVideo($item['body']);
2378 $item['body'] = OEmbed::HTML2BBCode($item['body']);
2380 $config = HTMLPurifier_Config::createDefault();
2381 $config->set('Cache.DefinitionImpl', null);
2383 // we shouldn't need a whitelist, because the bbcode converter
2384 // will strip out any unsupported tags.
2386 $purifier = new HTMLPurifier($config);
2387 $item['body'] = $purifier->purify($item['body']);
2389 $item['body'] = @HTML::toBBCode($item['body']);
2392 /// @todo We should check for a repeated post and if we know the repeated author.
2394 // We don't need the content element since "dfrn:env" is always present
2395 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2397 $item["location"] = XML::getFirstNodeValue($xpath, "dfrn:location/text()", $entry);
2399 $item["coord"] = XML::getFirstNodeValue($xpath, "georss:point", $entry);
2401 $item["private"] = XML::getFirstNodeValue($xpath, "dfrn:private/text()", $entry);
2403 $item["extid"] = XML::getFirstNodeValue($xpath, "dfrn:extid/text()", $entry);
2405 if (XML::getFirstNodeValue($xpath, "dfrn:bookmark/text()", $entry) == "true") {
2406 $item["post-type"] = Item::PT_PAGE;
2409 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2410 if ($notice_info && ($notice_info->length > 0)) {
2411 foreach ($notice_info->item(0)->attributes as $attributes) {
2412 if ($attributes->name == "source") {
2413 $item["app"] = strip_tags($attributes->textContent);
2418 $item["guid"] = XML::getFirstNodeValue($xpath, "dfrn:diaspora_guid/text()", $entry);
2420 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
2421 $dsprsig = XML::unescape(XML::getFirstNodeValue($xpath, "dfrn:diaspora_signature/text()", $entry));
2422 if ($dsprsig != "") {
2423 $item["dsprsig"] = $dsprsig;
2426 $item["verb"] = XML::getFirstNodeValue($xpath, "activity:verb/text()", $entry);
2428 if (XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry) != "") {
2429 $item["object-type"] = XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry);
2432 $object = $xpath->query("activity:object", $entry)->item(0);
2433 $item["object"] = self::transformActivity($xpath, $object, "object");
2435 if (trim($item["object"]) != "") {
2436 $r = XML::parseString($item["object"], false);
2437 if (isset($r->type)) {
2438 $item["object-type"] = $r->type;
2442 $target = $xpath->query("activity:target", $entry)->item(0);
2443 $item["target"] = self::transformActivity($xpath, $target, "target");
2445 $categories = $xpath->query("atom:category", $entry);
2447 foreach ($categories as $category) {
2450 foreach ($category->attributes as $attributes) {
2451 if ($attributes->name == "term") {
2452 $term = $attributes->textContent;
2455 if ($attributes->name == "scheme") {
2456 $scheme = $attributes->textContent;
2460 if (($term != "") && ($scheme != "")) {
2461 $parts = explode(":", $scheme);
2462 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2463 $termhash = array_shift($parts);
2464 $termurl = implode(":", $parts);
2466 if (!empty($item["tag"])) {
2467 $item["tag"] .= ",";
2472 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2478 $links = $xpath->query("atom:link", $entry);
2480 self::parseLinks($links, $item);
2483 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
2485 $conv = $xpath->query('ostatus:conversation', $entry);
2486 if (is_object($conv->item(0))) {
2487 foreach ($conv->item(0)->attributes as $attributes) {
2488 if ($attributes->name == "ref") {
2489 $item['conversation-uri'] = $attributes->textContent;
2491 if ($attributes->name == "href") {
2492 $item['conversation-href'] = $attributes->textContent;
2497 // Is it a reply or a top level posting?
2498 $item["parent-uri"] = $item["uri"];
2500 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2501 if (is_object($inreplyto->item(0))) {
2502 foreach ($inreplyto->item(0)->attributes as $attributes) {
2503 if ($attributes->name == "ref") {
2504 $item["parent-uri"] = $attributes->textContent;
2509 // Get the type of the item (Top level post, reply or remote reply)
2510 $entrytype = self::getEntryType($importer, $item);
2512 // Now assign the rest of the values that depend on the type of the message
2513 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2514 if (!isset($item["object-type"])) {
2515 $item["object-type"] = Activity\ObjectType::COMMENT;
2518 if ($item["contact-id"] != $owner["contact-id"]) {
2519 $item["contact-id"] = $owner["contact-id"];
2522 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2523 $item["network"] = $owner["network"];
2526 if ($item["contact-id"] != $author["contact-id"]) {
2527 $item["contact-id"] = $author["contact-id"];
2530 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2531 $item["network"] = $author["network"];
2535 // Ensure to have the correct share data
2536 $item = Item::addShareDataFromOriginal($item);
2538 if ($entrytype == DFRN::REPLY_RC) {
2540 } elseif ($entrytype == DFRN::TOP_LEVEL) {
2541 if (!isset($item["object-type"])) {
2542 $item["object-type"] = Activity\ObjectType::NOTE;
2546 if (($item["object-type"] == Activity\ObjectType::EVENT) && !$owner_unknown) {
2547 Logger::log("Item ".$item["uri"]." seems to contain an event.", Logger::DEBUG);
2548 $ev = Event::fromBBCode($item["body"]);
2549 if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
2550 Logger::log("Event in item ".$item["uri"]." was found.", Logger::DEBUG);
2551 $ev["cid"] = $importer["id"];
2552 $ev["uid"] = $importer["importer_uid"];
2553 $ev["uri"] = $item["uri"];
2554 $ev["edited"] = $item["edited"];
2555 $ev["private"] = $item["private"];
2556 $ev["guid"] = $item["guid"];
2557 $ev["plink"] = $item["plink"];
2559 $condition = ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]];
2560 $event = DBA::selectFirst('event', ['id'], $condition);
2561 if (DBA::isResult($event)) {
2562 $ev["id"] = $event["id"];
2565 $event_id = Event::store($ev);
2566 Logger::log("Event ".$event_id." was stored", Logger::DEBUG);
2572 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2573 Logger::log("Exiting because 'processVerbs' told us so", Logger::DEBUG);
2577 // This check is done here to be able to receive connection requests in "processVerbs"
2578 if (($entrytype == DFRN::TOP_LEVEL) && $owner_unknown) {
2579 Logger::log("Item won't be stored because user " . $importer["importer_uid"] . " doesn't follow " . $item["owner-link"] . ".", Logger::DEBUG);
2584 // Update content if 'updated' changes
2585 if (DBA::isResult($current)) {
2586 if (self::updateContent($current, $item, $importer, $entrytype)) {
2587 Logger::log("Item ".$item["uri"]." was updated.", Logger::DEBUG);
2589 Logger::log("Item " . $item["uri"] . " already existed.", Logger::DEBUG);
2594 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2595 $posted_id = Item::insert($item);
2597 Logger::log("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, Logger::DEBUG);
2599 if ($item['uid'] == 0) {
2600 Item::distribute($posted_id);
2605 } else { // $entrytype == DFRN::TOP_LEVEL
2606 if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
2607 Logger::log("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", Logger::DEBUG);
2610 if (!Strings::compareLink($item["owner-link"], $importer["url"])) {
2612 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2613 * but otherwise there's a possible data mixup on the sender's system.
2614 * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2615 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2617 Logger::log('Correcting item owner.', Logger::DEBUG);
2618 $item["owner-link"] = $importer["url"];
2619 $item["owner-id"] = Contact::getIdForURL($importer["url"], 0);
2622 if (($importer["rel"] == Contact::FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2623 Logger::log("Contact ".$importer["id"]." is only follower and tgroup check was negative.", Logger::DEBUG);
2627 // This is my contact on another system, but it's really me.
2628 // Turn this into a wall post.
2629 $notify = Item::isRemoteSelf($importer, $item);
2631 $posted_id = Item::insert($item, false, $notify);
2634 $posted_id = $notify;
2637 Logger::log("Item was stored with id ".$posted_id, Logger::DEBUG);
2639 if ($item['uid'] == 0) {
2640 Item::distribute($posted_id);
2643 if (stristr($item["verb"], Activity::POKE)) {
2644 $item['id'] = $posted_id;
2645 self::doPoke($item, $importer);
2653 * @param object $xpath XPath object
2654 * @param object $deletion deletion elements
2655 * @param array $importer Record of the importer user mixed with contact of the content
2657 * @throws \Exception
2658 * @todo set proper type-hints
2660 private static function processDeletion($xpath, $deletion, $importer)
2662 Logger::log("Processing deletions");
2665 foreach ($deletion->attributes as $attributes) {
2666 if ($attributes->name == "ref") {
2667 $uri = $attributes->textContent;
2671 if (!$uri || !$importer["id"]) {
2675 $condition = ['uri' => $uri, 'uid' => $importer["importer_uid"]];
2676 $item = Item::selectFirst(['id', 'parent', 'contact-id', 'file', 'deleted'], $condition);
2677 if (!DBA::isResult($item)) {
2678 Logger::log("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", Logger::DEBUG);
2682 if (strstr($item['file'], '[')) {
2683 Logger::log("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " is filed. So it won't be deleted.", Logger::DEBUG);
2687 // When it is a starting post it has to belong to the person that wants to delete it
2688 if (($item['id'] == $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2689 Logger::log("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", Logger::DEBUG);
2693 // Comments can be deleted by the thread owner or comment owner
2694 if (($item['id'] != $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2695 $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2696 if (!Item::exists($condition)) {
2697 Logger::log("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", Logger::DEBUG);
2702 if ($item["deleted"]) {
2706 Logger::log('deleting item '.$item['id'].' uri='.$uri, Logger::DEBUG);
2708 Item::delete(['id' => $item['id']]);
2712 * Imports a DFRN message
2714 * @param string $xml The DFRN message
2715 * @param array $importer Record of the importer user mixed with contact of the content
2716 * @param bool $sort_by_date Is used when feeds are polled
2717 * @return integer Import status
2718 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2719 * @throws \ImagickException
2720 * @todo set proper type-hints
2722 public static function import($xml, $importer, $sort_by_date = false)
2728 $doc = new DOMDocument();
2729 @$doc->loadXML($xml);
2731 $xpath = new DOMXPath($doc);
2732 $xpath->registerNamespace("atom", ActivityNamespace::ATOM1);
2733 $xpath->registerNamespace("thr", ActivityNamespace::THREAD);
2734 $xpath->registerNamespace("at", ActivityNamespace::TOMB);
2735 $xpath->registerNamespace("media", ActivityNamespace::MEDIA);
2736 $xpath->registerNamespace("dfrn", ActivityNamespace::DFRN);
2737 $xpath->registerNamespace("activity", ActivityNamespace::ACTIVITY);
2738 $xpath->registerNamespace("georss", ActivityNamespace::GEORSS);
2739 $xpath->registerNamespace("poco", ActivityNamespace::POCO);
2740 $xpath->registerNamespace("ostatus", ActivityNamespace::OSTATUS);
2741 $xpath->registerNamespace("statusnet", ActivityNamespace::STATUSNET);
2744 $header["uid"] = $importer["importer_uid"];
2745 $header["network"] = Protocol::DFRN;
2746 $header["wall"] = 0;
2747 $header["origin"] = 0;
2748 $header["contact-id"] = $importer["id"];
2750 // Update the contact table if the data has changed
2752 // The "atom:author" is only present in feeds
2753 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2754 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2757 // Only the "dfrn:owner" in the head section contains all data
2758 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2759 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2762 Logger::log("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], Logger::DEBUG);
2764 // is it a public forum? Private forums aren't exposed with this method
2765 $forum = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:community/text()"));
2767 // The account type is new since 3.5.1
2768 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2769 // Hint: We are using separate update calls for uid=0 and uid!=0 since a combined call is bad for the database performance
2771 $accounttype = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:account_type/text()"));
2773 if ($accounttype != $importer["contact-type"]) {
2774 DBA::update('contact', ['contact-type' => $accounttype], ['id' => $importer['id']]);
2776 // Updating the public contact as well
2777 DBA::update('contact', ['contact-type' => $accounttype], ['uid' => 0, 'nurl' => $importer['nurl']]);
2779 // A forum contact can either have set "forum" or "prv" - but not both
2780 if ($accounttype == User::ACCOUNT_TYPE_COMMUNITY) {
2781 // It's a forum, so either set the public or private forum flag
2782 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer['id']];
2783 DBA::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2785 // Updating the public contact as well
2786 $condition = ['(`forum` != ? OR `prv` != ?) AND `uid` = 0 AND `nurl` = ?', $forum, !$forum, $importer['nurl']];
2787 DBA::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2789 // It's not a forum, so remove the flags
2790 $condition = ['(`forum` OR `prv`) AND `id` = ?', $importer['id']];
2791 DBA::update('contact', ['forum' => false, 'prv' => false], $condition);
2793 // Updating the public contact as well
2794 $condition = ['(`forum` OR `prv`) AND `uid` = 0 AND `nurl` = ?', $importer['nurl']];
2795 DBA::update('contact', ['forum' => false, 'prv' => false], $condition);
2797 } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
2798 $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2799 DBA::update('contact', ['forum' => $forum], $condition);
2801 // Updating the public contact as well
2802 $condition = ['`forum` != ? AND `uid` = 0 AND `nurl` = ?', $forum, $importer['nurl']];
2803 DBA::update('contact', ['forum' => $forum], $condition);
2807 // We are processing relocations even if we are ignoring a contact
2808 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2809 foreach ($relocations as $relocation) {
2810 self::processRelocation($xpath, $relocation, $importer);
2813 if (($importer["uid"] != 0) && !$importer["readonly"]) {
2814 $mails = $xpath->query("/atom:feed/dfrn:mail");
2815 foreach ($mails as $mail) {
2816 self::processMail($xpath, $mail, $importer);
2819 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2820 foreach ($suggestions as $suggestion) {
2821 self::processSuggestion($xpath, $suggestion, $importer);
2825 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2826 foreach ($deletions as $deletion) {
2827 self::processDeletion($xpath, $deletion, $importer);
2830 if (!$sort_by_date) {
2831 $entries = $xpath->query("/atom:feed/atom:entry");
2832 foreach ($entries as $entry) {
2833 self::processEntry($header, $xpath, $entry, $importer, $xml);
2837 $entries = $xpath->query("/atom:feed/atom:entry");
2838 foreach ($entries as $entry) {
2839 $created = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2840 $newentries[strtotime($created)] = $entry;
2843 // Now sort after the publishing date
2846 foreach ($newentries as $entry) {
2847 self::processEntry($header, $xpath, $entry, $importer, $xml);
2850 Logger::log("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], Logger::DEBUG);
2855 * Returns the activity verb
2857 * @param array $item Item array
2859 * @return string activity verb
2861 private static function constructVerb(array $item)
2863 if ($item['verb']) {
2864 return $item['verb'];
2866 return Activity::POST;
2869 private static function tgroupCheck($uid, $item)
2873 // check that the message originated elsewhere and is a top-level post
2875 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['parent-uri'])) {
2879 $user = DBA::selectFirst('user', ['page-flags', 'nickname'], ['uid' => $uid]);
2880 if (!DBA::isResult($user)) {
2884 $community_page = ($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY);
2885 $prvgroup = ($user['page-flags'] == User::PAGE_FLAGS_PRVGROUP);
2887 $link = Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']);
2890 * Diaspora uses their own hardwired link URL in @-tags
2891 * instead of the one we supply with webfinger
2893 $dlink = Strings::normaliseLink(DI::baseUrl() . '/u/' . $user['nickname']);
2895 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2897 foreach ($matches as $mtch) {
2898 if (Strings::compareLink($link, $mtch[1]) || Strings::compareLink($dlink, $mtch[1])) {
2900 Logger::log('mention found: ' . $mtch[2]);
2909 return $community_page || $prvgroup;
2913 * This function returns true if $update has an edited timestamp newer
2914 * than $existing, i.e. $update contains new data which should override
2915 * what's already there. If there is no timestamp yet, the update is
2916 * assumed to be newer. If the update has no timestamp, the existing
2917 * item is assumed to be up-to-date. If the timestamps are equal it
2918 * assumes the update has been seen before and should be ignored.
2923 * @throws \Exception
2925 private static function isEditedTimestampNewer($existing, $update)
2927 if (empty($existing['edited'])) {
2930 if (empty($update['edited'])) {
2934 $existing_edited = DateTimeFormat::utc($existing['edited']);
2935 $update_edited = DateTimeFormat::utc($update['edited']);
2937 return (strcmp($existing_edited, $update_edited) < 0);
2941 * Checks if the given contact url does support DFRN
2943 * @param string $url profile url
2944 * @param boolean $update Update the profile
2946 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2947 * @throws \ImagickException
2949 public static function isSupportedByContactUrl($url, $update = false)
2951 $probe = Probe::uri($url, Protocol::DFRN, 0, !$update);
2952 return $probe['network'] == Protocol::DFRN;