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\BaseURL;
33 use Friendica\Util\Crypto;
34 use Friendica\Util\DateTimeFormat;
35 use Friendica\Util\Network;
36 use Friendica\Util\Strings;
37 use Friendica\Util\XML;
39 use HTMLPurifier_Config;
42 * @brief This class contain functions to create and send DFRN XML files
47 const TOP_LEVEL = 0; // Top level posting
48 const REPLY = 1; // Regular reply that is stored locally
49 const REPLY_RC = 2; // Reply that will be relayed
52 * @brief Generates an array of contact and user for DFRN imports
54 * This array contains not only the receiver but also the sender of the message.
56 * @param integer $cid Contact id
57 * @param integer $uid User id
59 * @return array importer
62 public static function getImporter($cid, $uid = 0)
64 $condition = ['id' => $cid, 'blocked' => false, 'pending' => false];
65 $contact = DBA::selectFirst('contact', [], $condition);
66 if (!DBA::isResult($contact)) {
70 $contact['cpubkey'] = $contact['pubkey'];
71 $contact['cprvkey'] = $contact['prvkey'];
72 $contact['senderName'] = $contact['name'];
75 $condition = ['uid' => $uid, 'account_expired' => false, 'account_removed' => false];
76 $user = DBA::selectFirst('user', [], $condition);
77 if (!DBA::isResult($user)) {
81 $user['importer_uid'] = $user['uid'];
82 $user['uprvkey'] = $user['prvkey'];
84 $user = ['importer_uid' => 0, 'uprvkey' => '', 'timezone' => 'UTC',
85 'nickname' => '', 'sprvkey' => '', 'spubkey' => '',
86 'page-flags' => 0, 'account-type' => 0, 'prvnets' => 0];
89 return array_merge($contact, $user);
93 * @brief Generates the atom entries for delivery.php
95 * This function is used whenever content is transmitted via DFRN.
97 * @param array $items Item elements
98 * @param array $owner Owner record
100 * @return string DFRN entries
101 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
102 * @throws \ImagickException
103 * @todo Find proper type-hints
105 public static function entries($items, $owner)
107 $doc = new DOMDocument('1.0', 'utf-8');
108 $doc->formatOutput = true;
110 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
112 if (! count($items)) {
113 return trim($doc->saveXML());
116 foreach ($items as $item) {
117 // These values aren't sent when sending from the queue.
118 /// @todo Check if we can set these values from the queue or if they are needed at all.
119 $item["entry:comment-allow"] = defaults($item, "entry:comment-allow", true);
120 $item["entry:cid"] = defaults($item, "entry:cid", 0);
122 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
124 $root->appendChild($entry);
128 return trim($doc->saveXML());
132 * @brief Generate an atom feed for the given user
134 * This function is called when another server is pulling data from the user feed.
136 * @param string $dfrn_id DFRN ID from the requesting party
137 * @param string $owner_nick Owner nick name
138 * @param string $last_update Date of the last update
139 * @param int $direction Can be -1, 0 or 1.
140 * @param boolean $onlyheader Output only the header without content? (Default is "no")
142 * @return string DFRN feed entries
143 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
144 * @throws \ImagickException
146 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false)
150 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
151 $public_feed = (($dfrn_id) ? false : true);
152 $starred = false; // not yet implemented, possible security issues
155 if ($public_feed && $a->argc > 2) {
156 for ($x = 2; $x < $a->argc; $x++) {
157 if ($a->argv[$x] == 'converse') {
160 if ($a->argv[$x] == 'starred') {
163 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
164 $category = $a->argv[$x+1];
169 // default permissions - anonymous user
171 $sql_extra = " AND NOT `item`.`private` ";
174 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
175 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
176 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
177 DBA::escape($owner_nick)
180 if (! DBA::isResult($r)) {
181 Logger::log(sprintf('No contact found for nickname=%d', $owner_nick), Logger::WARNING);
186 $owner_id = $owner['uid'];
188 $sql_post_table = "";
190 if (! $public_feed) {
191 switch ($direction) {
193 $sql_extra = sprintf(" AND `issued-id` = '%s' ", DBA::escape($dfrn_id));
196 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
199 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
207 "SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
211 if (! DBA::isResult($r)) {
212 Logger::log(sprintf('No contact found for uid=%d', $owner_id), Logger::WARNING);
218 $set = PermissionSet::get($owner_id, $contact['id']);
221 $sql_extra = " AND `item`.`psid` IN (" . implode(',', $set) .")";
223 $sql_extra = " AND NOT `item`.`private`";
233 if (! strlen($last_update)) {
234 $last_update = 'now -30 days';
237 if (isset($category)) {
238 $sql_post_table = sprintf(
239 "INNER JOIN (SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d ORDER BY `tid` DESC) AS `term` ON `item`.`id` = `term`.`oid` ",
240 DBA::escape(Strings::protectSprintf($category)),
241 intval(TERM_OBJ_POST),
242 intval(TERM_CATEGORY),
247 if ($public_feed && ! $converse) {
248 $sql_extra .= " AND `contact`.`self` = 1 ";
251 $check_date = DateTimeFormat::utc($last_update);
255 FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
256 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
257 WHERE `item`.`uid` = %d AND `item`.`wall` AND `item`.`changed` > '%s'
258 AND `item`.`visible` $sql_extra
259 ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
261 DBA::escape($check_date),
266 foreach ($r as $item) {
267 $ids[] = $item['id'];
271 $ret = Item::select(Item::DELIVER_FIELDLIST, ['id' => $ids]);
272 $items = Item::inArray($ret);
278 * Will check further below if this actually returned results.
279 * We will provide an empty feed if that is the case.
282 $doc = new DOMDocument('1.0', 'utf-8');
283 $doc->formatOutput = true;
285 $alternatelink = $owner['url'];
287 if (isset($category)) {
288 $alternatelink .= "/category/".$category;
292 $author = "dfrn:owner";
297 $root = self::addHeader($doc, $owner, $author, $alternatelink, true);
299 /// @TODO This hook can't work anymore
300 // \Friendica\Core\Hook::callAll('atom_feed', $atom);
302 if (!DBA::isResult($items) || $onlyheader) {
303 $atom = trim($doc->saveXML());
305 Hook::callAll('atom_feed_end', $atom);
310 foreach ($items as $item) {
311 // prevent private email from leaking.
312 if ($item['network'] == Protocol::MAIL) {
316 // public feeds get html, our own nodes use bbcode
320 // catch any email that's in a public conversation and make sure it doesn't leak
321 if ($item['private']) {
328 $entry = self::entry($doc, $type, $item, $owner, true);
330 $root->appendChild($entry);
334 $atom = trim($doc->saveXML());
336 Hook::callAll('atom_feed_end', $atom);
342 * @brief Generate an atom entry for a given item id
344 * @param int $item_id The item id
345 * @param boolean $conversation Show the conversation. If false show the single post.
347 * @return string DFRN feed entry
348 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
349 * @throws \ImagickException
351 public static function itemFeed($item_id, $conversation = false)
354 $condition = ['parent' => $item_id];
356 $condition = ['id' => $item_id];
359 $ret = Item::select(Item::DELIVER_FIELDLIST, $condition);
360 $items = Item::inArray($ret);
361 if (!DBA::isResult($items)) {
367 if ($item['uid'] != 0) {
368 $owner = User::getOwnerDataById($item['uid']);
373 $owner = ['uid' => 0, 'nick' => 'feed-item'];
376 $doc = new DOMDocument('1.0', 'utf-8');
377 $doc->formatOutput = true;
381 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
382 $doc->appendChild($root);
384 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
385 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
386 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
387 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
388 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
389 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
390 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
391 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
392 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
394 //$root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
396 foreach ($items as $item) {
397 $entry = self::entry($doc, $type, $item, $owner, true, 0);
399 $root->appendChild($entry);
403 $root = self::entry($doc, $type, $item, $owner, true, 0, true);
406 $atom = trim($doc->saveXML());
411 * @brief Create XML text for DFRN mails
413 * @param array $item message elements
414 * @param array $owner Owner record
416 * @return string DFRN mail
417 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
418 * @todo Find proper type-hints
420 public static function mail($item, $owner)
422 $doc = new DOMDocument('1.0', 'utf-8');
423 $doc->formatOutput = true;
425 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
427 $mail = $doc->createElement("dfrn:mail");
428 $sender = $doc->createElement("dfrn:sender");
430 XML::addElement($doc, $sender, "dfrn:name", $owner['name']);
431 XML::addElement($doc, $sender, "dfrn:uri", $owner['url']);
432 XML::addElement($doc, $sender, "dfrn:avatar", $owner['thumb']);
434 $mail->appendChild($sender);
436 XML::addElement($doc, $mail, "dfrn:id", $item['uri']);
437 XML::addElement($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
438 XML::addElement($doc, $mail, "dfrn:sentdate", DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
439 XML::addElement($doc, $mail, "dfrn:subject", $item['title']);
440 XML::addElement($doc, $mail, "dfrn:content", $item['body']);
442 $root->appendChild($mail);
444 return trim($doc->saveXML());
448 * @brief Create XML text for DFRN friend suggestions
450 * @param array $item suggestion elements
451 * @param array $owner Owner record
453 * @return string DFRN suggestions
454 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
455 * @todo Find proper type-hints
457 public static function fsuggest($item, $owner)
459 $doc = new DOMDocument('1.0', 'utf-8');
460 $doc->formatOutput = true;
462 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
464 $suggest = $doc->createElement("dfrn:suggest");
466 XML::addElement($doc, $suggest, "dfrn:url", $item['url']);
467 XML::addElement($doc, $suggest, "dfrn:name", $item['name']);
468 XML::addElement($doc, $suggest, "dfrn:photo", $item['photo']);
469 XML::addElement($doc, $suggest, "dfrn:request", $item['request']);
470 XML::addElement($doc, $suggest, "dfrn:note", $item['note']);
472 $root->appendChild($suggest);
474 return trim($doc->saveXML());
478 * @brief Create XML text for DFRN relocations
480 * @param array $owner Owner record
481 * @param int $uid User ID
483 * @return string DFRN relocations
484 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
485 * @todo Find proper type-hints
487 public static function relocate($owner, $uid)
490 /* get site pubkey. this could be a new installation with no site keys*/
491 $pubkey = Config::get('system', 'site_pubkey');
493 $res = Crypto::newKeypair(1024);
494 Config::set('system', 'site_prvkey', $res['prvkey']);
495 Config::set('system', 'site_pubkey', $res['pubkey']);
499 "SELECT `resource-id` , `scale`, type FROM `photo`
500 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;",
504 $ext = Image::supportedTypes();
506 foreach ($rp as $p) {
507 $photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
511 $doc = new DOMDocument('1.0', 'utf-8');
512 $doc->formatOutput = true;
514 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
516 $relocate = $doc->createElement("dfrn:relocate");
518 XML::addElement($doc, $relocate, "dfrn:url", $owner['url']);
519 XML::addElement($doc, $relocate, "dfrn:name", $owner['name']);
520 XML::addElement($doc, $relocate, "dfrn:addr", $owner['addr']);
521 XML::addElement($doc, $relocate, "dfrn:avatar", $owner['avatar']);
522 XML::addElement($doc, $relocate, "dfrn:photo", $photos[4]);
523 XML::addElement($doc, $relocate, "dfrn:thumb", $photos[5]);
524 XML::addElement($doc, $relocate, "dfrn:micro", $photos[6]);
525 XML::addElement($doc, $relocate, "dfrn:request", $owner['request']);
526 XML::addElement($doc, $relocate, "dfrn:confirm", $owner['confirm']);
527 XML::addElement($doc, $relocate, "dfrn:notify", $owner['notify']);
528 XML::addElement($doc, $relocate, "dfrn:poll", $owner['poll']);
529 XML::addElement($doc, $relocate, "dfrn:sitepubkey", Config::get('system', 'site_pubkey'));
531 $root->appendChild($relocate);
533 return trim($doc->saveXML());
537 * @brief Adds the header elements for the DFRN protocol
539 * @param DOMDocument $doc XML document
540 * @param array $owner Owner record
541 * @param string $authorelement Element name for the author
542 * @param string $alternatelink link to profile or category
543 * @param bool $public Is it a header for public posts?
545 * @return object XML root object
546 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
547 * @todo Find proper type-hints
549 private static function addHeader(DOMDocument $doc, $owner, $authorelement, $alternatelink = "", $public = false)
552 if ($alternatelink == "") {
553 $alternatelink = $owner['url'];
556 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
557 $doc->appendChild($root);
559 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
560 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
561 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
562 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
563 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
564 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
565 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
566 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
567 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
569 XML::addElement($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
570 XML::addElement($doc, $root, "title", $owner["name"]);
572 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION];
573 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
575 $attributes = ["rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/"];
576 XML::addElement($doc, $root, "link", "", $attributes);
578 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $alternatelink];
579 XML::addElement($doc, $root, "link", "", $attributes);
583 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
584 OStatus::hublinks($doc, $root, $owner["nick"]);
586 $attributes = ["rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
587 XML::addElement($doc, $root, "link", "", $attributes);
589 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
590 XML::addElement($doc, $root, "link", "", $attributes);
592 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
593 XML::addElement($doc, $root, "link", "", $attributes);
596 // For backward compatibility we keep this element
597 if ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY) {
598 XML::addElement($doc, $root, "dfrn:community", 1);
601 // The former element is replaced by this one
602 XML::addElement($doc, $root, "dfrn:account_type", $owner["account-type"]);
604 /// @todo We need a way to transmit the different page flags like "User::PAGE_FLAGS_PRVGROUP"
606 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
608 $author = self::addAuthor($doc, $owner, $authorelement, $public);
609 $root->appendChild($author);
615 * @brief Adds the author element in the header for the DFRN protocol
617 * @param DOMDocument $doc XML document
618 * @param array $owner Owner record
619 * @param string $authorelement Element name for the author
620 * @param boolean $public boolean
622 * @return \DOMElement XML author object
623 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
624 * @todo Find proper type-hints
626 private static function addAuthor(DOMDocument $doc, array $owner, $authorelement, $public)
628 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
630 "SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
631 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
632 intval($owner['uid'])
634 if (DBA::isResult($r)) {
640 $author = $doc->createElement($authorelement);
642 $namdate = DateTimeFormat::utc($owner['name-date'].'+00:00', DateTimeFormat::ATOM);
643 $uridate = DateTimeFormat::utc($owner['uri-date'].'+00:00', DateTimeFormat::ATOM);
644 $picdate = DateTimeFormat::utc($owner['avatar-date'].'+00:00', DateTimeFormat::ATOM);
648 if (!$public || !$hidewall) {
649 $attributes = ["dfrn:updated" => $namdate];
652 XML::addElement($doc, $author, "name", $owner["name"], $attributes);
653 XML::addElement($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
654 XML::addElement($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
656 $attributes = ["rel" => "photo", "type" => "image/jpeg",
657 "media:width" => 300, "media:height" => 300, "href" => $owner['photo']];
659 if (!$public || !$hidewall) {
660 $attributes["dfrn:updated"] = $picdate;
663 XML::addElement($doc, $author, "link", "", $attributes);
665 $attributes["rel"] = "avatar";
666 XML::addElement($doc, $author, "link", "", $attributes);
669 XML::addElement($doc, $author, "dfrn:hide", "true");
672 // The following fields will only be generated if the data isn't meant for a public feed
677 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
680 XML::addElement($doc, $author, "dfrn:birthday", $birthday);
683 // Only show contact details when we are allowed to
685 "SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
686 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
687 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
689 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
690 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
691 intval($owner['uid'])
693 if (DBA::isResult($r)) {
696 XML::addElement($doc, $author, "poco:displayName", $profile["name"]);
697 XML::addElement($doc, $author, "poco:updated", $namdate);
699 if (trim($profile["dob"]) > DBA::NULL_DATE) {
700 XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
703 XML::addElement($doc, $author, "poco:note", $profile["about"]);
704 XML::addElement($doc, $author, "poco:preferredUsername", $profile["nickname"]);
706 $savetz = date_default_timezone_get();
707 date_default_timezone_set($profile["timezone"]);
708 XML::addElement($doc, $author, "poco:utcOffset", date("P"));
709 date_default_timezone_set($savetz);
711 if (trim($profile["homepage"]) != "") {
712 $urls = $doc->createElement("poco:urls");
713 XML::addElement($doc, $urls, "poco:type", "homepage");
714 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
715 XML::addElement($doc, $urls, "poco:primary", "true");
716 $author->appendChild($urls);
719 if (trim($profile["pub_keywords"]) != "") {
720 $keywords = explode(",", $profile["pub_keywords"]);
722 foreach ($keywords as $keyword) {
723 XML::addElement($doc, $author, "poco:tags", trim($keyword));
727 if (trim($profile["xmpp"]) != "") {
728 $ims = $doc->createElement("poco:ims");
729 XML::addElement($doc, $ims, "poco:type", "xmpp");
730 XML::addElement($doc, $ims, "poco:value", $profile["xmpp"]);
731 XML::addElement($doc, $ims, "poco:primary", "true");
732 $author->appendChild($ims);
735 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
736 $element = $doc->createElement("poco:address");
738 XML::addElement($doc, $element, "poco:formatted", Profile::formatLocation($profile));
740 if (trim($profile["locality"]) != "") {
741 XML::addElement($doc, $element, "poco:locality", $profile["locality"]);
744 if (trim($profile["region"]) != "") {
745 XML::addElement($doc, $element, "poco:region", $profile["region"]);
748 if (trim($profile["country-name"]) != "") {
749 XML::addElement($doc, $element, "poco:country", $profile["country-name"]);
752 $author->appendChild($element);
760 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
762 * @param DOMDocument $doc XML document
763 * @param string $element Element name for the author
764 * @param string $contact_url Link of the contact
765 * @param array $item Item elements
767 * @return \DOMElement XML author object
768 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
769 * @todo Find proper type-hints
771 private static function addEntryAuthor(DOMDocument $doc, $element, $contact_url, $item)
773 $author = $doc->createElement($element);
775 $contact = Contact::getDetailsByURL($contact_url, $item["uid"]);
776 if (!empty($contact)) {
777 XML::addElement($doc, $author, "name", $contact["name"]);
778 XML::addElement($doc, $author, "uri", $contact["url"]);
779 XML::addElement($doc, $author, "dfrn:handle", $contact["addr"]);
782 /// - Check real image type and image size
783 /// - Check which of these boths elements we should use
786 "type" => "image/jpeg",
788 "media:height" => 80,
789 "href" => $contact["photo"]];
790 XML::addElement($doc, $author, "link", "", $attributes);
794 "type" => "image/jpeg",
796 "media:height" => 80,
797 "href" => $contact["photo"]];
798 XML::addElement($doc, $author, "link", "", $attributes);
805 * @brief Adds the activity elements
807 * @param DOMDocument $doc XML document
808 * @param string $element Element name for the activity
809 * @param string $activity activity value
811 * @return \DOMElement XML activity object
812 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
813 * @todo Find proper type-hints
815 private static function createActivity(DOMDocument $doc, $element, $activity)
818 $entry = $doc->createElement($element);
820 $r = XML::parseString($activity, false);
826 XML::addElement($doc, $entry, "activity:object-type", $r->type);
830 XML::addElement($doc, $entry, "id", $r->id);
834 XML::addElement($doc, $entry, "title", $r->title);
838 if (substr($r->link, 0, 1) == '<') {
839 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
840 $r->link = str_replace('&', '&', $r->link);
843 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
845 // XML does need a single element as root element so we add a dummy element here
846 $data = XML::parseString("<dummy>" . $r->link . "</dummy>", false);
847 if (is_object($data)) {
848 foreach ($data->link as $link) {
850 foreach ($link->attributes() as $parameter => $value) {
851 $attributes[$parameter] = $value;
853 XML::addElement($doc, $entry, "link", "", $attributes);
857 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
858 XML::addElement($doc, $entry, "link", "", $attributes);
862 XML::addElement($doc, $entry, "content", BBCode::convert($r->content), ["type" => "html"]);
872 * @brief Adds the elements for attachments
874 * @param object $doc XML document
875 * @param object $root XML root
876 * @param array $item Item element
878 * @return void XML attachment object
879 * @todo Find proper type-hints
881 private static function getAttachment($doc, $root, $item)
883 $arr = explode('[/attach],', $item['attach']);
885 foreach ($arr as $r) {
887 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
889 $attributes = ["rel" => "enclosure",
890 "href" => $matches[1],
891 "type" => $matches[3]];
893 if (intval($matches[2])) {
894 $attributes["length"] = intval($matches[2]);
897 if (trim($matches[4]) != "") {
898 $attributes["title"] = trim($matches[4]);
901 XML::addElement($doc, $root, "link", "", $attributes);
908 * @brief Adds the "entry" elements for the DFRN protocol
910 * @param DOMDocument $doc XML document
911 * @param string $type "text" or "html"
912 * @param array $item Item element
913 * @param array $owner Owner record
914 * @param bool $comment Trigger the sending of the "comment" element
915 * @param int $cid Contact ID of the recipient
916 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
918 * @return null|\DOMElement XML entry object
919 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
920 * @throws \ImagickException
921 * @todo Find proper type-hints
923 private static function entry(DOMDocument $doc, $type, array $item, array $owner, $comment = false, $cid = 0, $single = false)
927 if (!$item['parent']) {
928 Logger::notice('Item without parent found.', ['type' => $type, 'item' => $item]);
932 if ($item['deleted']) {
933 $attributes = ["ref" => $item['uri'], "when" => DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM)];
934 return XML::createElement($doc, "at:deleted-entry", "", $attributes);
938 $entry = $doc->createElement("entry");
940 $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry');
941 $doc->appendChild($entry);
943 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
944 $entry->setAttribute("xmlns:at", NAMESPACE_TOMB);
945 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
946 $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
947 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
948 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
949 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
950 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
951 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
954 if ($item['private']) {
955 $body = Item::fixPrivatePhotos($item['body'], $owner['uid'], $item, $cid);
957 $body = $item['body'];
960 // Remove the abstract element. It is only locally important.
961 $body = BBCode::stripAbstract($body);
964 if ($type == 'html') {
967 if ($item['title'] != "") {
968 $htmlbody = "[b]" . $item['title'] . "[/b]\n\n" . $htmlbody;
971 $htmlbody = BBCode::convert($htmlbody, false, 7);
974 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
975 $entry->appendChild($author);
977 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
978 $entry->appendChild($dfrnowner);
980 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
981 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
982 $parent = Item::selectFirst(['guid', 'plink'], ['uri' => $parent_item, 'uid' => $item['uid']]);
983 $attributes = ["ref" => $parent_item, "type" => "text/html",
984 "href" => $parent['plink'],
985 "dfrn:diaspora_guid" => $parent['guid']];
986 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
989 // Add conversation data. This is used for OStatus
990 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
991 $conversation_uri = $conversation_href;
993 if (isset($parent_item)) {
994 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $item['parent-uri']]);
995 if (DBA::isResult($conversation)) {
996 if ($conversation['conversation-uri'] != '') {
997 $conversation_uri = $conversation['conversation-uri'];
999 if ($conversation['conversation-href'] != '') {
1000 $conversation_href = $conversation['conversation-href'];
1006 "href" => $conversation_href,
1007 "ref" => $conversation_uri];
1009 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
1011 XML::addElement($doc, $entry, "id", $item["uri"]);
1012 XML::addElement($doc, $entry, "title", $item["title"]);
1014 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"] . "+00:00", DateTimeFormat::ATOM));
1015 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"] . "+00:00", DateTimeFormat::ATOM));
1017 // "dfrn:env" is used to read the content
1018 XML::addElement($doc, $entry, "dfrn:env", Strings::base64UrlEncode($body, true));
1020 // The "content" field is not read by the receiver. We could remove it when the type is "text"
1021 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
1022 XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
1024 // We save this value in "plink". Maybe we should read it from there as well?
1030 ["rel" => "alternate", "type" => "text/html",
1031 "href" => System::baseUrl() . "/display/" . $item["guid"]]
1034 // "comment-allow" is some old fashioned stuff for old Friendica versions.
1035 // It is included in the rewritten code for completeness
1037 XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
1040 if ($item['location']) {
1041 XML::addElement($doc, $entry, "dfrn:location", $item['location']);
1044 if ($item['coord']) {
1045 XML::addElement($doc, $entry, "georss:point", $item['coord']);
1048 if ($item['private']) {
1049 XML::addElement($doc, $entry, "dfrn:private", ($item['private'] ? $item['private'] : 1));
1052 if ($item['extid']) {
1053 XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
1056 if ($item['post-type'] == Item::PT_PAGE) {
1057 XML::addElement($doc, $entry, "dfrn:bookmark", "true");
1061 XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
1064 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
1066 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
1067 // It is needed for relayed comments to Diaspora.
1068 if ($item['signed_text']) {
1069 $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer']]));
1070 XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
1073 XML::addElement($doc, $entry, "activity:verb", self::constructVerb($item));
1075 if ($item['object-type'] != "") {
1076 XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
1077 } elseif ($item['id'] == $item['parent']) {
1078 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1080 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
1083 $actobj = self::createActivity($doc, "activity:object", $item['object']);
1085 $entry->appendChild($actobj);
1088 $actarg = self::createActivity($doc, "activity:target", $item['target']);
1090 $entry->appendChild($actarg);
1093 $tags = Item::getFeedTags($item);
1095 /// @TODO Combine this with similar below if() block?
1097 foreach ($tags as $t) {
1098 if (($type != 'html') || ($t[0] != "@")) {
1099 XML::addElement($doc, $entry, "category", "", ["scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]]);
1105 foreach ($tags as $t) {
1107 $mentioned[$t[1]] = $t[1];
1112 foreach ($mentioned as $mention) {
1113 $condition = ['uid' => $owner["uid"], 'nurl' => Strings::normaliseLink($mention)];
1114 $contact = DBA::selectFirst('contact', ['forum', 'prv'], $condition);
1116 if (DBA::isResult($contact) && ($contact["forum"] || $contact["prv"])) {
1122 ["rel" => "mentioned",
1123 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1132 ["rel" => "mentioned",
1133 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1139 self::getAttachment($doc, $entry, $item);
1145 * @brief encrypts data via AES
1147 * @param string $data The data that is to be encrypted
1148 * @param string $key The AES key
1150 * @return string encrypted data
1152 private static function aesEncrypt($data, $key)
1154 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1158 * @brief decrypts data via AES
1160 * @param string $encrypted The encrypted data
1161 * @param string $key The AES key
1163 * @return string decrypted data
1165 public static function aesDecrypt($encrypted, $key)
1167 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1171 * @brief Delivers the atom content to the contacts
1173 * @param array $owner Owner record
1174 * @param array $contact Contact record of the receiver
1175 * @param string $atom Content that will be transmitted
1176 * @param bool $dissolve (to be documented)
1178 * @param bool $legacy_transport
1179 * @return int Deliver status. Negative values mean an error.
1180 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1181 * @throws \ImagickException
1182 * @todo Add array type-hint for $owner, $contact
1184 public static function deliver($owner, $contact, $atom, $dissolve = false, $legacy_transport = false)
1186 // At first try the Diaspora transport layer
1187 if (!$dissolve && !$legacy_transport) {
1188 $curlResult = self::transmit($owner, $contact, $atom);
1189 if ($curlResult >= 200) {
1190 Logger::log('Delivery via Diaspora transport layer was successful with status ' . $curlResult);
1195 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1197 if ($contact['duplex'] && $contact['dfrn-id']) {
1198 $idtosend = '0:' . $orig_id;
1200 if ($contact['duplex'] && $contact['issued-id']) {
1201 $idtosend = '1:' . $orig_id;
1204 $rino = Config::get('system', 'rino_encrypt');
1205 $rino = intval($rino);
1207 Logger::log("Local rino version: ". $rino, Logger::DEBUG);
1209 $ssl_val = intval(Config::get('system', 'ssl_policy'));
1212 case BaseURL::SSL_POLICY_FULL:
1213 $ssl_policy = 'full';
1215 case BaseURL::SSL_POLICY_SELFSIGN:
1216 $ssl_policy = 'self';
1218 case BaseURL::SSL_POLICY_NONE:
1220 $ssl_policy = 'none';
1224 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1226 Logger::log('dfrn_deliver: ' . $url);
1228 $curlResult = Network::curl($url);
1230 if ($curlResult->isTimeout()) {
1231 Contact::markForArchival($contact);
1232 return -2; // timed out
1235 $xml = $curlResult->getBody();
1237 $curl_stat = $curlResult->getReturnCode();
1238 if (empty($curl_stat)) {
1239 Contact::markForArchival($contact);
1240 return -3; // timed out
1243 Logger::log('dfrn_deliver: ' . $xml, Logger::DATA);
1246 Contact::markForArchival($contact);
1250 if (strpos($xml, '<?xml') === false) {
1251 Logger::log('dfrn_deliver: no valid XML returned');
1252 Logger::log('dfrn_deliver: returned XML: ' . $xml, Logger::DATA);
1253 Contact::markForArchival($contact);
1257 $res = XML::parseString($xml);
1259 if (!is_object($res) || (intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
1260 Contact::markForArchival($contact);
1262 if (empty($res->status)) {
1265 $status = $res->status;
1272 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1273 $challenge = hex2bin((string) $res->challenge);
1274 $perm = (($res->perm) ? $res->perm : null);
1275 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1276 $rino_remote_version = intval($res->rino);
1277 $page = (($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? 1 : 0);
1279 Logger::log("Remote rino version: ".$rino_remote_version." for ".$contact["url"], Logger::DEBUG);
1281 if ($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
1285 $final_dfrn_id = '';
1288 if ((($perm == 'rw') && !intval($contact['writable']))
1289 || (($perm == 'r') && intval($contact['writable']))
1291 DBA::update('contact', ['writable' => ($perm == 'rw')], ['id' => $contact['id']]);
1293 $contact['writable'] = (string) 1 - intval($contact['writable']);
1297 if (($contact['duplex'] && strlen($contact['pubkey']))
1298 || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY && strlen($contact['pubkey']))
1299 || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
1301 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
1302 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
1304 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
1305 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
1308 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1310 if (strpos($final_dfrn_id, ':') == 1) {
1311 $final_dfrn_id = substr($final_dfrn_id, 2);
1314 if ($final_dfrn_id != $orig_id) {
1315 Logger::log('dfrn_deliver: wrong dfrn_id.');
1316 // did not decode properly - cannot trust this site
1317 Contact::markForArchival($contact);
1321 $postvars['dfrn_id'] = $idtosend;
1322 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1324 $postvars['dissolve'] = '1';
1327 if ((($contact['rel']) && ($contact['rel'] != Contact::SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY)) {
1328 $postvars['data'] = $atom;
1329 $postvars['perm'] = 'rw';
1331 $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
1332 $postvars['perm'] = 'r';
1335 $postvars['ssl_policy'] = $ssl_policy;
1338 $postvars['page'] = $page;
1342 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1343 Logger::log('rino version: '. $rino_remote_version);
1345 switch ($rino_remote_version) {
1347 $key = openssl_random_pseudo_bytes(16);
1348 $data = self::aesEncrypt($postvars['data'], $key);
1352 Logger::log("rino: invalid requested version '$rino_remote_version'");
1353 Contact::markForArchival($contact);
1357 $postvars['rino'] = $rino_remote_version;
1358 $postvars['data'] = bin2hex($data);
1360 if ($dfrn_version >= 2.1) {
1361 if (($contact['duplex'] && strlen($contact['pubkey']))
1362 || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY && strlen($contact['pubkey']))
1363 || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
1365 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1367 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1370 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY)) {
1371 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1373 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1377 Logger::log('md5 rawkey ' . md5($postvars['key']));
1379 $postvars['key'] = bin2hex($postvars['key']);
1383 Logger::log('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), Logger::DATA);
1385 $postResult = Network::post($contact['notify'], $postvars);
1387 $xml = $postResult->getBody();
1389 Logger::log('dfrn_deliver: ' . "RECEIVED: " . $xml, Logger::DATA);
1391 $curl_stat = $postResult->getReturnCode();
1392 if (empty($curl_stat) || empty($xml)) {
1393 Contact::markForArchival($contact);
1394 return -9; // timed out
1397 if (($curl_stat == 503) && stristr($postResult->getHeader(), 'retry-after')) {
1398 Contact::markForArchival($contact);
1402 if (strpos($xml, '<?xml') === false) {
1403 Logger::log('dfrn_deliver: phase 2: no valid XML returned');
1404 Logger::log('dfrn_deliver: phase 2: returned XML: ' . $xml, Logger::DATA);
1405 Contact::markForArchival($contact);
1409 $res = XML::parseString($xml);
1411 if (!isset($res->status)) {
1412 Contact::markForArchival($contact);
1416 // Possibly old servers had returned an empty value when everything was okay
1417 if (empty($res->status)) {
1421 if (!empty($res->message)) {
1422 Logger::log('Delivery returned status '.$res->status.' - '.$res->message, Logger::DEBUG);
1425 if (($res->status >= 200) && ($res->status <= 299)) {
1426 Contact::unmarkForArchival($contact);
1429 return intval($res->status);
1433 * @brief Transmits atom content to the contacts via the Diaspora transport layer
1435 * @param array $owner Owner record
1436 * @param array $contact Contact record of the receiver
1437 * @param string $atom Content that will be transmitted
1439 * @param bool $public_batch
1440 * @return int Deliver status. Negative values mean an error.
1441 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1442 * @throws \ImagickException
1444 public static function transmit($owner, $contact, $atom, $public_batch = false)
1446 if (!$public_batch) {
1447 if (empty($contact['addr'])) {
1448 Logger::log('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.');
1449 if (Contact::updateFromProbe($contact['id'])) {
1450 $new_contact = DBA::selectFirst('contact', ['addr'], ['id' => $contact['id']]);
1451 $contact['addr'] = $new_contact['addr'];
1454 if (empty($contact['addr'])) {
1455 Logger::log('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
1456 Contact::markForArchival($contact);
1461 $fcontact = Diaspora::personByHandle($contact['addr']);
1462 if (empty($fcontact)) {
1463 Logger::log('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
1464 Contact::markForArchival($contact);
1467 $pubkey = $fcontact['pubkey'];
1472 $envelope = Diaspora::buildMessage($atom, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
1474 // Create the endpoint for public posts. This is some WIP and should later be added to the probing
1475 if ($public_batch && empty($contact["batch"])) {
1476 $parts = parse_url($contact["notify"]);
1477 $path_parts = explode('/', $parts['path']);
1478 array_pop($path_parts);
1479 $parts['path'] = implode('/', $path_parts);
1480 $contact["batch"] = Network::unparseURL($parts);
1483 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
1485 $content_type = ($public_batch ? "application/magic-envelope+xml" : "application/json");
1487 $postResult = Network::post($dest_url, $envelope, ["Content-Type: ".$content_type]);
1488 $xml = $postResult->getBody();
1490 $curl_stat = $postResult->getReturnCode();
1491 if (empty($curl_stat) || empty($xml)) {
1492 Logger::log('Empty answer from ' . $contact['id'] . ' - ' . $dest_url);
1493 Contact::markForArchival($contact);
1494 return -9; // timed out
1497 if (($curl_stat == 503) && (stristr($postResult->getHeader(), 'retry-after'))) {
1498 Contact::markForArchival($contact);
1502 if (strpos($xml, '<?xml') === false) {
1503 Logger::log('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url);
1504 Logger::log('Returned XML: ' . $xml, Logger::DATA);
1505 Contact::markForArchival($contact);
1509 $res = XML::parseString($xml);
1511 if (empty($res->status)) {
1512 Contact::markForArchival($contact);
1516 if (!empty($res->message)) {
1517 Logger::log('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message, Logger::DEBUG);
1520 if (($res->status >= 200) && ($res->status <= 299)) {
1521 Contact::unmarkForArchival($contact);
1524 return intval($res->status);
1528 * @brief Fetch the author data from head or entry items
1530 * @param object $xpath XPath object
1531 * @param object $context In which context should the data be searched
1532 * @param array $importer Record of the importer user mixed with contact of the content
1533 * @param string $element Element name from which the data is fetched
1534 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1535 * @param string $xml optional, default empty
1537 * @return array Relevant data of the author
1538 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1539 * @throws \ImagickException
1540 * @todo Find good type-hints for all parameter
1542 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
1545 $author["name"] = XML::getFirstNodeValue($xpath, $element."/atom:name/text()", $context);
1546 $author["link"] = XML::getFirstNodeValue($xpath, $element."/atom:uri/text()", $context);
1548 $fields = ['id', 'uid', 'url', 'network', 'avatar-date', 'avatar', 'name-date', 'uri-date', 'addr',
1549 'name', 'nick', 'about', 'location', 'keywords', 'xmpp', 'bdyear', 'bd', 'hidden', 'contact-type'];
1550 $condition = ["`uid` = ? AND `nurl` = ? AND `network` != ?",
1551 $importer["importer_uid"], Strings::normaliseLink($author["link"]), Protocol::STATUSNET];
1552 $contact_old = DBA::selectFirst('contact', $fields, $condition);
1554 if (DBA::isResult($contact_old)) {
1555 $author["contact-id"] = $contact_old["id"];
1556 $author["network"] = $contact_old["network"];
1559 Logger::debug("Contact ".$author["link"]." wasn't found for user ".$importer["importer_uid"]." XML: ".$xml);
1562 $author["contact-unknown"] = true;
1563 $author["contact-id"] = $importer["id"];
1564 $author["network"] = $importer["network"];
1568 // Until now we aren't serving different sizes - but maybe later
1570 /// @todo check if "avatar" or "photo" would be the best field in the specification
1571 $avatars = $xpath->query($element . "/atom:link[@rel='avatar']", $context);
1572 foreach ($avatars as $avatar) {
1575 foreach ($avatar->attributes as $attributes) {
1576 /// @TODO Rewrite these similar if() to one switch
1577 if ($attributes->name == "href") {
1578 $href = $attributes->textContent;
1580 if ($attributes->name == "width") {
1581 $width = $attributes->textContent;
1583 if ($attributes->name == "updated") {
1584 $author["avatar-date"] = $attributes->textContent;
1587 if (($width > 0) && ($href != "")) {
1588 $avatarlist[$width] = $href;
1592 if (count($avatarlist) > 0) {
1593 krsort($avatarlist);
1594 $author["avatar"] = current($avatarlist);
1597 if (empty($author['avatar']) && !empty($author['link'])) {
1598 $cid = Contact::getIdForURL($author['link'], 0);
1600 $contact = DBA::selectFirst('contact', ['avatar'], ['id' => $cid]);
1601 if (DBA::isResult($contact)) {
1602 $author['avatar'] = $contact['avatar'];
1607 if (empty($author['avatar'])) {
1608 Logger::log('Empty author: ' . $xml);
1609 $author['avatar'] = '';
1612 if (DBA::isResult($contact_old) && !$onlyfetch) {
1613 Logger::log("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", Logger::DEBUG);
1615 $poco = ["url" => $contact_old["url"]];
1617 // When was the last change to name or uri?
1618 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1619 foreach ($name_element->attributes as $attributes) {
1620 if ($attributes->name == "updated") {
1621 $poco["name-date"] = $attributes->textContent;
1625 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1626 foreach ($link_element->attributes as $attributes) {
1627 if ($attributes->name == "updated") {
1628 $poco["uri-date"] = $attributes->textContent;
1632 // Update contact data
1633 $value = XML::getFirstNodeValue($xpath, $element . "/dfrn:handle/text()", $context);
1635 $poco["addr"] = $value;
1638 $value = XML::getFirstNodeValue($xpath, $element . "/poco:displayName/text()", $context);
1640 $poco["name"] = $value;
1643 $value = XML::getFirstNodeValue($xpath, $element . "/poco:preferredUsername/text()", $context);
1645 $poco["nick"] = $value;
1648 $value = XML::getFirstNodeValue($xpath, $element . "/poco:note/text()", $context);
1650 $poco["about"] = $value;
1653 $value = XML::getFirstNodeValue($xpath, $element . "/poco:address/poco:formatted/text()", $context);
1655 $poco["location"] = $value;
1658 /// @todo Only search for elements with "poco:type" = "xmpp"
1659 $value = XML::getFirstNodeValue($xpath, $element . "/poco:ims/poco:value/text()", $context);
1661 $poco["xmpp"] = $value;
1664 /// @todo Add support for the following fields that we don't support by now in the contact table:
1665 /// - poco:utcOffset
1671 // If the "hide" element is present then the profile isn't searchable.
1672 $hide = intval(XML::getFirstNodeValue($xpath, $element . "/dfrn:hide/text()", $context) == "true");
1674 Logger::log("Hidden status for contact " . $contact_old["url"] . ": " . $hide, Logger::DEBUG);
1676 // If the contact isn't searchable then set the contact to "hidden".
1677 // Problem: This can be manually overridden by the user.
1679 $contact_old["hidden"] = true;
1682 // Save the keywords into the contact table
1684 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1685 foreach ($tagelements as $tag) {
1686 $tags[$tag->nodeValue] = $tag->nodeValue;
1690 $poco["keywords"] = implode(", ", $tags);
1693 // "dfrn:birthday" contains the birthday converted to UTC
1694 $birthday = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1696 if (strtotime($birthday) > time()) {
1697 $bd_timestamp = strtotime($birthday);
1699 $poco["bdyear"] = date("Y", $bd_timestamp);
1702 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1703 $value = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1705 if (!in_array($value, ["", "0000-00-00", DBA::NULL_DATE])) {
1706 $bdyear = date("Y");
1707 $value = str_replace(["0000", "0001"], $bdyear, $value);
1709 if (strtotime($value) < time()) {
1710 $value = str_replace($bdyear, $bdyear + 1, $value);
1713 $poco["bd"] = $value;
1716 $contact = array_merge($contact_old, $poco);
1718 if ($contact_old["bdyear"] != $contact["bdyear"]) {
1719 Event::createBirthday($contact, $birthday);
1722 // Get all field names
1724 foreach ($contact_old as $field => $data) {
1725 $fields[$field] = $data;
1728 unset($fields["id"]);
1729 unset($fields["uid"]);
1730 unset($fields["url"]);
1731 unset($fields["avatar-date"]);
1732 unset($fields["avatar"]);
1733 unset($fields["name-date"]);
1734 unset($fields["uri-date"]);
1737 // Update check for this field has to be done differently
1738 $datefields = ["name-date", "uri-date"];
1739 foreach ($datefields as $field) {
1740 // The date fields arrives as '2018-07-17T10:44:45Z' - the database return '2018-07-17 10:44:45'
1741 // The fields have to be in the same format to be comparable, since strtotime does add timezones.
1742 $contact[$field] = DateTimeFormat::utc($contact[$field]);
1744 if (strtotime($contact[$field]) > strtotime($contact_old[$field])) {
1745 Logger::log("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", Logger::DEBUG);
1750 foreach ($fields as $field => $data) {
1751 if ($contact[$field] != $contact_old[$field]) {
1752 Logger::log("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", Logger::DEBUG);
1758 Logger::log("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", Logger::DEBUG);
1761 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1762 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1763 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1764 WHERE `id` = %d AND `network` = '%s'",
1765 DBA::escape($contact["name"]), DBA::escape($contact["nick"]), DBA::escape($contact["about"]), DBA::escape($contact["location"]),
1766 DBA::escape($contact["addr"]), DBA::escape($contact["keywords"]), DBA::escape($contact["bdyear"]),
1767 DBA::escape($contact["bd"]), intval($contact["hidden"]), DBA::escape($contact["xmpp"]),
1768 DBA::escape(DateTimeFormat::utc($contact["name-date"])), DBA::escape(DateTimeFormat::utc($contact["uri-date"])),
1769 intval($contact["id"]), DBA::escape($contact["network"])
1773 Contact::updateAvatar(
1775 $importer['importer_uid'],
1777 (strtotime($contact['avatar-date']) > strtotime($contact_old['avatar-date']) || ($author['avatar'] != $contact_old['avatar']))
1781 * The generation is a sign for the reliability of the provided data.
1782 * It is used in the socgraph.php to prevent that old contact data
1783 * that was relayed over several servers can overwrite contact
1784 * data that we received directly.
1787 $poco["generation"] = 2;
1788 $poco["photo"] = $author["avatar"];
1789 $poco["hide"] = $hide;
1790 $poco["contact-type"] = $contact["contact-type"];
1791 $gcid = GContact::update($poco);
1793 GContact::link($gcid, $importer["importer_uid"], $contact["id"]);
1800 * @brief Transforms activity objects into an XML string
1802 * @param object $xpath XPath object
1803 * @param object $activity Activity object
1804 * @param string $element element name
1806 * @return string XML string
1807 * @todo Find good type-hints for all parameter
1809 private static function transformActivity($xpath, $activity, $element)
1811 if (!is_object($activity)) {
1815 $obj_doc = new DOMDocument("1.0", "utf-8");
1816 $obj_doc->formatOutput = true;
1818 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1820 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1821 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1823 $id = $xpath->query("atom:id", $activity)->item(0);
1824 if (is_object($id)) {
1825 $obj_element->appendChild($obj_doc->importNode($id, true));
1828 $title = $xpath->query("atom:title", $activity)->item(0);
1829 if (is_object($title)) {
1830 $obj_element->appendChild($obj_doc->importNode($title, true));
1833 $links = $xpath->query("atom:link", $activity);
1834 if (is_object($links)) {
1835 foreach ($links as $link) {
1836 $obj_element->appendChild($obj_doc->importNode($link, true));
1840 $content = $xpath->query("atom:content", $activity)->item(0);
1841 if (is_object($content)) {
1842 $obj_element->appendChild($obj_doc->importNode($content, true));
1845 $obj_doc->appendChild($obj_element);
1847 $objxml = $obj_doc->saveXML($obj_element);
1849 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1850 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1855 * @brief Processes the mail elements
1857 * @param object $xpath XPath object
1858 * @param object $mail mail elements
1859 * @param array $importer Record of the importer user mixed with contact of the content
1861 * @throws \Exception
1862 * @todo Find good type-hints for all parameter
1864 private static function processMail($xpath, $mail, $importer)
1866 Logger::log("Processing mails");
1868 /// @TODO Rewrite this to one statement
1870 $msg["uid"] = $importer["importer_uid"];
1871 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1872 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1873 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1874 $msg["contact-id"] = $importer["id"];
1875 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1876 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1877 $msg["created"] = DateTimeFormat::utc($xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue);
1878 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1879 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1881 $msg["replied"] = 0;
1883 DBA::insert('mail', $msg);
1885 $msg["id"] = DBA::lastInsertId();
1887 // send notifications.
1888 /// @TODO Arange this mess
1890 "type" => NOTIFY_MAIL,
1891 "notify_flags" => $importer["notify-flags"],
1892 "language" => $importer["language"],
1893 "to_name" => $importer["username"],
1894 "to_email" => $importer["email"],
1895 "uid" => $importer["importer_uid"],
1897 "parent" => $msg["parent-uri"],
1898 "source_name" => $msg["from-name"],
1899 "source_link" => $importer["url"],
1900 "source_photo" => $importer["thumb"],
1901 "verb" => ACTIVITY_POST,
1905 notification($notif_params);
1907 Logger::log("Mail is processed, notification was sent.");
1911 * @brief Processes the suggestion elements
1913 * @param object $xpath XPath object
1914 * @param object $suggestion suggestion elements
1915 * @param array $importer Record of the importer user mixed with contact of the content
1917 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1918 * @todo Find good type-hints for all parameter
1920 private static function processSuggestion($xpath, $suggestion, $importer)
1922 Logger::log("Processing suggestions");
1924 /// @TODO Rewrite this to one statement
1926 $suggest["uid"] = $importer["importer_uid"];
1927 $suggest["cid"] = $importer["id"];
1928 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1929 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1930 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1931 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1932 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1934 // Does our member already have a friend matching this description?
1937 * The valid result means the friend we're about to send a friend
1938 * suggestion already has them in their contact, which means no further
1939 * action is required.
1941 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1943 $condition = ['name' => $suggest["name"], 'nurl' => Strings::normaliseLink($suggest["url"]),
1944 'uid' => $suggest["uid"]];
1945 if (DBA::exists('contact', $condition)) {
1949 // Do we already have an fcontact record for this person?
1952 $condition = ['url' => $suggest["url"], 'name' => $suggest["name"], 'request' => $suggest["request"]];
1953 $fcontact = DBA::selectFirst('fcontact', ['id'], $condition);
1954 if (DBA::isResult($fcontact)) {
1955 $fid = $fcontact["id"];
1957 // OK, we do. Do we already have an introduction for this person?
1958 if (DBA::exists('intro', ['uid' => $suggest["uid"], 'fid' => $fid])) {
1960 * The valid result means the friend we're about to send a friend
1961 * suggestion already has them in their contact, which means no further
1962 * action is required.
1964 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1971 "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1972 DBA::escape($suggest["name"]),
1973 DBA::escape($suggest["url"]),
1974 DBA::escape($suggest["photo"]),
1975 DBA::escape($suggest["request"])
1980 $condition = ['url' => $suggest["url"], 'name' => $suggest["name"], 'request' => $suggest["request"]];
1981 $fcontact = DBA::selectFirst('fcontact', ['id'], $condition);
1984 * If no record in fcontact is found, below INSERT statement will not
1985 * link an introduction to it.
1987 if (!DBA::isResult($fcontact)) {
1988 // Database record did not get created. Quietly give up.
1992 $hash = Strings::getRandomHex();
1995 "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1996 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1997 intval($suggest["uid"]),
1999 intval($suggest["cid"]),
2000 DBA::escape($suggest["body"]),
2002 DBA::escape(DateTimeFormat::utcNow()),
2008 "type" => NOTIFY_SUGGEST,
2009 "notify_flags" => $importer["notify-flags"],
2010 "language" => $importer["language"],
2011 "to_name" => $importer["username"],
2012 "to_email" => $importer["email"],
2013 "uid" => $importer["importer_uid"],
2015 "link" => System::baseUrl()."/notifications/intros",
2016 "source_name" => $importer["name"],
2017 "source_link" => $importer["url"],
2018 "source_photo" => $importer["photo"],
2019 "verb" => ACTIVITY_REQ_FRIEND,
2027 * @brief Processes the relocation elements
2029 * @param object $xpath XPath object
2030 * @param object $relocation relocation elements
2031 * @param array $importer Record of the importer user mixed with contact of the content
2033 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2034 * @throws \ImagickException
2035 * @todo Find good type-hints for all parameter
2037 private static function processRelocation($xpath, $relocation, $importer)
2039 Logger::log("Processing relocations");
2041 /// @TODO Rewrite this to one statement
2043 $relocate["uid"] = $importer["importer_uid"];
2044 $relocate["cid"] = $importer["id"];
2045 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
2046 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
2047 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
2048 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
2049 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
2050 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
2051 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
2052 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
2053 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
2054 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
2055 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
2056 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
2058 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
2059 $relocate["avatar"] = $relocate["photo"];
2062 if ($relocate["addr"] == "") {
2063 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
2068 "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d",
2069 intval($importer["id"]),
2070 intval($importer["importer_uid"])
2073 if (!DBA::isResult($r)) {
2074 Logger::log("Query failed to execute, no result returned in " . __FUNCTION__);
2080 // Update the gcontact entry
2081 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
2083 $fields = ['name' => $relocate["name"], 'photo' => $relocate["avatar"],
2084 'url' => $relocate["url"], 'nurl' => Strings::normaliseLink($relocate["url"]),
2085 'addr' => $relocate["addr"], 'connect' => $relocate["addr"],
2086 'notify' => $relocate["notify"], 'server_url' => $relocate["server_url"]];
2087 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($old["url"])]);
2089 // Update the contact table. We try to find every entry.
2090 $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
2091 'url' => $relocate["url"], 'nurl' => Strings::normaliseLink($relocate["url"]),
2092 'addr' => $relocate["addr"], 'request' => $relocate["request"],
2093 'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
2094 'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
2095 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], Strings::normaliseLink($old["url"])];
2097 DBA::update('contact', $fields, $condition);
2099 Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
2101 Logger::log('Contacts are updated.');
2104 /// merge with current record, current contents have priority
2105 /// update record, set url-updated
2106 /// update profile photos
2107 /// schedule a scan?
2112 * @brief Updates an item
2114 * @param array $current the current item record
2115 * @param array $item the new item record
2116 * @param array $importer Record of the importer user mixed with contact of the content
2117 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2119 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2120 * @todo set proper type-hints (array?)
2122 private static function updateContent($current, $item, $importer, $entrytype)
2126 if (self::isEditedTimestampNewer($current, $item)) {
2127 // do not accept (ignore) an earlier edit than one we currently have.
2128 if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
2132 $fields = ['title' => defaults($item, 'title', ''), 'body' => defaults($item, 'body', ''),
2133 'tag' => defaults($item, 'tag', ''), 'changed' => DateTimeFormat::utcNow(),
2134 'edited' => DateTimeFormat::utc($item["edited"])];
2136 $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
2137 Item::update($fields, $condition);
2145 * @brief Detects the entry type of the item
2147 * @param array $importer Record of the importer user mixed with contact of the content
2148 * @param array $item the new item record
2150 * @return int Is it a toplevel entry, a comment or a relayed comment?
2151 * @throws \Exception
2152 * @todo set proper type-hints (array?)
2154 private static function getEntryType($importer, $item)
2156 if ($item["parent-uri"] != $item["uri"]) {
2159 if ($importer["page-flags"] == User::PAGE_FLAGS_COMMUNITY || $importer["page-flags"] == User::PAGE_FLAGS_PRVGROUP) {
2162 Logger::log("possible community action");
2164 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2167 // was the top-level post for this action written by somebody on this site?
2168 // Specifically, the recipient?
2170 $is_a_remote_action = false;
2172 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item["parent-uri"]]);
2173 if (DBA::isResult($parent)) {
2175 "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2176 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2177 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2178 AND `item`.`uid` = %d
2181 DBA::escape($parent["parent-uri"]),
2182 DBA::escape($parent["parent-uri"]),
2183 DBA::escape($parent["parent-uri"]),
2184 intval($importer["importer_uid"])
2186 if (DBA::isResult($r)) {
2187 $is_a_remote_action = true;
2192 * Does this have the characteristics of a community or private group action?
2193 * If it's an action to a wall post on a community/prvgroup page it's a
2194 * valid community action. Also forum_mode makes it valid for sure.
2195 * If neither, it's not.
2197 if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2198 $is_a_remote_action = false;
2199 Logger::log("not a community action");
2202 if ($is_a_remote_action) {
2203 return DFRN::REPLY_RC;
2208 return DFRN::TOP_LEVEL;
2213 * @brief Send a "poke"
2215 * @param array $item the new item record
2216 * @param array $importer Record of the importer user mixed with contact of the content
2217 * @param int $posted_id The record number of item record that was just posted
2219 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2220 * @todo set proper type-hints (array?)
2222 private static function doPoke($item, $importer, $posted_id)
2224 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2228 $xo = XML::parseString($item["object"], false);
2230 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2231 // somebody was poked/prodded. Was it me?
2233 foreach ($xo->link as $l) {
2234 $atts = $l->attributes();
2235 switch ($atts["rel"]) {
2237 $Blink = $atts["href"];
2244 if ($Blink && Strings::compareLink($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2245 $author = DBA::selectFirst('contact', ['name', 'thumb', 'url'], ['id' => $item['author-id']]);
2247 $item['id'] = $posted_id;
2249 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => $importer["importer_uid"]]);
2250 $item["parent"] = $parent['id'];
2252 // send a notification
2255 "type" => NOTIFY_POKE,
2256 "notify_flags" => $importer["notify-flags"],
2257 "language" => $importer["language"],
2258 "to_name" => $importer["username"],
2259 "to_email" => $importer["email"],
2260 "uid" => $importer["importer_uid"],
2262 "link" => System::baseUrl()."/display/".urlencode(Item::getGuidById($posted_id)),
2263 "source_name" => $author["name"],
2264 "source_link" => $author["url"],
2265 "source_photo" => $author["thumb"],
2266 "verb" => $item["verb"],
2267 "otype" => "person",
2268 "activity" => $verb,
2269 "parent" => $item["parent"]]
2276 * @brief Processes several actions, depending on the verb
2278 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2279 * @param array $importer Record of the importer user mixed with contact of the content
2280 * @param array $item the new item record
2281 * @param bool $is_like Is the verb a "like"?
2283 * @return bool Should the processing of the entries be continued?
2284 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2285 * @todo set proper type-hints (array?)
2287 private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2289 Logger::log("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, Logger::DEBUG);
2291 if (($entrytype == DFRN::TOP_LEVEL)) {
2292 // The filling of the the "contact" variable is done for legcy reasons
2293 // The functions below are partly used by ostatus.php as well - where we have this variable
2294 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2296 $nickname = $contact["nick"];
2298 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2299 // This function once was responsible for DFRN and OStatus.
2300 if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2301 Logger::log("New follower");
2302 Contact::addRelationship($importer, $contact, $item, $nickname);
2305 if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2306 Logger::log("Lost follower");
2307 Contact::removeFollower($importer, $contact, $item);
2310 if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2311 Logger::log("New friend request");
2312 Contact::addRelationship($importer, $contact, $item, $nickname, true);
2315 if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2316 Logger::log("Lost sharer");
2317 Contact::removeSharer($importer, $contact, $item);
2321 if (($item["verb"] == ACTIVITY_LIKE)
2322 || ($item["verb"] == ACTIVITY_DISLIKE)
2323 || ($item["verb"] == ACTIVITY_ATTEND)
2324 || ($item["verb"] == ACTIVITY_ATTENDNO)
2325 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
2328 $item["gravity"] = GRAVITY_ACTIVITY;
2329 // only one like or dislike per person
2330 // splitted into two queries for performance issues
2331 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2332 'verb' => $item["verb"], 'parent-uri' => $item["parent-uri"]];
2333 if (Item::exists($condition)) {
2337 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2338 'verb' => $item["verb"], 'thr-parent' => $item["parent-uri"]];
2339 if (Item::exists($condition)) {
2343 // The owner of an activity must be the author
2344 $item["owner-name"] = $item["author-name"];
2345 $item["owner-link"] = $item["author-link"];
2346 $item["owner-avatar"] = $item["author-avatar"];
2347 $item["owner-id"] = $item["author-id"];
2352 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2353 $xo = XML::parseString($item["object"], false);
2354 $xt = XML::parseString($item["target"], false);
2356 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2357 $item_tag = Item::selectFirst(['id', 'tag'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]);
2359 if (!DBA::isResult($item_tag)) {
2360 Logger::log("Query failed to execute, no result returned in " . __FUNCTION__);
2364 // extract tag, if not duplicate, add to parent item
2366 if (!stristr($item_tag["tag"], trim($xo->content))) {
2367 $tag = $item_tag["tag"] . (strlen($item_tag["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2368 Item::update(['tag' => $tag], ['id' => $item_tag["id"]]);
2378 * @brief Processes the link elements
2380 * @param object $links link elements
2381 * @param array $item the item record
2383 * @todo set proper type-hints
2385 private static function parseLinks($links, &$item)
2392 foreach ($links as $link) {
2393 foreach ($link->attributes as $attributes) {
2394 switch ($attributes->name) {
2395 case "href" : $href = $attributes->textContent; break;
2396 case "rel" : $rel = $attributes->textContent; break;
2397 case "type" : $type = $attributes->textContent; break;
2398 case "length": $length = $attributes->textContent; break;
2399 case "title" : $title = $attributes->textContent; break;
2402 if (($rel != "") && ($href != "")) {
2405 $item["plink"] = $href;
2408 if (!empty($item["attach"])) {
2409 $item["attach"] .= ",";
2411 $item["attach"] = "";
2414 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2422 * @brief Processes the entry elements which contain the items and comments
2424 * @param array $header Array of the header elements that always stay the same
2425 * @param object $xpath XPath object
2426 * @param object $entry entry elements
2427 * @param array $importer Record of the importer user mixed with contact of the content
2428 * @param string $xml xml
2430 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2431 * @throws \ImagickException
2432 * @todo Add type-hints
2434 private static function processEntry($header, $xpath, $entry, $importer, $xml)
2436 Logger::log("Processing entries");
2440 $item["protocol"] = Conversation::PARCEL_DFRN;
2442 $item["source"] = $xml;
2445 $item["uri"] = XML::getFirstNodeValue($xpath, "atom:id/text()", $entry);
2447 $item["edited"] = XML::getFirstNodeValue($xpath, "atom:updated/text()", $entry);
2449 $current = Item::selectFirst(['id', 'uid', 'edited', 'body'],
2450 ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
2452 // Is there an existing item?
2453 if (DBA::isResult($current) && !self::isEditedTimestampNewer($current, $item)) {
2454 Logger::log("Item ".$item["uri"]." (".$item['edited'].") already existed.", Logger::DEBUG);
2459 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true, $xml);
2461 $owner_unknown = (isset($owner["contact-unknown"]) && $owner["contact-unknown"]);
2463 $item["owner-name"] = $owner["name"];
2464 $item["owner-link"] = $owner["link"];
2465 $item["owner-avatar"] = $owner["avatar"];
2466 $item["owner-id"] = Contact::getIdForURL($owner["link"], 0);
2469 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true, $xml);
2471 $item["author-name"] = $author["name"];
2472 $item["author-link"] = $author["link"];
2473 $item["author-avatar"] = $author["avatar"];
2474 $item["author-id"] = Contact::getIdForURL($author["link"], 0);
2476 $item["title"] = XML::getFirstNodeValue($xpath, "atom:title/text()", $entry);
2478 $item["created"] = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2480 $item["body"] = XML::getFirstNodeValue($xpath, "dfrn:env/text()", $entry);
2481 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2482 // make sure nobody is trying to sneak some html tags by us
2483 $item["body"] = Strings::escapeTags(Strings::base64UrlDecode($item["body"]));
2485 $item["body"] = BBCode::limitBodySize($item["body"]);
2487 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2488 if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
2489 $base_url = \get_app()->getBaseURL();
2490 $item['body'] = HTML::relToAbs($item['body'], $base_url);
2492 $item['body'] = HTML::toBBCodeVideo($item['body']);
2494 $item['body'] = OEmbed::HTML2BBCode($item['body']);
2496 $config = HTMLPurifier_Config::createDefault();
2497 $config->set('Cache.DefinitionImpl', null);
2499 // we shouldn't need a whitelist, because the bbcode converter
2500 // will strip out any unsupported tags.
2502 $purifier = new HTMLPurifier($config);
2503 $item['body'] = $purifier->purify($item['body']);
2505 $item['body'] = @HTML::toBBCode($item['body']);
2508 /// @todo We should check for a repeated post and if we know the repeated author.
2510 // We don't need the content element since "dfrn:env" is always present
2511 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2513 $item["location"] = XML::getFirstNodeValue($xpath, "dfrn:location/text()", $entry);
2515 $item["coord"] = XML::getFirstNodeValue($xpath, "georss:point", $entry);
2517 $item["private"] = XML::getFirstNodeValue($xpath, "dfrn:private/text()", $entry);
2519 $item["extid"] = XML::getFirstNodeValue($xpath, "dfrn:extid/text()", $entry);
2521 if (XML::getFirstNodeValue($xpath, "dfrn:bookmark/text()", $entry) == "true") {
2522 $item["post-type"] = Item::PT_PAGE;
2525 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2526 if ($notice_info && ($notice_info->length > 0)) {
2527 foreach ($notice_info->item(0)->attributes as $attributes) {
2528 if ($attributes->name == "source") {
2529 $item["app"] = strip_tags($attributes->textContent);
2534 $item["guid"] = XML::getFirstNodeValue($xpath, "dfrn:diaspora_guid/text()", $entry);
2536 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
2537 $dsprsig = XML::unescape(XML::getFirstNodeValue($xpath, "dfrn:diaspora_signature/text()", $entry));
2538 if ($dsprsig != "") {
2539 $item["dsprsig"] = $dsprsig;
2542 $item["verb"] = XML::getFirstNodeValue($xpath, "activity:verb/text()", $entry);
2544 if (XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry) != "") {
2545 $item["object-type"] = XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry);
2548 $object = $xpath->query("activity:object", $entry)->item(0);
2549 $item["object"] = self::transformActivity($xpath, $object, "object");
2551 if (trim($item["object"]) != "") {
2552 $r = XML::parseString($item["object"], false);
2553 if (isset($r->type)) {
2554 $item["object-type"] = $r->type;
2558 $target = $xpath->query("activity:target", $entry)->item(0);
2559 $item["target"] = self::transformActivity($xpath, $target, "target");
2561 $categories = $xpath->query("atom:category", $entry);
2563 foreach ($categories as $category) {
2566 foreach ($category->attributes as $attributes) {
2567 if ($attributes->name == "term") {
2568 $term = $attributes->textContent;
2571 if ($attributes->name == "scheme") {
2572 $scheme = $attributes->textContent;
2576 if (($term != "") && ($scheme != "")) {
2577 $parts = explode(":", $scheme);
2578 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2579 $termhash = array_shift($parts);
2580 $termurl = implode(":", $parts);
2582 if (!empty($item["tag"])) {
2583 $item["tag"] .= ",";
2588 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2594 $links = $xpath->query("atom:link", $entry);
2596 self::parseLinks($links, $item);
2599 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
2601 $conv = $xpath->query('ostatus:conversation', $entry);
2602 if (is_object($conv->item(0))) {
2603 foreach ($conv->item(0)->attributes as $attributes) {
2604 if ($attributes->name == "ref") {
2605 $item['conversation-uri'] = $attributes->textContent;
2607 if ($attributes->name == "href") {
2608 $item['conversation-href'] = $attributes->textContent;
2613 // Is it a reply or a top level posting?
2614 $item["parent-uri"] = $item["uri"];
2616 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2617 if (is_object($inreplyto->item(0))) {
2618 foreach ($inreplyto->item(0)->attributes as $attributes) {
2619 if ($attributes->name == "ref") {
2620 $item["parent-uri"] = $attributes->textContent;
2625 // Get the type of the item (Top level post, reply or remote reply)
2626 $entrytype = self::getEntryType($importer, $item);
2628 // Now assign the rest of the values that depend on the type of the message
2629 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2630 if (!isset($item["object-type"])) {
2631 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2634 if ($item["contact-id"] != $owner["contact-id"]) {
2635 $item["contact-id"] = $owner["contact-id"];
2638 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2639 $item["network"] = $owner["network"];
2642 if ($item["contact-id"] != $author["contact-id"]) {
2643 $item["contact-id"] = $author["contact-id"];
2646 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2647 $item["network"] = $author["network"];
2651 if ($entrytype == DFRN::REPLY_RC) {
2653 } elseif ($entrytype == DFRN::TOP_LEVEL) {
2654 if (!isset($item["object-type"])) {
2655 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2659 if (($item["object-type"] == ACTIVITY_OBJ_EVENT) && !$owner_unknown) {
2660 Logger::log("Item ".$item["uri"]." seems to contain an event.", Logger::DEBUG);
2661 $ev = Event::fromBBCode($item["body"]);
2662 if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
2663 Logger::log("Event in item ".$item["uri"]." was found.", Logger::DEBUG);
2664 $ev["cid"] = $importer["id"];
2665 $ev["uid"] = $importer["importer_uid"];
2666 $ev["uri"] = $item["uri"];
2667 $ev["edited"] = $item["edited"];
2668 $ev["private"] = $item["private"];
2669 $ev["guid"] = $item["guid"];
2670 $ev["plink"] = $item["plink"];
2672 $condition = ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]];
2673 $event = DBA::selectFirst('event', ['id'], $condition);
2674 if (DBA::isResult($event)) {
2675 $ev["id"] = $event["id"];
2678 $event_id = Event::store($ev);
2679 Logger::log("Event ".$event_id." was stored", Logger::DEBUG);
2685 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2686 Logger::log("Exiting because 'processVerbs' told us so", Logger::DEBUG);
2690 // This check is done here to be able to receive connection requests in "processVerbs"
2691 if (($entrytype == DFRN::TOP_LEVEL) && $owner_unknown) {
2692 Logger::log("Item won't be stored because user " . $importer["importer_uid"] . " doesn't follow " . $item["owner-link"] . ".", Logger::DEBUG);
2697 // Update content if 'updated' changes
2698 if (DBA::isResult($current)) {
2699 if (self::updateContent($current, $item, $importer, $entrytype)) {
2700 Logger::log("Item ".$item["uri"]." was updated.", Logger::DEBUG);
2702 Logger::log("Item " . $item["uri"] . " already existed.", Logger::DEBUG);
2707 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2708 $posted_id = Item::insert($item);
2710 Logger::log("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, Logger::DEBUG);
2712 if ($item['uid'] == 0) {
2713 Item::distribute($posted_id);
2718 } else { // $entrytype == DFRN::TOP_LEVEL
2719 if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
2720 Logger::log("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", Logger::DEBUG);
2723 if (!Strings::compareLink($item["owner-link"], $importer["url"])) {
2725 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2726 * but otherwise there's a possible data mixup on the sender's system.
2727 * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2728 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2730 Logger::log('Correcting item owner.', Logger::DEBUG);
2731 $item["owner-link"] = $importer["url"];
2732 $item["owner-id"] = Contact::getIdForURL($importer["url"], 0);
2735 if (($importer["rel"] == Contact::FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2736 Logger::log("Contact ".$importer["id"]." is only follower and tgroup check was negative.", Logger::DEBUG);
2740 // This is my contact on another system, but it's really me.
2741 // Turn this into a wall post.
2742 $notify = Item::isRemoteSelf($importer, $item);
2744 $posted_id = Item::insert($item, false, $notify);
2747 $posted_id = $notify;
2750 Logger::log("Item was stored with id ".$posted_id, Logger::DEBUG);
2752 if ($item['uid'] == 0) {
2753 Item::distribute($posted_id);
2756 if (stristr($item["verb"], ACTIVITY_POKE)) {
2757 self::doPoke($item, $importer, $posted_id);
2763 * @brief Deletes items
2765 * @param object $xpath XPath object
2766 * @param object $deletion deletion elements
2767 * @param array $importer Record of the importer user mixed with contact of the content
2769 * @throws \Exception
2770 * @todo set proper type-hints
2772 private static function processDeletion($xpath, $deletion, $importer)
2774 Logger::log("Processing deletions");
2777 foreach ($deletion->attributes as $attributes) {
2778 if ($attributes->name == "ref") {
2779 $uri = $attributes->textContent;
2783 if (!$uri || !$importer["id"]) {
2787 $condition = ['uri' => $uri, 'uid' => $importer["importer_uid"]];
2788 $item = Item::selectFirst(['id', 'parent', 'contact-id', 'file', 'deleted'], $condition);
2789 if (!DBA::isResult($item)) {
2790 Logger::log("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", Logger::DEBUG);
2794 if (strstr($item['file'], '[')) {
2795 Logger::log("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " is filed. So it won't be deleted.", Logger::DEBUG);
2799 // When it is a starting post it has to belong to the person that wants to delete it
2800 if (($item['id'] == $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2801 Logger::log("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", Logger::DEBUG);
2805 // Comments can be deleted by the thread owner or comment owner
2806 if (($item['id'] != $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2807 $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2808 if (!Item::exists($condition)) {
2809 Logger::log("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", Logger::DEBUG);
2814 if ($item["deleted"]) {
2818 Logger::log('deleting item '.$item['id'].' uri='.$uri, Logger::DEBUG);
2820 Item::delete(['id' => $item['id']]);
2824 * @brief Imports a DFRN message
2826 * @param string $xml The DFRN message
2827 * @param array $importer Record of the importer user mixed with contact of the content
2828 * @param bool $sort_by_date Is used when feeds are polled
2829 * @return integer Import status
2830 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2831 * @throws \ImagickException
2832 * @todo set proper type-hints
2834 public static function import($xml, $importer, $sort_by_date = false)
2840 $doc = new DOMDocument();
2841 @$doc->loadXML($xml);
2843 $xpath = new DOMXPath($doc);
2844 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2845 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2846 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2847 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2848 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2849 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2850 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2851 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2852 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2853 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2856 $header["uid"] = $importer["importer_uid"];
2857 $header["network"] = Protocol::DFRN;
2858 $header["wall"] = 0;
2859 $header["origin"] = 0;
2860 $header["contact-id"] = $importer["id"];
2862 // Update the contact table if the data has changed
2864 // The "atom:author" is only present in feeds
2865 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2866 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2869 // Only the "dfrn:owner" in the head section contains all data
2870 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2871 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2874 Logger::log("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], Logger::DEBUG);
2876 // is it a public forum? Private forums aren't exposed with this method
2877 $forum = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:community/text()"));
2879 // The account type is new since 3.5.1
2880 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2881 // Hint: We are using separate update calls for uid=0 and uid!=0 since a combined call is bad for the database performance
2883 $accounttype = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:account_type/text()"));
2885 if ($accounttype != $importer["contact-type"]) {
2886 DBA::update('contact', ['contact-type' => $accounttype], ['id' => $importer['id']]);
2888 // Updating the public contact as well
2889 DBA::update('contact', ['contact-type' => $accounttype], ['uid' => 0, 'nurl' => $importer['nurl']]);
2891 // A forum contact can either have set "forum" or "prv" - but not both
2892 if ($accounttype == User::ACCOUNT_TYPE_COMMUNITY) {
2893 // It's a forum, so either set the public or private forum flag
2894 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer['id']];
2895 DBA::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2897 // Updating the public contact as well
2898 $condition = ['(`forum` != ? OR `prv` != ?) AND `uid` = 0 AND `nurl` = ?', $forum, !$forum, $importer['nurl']];
2899 DBA::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2901 // It's not a forum, so remove the flags
2902 $condition = ['(`forum` OR `prv`) AND `id` = ?', $importer['id']];
2903 DBA::update('contact', ['forum' => false, 'prv' => false], $condition);
2905 // Updating the public contact as well
2906 $condition = ['(`forum` OR `prv`) AND `uid` = 0 AND `nurl` = ?', $importer['nurl']];
2907 DBA::update('contact', ['forum' => false, 'prv' => false], $condition);
2909 } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
2910 $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2911 DBA::update('contact', ['forum' => $forum], $condition);
2913 // Updating the public contact as well
2914 $condition = ['`forum` != ? AND `uid` = 0 AND `nurl` = ?', $forum, $importer['nurl']];
2915 DBA::update('contact', ['forum' => $forum], $condition);
2919 // We are processing relocations even if we are ignoring a contact
2920 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2921 foreach ($relocations as $relocation) {
2922 self::processRelocation($xpath, $relocation, $importer);
2925 if (($importer["uid"] != 0) && !$importer["readonly"]) {
2926 $mails = $xpath->query("/atom:feed/dfrn:mail");
2927 foreach ($mails as $mail) {
2928 self::processMail($xpath, $mail, $importer);
2931 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2932 foreach ($suggestions as $suggestion) {
2933 self::processSuggestion($xpath, $suggestion, $importer);
2937 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2938 foreach ($deletions as $deletion) {
2939 self::processDeletion($xpath, $deletion, $importer);
2942 if (!$sort_by_date) {
2943 $entries = $xpath->query("/atom:feed/atom:entry");
2944 foreach ($entries as $entry) {
2945 self::processEntry($header, $xpath, $entry, $importer, $xml);
2949 $entries = $xpath->query("/atom:feed/atom:entry");
2950 foreach ($entries as $entry) {
2951 $created = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2952 $newentries[strtotime($created)] = $entry;
2955 // Now sort after the publishing date
2958 foreach ($newentries as $entry) {
2959 self::processEntry($header, $xpath, $entry, $importer, $xml);
2962 Logger::log("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], Logger::DEBUG);
2968 * @param string $contact_nick contact nickname
2969 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2971 public static function autoRedir(App $a, $contact_nick)
2974 if (!empty($_REQUEST['redir'])) {
2978 if ((! $contact_nick) || ($contact_nick === $a->user['nickname'])) {
2983 // We need to find out if $contact_nick is a user on this hub, and if so, if I
2984 // am a contact of that user. However, that user may have other contacts with the
2985 // same nickname as me on other hubs or other networks. Exclude these by requiring
2986 // that the contact have a local URL. I will be the only person with my nickname at
2987 // this URL, so if a result is found, then I am a contact of the $contact_nick user.
2989 // We also have to make sure that I'm a legitimate contact--I'm not blocked or pending.
2991 $baseurl = System::baseUrl();
2992 $domain_st = strpos($baseurl, "://");
2993 if ($domain_st === false) {
2996 $baseurl = substr($baseurl, $domain_st + 3);
2997 $nurl = Strings::normaliseLink($baseurl);
2999 /// @todo Why is there a query for "url" *and* "nurl"? Especially this normalising is strange.
3000 $r = q("SELECT `id` FROM `contact` WHERE `uid` = (SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1)
3001 AND `nick` = '%s' AND NOT `self` AND (`url` LIKE '%%%s%%' OR `nurl` LIKE '%%%s%%') AND NOT `blocked` AND NOT `pending` LIMIT 1",
3002 DBA::escape($contact_nick),
3003 DBA::escape($a->user['nickname']),
3004 DBA::escape($baseurl),
3007 if ((! DBA::isResult($r)) || $r[0]['id'] == remote_user()) {
3011 $r = q("SELECT * FROM contact WHERE nick = '%s'
3012 AND network = '%s' AND uid = %d AND url LIKE '%%%s%%' LIMIT 1",
3013 DBA::escape($contact_nick),
3014 DBA::escape(Protocol::DFRN),
3015 intval(local_user()),
3016 DBA::escape($baseurl)
3018 if (! DBA::isResult($r)) {
3024 $dfrn_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
3026 if ($r[0]['duplex'] && $r[0]['issued-id']) {
3027 $orig_id = $r[0]['issued-id'];
3028 $dfrn_id = '1:' . $orig_id;
3030 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
3031 $orig_id = $r[0]['dfrn-id'];
3032 $dfrn_id = '0:' . $orig_id;
3035 // ensure that we've got a valid ID. There may be some edge cases with forums and non-duplex mode
3036 // that may have triggered some of the "went to {profile/intro} and got an RSS feed" issues
3038 if (strlen($dfrn_id) < 3) {
3042 $sec = Strings::getRandomHex();
3044 DBA::insert('profile_check', ['uid' => local_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id, 'sec' => $sec, 'expire' => time() + 45]);
3046 $url = curPageURL();
3048 Logger::log('auto_redir: ' . $r[0]['name'] . ' ' . $sec, Logger::DEBUG);
3049 $dest = (($url) ? '&destination_url=' . $url : '');
3050 System::externalRedirect($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
3051 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest);
3058 * @brief Returns the activity verb
3060 * @param array $item Item array
3062 * @return string activity verb
3064 private static function constructVerb(array $item)
3066 if ($item['verb']) {
3067 return $item['verb'];
3069 return ACTIVITY_POST;
3072 private static function tgroupCheck($uid, $item)
3076 // check that the message originated elsewhere and is a top-level post
3078 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['parent-uri'])) {
3082 $user = DBA::selectFirst('user', ['page-flags', 'nickname'], ['uid' => $uid]);
3083 if (!DBA::isResult($user)) {
3087 $community_page = ($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY);
3088 $prvgroup = ($user['page-flags'] == User::PAGE_FLAGS_PRVGROUP);
3090 $link = Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']);
3093 * Diaspora uses their own hardwired link URL in @-tags
3094 * instead of the one we supply with webfinger
3096 $dlink = Strings::normaliseLink(System::baseUrl() . '/u/' . $user['nickname']);
3098 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
3100 foreach ($matches as $mtch) {
3101 if (Strings::compareLink($link, $mtch[1]) || Strings::compareLink($dlink, $mtch[1])) {
3103 Logger::log('mention found: ' . $mtch[2]);
3112 return $community_page || $prvgroup;
3116 * This function returns true if $update has an edited timestamp newer
3117 * than $existing, i.e. $update contains new data which should override
3118 * what's already there. If there is no timestamp yet, the update is
3119 * assumed to be newer. If the update has no timestamp, the existing
3120 * item is assumed to be up-to-date. If the timestamps are equal it
3121 * assumes the update has been seen before and should be ignored.
3126 * @throws \Exception
3128 private static function isEditedTimestampNewer($existing, $update)
3130 if (empty($existing['edited'])) {
3133 if (empty($update['edited'])) {
3137 $existing_edited = DateTimeFormat::utc($existing['edited']);
3138 $update_edited = DateTimeFormat::utc($update['edited']);
3140 return (strcmp($existing_edited, $update_edited) < 0);