3 * @file include/dfrn.php
4 * @brief The implementation of the dfrn protocol
6 * @see https://github.com/friendica/friendica/wiki/Protocol and
7 * https://github.com/friendica/friendica/blob/master/spec/dfrn2.pdf
9 namespace Friendica\Protocol;
14 use Friendica\Content\OEmbed;
15 use Friendica\Content\Text\BBCode;
16 use Friendica\Content\Text\HTML;
17 use Friendica\Core\Config;
18 use Friendica\Core\Hook;
19 use Friendica\Core\Logger;
20 use Friendica\Core\Protocol;
21 use Friendica\Core\System;
22 use Friendica\Database\DBA;
23 use Friendica\Model\Contact;
24 use Friendica\Model\Conversation;
25 use Friendica\Model\Event;
26 use Friendica\Model\GContact;
27 use Friendica\Model\Item;
28 use Friendica\Model\PermissionSet;
29 use Friendica\Model\Profile;
30 use Friendica\Model\User;
31 use Friendica\Object\Image;
32 use Friendica\Util\Crypto;
33 use Friendica\Util\DateTimeFormat;
34 use Friendica\Util\Network;
35 use Friendica\Util\Strings;
36 use Friendica\Util\XML;
38 use HTMLPurifier_Config;
41 * @brief This class contain functions to create and send DFRN XML files
46 const TOP_LEVEL = 0; // Top level posting
47 const REPLY = 1; // Regular reply that is stored locally
48 const REPLY_RC = 2; // Reply that will be relayed
51 * @brief Generates an array of contact and user for DFRN imports
53 * This array contains not only the receiver but also the sender of the message.
55 * @param integer $cid Contact id
56 * @param integer $uid User id
58 * @return array importer
61 public static function getImporter($cid, $uid = 0)
63 $condition = ['id' => $cid, 'blocked' => false, 'pending' => false];
64 $contact = DBA::selectFirst('contact', [], $condition);
65 if (!DBA::isResult($contact)) {
69 $contact['cpubkey'] = $contact['pubkey'];
70 $contact['cprvkey'] = $contact['prvkey'];
71 $contact['senderName'] = $contact['name'];
74 $condition = ['uid' => $uid, 'account_expired' => false, 'account_removed' => false];
75 $user = DBA::selectFirst('user', [], $condition);
76 if (!DBA::isResult($user)) {
80 $user['importer_uid'] = $user['uid'];
81 $user['uprvkey'] = $user['prvkey'];
83 $user = ['importer_uid' => 0, 'uprvkey' => '', 'timezone' => 'UTC',
84 'nickname' => '', 'sprvkey' => '', 'spubkey' => '',
85 'page-flags' => 0, 'account-type' => 0, 'prvnets' => 0];
88 return array_merge($contact, $user);
92 * @brief Generates the atom entries for delivery.php
94 * This function is used whenever content is transmitted via DFRN.
96 * @param array $items Item elements
97 * @param array $owner Owner record
99 * @return string DFRN entries
100 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
101 * @throws \ImagickException
102 * @todo Find proper type-hints
104 public static function entries($items, $owner)
106 $doc = new DOMDocument('1.0', 'utf-8');
107 $doc->formatOutput = true;
109 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
111 if (! count($items)) {
112 return trim($doc->saveXML());
115 foreach ($items as $item) {
116 // These values aren't sent when sending from the queue.
117 /// @todo Check if we can set these values from the queue or if they are needed at all.
118 $item["entry:comment-allow"] = defaults($item, "entry:comment-allow", true);
119 $item["entry:cid"] = defaults($item, "entry:cid", 0);
121 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
123 $root->appendChild($entry);
127 return trim($doc->saveXML());
131 * @brief Generate an atom feed for the given user
133 * This function is called when another server is pulling data from the user feed.
135 * @param string $dfrn_id DFRN ID from the requesting party
136 * @param string $owner_nick Owner nick name
137 * @param string $last_update Date of the last update
138 * @param int $direction Can be -1, 0 or 1.
139 * @param boolean $onlyheader Output only the header without content? (Default is "no")
141 * @return string DFRN feed entries
142 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
143 * @throws \ImagickException
145 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false)
149 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
150 $public_feed = (($dfrn_id) ? false : true);
151 $starred = false; // not yet implemented, possible security issues
154 if ($public_feed && $a->argc > 2) {
155 for ($x = 2; $x < $a->argc; $x++) {
156 if ($a->argv[$x] == 'converse') {
159 if ($a->argv[$x] == 'starred') {
162 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
163 $category = $a->argv[$x+1];
168 // default permissions - anonymous user
170 $sql_extra = " AND NOT `item`.`private` ";
173 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
174 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
175 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
176 DBA::escape($owner_nick)
179 if (! DBA::isResult($r)) {
180 Logger::log(sprintf('No contact found for nickname=%d', $owner_nick), Logger::WARNING);
185 $owner_id = $owner['uid'];
187 $sql_post_table = "";
189 if (! $public_feed) {
190 switch ($direction) {
192 $sql_extra = sprintf(" AND `issued-id` = '%s' ", DBA::escape($dfrn_id));
195 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
198 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
206 "SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
210 if (! DBA::isResult($r)) {
211 Logger::log(sprintf('No contact found for uid=%d', $owner_id), Logger::WARNING);
217 $set = PermissionSet::get($owner_id, $contact['id']);
220 $sql_extra = " AND `item`.`psid` IN (" . implode(',', $set) .")";
222 $sql_extra = " AND NOT `item`.`private`";
232 if (! strlen($last_update)) {
233 $last_update = 'now -30 days';
236 if (isset($category)) {
237 $sql_post_table = sprintf(
238 "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` ",
239 DBA::escape(Strings::protectSprintf($category)),
240 intval(TERM_OBJ_POST),
241 intval(TERM_CATEGORY),
246 if ($public_feed && ! $converse) {
247 $sql_extra .= " AND `contact`.`self` = 1 ";
250 $check_date = DateTimeFormat::utc($last_update);
254 FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
255 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
256 WHERE `item`.`uid` = %d AND `item`.`wall` AND `item`.`changed` > '%s'
257 AND `item`.`visible` $sql_extra
258 ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
260 DBA::escape($check_date),
265 foreach ($r as $item) {
266 $ids[] = $item['id'];
270 $ret = Item::select(Item::DELIVER_FIELDLIST, ['id' => $ids]);
271 $items = Item::inArray($ret);
277 * Will check further below if this actually returned results.
278 * We will provide an empty feed if that is the case.
281 $doc = new DOMDocument('1.0', 'utf-8');
282 $doc->formatOutput = true;
284 $alternatelink = $owner['url'];
286 if (isset($category)) {
287 $alternatelink .= "/category/".$category;
291 $author = "dfrn:owner";
296 $root = self::addHeader($doc, $owner, $author, $alternatelink, true);
298 /// @TODO This hook can't work anymore
299 // \Friendica\Core\Hook::callAll('atom_feed', $atom);
301 if (!DBA::isResult($items) || $onlyheader) {
302 $atom = trim($doc->saveXML());
304 Hook::callAll('atom_feed_end', $atom);
309 foreach ($items as $item) {
310 // prevent private email from leaking.
311 if ($item['network'] == Protocol::MAIL) {
315 // public feeds get html, our own nodes use bbcode
319 // catch any email that's in a public conversation and make sure it doesn't leak
320 if ($item['private']) {
327 $entry = self::entry($doc, $type, $item, $owner, true);
329 $root->appendChild($entry);
333 $atom = trim($doc->saveXML());
335 Hook::callAll('atom_feed_end', $atom);
341 * @brief Generate an atom entry for a given item id
343 * @param int $item_id The item id
344 * @param boolean $conversation Show the conversation. If false show the single post.
346 * @return string DFRN feed entry
347 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
348 * @throws \ImagickException
350 public static function itemFeed($item_id, $conversation = false)
353 $condition = ['parent' => $item_id];
355 $condition = ['id' => $item_id];
358 $ret = Item::select(Item::DELIVER_FIELDLIST, $condition);
359 $items = Item::inArray($ret);
360 if (!DBA::isResult($items)) {
366 if ($item['uid'] != 0) {
367 $owner = User::getOwnerDataById($item['uid']);
372 $owner = ['uid' => 0, 'nick' => 'feed-item'];
375 $doc = new DOMDocument('1.0', 'utf-8');
376 $doc->formatOutput = true;
380 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
381 $doc->appendChild($root);
383 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
384 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
385 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
386 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
387 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
388 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
389 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
390 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
391 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
393 //$root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
395 foreach ($items as $item) {
396 $entry = self::entry($doc, $type, $item, $owner, true, 0);
398 $root->appendChild($entry);
402 $root = self::entry($doc, $type, $item, $owner, true, 0, true);
405 $atom = trim($doc->saveXML());
410 * @brief Create XML text for DFRN mails
412 * @param array $item message elements
413 * @param array $owner Owner record
415 * @return string DFRN mail
416 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
417 * @todo Find proper type-hints
419 public static function mail($item, $owner)
421 $doc = new DOMDocument('1.0', 'utf-8');
422 $doc->formatOutput = true;
424 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
426 $mail = $doc->createElement("dfrn:mail");
427 $sender = $doc->createElement("dfrn:sender");
429 XML::addElement($doc, $sender, "dfrn:name", $owner['name']);
430 XML::addElement($doc, $sender, "dfrn:uri", $owner['url']);
431 XML::addElement($doc, $sender, "dfrn:avatar", $owner['thumb']);
433 $mail->appendChild($sender);
435 XML::addElement($doc, $mail, "dfrn:id", $item['uri']);
436 XML::addElement($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
437 XML::addElement($doc, $mail, "dfrn:sentdate", DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
438 XML::addElement($doc, $mail, "dfrn:subject", $item['title']);
439 XML::addElement($doc, $mail, "dfrn:content", $item['body']);
441 $root->appendChild($mail);
443 return trim($doc->saveXML());
447 * @brief Create XML text for DFRN friend suggestions
449 * @param array $item suggestion elements
450 * @param array $owner Owner record
452 * @return string DFRN suggestions
453 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
454 * @todo Find proper type-hints
456 public static function fsuggest($item, $owner)
458 $doc = new DOMDocument('1.0', 'utf-8');
459 $doc->formatOutput = true;
461 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
463 $suggest = $doc->createElement("dfrn:suggest");
465 XML::addElement($doc, $suggest, "dfrn:url", $item['url']);
466 XML::addElement($doc, $suggest, "dfrn:name", $item['name']);
467 XML::addElement($doc, $suggest, "dfrn:photo", $item['photo']);
468 XML::addElement($doc, $suggest, "dfrn:request", $item['request']);
469 XML::addElement($doc, $suggest, "dfrn:note", $item['note']);
471 $root->appendChild($suggest);
473 return trim($doc->saveXML());
477 * @brief Create XML text for DFRN relocations
479 * @param array $owner Owner record
480 * @param int $uid User ID
482 * @return string DFRN relocations
483 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
484 * @todo Find proper type-hints
486 public static function relocate($owner, $uid)
489 /* get site pubkey. this could be a new installation with no site keys*/
490 $pubkey = Config::get('system', 'site_pubkey');
492 $res = Crypto::newKeypair(1024);
493 Config::set('system', 'site_prvkey', $res['prvkey']);
494 Config::set('system', 'site_pubkey', $res['pubkey']);
498 "SELECT `resource-id` , `scale`, type FROM `photo`
499 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;",
503 $ext = Image::supportedTypes();
505 foreach ($rp as $p) {
506 $photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
510 $doc = new DOMDocument('1.0', 'utf-8');
511 $doc->formatOutput = true;
513 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
515 $relocate = $doc->createElement("dfrn:relocate");
517 XML::addElement($doc, $relocate, "dfrn:url", $owner['url']);
518 XML::addElement($doc, $relocate, "dfrn:name", $owner['name']);
519 XML::addElement($doc, $relocate, "dfrn:addr", $owner['addr']);
520 XML::addElement($doc, $relocate, "dfrn:avatar", $owner['avatar']);
521 XML::addElement($doc, $relocate, "dfrn:photo", $photos[4]);
522 XML::addElement($doc, $relocate, "dfrn:thumb", $photos[5]);
523 XML::addElement($doc, $relocate, "dfrn:micro", $photos[6]);
524 XML::addElement($doc, $relocate, "dfrn:request", $owner['request']);
525 XML::addElement($doc, $relocate, "dfrn:confirm", $owner['confirm']);
526 XML::addElement($doc, $relocate, "dfrn:notify", $owner['notify']);
527 XML::addElement($doc, $relocate, "dfrn:poll", $owner['poll']);
528 XML::addElement($doc, $relocate, "dfrn:sitepubkey", Config::get('system', 'site_pubkey'));
530 $root->appendChild($relocate);
532 return trim($doc->saveXML());
536 * @brief Adds the header elements for the DFRN protocol
538 * @param DOMDocument $doc XML document
539 * @param array $owner Owner record
540 * @param string $authorelement Element name for the author
541 * @param string $alternatelink link to profile or category
542 * @param bool $public Is it a header for public posts?
544 * @return object XML root object
545 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
546 * @todo Find proper type-hints
548 private static function addHeader(DOMDocument $doc, $owner, $authorelement, $alternatelink = "", $public = false)
551 if ($alternatelink == "") {
552 $alternatelink = $owner['url'];
555 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
556 $doc->appendChild($root);
558 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
559 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
560 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
561 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
562 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
563 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
564 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
565 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
566 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
568 XML::addElement($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
569 XML::addElement($doc, $root, "title", $owner["name"]);
571 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION];
572 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
574 $attributes = ["rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/"];
575 XML::addElement($doc, $root, "link", "", $attributes);
577 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $alternatelink];
578 XML::addElement($doc, $root, "link", "", $attributes);
582 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
583 OStatus::hublinks($doc, $root, $owner["nick"]);
585 $attributes = ["rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
586 XML::addElement($doc, $root, "link", "", $attributes);
588 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
589 XML::addElement($doc, $root, "link", "", $attributes);
591 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
592 XML::addElement($doc, $root, "link", "", $attributes);
595 // For backward compatibility we keep this element
596 if ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY) {
597 XML::addElement($doc, $root, "dfrn:community", 1);
600 // The former element is replaced by this one
601 XML::addElement($doc, $root, "dfrn:account_type", $owner["account-type"]);
603 /// @todo We need a way to transmit the different page flags like "User::PAGE_FLAGS_PRVGROUP"
605 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
607 $author = self::addAuthor($doc, $owner, $authorelement, $public);
608 $root->appendChild($author);
614 * @brief Adds the author element in the header for the DFRN protocol
616 * @param DOMDocument $doc XML document
617 * @param array $owner Owner record
618 * @param string $authorelement Element name for the author
619 * @param boolean $public boolean
621 * @return \DOMElement XML author object
622 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
623 * @todo Find proper type-hints
625 private static function addAuthor(DOMDocument $doc, array $owner, $authorelement, $public)
627 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
629 "SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
630 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
631 intval($owner['uid'])
633 if (DBA::isResult($r)) {
639 $author = $doc->createElement($authorelement);
641 $namdate = DateTimeFormat::utc($owner['name-date'].'+00:00', DateTimeFormat::ATOM);
642 $uridate = DateTimeFormat::utc($owner['uri-date'].'+00:00', DateTimeFormat::ATOM);
643 $picdate = DateTimeFormat::utc($owner['avatar-date'].'+00:00', DateTimeFormat::ATOM);
647 if (!$public || !$hidewall) {
648 $attributes = ["dfrn:updated" => $namdate];
651 XML::addElement($doc, $author, "name", $owner["name"], $attributes);
652 XML::addElement($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
653 XML::addElement($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
655 $attributes = ["rel" => "photo", "type" => "image/jpeg",
656 "media:width" => 300, "media:height" => 300, "href" => $owner['photo']];
658 if (!$public || !$hidewall) {
659 $attributes["dfrn:updated"] = $picdate;
662 XML::addElement($doc, $author, "link", "", $attributes);
664 $attributes["rel"] = "avatar";
665 XML::addElement($doc, $author, "link", "", $attributes);
668 XML::addElement($doc, $author, "dfrn:hide", "true");
671 // The following fields will only be generated if the data isn't meant for a public feed
676 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
679 XML::addElement($doc, $author, "dfrn:birthday", $birthday);
682 // Only show contact details when we are allowed to
684 "SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
685 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
686 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
688 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
689 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
690 intval($owner['uid'])
692 if (DBA::isResult($r)) {
695 XML::addElement($doc, $author, "poco:displayName", $profile["name"]);
696 XML::addElement($doc, $author, "poco:updated", $namdate);
698 if (trim($profile["dob"]) > DBA::NULL_DATE) {
699 XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
702 XML::addElement($doc, $author, "poco:note", $profile["about"]);
703 XML::addElement($doc, $author, "poco:preferredUsername", $profile["nickname"]);
705 $savetz = date_default_timezone_get();
706 date_default_timezone_set($profile["timezone"]);
707 XML::addElement($doc, $author, "poco:utcOffset", date("P"));
708 date_default_timezone_set($savetz);
710 if (trim($profile["homepage"]) != "") {
711 $urls = $doc->createElement("poco:urls");
712 XML::addElement($doc, $urls, "poco:type", "homepage");
713 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
714 XML::addElement($doc, $urls, "poco:primary", "true");
715 $author->appendChild($urls);
718 if (trim($profile["pub_keywords"]) != "") {
719 $keywords = explode(",", $profile["pub_keywords"]);
721 foreach ($keywords as $keyword) {
722 XML::addElement($doc, $author, "poco:tags", trim($keyword));
726 if (trim($profile["xmpp"]) != "") {
727 $ims = $doc->createElement("poco:ims");
728 XML::addElement($doc, $ims, "poco:type", "xmpp");
729 XML::addElement($doc, $ims, "poco:value", $profile["xmpp"]);
730 XML::addElement($doc, $ims, "poco:primary", "true");
731 $author->appendChild($ims);
734 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
735 $element = $doc->createElement("poco:address");
737 XML::addElement($doc, $element, "poco:formatted", Profile::formatLocation($profile));
739 if (trim($profile["locality"]) != "") {
740 XML::addElement($doc, $element, "poco:locality", $profile["locality"]);
743 if (trim($profile["region"]) != "") {
744 XML::addElement($doc, $element, "poco:region", $profile["region"]);
747 if (trim($profile["country-name"]) != "") {
748 XML::addElement($doc, $element, "poco:country", $profile["country-name"]);
751 $author->appendChild($element);
759 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
761 * @param DOMDocument $doc XML document
762 * @param string $element Element name for the author
763 * @param string $contact_url Link of the contact
764 * @param array $item Item elements
766 * @return \DOMElement XML author object
767 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
768 * @todo Find proper type-hints
770 private static function addEntryAuthor(DOMDocument $doc, $element, $contact_url, $item)
772 $author = $doc->createElement($element);
774 $contact = Contact::getDetailsByURL($contact_url, $item["uid"]);
775 if (!empty($contact)) {
776 XML::addElement($doc, $author, "name", $contact["name"]);
777 XML::addElement($doc, $author, "uri", $contact["url"]);
778 XML::addElement($doc, $author, "dfrn:handle", $contact["addr"]);
781 /// - Check real image type and image size
782 /// - Check which of these boths elements we should use
785 "type" => "image/jpeg",
787 "media:height" => 80,
788 "href" => $contact["photo"]];
789 XML::addElement($doc, $author, "link", "", $attributes);
793 "type" => "image/jpeg",
795 "media:height" => 80,
796 "href" => $contact["photo"]];
797 XML::addElement($doc, $author, "link", "", $attributes);
804 * @brief Adds the activity elements
806 * @param DOMDocument $doc XML document
807 * @param string $element Element name for the activity
808 * @param string $activity activity value
810 * @return \DOMElement XML activity object
811 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
812 * @todo Find proper type-hints
814 private static function createActivity(DOMDocument $doc, $element, $activity)
817 $entry = $doc->createElement($element);
819 $r = XML::parseString($activity, false);
825 XML::addElement($doc, $entry, "activity:object-type", $r->type);
829 XML::addElement($doc, $entry, "id", $r->id);
833 XML::addElement($doc, $entry, "title", $r->title);
837 if (substr($r->link, 0, 1) == '<') {
838 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
839 $r->link = str_replace('&', '&', $r->link);
842 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
844 // XML does need a single element as root element so we add a dummy element here
845 $data = XML::parseString("<dummy>" . $r->link . "</dummy>", false);
846 if (is_object($data)) {
847 foreach ($data->link as $link) {
849 foreach ($link->attributes() as $parameter => $value) {
850 $attributes[$parameter] = $value;
852 XML::addElement($doc, $entry, "link", "", $attributes);
856 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
857 XML::addElement($doc, $entry, "link", "", $attributes);
861 XML::addElement($doc, $entry, "content", BBCode::convert($r->content), ["type" => "html"]);
871 * @brief Adds the elements for attachments
873 * @param object $doc XML document
874 * @param object $root XML root
875 * @param array $item Item element
877 * @return void XML attachment object
878 * @todo Find proper type-hints
880 private static function getAttachment($doc, $root, $item)
882 $arr = explode('[/attach],', $item['attach']);
884 foreach ($arr as $r) {
886 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
888 $attributes = ["rel" => "enclosure",
889 "href" => $matches[1],
890 "type" => $matches[3]];
892 if (intval($matches[2])) {
893 $attributes["length"] = intval($matches[2]);
896 if (trim($matches[4]) != "") {
897 $attributes["title"] = trim($matches[4]);
900 XML::addElement($doc, $root, "link", "", $attributes);
907 * @brief Adds the "entry" elements for the DFRN protocol
909 * @param DOMDocument $doc XML document
910 * @param string $type "text" or "html"
911 * @param array $item Item element
912 * @param array $owner Owner record
913 * @param bool $comment Trigger the sending of the "comment" element
914 * @param int $cid Contact ID of the recipient
915 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
917 * @return null|\DOMElement XML entry object
918 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
919 * @throws \ImagickException
920 * @todo Find proper type-hints
922 private static function entry(DOMDocument $doc, $type, array $item, array $owner, $comment = false, $cid = 0, $single = false)
926 if (!$item['parent']) {
927 Logger::notice('Item without parent found.', ['type' => $type, 'item' => $item]);
931 if ($item['deleted']) {
932 $attributes = ["ref" => $item['uri'], "when" => DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM)];
933 return XML::createElement($doc, "at:deleted-entry", "", $attributes);
937 $entry = $doc->createElement("entry");
939 $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry');
940 $doc->appendChild($entry);
942 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
943 $entry->setAttribute("xmlns:at", NAMESPACE_TOMB);
944 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
945 $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
946 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
947 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
948 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
949 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
950 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
953 if ($item['private']) {
954 $body = Item::fixPrivatePhotos($item['body'], $owner['uid'], $item, $cid);
956 $body = $item['body'];
959 // Remove the abstract element. It is only locally important.
960 $body = BBCode::stripAbstract($body);
963 if ($type == 'html') {
966 if ($item['title'] != "") {
967 $htmlbody = "[b]" . $item['title'] . "[/b]\n\n" . $htmlbody;
970 $htmlbody = BBCode::convert($htmlbody, false, 7);
973 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
974 $entry->appendChild($author);
976 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
977 $entry->appendChild($dfrnowner);
979 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
980 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
981 $parent = Item::selectFirst(['guid', 'plink'], ['uri' => $parent_item, 'uid' => $item['uid']]);
982 $attributes = ["ref" => $parent_item, "type" => "text/html",
983 "href" => $parent['plink'],
984 "dfrn:diaspora_guid" => $parent['guid']];
985 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
988 // Add conversation data. This is used for OStatus
989 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
990 $conversation_uri = $conversation_href;
992 if (isset($parent_item)) {
993 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $item['parent-uri']]);
994 if (DBA::isResult($conversation)) {
995 if ($conversation['conversation-uri'] != '') {
996 $conversation_uri = $conversation['conversation-uri'];
998 if ($conversation['conversation-href'] != '') {
999 $conversation_href = $conversation['conversation-href'];
1005 "href" => $conversation_href,
1006 "ref" => $conversation_uri];
1008 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
1010 XML::addElement($doc, $entry, "id", $item["uri"]);
1011 XML::addElement($doc, $entry, "title", $item["title"]);
1013 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"] . "+00:00", DateTimeFormat::ATOM));
1014 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"] . "+00:00", DateTimeFormat::ATOM));
1016 // "dfrn:env" is used to read the content
1017 XML::addElement($doc, $entry, "dfrn:env", Strings::base64UrlEncode($body, true));
1019 // The "content" field is not read by the receiver. We could remove it when the type is "text"
1020 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
1021 XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
1023 // We save this value in "plink". Maybe we should read it from there as well?
1029 ["rel" => "alternate", "type" => "text/html",
1030 "href" => System::baseUrl() . "/display/" . $item["guid"]]
1033 // "comment-allow" is some old fashioned stuff for old Friendica versions.
1034 // It is included in the rewritten code for completeness
1036 XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
1039 if ($item['location']) {
1040 XML::addElement($doc, $entry, "dfrn:location", $item['location']);
1043 if ($item['coord']) {
1044 XML::addElement($doc, $entry, "georss:point", $item['coord']);
1047 if ($item['private']) {
1048 XML::addElement($doc, $entry, "dfrn:private", ($item['private'] ? $item['private'] : 1));
1051 if ($item['extid']) {
1052 XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
1055 if ($item['post-type'] == Item::PT_PAGE) {
1056 XML::addElement($doc, $entry, "dfrn:bookmark", "true");
1060 XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
1063 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
1065 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
1066 // It is needed for relayed comments to Diaspora.
1067 if ($item['signed_text']) {
1068 $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer']]));
1069 XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
1072 XML::addElement($doc, $entry, "activity:verb", self::constructVerb($item));
1074 if ($item['object-type'] != "") {
1075 XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
1076 } elseif ($item['id'] == $item['parent']) {
1077 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1079 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
1082 $actobj = self::createActivity($doc, "activity:object", $item['object']);
1084 $entry->appendChild($actobj);
1087 $actarg = self::createActivity($doc, "activity:target", $item['target']);
1089 $entry->appendChild($actarg);
1092 $tags = Item::getFeedTags($item);
1094 /// @TODO Combine this with similar below if() block?
1096 foreach ($tags as $t) {
1097 if (($type != 'html') || ($t[0] != "@")) {
1098 XML::addElement($doc, $entry, "category", "", ["scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]]);
1104 foreach ($tags as $t) {
1106 $mentioned[$t[1]] = $t[1];
1111 foreach ($mentioned as $mention) {
1112 $condition = ['uid' => $owner["uid"], 'nurl' => Strings::normaliseLink($mention)];
1113 $contact = DBA::selectFirst('contact', ['forum', 'prv'], $condition);
1115 if (DBA::isResult($contact) && ($contact["forum"] || $contact["prv"])) {
1121 ["rel" => "mentioned",
1122 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1131 ["rel" => "mentioned",
1132 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1138 self::getAttachment($doc, $entry, $item);
1144 * @brief encrypts data via AES
1146 * @param string $data The data that is to be encrypted
1147 * @param string $key The AES key
1149 * @return string encrypted data
1151 private static function aesEncrypt($data, $key)
1153 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1157 * @brief decrypts data via AES
1159 * @param string $encrypted The encrypted data
1160 * @param string $key The AES key
1162 * @return string decrypted data
1164 public static function aesDecrypt($encrypted, $key)
1166 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1170 * @brief Delivers the atom content to the contacts
1172 * @param array $owner Owner record
1173 * @param array $contact Contact record of the receiver
1174 * @param string $atom Content that will be transmitted
1175 * @param bool $dissolve (to be documented)
1177 * @param bool $legacy_transport
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, $legacy_transport = false)
1185 // At first try the Diaspora transport layer
1186 if (!$dissolve && !$legacy_transport) {
1187 $curlResult = self::transmit($owner, $contact, $atom);
1188 if ($curlResult >= 200) {
1189 Logger::log('Delivery via Diaspora transport layer was successful with status ' . $curlResult);
1194 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1196 if ($contact['duplex'] && $contact['dfrn-id']) {
1197 $idtosend = '0:' . $orig_id;
1199 if ($contact['duplex'] && $contact['issued-id']) {
1200 $idtosend = '1:' . $orig_id;
1203 $rino = Config::get('system', 'rino_encrypt');
1204 $rino = intval($rino);
1206 Logger::log("Local rino version: ". $rino, Logger::DEBUG);
1208 $ssl_val = intval(Config::get('system', 'ssl_policy'));
1211 case SSL_POLICY_FULL:
1212 $ssl_policy = 'full';
1214 case SSL_POLICY_SELFSIGN:
1215 $ssl_policy = 'self';
1217 case SSL_POLICY_NONE:
1219 $ssl_policy = 'none';
1223 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1225 Logger::log('dfrn_deliver: ' . $url);
1227 $curlResult = Network::curl($url);
1229 if ($curlResult->isTimeout()) {
1230 Contact::markForArchival($contact);
1231 return -2; // timed out
1234 $xml = $curlResult->getBody();
1236 $curl_stat = $curlResult->getReturnCode();
1237 if (empty($curl_stat)) {
1238 Contact::markForArchival($contact);
1239 return -3; // timed out
1242 Logger::log('dfrn_deliver: ' . $xml, Logger::DATA);
1245 Contact::markForArchival($contact);
1249 if (strpos($xml, '<?xml') === false) {
1250 Logger::log('dfrn_deliver: no valid XML returned');
1251 Logger::log('dfrn_deliver: returned XML: ' . $xml, Logger::DATA);
1252 Contact::markForArchival($contact);
1256 $res = XML::parseString($xml);
1258 if (!is_object($res) || (intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
1259 Contact::markForArchival($contact);
1261 if (empty($res->status)) {
1264 $status = $res->status;
1271 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1272 $challenge = hex2bin((string) $res->challenge);
1273 $perm = (($res->perm) ? $res->perm : null);
1274 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1275 $rino_remote_version = intval($res->rino);
1276 $page = (($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? 1 : 0);
1278 Logger::log("Remote rino version: ".$rino_remote_version." for ".$contact["url"], Logger::DEBUG);
1280 if ($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
1284 $final_dfrn_id = '';
1287 if ((($perm == 'rw') && !intval($contact['writable']))
1288 || (($perm == 'r') && intval($contact['writable']))
1290 DBA::update('contact', ['writable' => ($perm == 'rw')], ['id' => $contact['id']]);
1292 $contact['writable'] = (string) 1 - intval($contact['writable']);
1296 if (($contact['duplex'] && strlen($contact['pubkey']))
1297 || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY && strlen($contact['pubkey']))
1298 || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
1300 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
1301 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
1303 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
1304 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
1307 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1309 if (strpos($final_dfrn_id, ':') == 1) {
1310 $final_dfrn_id = substr($final_dfrn_id, 2);
1313 if ($final_dfrn_id != $orig_id) {
1314 Logger::log('dfrn_deliver: wrong dfrn_id.');
1315 // did not decode properly - cannot trust this site
1316 Contact::markForArchival($contact);
1320 $postvars['dfrn_id'] = $idtosend;
1321 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1323 $postvars['dissolve'] = '1';
1326 if ((($contact['rel']) && ($contact['rel'] != Contact::SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY)) {
1327 $postvars['data'] = $atom;
1328 $postvars['perm'] = 'rw';
1330 $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
1331 $postvars['perm'] = 'r';
1334 $postvars['ssl_policy'] = $ssl_policy;
1337 $postvars['page'] = $page;
1341 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1342 Logger::log('rino version: '. $rino_remote_version);
1344 switch ($rino_remote_version) {
1346 $key = openssl_random_pseudo_bytes(16);
1347 $data = self::aesEncrypt($postvars['data'], $key);
1351 Logger::log("rino: invalid requested version '$rino_remote_version'");
1352 Contact::markForArchival($contact);
1356 $postvars['rino'] = $rino_remote_version;
1357 $postvars['data'] = bin2hex($data);
1359 if ($dfrn_version >= 2.1) {
1360 if (($contact['duplex'] && strlen($contact['pubkey']))
1361 || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY && strlen($contact['pubkey']))
1362 || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
1364 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1366 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1369 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY)) {
1370 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1372 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1376 Logger::log('md5 rawkey ' . md5($postvars['key']));
1378 $postvars['key'] = bin2hex($postvars['key']);
1382 Logger::log('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), Logger::DATA);
1384 $postResult = Network::post($contact['notify'], $postvars);
1386 $xml = $postResult->getBody();
1388 Logger::log('dfrn_deliver: ' . "RECEIVED: " . $xml, Logger::DATA);
1390 $curl_stat = $postResult->getReturnCode();
1391 if (empty($curl_stat) || empty($xml)) {
1392 Contact::markForArchival($contact);
1393 return -9; // timed out
1396 if (($curl_stat == 503) && stristr($postResult->getHeader(), 'retry-after')) {
1397 Contact::markForArchival($contact);
1401 if (strpos($xml, '<?xml') === false) {
1402 Logger::log('dfrn_deliver: phase 2: no valid XML returned');
1403 Logger::log('dfrn_deliver: phase 2: returned XML: ' . $xml, Logger::DATA);
1404 Contact::markForArchival($contact);
1408 $res = XML::parseString($xml);
1410 if (!isset($res->status)) {
1411 Contact::markForArchival($contact);
1415 // Possibly old servers had returned an empty value when everything was okay
1416 if (empty($res->status)) {
1420 if (!empty($res->message)) {
1421 Logger::log('Delivery returned status '.$res->status.' - '.$res->message, Logger::DEBUG);
1424 if (($res->status >= 200) && ($res->status <= 299)) {
1425 Contact::unmarkForArchival($contact);
1428 return intval($res->status);
1432 * @brief Transmits atom content to the contacts via the Diaspora transport layer
1434 * @param array $owner Owner record
1435 * @param array $contact Contact record of the receiver
1436 * @param string $atom Content that will be transmitted
1438 * @param bool $public_batch
1439 * @return int Deliver status. Negative values mean an error.
1440 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1441 * @throws \ImagickException
1443 public static function transmit($owner, $contact, $atom, $public_batch = false)
1445 if (!$public_batch) {
1446 if (empty($contact['addr'])) {
1447 Logger::log('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.');
1448 if (Contact::updateFromProbe($contact['id'])) {
1449 $new_contact = DBA::selectFirst('contact', ['addr'], ['id' => $contact['id']]);
1450 $contact['addr'] = $new_contact['addr'];
1453 if (empty($contact['addr'])) {
1454 Logger::log('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
1455 Contact::markForArchival($contact);
1460 $fcontact = Diaspora::personByHandle($contact['addr']);
1461 if (empty($fcontact)) {
1462 Logger::log('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
1463 Contact::markForArchival($contact);
1466 $pubkey = $fcontact['pubkey'];
1471 $envelope = Diaspora::buildMessage($atom, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
1473 // Create the endpoint for public posts. This is some WIP and should later be added to the probing
1474 if ($public_batch && empty($contact["batch"])) {
1475 $parts = parse_url($contact["notify"]);
1476 $path_parts = explode('/', $parts['path']);
1477 array_pop($path_parts);
1478 $parts['path'] = implode('/', $path_parts);
1479 $contact["batch"] = Network::unparseURL($parts);
1482 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
1484 $content_type = ($public_batch ? "application/magic-envelope+xml" : "application/json");
1486 $postResult = Network::post($dest_url, $envelope, ["Content-Type: ".$content_type]);
1487 $xml = $postResult->getBody();
1489 $curl_stat = $postResult->getReturnCode();
1490 if (empty($curl_stat) || empty($xml)) {
1491 Logger::log('Empty answer from ' . $contact['id'] . ' - ' . $dest_url);
1492 Contact::markForArchival($contact);
1493 return -9; // timed out
1496 if (($curl_stat == 503) && (stristr($postResult->getHeader(), 'retry-after'))) {
1497 Contact::markForArchival($contact);
1501 if (strpos($xml, '<?xml') === false) {
1502 Logger::log('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url);
1503 Logger::log('Returned XML: ' . $xml, Logger::DATA);
1504 Contact::markForArchival($contact);
1508 $res = XML::parseString($xml);
1510 if (empty($res->status)) {
1511 Contact::markForArchival($contact);
1515 if (!empty($res->message)) {
1516 Logger::log('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message, Logger::DEBUG);
1519 if (($res->status >= 200) && ($res->status <= 299)) {
1520 Contact::unmarkForArchival($contact);
1523 return intval($res->status);
1527 * @brief Fetch the author data from head or entry items
1529 * @param object $xpath XPath object
1530 * @param object $context In which context should the data be searched
1531 * @param array $importer Record of the importer user mixed with contact of the content
1532 * @param string $element Element name from which the data is fetched
1533 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1534 * @param string $xml optional, default empty
1536 * @return array Relevant data of the author
1537 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1538 * @throws \ImagickException
1539 * @todo Find good type-hints for all parameter
1541 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
1544 $author["name"] = XML::getFirstNodeValue($xpath, $element."/atom:name/text()", $context);
1545 $author["link"] = XML::getFirstNodeValue($xpath, $element."/atom:uri/text()", $context);
1547 $fields = ['id', 'uid', 'url', 'network', 'avatar-date', 'avatar', 'name-date', 'uri-date', 'addr',
1548 'name', 'nick', 'about', 'location', 'keywords', 'xmpp', 'bdyear', 'bd', 'hidden', 'contact-type'];
1549 $condition = ["`uid` = ? AND `nurl` = ? AND `network` != ?",
1550 $importer["importer_uid"], Strings::normaliseLink($author["link"]), Protocol::STATUSNET];
1551 $contact_old = DBA::selectFirst('contact', $fields, $condition);
1553 if (DBA::isResult($contact_old)) {
1554 $author["contact-id"] = $contact_old["id"];
1555 $author["network"] = $contact_old["network"];
1558 Logger::debug("Contact ".$author["link"]." wasn't found for user ".$importer["importer_uid"]." XML: ".$xml);
1561 $author["contact-unknown"] = true;
1562 $author["contact-id"] = $importer["id"];
1563 $author["network"] = $importer["network"];
1567 // Until now we aren't serving different sizes - but maybe later
1569 /// @todo check if "avatar" or "photo" would be the best field in the specification
1570 $avatars = $xpath->query($element . "/atom:link[@rel='avatar']", $context);
1571 foreach ($avatars as $avatar) {
1574 foreach ($avatar->attributes as $attributes) {
1575 /// @TODO Rewrite these similar if() to one switch
1576 if ($attributes->name == "href") {
1577 $href = $attributes->textContent;
1579 if ($attributes->name == "width") {
1580 $width = $attributes->textContent;
1582 if ($attributes->name == "updated") {
1583 $author["avatar-date"] = $attributes->textContent;
1586 if (($width > 0) && ($href != "")) {
1587 $avatarlist[$width] = $href;
1591 if (count($avatarlist) > 0) {
1592 krsort($avatarlist);
1593 $author["avatar"] = current($avatarlist);
1596 if (empty($author['avatar']) && !empty($author['link'])) {
1597 $cid = Contact::getIdForURL($author['link'], 0);
1599 $contact = DBA::selectFirst('contact', ['avatar'], ['id' => $cid]);
1600 if (DBA::isResult($contact)) {
1601 $author['avatar'] = $contact['avatar'];
1606 if (empty($author['avatar'])) {
1607 Logger::log('Empty author: ' . $xml);
1608 $author['avatar'] = '';
1611 if (DBA::isResult($contact_old) && !$onlyfetch) {
1612 Logger::log("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", Logger::DEBUG);
1614 $poco = ["url" => $contact_old["url"]];
1616 // When was the last change to name or uri?
1617 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1618 foreach ($name_element->attributes as $attributes) {
1619 if ($attributes->name == "updated") {
1620 $poco["name-date"] = $attributes->textContent;
1624 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1625 foreach ($link_element->attributes as $attributes) {
1626 if ($attributes->name == "updated") {
1627 $poco["uri-date"] = $attributes->textContent;
1631 // Update contact data
1632 $value = XML::getFirstNodeValue($xpath, $element . "/dfrn:handle/text()", $context);
1634 $poco["addr"] = $value;
1637 $value = XML::getFirstNodeValue($xpath, $element . "/poco:displayName/text()", $context);
1639 $poco["name"] = $value;
1642 $value = XML::getFirstNodeValue($xpath, $element . "/poco:preferredUsername/text()", $context);
1644 $poco["nick"] = $value;
1647 $value = XML::getFirstNodeValue($xpath, $element . "/poco:note/text()", $context);
1649 $poco["about"] = $value;
1652 $value = XML::getFirstNodeValue($xpath, $element . "/poco:address/poco:formatted/text()", $context);
1654 $poco["location"] = $value;
1657 /// @todo Only search for elements with "poco:type" = "xmpp"
1658 $value = XML::getFirstNodeValue($xpath, $element . "/poco:ims/poco:value/text()", $context);
1660 $poco["xmpp"] = $value;
1663 /// @todo Add support for the following fields that we don't support by now in the contact table:
1664 /// - poco:utcOffset
1670 // If the "hide" element is present then the profile isn't searchable.
1671 $hide = intval(XML::getFirstNodeValue($xpath, $element . "/dfrn:hide/text()", $context) == "true");
1673 Logger::log("Hidden status for contact " . $contact_old["url"] . ": " . $hide, Logger::DEBUG);
1675 // If the contact isn't searchable then set the contact to "hidden".
1676 // Problem: This can be manually overridden by the user.
1678 $contact_old["hidden"] = true;
1681 // Save the keywords into the contact table
1683 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1684 foreach ($tagelements as $tag) {
1685 $tags[$tag->nodeValue] = $tag->nodeValue;
1689 $poco["keywords"] = implode(", ", $tags);
1692 // "dfrn:birthday" contains the birthday converted to UTC
1693 $birthday = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1695 if (strtotime($birthday) > time()) {
1696 $bd_timestamp = strtotime($birthday);
1698 $poco["bdyear"] = date("Y", $bd_timestamp);
1701 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1702 $value = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1704 if (!in_array($value, ["", "0000-00-00", DBA::NULL_DATE])) {
1705 $bdyear = date("Y");
1706 $value = str_replace(["0000", "0001"], $bdyear, $value);
1708 if (strtotime($value) < time()) {
1709 $value = str_replace($bdyear, $bdyear + 1, $value);
1712 $poco["bd"] = $value;
1715 $contact = array_merge($contact_old, $poco);
1717 if ($contact_old["bdyear"] != $contact["bdyear"]) {
1718 Event::createBirthday($contact, $birthday);
1721 // Get all field names
1723 foreach ($contact_old as $field => $data) {
1724 $fields[$field] = $data;
1727 unset($fields["id"]);
1728 unset($fields["uid"]);
1729 unset($fields["url"]);
1730 unset($fields["avatar-date"]);
1731 unset($fields["avatar"]);
1732 unset($fields["name-date"]);
1733 unset($fields["uri-date"]);
1736 // Update check for this field has to be done differently
1737 $datefields = ["name-date", "uri-date"];
1738 foreach ($datefields as $field) {
1739 // The date fields arrives as '2018-07-17T10:44:45Z' - the database return '2018-07-17 10:44:45'
1740 // The fields have to be in the same format to be comparable, since strtotime does add timezones.
1741 $contact[$field] = DateTimeFormat::utc($contact[$field]);
1743 if (strtotime($contact[$field]) > strtotime($contact_old[$field])) {
1744 Logger::log("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", Logger::DEBUG);
1749 foreach ($fields as $field => $data) {
1750 if ($contact[$field] != $contact_old[$field]) {
1751 Logger::log("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", Logger::DEBUG);
1757 Logger::log("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", Logger::DEBUG);
1760 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1761 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1762 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1763 WHERE `id` = %d AND `network` = '%s'",
1764 DBA::escape($contact["name"]), DBA::escape($contact["nick"]), DBA::escape($contact["about"]), DBA::escape($contact["location"]),
1765 DBA::escape($contact["addr"]), DBA::escape($contact["keywords"]), DBA::escape($contact["bdyear"]),
1766 DBA::escape($contact["bd"]), intval($contact["hidden"]), DBA::escape($contact["xmpp"]),
1767 DBA::escape(DateTimeFormat::utc($contact["name-date"])), DBA::escape(DateTimeFormat::utc($contact["uri-date"])),
1768 intval($contact["id"]), DBA::escape($contact["network"])
1772 Contact::updateAvatar(
1774 $importer['importer_uid'],
1776 (strtotime($contact['avatar-date']) > strtotime($contact_old['avatar-date']) || ($author['avatar'] != $contact_old['avatar']))
1780 * The generation is a sign for the reliability of the provided data.
1781 * It is used in the socgraph.php to prevent that old contact data
1782 * that was relayed over several servers can overwrite contact
1783 * data that we received directly.
1786 $poco["generation"] = 2;
1787 $poco["photo"] = $author["avatar"];
1788 $poco["hide"] = $hide;
1789 $poco["contact-type"] = $contact["contact-type"];
1790 $gcid = GContact::update($poco);
1792 GContact::link($gcid, $importer["importer_uid"], $contact["id"]);
1799 * @brief Transforms activity objects into an XML string
1801 * @param object $xpath XPath object
1802 * @param object $activity Activity object
1803 * @param string $element element name
1805 * @return string XML string
1806 * @todo Find good type-hints for all parameter
1808 private static function transformActivity($xpath, $activity, $element)
1810 if (!is_object($activity)) {
1814 $obj_doc = new DOMDocument("1.0", "utf-8");
1815 $obj_doc->formatOutput = true;
1817 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1819 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1820 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1822 $id = $xpath->query("atom:id", $activity)->item(0);
1823 if (is_object($id)) {
1824 $obj_element->appendChild($obj_doc->importNode($id, true));
1827 $title = $xpath->query("atom:title", $activity)->item(0);
1828 if (is_object($title)) {
1829 $obj_element->appendChild($obj_doc->importNode($title, true));
1832 $links = $xpath->query("atom:link", $activity);
1833 if (is_object($links)) {
1834 foreach ($links as $link) {
1835 $obj_element->appendChild($obj_doc->importNode($link, true));
1839 $content = $xpath->query("atom:content", $activity)->item(0);
1840 if (is_object($content)) {
1841 $obj_element->appendChild($obj_doc->importNode($content, true));
1844 $obj_doc->appendChild($obj_element);
1846 $objxml = $obj_doc->saveXML($obj_element);
1848 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1849 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1854 * @brief Processes the mail elements
1856 * @param object $xpath XPath object
1857 * @param object $mail mail elements
1858 * @param array $importer Record of the importer user mixed with contact of the content
1860 * @throws \Exception
1861 * @todo Find good type-hints for all parameter
1863 private static function processMail($xpath, $mail, $importer)
1865 Logger::log("Processing mails");
1867 /// @TODO Rewrite this to one statement
1869 $msg["uid"] = $importer["importer_uid"];
1870 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1871 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1872 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1873 $msg["contact-id"] = $importer["id"];
1874 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1875 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1876 $msg["created"] = DateTimeFormat::utc($xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue);
1877 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1878 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1880 $msg["replied"] = 0;
1882 DBA::insert('mail', $msg);
1884 $msg["id"] = DBA::lastInsertId();
1886 // send notifications.
1887 /// @TODO Arange this mess
1889 "type" => NOTIFY_MAIL,
1890 "notify_flags" => $importer["notify-flags"],
1891 "language" => $importer["language"],
1892 "to_name" => $importer["username"],
1893 "to_email" => $importer["email"],
1894 "uid" => $importer["importer_uid"],
1896 "parent" => $msg["parent-uri"],
1897 "source_name" => $msg["from-name"],
1898 "source_link" => $importer["url"],
1899 "source_photo" => $importer["thumb"],
1900 "verb" => ACTIVITY_POST,
1904 notification($notif_params);
1906 Logger::log("Mail is processed, notification was sent.");
1910 * @brief Processes the suggestion elements
1912 * @param object $xpath XPath object
1913 * @param object $suggestion suggestion elements
1914 * @param array $importer Record of the importer user mixed with contact of the content
1916 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1917 * @todo Find good type-hints for all parameter
1919 private static function processSuggestion($xpath, $suggestion, $importer)
1921 Logger::log("Processing suggestions");
1923 /// @TODO Rewrite this to one statement
1925 $suggest["uid"] = $importer["importer_uid"];
1926 $suggest["cid"] = $importer["id"];
1927 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1928 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1929 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1930 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1931 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1933 // Does our member already have a friend matching this description?
1936 * The valid result means the friend we're about to send a friend
1937 * suggestion already has them in their contact, which means no further
1938 * action is required.
1940 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1942 $condition = ['name' => $suggest["name"], 'nurl' => Strings::normaliseLink($suggest["url"]),
1943 'uid' => $suggest["uid"]];
1944 if (DBA::exists('contact', $condition)) {
1948 // Do we already have an fcontact record for this person?
1951 $condition = ['url' => $suggest["url"], 'name' => $suggest["name"], 'request' => $suggest["request"]];
1952 $fcontact = DBA::selectFirst('fcontact', ['id'], $condition);
1953 if (DBA::isResult($fcontact)) {
1954 $fid = $fcontact["id"];
1956 // OK, we do. Do we already have an introduction for this person?
1957 if (DBA::exists('intro', ['uid' => $suggest["uid"], 'fid' => $fid])) {
1959 * The valid result means the friend we're about to send a friend
1960 * suggestion already has them in their contact, which means no further
1961 * action is required.
1963 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1970 "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1971 DBA::escape($suggest["name"]),
1972 DBA::escape($suggest["url"]),
1973 DBA::escape($suggest["photo"]),
1974 DBA::escape($suggest["request"])
1979 $condition = ['url' => $suggest["url"], 'name' => $suggest["name"], 'request' => $suggest["request"]];
1980 $fcontact = DBA::selectFirst('fcontact', ['id'], $condition);
1983 * If no record in fcontact is found, below INSERT statement will not
1984 * link an introduction to it.
1986 if (!DBA::isResult($fcontact)) {
1987 // Database record did not get created. Quietly give up.
1991 $hash = Strings::getRandomHex();
1994 "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1995 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1996 intval($suggest["uid"]),
1998 intval($suggest["cid"]),
1999 DBA::escape($suggest["body"]),
2001 DBA::escape(DateTimeFormat::utcNow()),
2007 "type" => NOTIFY_SUGGEST,
2008 "notify_flags" => $importer["notify-flags"],
2009 "language" => $importer["language"],
2010 "to_name" => $importer["username"],
2011 "to_email" => $importer["email"],
2012 "uid" => $importer["importer_uid"],
2014 "link" => System::baseUrl()."/notifications/intros",
2015 "source_name" => $importer["name"],
2016 "source_link" => $importer["url"],
2017 "source_photo" => $importer["photo"],
2018 "verb" => ACTIVITY_REQ_FRIEND,
2026 * @brief Processes the relocation elements
2028 * @param object $xpath XPath object
2029 * @param object $relocation relocation elements
2030 * @param array $importer Record of the importer user mixed with contact of the content
2032 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2033 * @throws \ImagickException
2034 * @todo Find good type-hints for all parameter
2036 private static function processRelocation($xpath, $relocation, $importer)
2038 Logger::log("Processing relocations");
2040 /// @TODO Rewrite this to one statement
2042 $relocate["uid"] = $importer["importer_uid"];
2043 $relocate["cid"] = $importer["id"];
2044 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
2045 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
2046 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
2047 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
2048 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
2049 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
2050 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
2051 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
2052 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
2053 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
2054 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
2055 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
2057 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
2058 $relocate["avatar"] = $relocate["photo"];
2061 if ($relocate["addr"] == "") {
2062 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
2067 "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d",
2068 intval($importer["id"]),
2069 intval($importer["importer_uid"])
2072 if (!DBA::isResult($r)) {
2073 Logger::log("Query failed to execute, no result returned in " . __FUNCTION__);
2079 // Update the gcontact entry
2080 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
2082 $fields = ['name' => $relocate["name"], 'photo' => $relocate["avatar"],
2083 'url' => $relocate["url"], 'nurl' => Strings::normaliseLink($relocate["url"]),
2084 'addr' => $relocate["addr"], 'connect' => $relocate["addr"],
2085 'notify' => $relocate["notify"], 'server_url' => $relocate["server_url"]];
2086 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($old["url"])]);
2088 // Update the contact table. We try to find every entry.
2089 $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
2090 'url' => $relocate["url"], 'nurl' => Strings::normaliseLink($relocate["url"]),
2091 'addr' => $relocate["addr"], 'request' => $relocate["request"],
2092 'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
2093 'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
2094 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], Strings::normaliseLink($old["url"])];
2096 DBA::update('contact', $fields, $condition);
2098 Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
2100 Logger::log('Contacts are updated.');
2103 /// merge with current record, current contents have priority
2104 /// update record, set url-updated
2105 /// update profile photos
2106 /// schedule a scan?
2111 * @brief Updates an item
2113 * @param array $current the current item record
2114 * @param array $item the new item record
2115 * @param array $importer Record of the importer user mixed with contact of the content
2116 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2118 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2119 * @todo set proper type-hints (array?)
2121 private static function updateContent($current, $item, $importer, $entrytype)
2125 if (self::isEditedTimestampNewer($current, $item)) {
2126 // do not accept (ignore) an earlier edit than one we currently have.
2127 if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
2131 $fields = ['title' => defaults($item, 'title', ''), 'body' => defaults($item, 'body', ''),
2132 'tag' => defaults($item, 'tag', ''), 'changed' => DateTimeFormat::utcNow(),
2133 'edited' => DateTimeFormat::utc($item["edited"])];
2135 $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
2136 Item::update($fields, $condition);
2144 * @brief Detects the entry type of the item
2146 * @param array $importer Record of the importer user mixed with contact of the content
2147 * @param array $item the new item record
2149 * @return int Is it a toplevel entry, a comment or a relayed comment?
2150 * @throws \Exception
2151 * @todo set proper type-hints (array?)
2153 private static function getEntryType($importer, $item)
2155 if ($item["parent-uri"] != $item["uri"]) {
2158 if ($importer["page-flags"] == User::PAGE_FLAGS_COMMUNITY || $importer["page-flags"] == User::PAGE_FLAGS_PRVGROUP) {
2161 Logger::log("possible community action");
2163 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2166 // was the top-level post for this action written by somebody on this site?
2167 // Specifically, the recipient?
2169 $is_a_remote_action = false;
2171 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item["parent-uri"]]);
2172 if (DBA::isResult($parent)) {
2174 "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2175 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2176 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2177 AND `item`.`uid` = %d
2180 DBA::escape($parent["parent-uri"]),
2181 DBA::escape($parent["parent-uri"]),
2182 DBA::escape($parent["parent-uri"]),
2183 intval($importer["importer_uid"])
2185 if (DBA::isResult($r)) {
2186 $is_a_remote_action = true;
2191 * Does this have the characteristics of a community or private group action?
2192 * If it's an action to a wall post on a community/prvgroup page it's a
2193 * valid community action. Also forum_mode makes it valid for sure.
2194 * If neither, it's not.
2196 if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2197 $is_a_remote_action = false;
2198 Logger::log("not a community action");
2201 if ($is_a_remote_action) {
2202 return DFRN::REPLY_RC;
2207 return DFRN::TOP_LEVEL;
2212 * @brief Send a "poke"
2214 * @param array $item the new item record
2215 * @param array $importer Record of the importer user mixed with contact of the content
2216 * @param int $posted_id The record number of item record that was just posted
2218 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2219 * @todo set proper type-hints (array?)
2221 private static function doPoke($item, $importer, $posted_id)
2223 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2227 $xo = XML::parseString($item["object"], false);
2229 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2230 // somebody was poked/prodded. Was it me?
2232 foreach ($xo->link as $l) {
2233 $atts = $l->attributes();
2234 switch ($atts["rel"]) {
2236 $Blink = $atts["href"];
2243 if ($Blink && Strings::compareLink($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2244 $author = DBA::selectFirst('contact', ['name', 'thumb', 'url'], ['id' => $item['author-id']]);
2246 $item['id'] = $posted_id;
2248 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => $importer["importer_uid"]]);
2249 $item["parent"] = $parent['id'];
2251 // send a notification
2254 "type" => NOTIFY_POKE,
2255 "notify_flags" => $importer["notify-flags"],
2256 "language" => $importer["language"],
2257 "to_name" => $importer["username"],
2258 "to_email" => $importer["email"],
2259 "uid" => $importer["importer_uid"],
2261 "link" => System::baseUrl()."/display/".urlencode(Item::getGuidById($posted_id)),
2262 "source_name" => $author["name"],
2263 "source_link" => $author["url"],
2264 "source_photo" => $author["thumb"],
2265 "verb" => $item["verb"],
2266 "otype" => "person",
2267 "activity" => $verb,
2268 "parent" => $item["parent"]]
2275 * @brief Processes several actions, depending on the verb
2277 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2278 * @param array $importer Record of the importer user mixed with contact of the content
2279 * @param array $item the new item record
2280 * @param bool $is_like Is the verb a "like"?
2282 * @return bool Should the processing of the entries be continued?
2283 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2284 * @todo set proper type-hints (array?)
2286 private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2288 Logger::log("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, Logger::DEBUG);
2290 if (($entrytype == DFRN::TOP_LEVEL)) {
2291 // The filling of the the "contact" variable is done for legcy reasons
2292 // The functions below are partly used by ostatus.php as well - where we have this variable
2293 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2295 $nickname = $contact["nick"];
2297 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2298 // This function once was responsible for DFRN and OStatus.
2299 if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2300 Logger::log("New follower");
2301 Contact::addRelationship($importer, $contact, $item, $nickname);
2304 if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2305 Logger::log("Lost follower");
2306 Contact::removeFollower($importer, $contact, $item);
2309 if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2310 Logger::log("New friend request");
2311 Contact::addRelationship($importer, $contact, $item, $nickname, true);
2314 if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2315 Logger::log("Lost sharer");
2316 Contact::removeSharer($importer, $contact, $item);
2320 if (($item["verb"] == ACTIVITY_LIKE)
2321 || ($item["verb"] == ACTIVITY_DISLIKE)
2322 || ($item["verb"] == ACTIVITY_ATTEND)
2323 || ($item["verb"] == ACTIVITY_ATTENDNO)
2324 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
2327 $item["gravity"] = GRAVITY_ACTIVITY;
2328 // only one like or dislike per person
2329 // splitted into two queries for performance issues
2330 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2331 'verb' => $item["verb"], 'parent-uri' => $item["parent-uri"]];
2332 if (Item::exists($condition)) {
2336 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2337 'verb' => $item["verb"], 'thr-parent' => $item["parent-uri"]];
2338 if (Item::exists($condition)) {
2342 // The owner of an activity must be the author
2343 $item["owner-name"] = $item["author-name"];
2344 $item["owner-link"] = $item["author-link"];
2345 $item["owner-avatar"] = $item["author-avatar"];
2346 $item["owner-id"] = $item["author-id"];
2351 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2352 $xo = XML::parseString($item["object"], false);
2353 $xt = XML::parseString($item["target"], false);
2355 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2356 $item_tag = Item::selectFirst(['id', 'tag'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]);
2358 if (!DBA::isResult($item_tag)) {
2359 Logger::log("Query failed to execute, no result returned in " . __FUNCTION__);
2363 // extract tag, if not duplicate, add to parent item
2365 if (!stristr($item_tag["tag"], trim($xo->content))) {
2366 $tag = $item_tag["tag"] . (strlen($item_tag["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2367 Item::update(['tag' => $tag], ['id' => $item_tag["id"]]);
2377 * @brief Processes the link elements
2379 * @param object $links link elements
2380 * @param array $item the item record
2382 * @todo set proper type-hints
2384 private static function parseLinks($links, &$item)
2391 foreach ($links as $link) {
2392 foreach ($link->attributes as $attributes) {
2393 switch ($attributes->name) {
2394 case "href" : $href = $attributes->textContent; break;
2395 case "rel" : $rel = $attributes->textContent; break;
2396 case "type" : $type = $attributes->textContent; break;
2397 case "length": $length = $attributes->textContent; break;
2398 case "title" : $title = $attributes->textContent; break;
2401 if (($rel != "") && ($href != "")) {
2404 $item["plink"] = $href;
2407 if (!empty($item["attach"])) {
2408 $item["attach"] .= ",";
2410 $item["attach"] = "";
2413 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2421 * @brief Processes the entry elements which contain the items and comments
2423 * @param array $header Array of the header elements that always stay the same
2424 * @param object $xpath XPath object
2425 * @param object $entry entry elements
2426 * @param array $importer Record of the importer user mixed with contact of the content
2427 * @param string $xml xml
2429 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2430 * @throws \ImagickException
2431 * @todo Add type-hints
2433 private static function processEntry($header, $xpath, $entry, $importer, $xml)
2435 Logger::log("Processing entries");
2439 $item["protocol"] = Conversation::PARCEL_DFRN;
2441 $item["source"] = $xml;
2444 $item["uri"] = XML::getFirstNodeValue($xpath, "atom:id/text()", $entry);
2446 $item["edited"] = XML::getFirstNodeValue($xpath, "atom:updated/text()", $entry);
2448 $current = Item::selectFirst(['id', 'uid', 'edited', 'body'],
2449 ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
2451 // Is there an existing item?
2452 if (DBA::isResult($current) && !self::isEditedTimestampNewer($current, $item)) {
2453 Logger::log("Item ".$item["uri"]." (".$item['edited'].") already existed.", Logger::DEBUG);
2458 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true, $xml);
2460 $owner_unknown = (isset($owner["contact-unknown"]) && $owner["contact-unknown"]);
2462 $item["owner-name"] = $owner["name"];
2463 $item["owner-link"] = $owner["link"];
2464 $item["owner-avatar"] = $owner["avatar"];
2465 $item["owner-id"] = Contact::getIdForURL($owner["link"], 0);
2468 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true, $xml);
2470 $item["author-name"] = $author["name"];
2471 $item["author-link"] = $author["link"];
2472 $item["author-avatar"] = $author["avatar"];
2473 $item["author-id"] = Contact::getIdForURL($author["link"], 0);
2475 $item["title"] = XML::getFirstNodeValue($xpath, "atom:title/text()", $entry);
2477 $item["created"] = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2479 $item["body"] = XML::getFirstNodeValue($xpath, "dfrn:env/text()", $entry);
2480 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2481 // make sure nobody is trying to sneak some html tags by us
2482 $item["body"] = Strings::escapeTags(Strings::base64UrlDecode($item["body"]));
2484 $item["body"] = BBCode::limitBodySize($item["body"]);
2486 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2487 if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
2488 $base_url = \get_app()->getBaseURL();
2489 $item['body'] = HTML::relToAbs($item['body'], $base_url);
2491 $item['body'] = HTML::toBBCodeVideo($item['body']);
2493 $item['body'] = OEmbed::HTML2BBCode($item['body']);
2495 $config = HTMLPurifier_Config::createDefault();
2496 $config->set('Cache.DefinitionImpl', null);
2498 // we shouldn't need a whitelist, because the bbcode converter
2499 // will strip out any unsupported tags.
2501 $purifier = new HTMLPurifier($config);
2502 $item['body'] = $purifier->purify($item['body']);
2504 $item['body'] = @HTML::toBBCode($item['body']);
2507 /// @todo We should check for a repeated post and if we know the repeated author.
2509 // We don't need the content element since "dfrn:env" is always present
2510 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2512 $item["location"] = XML::getFirstNodeValue($xpath, "dfrn:location/text()", $entry);
2514 $item["coord"] = XML::getFirstNodeValue($xpath, "georss:point", $entry);
2516 $item["private"] = XML::getFirstNodeValue($xpath, "dfrn:private/text()", $entry);
2518 $item["extid"] = XML::getFirstNodeValue($xpath, "dfrn:extid/text()", $entry);
2520 if (XML::getFirstNodeValue($xpath, "dfrn:bookmark/text()", $entry) == "true") {
2521 $item["post-type"] = Item::PT_PAGE;
2524 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2525 if ($notice_info && ($notice_info->length > 0)) {
2526 foreach ($notice_info->item(0)->attributes as $attributes) {
2527 if ($attributes->name == "source") {
2528 $item["app"] = strip_tags($attributes->textContent);
2533 $item["guid"] = XML::getFirstNodeValue($xpath, "dfrn:diaspora_guid/text()", $entry);
2535 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
2536 $dsprsig = XML::unescape(XML::getFirstNodeValue($xpath, "dfrn:diaspora_signature/text()", $entry));
2537 if ($dsprsig != "") {
2538 $item["dsprsig"] = $dsprsig;
2541 $item["verb"] = XML::getFirstNodeValue($xpath, "activity:verb/text()", $entry);
2543 if (XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry) != "") {
2544 $item["object-type"] = XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry);
2547 $object = $xpath->query("activity:object", $entry)->item(0);
2548 $item["object"] = self::transformActivity($xpath, $object, "object");
2550 if (trim($item["object"]) != "") {
2551 $r = XML::parseString($item["object"], false);
2552 if (isset($r->type)) {
2553 $item["object-type"] = $r->type;
2557 $target = $xpath->query("activity:target", $entry)->item(0);
2558 $item["target"] = self::transformActivity($xpath, $target, "target");
2560 $categories = $xpath->query("atom:category", $entry);
2562 foreach ($categories as $category) {
2565 foreach ($category->attributes as $attributes) {
2566 if ($attributes->name == "term") {
2567 $term = $attributes->textContent;
2570 if ($attributes->name == "scheme") {
2571 $scheme = $attributes->textContent;
2575 if (($term != "") && ($scheme != "")) {
2576 $parts = explode(":", $scheme);
2577 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2578 $termhash = array_shift($parts);
2579 $termurl = implode(":", $parts);
2581 if (!empty($item["tag"])) {
2582 $item["tag"] .= ",";
2587 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2593 $links = $xpath->query("atom:link", $entry);
2595 self::parseLinks($links, $item);
2598 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
2600 $conv = $xpath->query('ostatus:conversation', $entry);
2601 if (is_object($conv->item(0))) {
2602 foreach ($conv->item(0)->attributes as $attributes) {
2603 if ($attributes->name == "ref") {
2604 $item['conversation-uri'] = $attributes->textContent;
2606 if ($attributes->name == "href") {
2607 $item['conversation-href'] = $attributes->textContent;
2612 // Is it a reply or a top level posting?
2613 $item["parent-uri"] = $item["uri"];
2615 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2616 if (is_object($inreplyto->item(0))) {
2617 foreach ($inreplyto->item(0)->attributes as $attributes) {
2618 if ($attributes->name == "ref") {
2619 $item["parent-uri"] = $attributes->textContent;
2624 // Get the type of the item (Top level post, reply or remote reply)
2625 $entrytype = self::getEntryType($importer, $item);
2627 // Now assign the rest of the values that depend on the type of the message
2628 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2629 if (!isset($item["object-type"])) {
2630 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2633 if ($item["contact-id"] != $owner["contact-id"]) {
2634 $item["contact-id"] = $owner["contact-id"];
2637 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2638 $item["network"] = $owner["network"];
2641 if ($item["contact-id"] != $author["contact-id"]) {
2642 $item["contact-id"] = $author["contact-id"];
2645 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2646 $item["network"] = $author["network"];
2650 if ($entrytype == DFRN::REPLY_RC) {
2652 } elseif ($entrytype == DFRN::TOP_LEVEL) {
2653 if (!isset($item["object-type"])) {
2654 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2658 if (($item["object-type"] == ACTIVITY_OBJ_EVENT) && !$owner_unknown) {
2659 Logger::log("Item ".$item["uri"]." seems to contain an event.", Logger::DEBUG);
2660 $ev = Event::fromBBCode($item["body"]);
2661 if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
2662 Logger::log("Event in item ".$item["uri"]." was found.", Logger::DEBUG);
2663 $ev["cid"] = $importer["id"];
2664 $ev["uid"] = $importer["importer_uid"];
2665 $ev["uri"] = $item["uri"];
2666 $ev["edited"] = $item["edited"];
2667 $ev["private"] = $item["private"];
2668 $ev["guid"] = $item["guid"];
2669 $ev["plink"] = $item["plink"];
2671 $condition = ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]];
2672 $event = DBA::selectFirst('event', ['id'], $condition);
2673 if (DBA::isResult($event)) {
2674 $ev["id"] = $event["id"];
2677 $event_id = Event::store($ev);
2678 Logger::log("Event ".$event_id." was stored", Logger::DEBUG);
2684 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2685 Logger::log("Exiting because 'processVerbs' told us so", Logger::DEBUG);
2689 // This check is done here to be able to receive connection requests in "processVerbs"
2690 if (($entrytype == DFRN::TOP_LEVEL) && $owner_unknown) {
2691 Logger::log("Item won't be stored because user " . $importer["importer_uid"] . " doesn't follow " . $item["owner-link"] . ".", Logger::DEBUG);
2696 // Update content if 'updated' changes
2697 if (DBA::isResult($current)) {
2698 if (self::updateContent($current, $item, $importer, $entrytype)) {
2699 Logger::log("Item ".$item["uri"]." was updated.", Logger::DEBUG);
2701 Logger::log("Item " . $item["uri"] . " already existed.", Logger::DEBUG);
2706 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2707 $posted_id = Item::insert($item);
2709 Logger::log("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, Logger::DEBUG);
2711 if ($item['uid'] == 0) {
2712 Item::distribute($posted_id);
2717 } else { // $entrytype == DFRN::TOP_LEVEL
2718 if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
2719 Logger::log("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", Logger::DEBUG);
2722 if (!Strings::compareLink($item["owner-link"], $importer["url"])) {
2724 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2725 * but otherwise there's a possible data mixup on the sender's system.
2726 * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2727 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2729 Logger::log('Correcting item owner.', Logger::DEBUG);
2730 $item["owner-link"] = $importer["url"];
2731 $item["owner-id"] = Contact::getIdForURL($importer["url"], 0);
2734 if (($importer["rel"] == Contact::FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2735 Logger::log("Contact ".$importer["id"]." is only follower and tgroup check was negative.", Logger::DEBUG);
2739 // This is my contact on another system, but it's really me.
2740 // Turn this into a wall post.
2741 $notify = Item::isRemoteSelf($importer, $item);
2743 $posted_id = Item::insert($item, false, $notify);
2746 $posted_id = $notify;
2749 Logger::log("Item was stored with id ".$posted_id, Logger::DEBUG);
2751 if ($item['uid'] == 0) {
2752 Item::distribute($posted_id);
2755 if (stristr($item["verb"], ACTIVITY_POKE)) {
2756 self::doPoke($item, $importer, $posted_id);
2762 * @brief Deletes items
2764 * @param object $xpath XPath object
2765 * @param object $deletion deletion elements
2766 * @param array $importer Record of the importer user mixed with contact of the content
2768 * @throws \Exception
2769 * @todo set proper type-hints
2771 private static function processDeletion($xpath, $deletion, $importer)
2773 Logger::log("Processing deletions");
2776 foreach ($deletion->attributes as $attributes) {
2777 if ($attributes->name == "ref") {
2778 $uri = $attributes->textContent;
2782 if (!$uri || !$importer["id"]) {
2786 $condition = ['uri' => $uri, 'uid' => $importer["importer_uid"]];
2787 $item = Item::selectFirst(['id', 'parent', 'contact-id', 'file', 'deleted'], $condition);
2788 if (!DBA::isResult($item)) {
2789 Logger::log("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", Logger::DEBUG);
2793 if (strstr($item['file'], '[')) {
2794 Logger::log("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " is filed. So it won't be deleted.", Logger::DEBUG);
2798 // When it is a starting post it has to belong to the person that wants to delete it
2799 if (($item['id'] == $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2800 Logger::log("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", Logger::DEBUG);
2804 // Comments can be deleted by the thread owner or comment owner
2805 if (($item['id'] != $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2806 $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2807 if (!Item::exists($condition)) {
2808 Logger::log("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", Logger::DEBUG);
2813 if ($item["deleted"]) {
2817 Logger::log('deleting item '.$item['id'].' uri='.$uri, Logger::DEBUG);
2819 Item::delete(['id' => $item['id']]);
2823 * @brief Imports a DFRN message
2825 * @param string $xml The DFRN message
2826 * @param array $importer Record of the importer user mixed with contact of the content
2827 * @param bool $sort_by_date Is used when feeds are polled
2828 * @return integer Import status
2829 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2830 * @throws \ImagickException
2831 * @todo set proper type-hints
2833 public static function import($xml, $importer, $sort_by_date = false)
2839 $doc = new DOMDocument();
2840 @$doc->loadXML($xml);
2842 $xpath = new DOMXPath($doc);
2843 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2844 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2845 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2846 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2847 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2848 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2849 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2850 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2851 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2852 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2855 $header["uid"] = $importer["importer_uid"];
2856 $header["network"] = Protocol::DFRN;
2857 $header["wall"] = 0;
2858 $header["origin"] = 0;
2859 $header["contact-id"] = $importer["id"];
2861 // Update the contact table if the data has changed
2863 // The "atom:author" is only present in feeds
2864 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2865 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2868 // Only the "dfrn:owner" in the head section contains all data
2869 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2870 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2873 Logger::log("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], Logger::DEBUG);
2875 // is it a public forum? Private forums aren't exposed with this method
2876 $forum = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:community/text()"));
2878 // The account type is new since 3.5.1
2879 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2880 // Hint: We are using separate update calls for uid=0 and uid!=0 since a combined call is bad for the database performance
2882 $accounttype = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:account_type/text()"));
2884 if ($accounttype != $importer["contact-type"]) {
2885 DBA::update('contact', ['contact-type' => $accounttype], ['id' => $importer['id']]);
2887 // Updating the public contact as well
2888 DBA::update('contact', ['contact-type' => $accounttype], ['uid' => 0, 'nurl' => $importer['nurl']]);
2890 // A forum contact can either have set "forum" or "prv" - but not both
2891 if ($accounttype == User::ACCOUNT_TYPE_COMMUNITY) {
2892 // It's a forum, so either set the public or private forum flag
2893 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer['id']];
2894 DBA::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2896 // Updating the public contact as well
2897 $condition = ['(`forum` != ? OR `prv` != ?) AND `uid` = 0 AND `nurl` = ?', $forum, !$forum, $importer['nurl']];
2898 DBA::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2900 // It's not a forum, so remove the flags
2901 $condition = ['(`forum` OR `prv`) AND `id` = ?', $importer['id']];
2902 DBA::update('contact', ['forum' => false, 'prv' => false], $condition);
2904 // Updating the public contact as well
2905 $condition = ['(`forum` OR `prv`) AND `uid` = 0 AND `nurl` = ?', $importer['nurl']];
2906 DBA::update('contact', ['forum' => false, 'prv' => false], $condition);
2908 } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
2909 $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2910 DBA::update('contact', ['forum' => $forum], $condition);
2912 // Updating the public contact as well
2913 $condition = ['`forum` != ? AND `uid` = 0 AND `nurl` = ?', $forum, $importer['nurl']];
2914 DBA::update('contact', ['forum' => $forum], $condition);
2918 // We are processing relocations even if we are ignoring a contact
2919 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2920 foreach ($relocations as $relocation) {
2921 self::processRelocation($xpath, $relocation, $importer);
2924 if (($importer["uid"] != 0) && !$importer["readonly"]) {
2925 $mails = $xpath->query("/atom:feed/dfrn:mail");
2926 foreach ($mails as $mail) {
2927 self::processMail($xpath, $mail, $importer);
2930 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2931 foreach ($suggestions as $suggestion) {
2932 self::processSuggestion($xpath, $suggestion, $importer);
2936 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2937 foreach ($deletions as $deletion) {
2938 self::processDeletion($xpath, $deletion, $importer);
2941 if (!$sort_by_date) {
2942 $entries = $xpath->query("/atom:feed/atom:entry");
2943 foreach ($entries as $entry) {
2944 self::processEntry($header, $xpath, $entry, $importer, $xml);
2948 $entries = $xpath->query("/atom:feed/atom:entry");
2949 foreach ($entries as $entry) {
2950 $created = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2951 $newentries[strtotime($created)] = $entry;
2954 // Now sort after the publishing date
2957 foreach ($newentries as $entry) {
2958 self::processEntry($header, $xpath, $entry, $importer, $xml);
2961 Logger::log("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], Logger::DEBUG);
2967 * @param string $contact_nick contact nickname
2968 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2970 public static function autoRedir(App $a, $contact_nick)
2973 if (!empty($_REQUEST['redir'])) {
2977 if ((! $contact_nick) || ($contact_nick === $a->user['nickname'])) {
2982 // We need to find out if $contact_nick is a user on this hub, and if so, if I
2983 // am a contact of that user. However, that user may have other contacts with the
2984 // same nickname as me on other hubs or other networks. Exclude these by requiring
2985 // that the contact have a local URL. I will be the only person with my nickname at
2986 // this URL, so if a result is found, then I am a contact of the $contact_nick user.
2988 // We also have to make sure that I'm a legitimate contact--I'm not blocked or pending.
2990 $baseurl = System::baseUrl();
2991 $domain_st = strpos($baseurl, "://");
2992 if ($domain_st === false) {
2995 $baseurl = substr($baseurl, $domain_st + 3);
2996 $nurl = Strings::normaliseLink($baseurl);
2998 /// @todo Why is there a query for "url" *and* "nurl"? Especially this normalising is strange.
2999 $r = q("SELECT `id` FROM `contact` WHERE `uid` = (SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1)
3000 AND `nick` = '%s' AND NOT `self` AND (`url` LIKE '%%%s%%' OR `nurl` LIKE '%%%s%%') AND NOT `blocked` AND NOT `pending` LIMIT 1",
3001 DBA::escape($contact_nick),
3002 DBA::escape($a->user['nickname']),
3003 DBA::escape($baseurl),
3006 if ((! DBA::isResult($r)) || $r[0]['id'] == remote_user()) {
3010 $r = q("SELECT * FROM contact WHERE nick = '%s'
3011 AND network = '%s' AND uid = %d AND url LIKE '%%%s%%' LIMIT 1",
3012 DBA::escape($contact_nick),
3013 DBA::escape(Protocol::DFRN),
3014 intval(local_user()),
3015 DBA::escape($baseurl)
3017 if (! DBA::isResult($r)) {
3023 $dfrn_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
3025 if ($r[0]['duplex'] && $r[0]['issued-id']) {
3026 $orig_id = $r[0]['issued-id'];
3027 $dfrn_id = '1:' . $orig_id;
3029 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
3030 $orig_id = $r[0]['dfrn-id'];
3031 $dfrn_id = '0:' . $orig_id;
3034 // ensure that we've got a valid ID. There may be some edge cases with forums and non-duplex mode
3035 // that may have triggered some of the "went to {profile/intro} and got an RSS feed" issues
3037 if (strlen($dfrn_id) < 3) {
3041 $sec = Strings::getRandomHex();
3043 DBA::insert('profile_check', ['uid' => local_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id, 'sec' => $sec, 'expire' => time() + 45]);
3045 $url = curPageURL();
3047 Logger::log('auto_redir: ' . $r[0]['name'] . ' ' . $sec, Logger::DEBUG);
3048 $dest = (($url) ? '&destination_url=' . $url : '');
3049 System::externalRedirect($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
3050 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest);
3057 * @brief Returns the activity verb
3059 * @param array $item Item array
3061 * @return string activity verb
3063 private static function constructVerb(array $item)
3065 if ($item['verb']) {
3066 return $item['verb'];
3068 return ACTIVITY_POST;
3071 private static function tgroupCheck($uid, $item)
3075 // check that the message originated elsewhere and is a top-level post
3077 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['parent-uri'])) {
3081 $user = DBA::selectFirst('user', ['page-flags', 'nickname'], ['uid' => $uid]);
3082 if (!DBA::isResult($user)) {
3086 $community_page = ($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY);
3087 $prvgroup = ($user['page-flags'] == User::PAGE_FLAGS_PRVGROUP);
3089 $link = Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']);
3092 * Diaspora uses their own hardwired link URL in @-tags
3093 * instead of the one we supply with webfinger
3095 $dlink = Strings::normaliseLink(System::baseUrl() . '/u/' . $user['nickname']);
3097 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
3099 foreach ($matches as $mtch) {
3100 if (Strings::compareLink($link, $mtch[1]) || Strings::compareLink($dlink, $mtch[1])) {
3102 Logger::log('mention found: ' . $mtch[2]);
3111 return $community_page || $prvgroup;
3115 * This function returns true if $update has an edited timestamp newer
3116 * than $existing, i.e. $update contains new data which should override
3117 * what's already there. If there is no timestamp yet, the update is
3118 * assumed to be newer. If the update has no timestamp, the existing
3119 * item is assumed to be up-to-date. If the timestamps are equal it
3120 * assumes the update has been seen before and should be ignored.
3125 * @throws \Exception
3127 private static function isEditedTimestampNewer($existing, $update)
3129 if (empty($existing['edited'])) {
3132 if (empty($update['edited'])) {
3136 $existing_edited = DateTimeFormat::utc($existing['edited']);
3137 $update_edited = DateTimeFormat::utc($update['edited']);
3139 return (strcmp($existing_edited, $update_edited) < 0);