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\Addon;
18 use Friendica\Core\Config;
19 use Friendica\Core\L10n;
20 use Friendica\Core\Logger;
21 use Friendica\Core\Protocol;
22 use Friendica\Core\System;
23 use Friendica\Database\DBA;
24 use Friendica\Model\Contact;
25 use Friendica\Model\Conversation;
26 use Friendica\Model\Event;
27 use Friendica\Model\GContact;
28 use Friendica\Model\Item;
29 use Friendica\Model\PermissionSet;
30 use Friendica\Model\Profile;
31 use Friendica\Model\User;
32 use Friendica\Object\Image;
33 use Friendica\Util\Crypto;
34 use Friendica\Util\DateTimeFormat;
35 use Friendica\Util\Network;
36 use Friendica\Util\XML;
38 use HTMLPurifier_Config;
40 require_once 'boot.php';
41 require_once 'include/dba.php';
42 require_once "include/enotify.php";
43 require_once "include/items.php";
44 require_once "include/text.php";
47 * @brief This class contain functions to create and send DFRN XML files
52 const TOP_LEVEL = 0; // Top level posting
53 const REPLY = 1; // Regular reply that is stored locally
54 const REPLY_RC = 2; // Reply that will be relayed
57 * @brief Generates an array of contact and user for DFRN imports
59 * This array contains not only the receiver but also the sender of the message.
61 * @param integer $cid Contact id
62 * @param integer $uid User id
64 * @return array importer
66 public static function getImporter($cid, $uid = 0)
68 $condition = ['id' => $cid, 'blocked' => false, 'pending' => false];
69 $contact = DBA::selectFirst('contact', [], $condition);
70 if (!DBA::isResult($contact)) {
74 $contact['cpubkey'] = $contact['pubkey'];
75 $contact['cprvkey'] = $contact['prvkey'];
76 $contact['senderName'] = $contact['name'];
79 $condition = ['uid' => $uid, 'account_expired' => false, 'account_removed' => false];
80 $user = DBA::selectFirst('user', [], $condition);
81 if (!DBA::isResult($user)) {
85 $user['importer_uid'] = $user['uid'];
86 $user['uprvkey'] = $user['prvkey'];
88 $user = ['importer_uid' => 0, 'uprvkey' => '', 'timezone' => 'UTC',
89 'nickname' => '', 'sprvkey' => '', 'spubkey' => '',
90 'page-flags' => 0, 'account-type' => 0, 'prvnets' => 0];
93 return array_merge($contact, $user);
97 * @brief Generates the atom entries for delivery.php
99 * This function is used whenever content is transmitted via DFRN.
101 * @param array $items Item elements
102 * @param array $owner Owner record
104 * @return string DFRN entries
105 * @todo Find proper type-hints
107 public static function entries($items, $owner)
109 $doc = new DOMDocument('1.0', 'utf-8');
110 $doc->formatOutput = true;
112 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
114 if (! count($items)) {
115 return trim($doc->saveXML());
118 foreach ($items as $item) {
119 // These values aren't sent when sending from the queue.
120 /// @todo Check if we can set these values from the queue or if they are needed at all.
121 $item["entry:comment-allow"] = defaults($item, "entry:comment-allow", true);
122 $item["entry:cid"] = defaults($item, "entry:cid", 0);
124 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
125 $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
144 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false)
148 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
149 $public_feed = (($dfrn_id) ? false : true);
150 $starred = false; // not yet implemented, possible security issues
153 if ($public_feed && $a->argc > 2) {
154 for ($x = 2; $x < $a->argc; $x++) {
155 if ($a->argv[$x] == 'converse') {
158 if ($a->argv[$x] == 'starred') {
161 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
162 $category = $a->argv[$x+1];
167 // default permissions - anonymous user
169 $sql_extra = " AND NOT `item`.`private` ";
172 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
173 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
174 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
175 DBA::escape($owner_nick)
178 if (! DBA::isResult($r)) {
179 Logger::log(sprintf('No contact found for nickname=%d', $owner_nick), Logger::WARNING);
184 $owner_id = $owner['uid'];
185 $owner_nick = $owner['nickname'];
187 $sql_post_table = "";
189 if (! $public_feed) {
191 switch ($direction) {
193 $sql_extra = sprintf(" AND `issued-id` = '%s' ", DBA::escape($dfrn_id));
197 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
198 $my_id = '1:' . $dfrn_id;
201 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
202 $my_id = '0:' . $dfrn_id;
210 "SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
214 if (! DBA::isResult($r)) {
215 Logger::log(sprintf('No contact found for uid=%d', $owner_id), Logger::WARNING);
221 $set = PermissionSet::get($owner_id, $contact['id']);
224 $sql_extra = " AND `item`.`psid` IN (" . implode(',', $set) .")";
226 $sql_extra = " AND NOT `item`.`private`";
236 if (! strlen($last_update)) {
237 $last_update = 'now -30 days';
240 if (isset($category)) {
241 $sql_post_table = sprintf(
242 "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` ",
243 DBA::escape(protect_sprintf($category)),
244 intval(TERM_OBJ_POST),
245 intval(TERM_CATEGORY),
248 //$sql_extra .= FileTag::fileQuery('item',$category,'category');
251 if ($public_feed && ! $converse) {
252 $sql_extra .= " AND `contact`.`self` = 1 ";
255 $check_date = DateTimeFormat::utc($last_update);
259 FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
260 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
261 WHERE `item`.`uid` = %d AND `item`.`wall` AND `item`.`changed` > '%s'
263 ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
265 DBA::escape($check_date),
270 foreach ($r as $item) {
271 $ids[] = $item['id'];
275 $ret = Item::select(Item::DELIVER_FIELDLIST, ['id' => $ids]);
276 $items = Item::inArray($ret);
282 * Will check further below if this actually returned results.
283 * We will provide an empty feed if that is the case.
286 $doc = new DOMDocument('1.0', 'utf-8');
287 $doc->formatOutput = true;
289 $alternatelink = $owner['url'];
291 if (isset($category)) {
292 $alternatelink .= "/category/".$category;
296 $author = "dfrn:owner";
301 $root = self::addHeader($doc, $owner, $author, $alternatelink, true);
303 /// @TODO This hook can't work anymore
304 // Addon::callHooks('atom_feed', $atom);
306 if (!DBA::isResult($items) || $onlyheader) {
307 $atom = trim($doc->saveXML());
309 Addon::callHooks('atom_feed_end', $atom);
314 foreach ($items as $item) {
315 // prevent private email from leaking.
316 if ($item['network'] == Protocol::MAIL) {
320 // public feeds get html, our own nodes use bbcode
324 // catch any email that's in a public conversation and make sure it doesn't leak
325 if ($item['private']) {
332 $entry = self::entry($doc, $type, $item, $owner, true);
333 $root->appendChild($entry);
336 $atom = trim($doc->saveXML());
338 Addon::callHooks('atom_feed_end', $atom);
344 * @brief Generate an atom entry for a given item id
346 * @param int $item_id The item id
347 * @param boolean $conversation Show the conversation. If false show the single post.
349 * @return string DFRN feed entry
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);
398 $root->appendChild($entry);
401 $root = self::entry($doc, $type, $item, $owner, true, 0, true);
404 $atom = trim($doc->saveXML());
409 * @brief Create XML text for DFRN mails
411 * @param array $item message elements
412 * @param array $owner Owner record
414 * @return string DFRN mail
415 * @todo Find proper type-hints
417 public static function mail($item, $owner)
419 $doc = new DOMDocument('1.0', 'utf-8');
420 $doc->formatOutput = true;
422 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
424 $mail = $doc->createElement("dfrn:mail");
425 $sender = $doc->createElement("dfrn:sender");
427 XML::addElement($doc, $sender, "dfrn:name", $owner['name']);
428 XML::addElement($doc, $sender, "dfrn:uri", $owner['url']);
429 XML::addElement($doc, $sender, "dfrn:avatar", $owner['thumb']);
431 $mail->appendChild($sender);
433 XML::addElement($doc, $mail, "dfrn:id", $item['uri']);
434 XML::addElement($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
435 XML::addElement($doc, $mail, "dfrn:sentdate", DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
436 XML::addElement($doc, $mail, "dfrn:subject", $item['title']);
437 XML::addElement($doc, $mail, "dfrn:content", $item['body']);
439 $root->appendChild($mail);
441 return trim($doc->saveXML());
445 * @brief Create XML text for DFRN friend suggestions
447 * @param array $item suggestion elements
448 * @param array $owner Owner record
450 * @return string DFRN suggestions
451 * @todo Find proper type-hints
453 public static function fsuggest($item, $owner)
455 $doc = new DOMDocument('1.0', 'utf-8');
456 $doc->formatOutput = true;
458 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
460 $suggest = $doc->createElement("dfrn:suggest");
462 XML::addElement($doc, $suggest, "dfrn:url", $item['url']);
463 XML::addElement($doc, $suggest, "dfrn:name", $item['name']);
464 XML::addElement($doc, $suggest, "dfrn:photo", $item['photo']);
465 XML::addElement($doc, $suggest, "dfrn:request", $item['request']);
466 XML::addElement($doc, $suggest, "dfrn:note", $item['note']);
468 $root->appendChild($suggest);
470 return trim($doc->saveXML());
474 * @brief Create XML text for DFRN relocations
476 * @param array $owner Owner record
477 * @param int $uid User ID
479 * @return string DFRN relocations
480 * @todo Find proper type-hints
482 public static function relocate($owner, $uid)
485 /* get site pubkey. this could be a new installation with no site keys*/
486 $pubkey = Config::get('system', 'site_pubkey');
488 $res = Crypto::newKeypair(1024);
489 Config::set('system', 'site_prvkey', $res['prvkey']);
490 Config::set('system', 'site_pubkey', $res['pubkey']);
494 "SELECT `resource-id` , `scale`, type FROM `photo`
495 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;",
499 $ext = Image::supportedTypes();
501 foreach ($rp as $p) {
502 $photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
506 $doc = new DOMDocument('1.0', 'utf-8');
507 $doc->formatOutput = true;
509 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
511 $relocate = $doc->createElement("dfrn:relocate");
513 XML::addElement($doc, $relocate, "dfrn:url", $owner['url']);
514 XML::addElement($doc, $relocate, "dfrn:name", $owner['name']);
515 XML::addElement($doc, $relocate, "dfrn:addr", $owner['addr']);
516 XML::addElement($doc, $relocate, "dfrn:avatar", $owner['avatar']);
517 XML::addElement($doc, $relocate, "dfrn:photo", $photos[4]);
518 XML::addElement($doc, $relocate, "dfrn:thumb", $photos[5]);
519 XML::addElement($doc, $relocate, "dfrn:micro", $photos[6]);
520 XML::addElement($doc, $relocate, "dfrn:request", $owner['request']);
521 XML::addElement($doc, $relocate, "dfrn:confirm", $owner['confirm']);
522 XML::addElement($doc, $relocate, "dfrn:notify", $owner['notify']);
523 XML::addElement($doc, $relocate, "dfrn:poll", $owner['poll']);
524 XML::addElement($doc, $relocate, "dfrn:sitepubkey", Config::get('system', 'site_pubkey'));
526 $root->appendChild($relocate);
528 return trim($doc->saveXML());
532 * @brief Adds the header elements for the DFRN protocol
534 * @param object $doc XML document
535 * @param array $owner Owner record
536 * @param string $authorelement Element name for the author
537 * @param string $alternatelink link to profile or category
538 * @param bool $public Is it a header for public posts?
540 * @return object XML root object
541 * @todo Find proper type-hints
543 private static function addHeader($doc, $owner, $authorelement, $alternatelink = "", $public = false)
546 if ($alternatelink == "") {
547 $alternatelink = $owner['url'];
550 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
551 $doc->appendChild($root);
553 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
554 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
555 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
556 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
557 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
558 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
559 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
560 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
561 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
563 XML::addElement($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
564 XML::addElement($doc, $root, "title", $owner["name"]);
566 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION];
567 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
569 $attributes = ["rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/"];
570 XML::addElement($doc, $root, "link", "", $attributes);
572 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $alternatelink];
573 XML::addElement($doc, $root, "link", "", $attributes);
577 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
578 OStatus::hublinks($doc, $root, $owner["nick"]);
580 $attributes = ["rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
581 XML::addElement($doc, $root, "link", "", $attributes);
583 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
584 XML::addElement($doc, $root, "link", "", $attributes);
586 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
587 XML::addElement($doc, $root, "link", "", $attributes);
590 // For backward compatibility we keep this element
591 if ($owner['page-flags'] == Contact::PAGE_COMMUNITY) {
592 XML::addElement($doc, $root, "dfrn:community", 1);
595 // The former element is replaced by this one
596 XML::addElement($doc, $root, "dfrn:account_type", $owner["account-type"]);
598 /// @todo We need a way to transmit the different page flags like "Contact::PAGE_PRVGROUP"
600 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
602 $author = self::addAuthor($doc, $owner, $authorelement, $public);
603 $root->appendChild($author);
609 * @brief Adds the author element in the header for the DFRN protocol
611 * @param object $doc XML document
612 * @param array $owner Owner record
613 * @param string $authorelement Element name for the author
614 * @param boolean $public boolean
616 * @return object XML author object
617 * @todo Find proper type-hints
619 private static function addAuthor($doc, $owner, $authorelement, $public)
621 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
623 "SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
624 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
625 intval($owner['uid'])
627 if (DBA::isResult($r)) {
633 $author = $doc->createElement($authorelement);
635 $namdate = DateTimeFormat::utc($owner['name-date'].'+00:00', DateTimeFormat::ATOM);
636 $uridate = DateTimeFormat::utc($owner['uri-date'].'+00:00', DateTimeFormat::ATOM);
637 $picdate = DateTimeFormat::utc($owner['avatar-date'].'+00:00', DateTimeFormat::ATOM);
641 if (!$public || !$hidewall) {
642 $attributes = ["dfrn:updated" => $namdate];
645 XML::addElement($doc, $author, "name", $owner["name"], $attributes);
646 XML::addElement($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
647 XML::addElement($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
649 $attributes = ["rel" => "photo", "type" => "image/jpeg",
650 "media:width" => 300, "media:height" => 300, "href" => $owner['photo']];
652 if (!$public || !$hidewall) {
653 $attributes["dfrn:updated"] = $picdate;
656 XML::addElement($doc, $author, "link", "", $attributes);
658 $attributes["rel"] = "avatar";
659 XML::addElement($doc, $author, "link", "", $attributes);
662 XML::addElement($doc, $author, "dfrn:hide", "true");
665 // The following fields will only be generated if the data isn't meant for a public feed
670 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
673 XML::addElement($doc, $author, "dfrn:birthday", $birthday);
676 // Only show contact details when we are allowed to
678 "SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
679 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
680 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
682 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
683 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
684 intval($owner['uid'])
686 if (DBA::isResult($r)) {
689 XML::addElement($doc, $author, "poco:displayName", $profile["name"]);
690 XML::addElement($doc, $author, "poco:updated", $namdate);
692 if (trim($profile["dob"]) > '0001-01-01') {
693 XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
696 XML::addElement($doc, $author, "poco:note", $profile["about"]);
697 XML::addElement($doc, $author, "poco:preferredUsername", $profile["nickname"]);
699 $savetz = date_default_timezone_get();
700 date_default_timezone_set($profile["timezone"]);
701 XML::addElement($doc, $author, "poco:utcOffset", date("P"));
702 date_default_timezone_set($savetz);
704 if (trim($profile["homepage"]) != "") {
705 $urls = $doc->createElement("poco:urls");
706 XML::addElement($doc, $urls, "poco:type", "homepage");
707 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
708 XML::addElement($doc, $urls, "poco:primary", "true");
709 $author->appendChild($urls);
712 if (trim($profile["pub_keywords"]) != "") {
713 $keywords = explode(",", $profile["pub_keywords"]);
715 foreach ($keywords as $keyword) {
716 XML::addElement($doc, $author, "poco:tags", trim($keyword));
720 if (trim($profile["xmpp"]) != "") {
721 $ims = $doc->createElement("poco:ims");
722 XML::addElement($doc, $ims, "poco:type", "xmpp");
723 XML::addElement($doc, $ims, "poco:value", $profile["xmpp"]);
724 XML::addElement($doc, $ims, "poco:primary", "true");
725 $author->appendChild($ims);
728 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
729 $element = $doc->createElement("poco:address");
731 XML::addElement($doc, $element, "poco:formatted", Profile::formatLocation($profile));
733 if (trim($profile["locality"]) != "") {
734 XML::addElement($doc, $element, "poco:locality", $profile["locality"]);
737 if (trim($profile["region"]) != "") {
738 XML::addElement($doc, $element, "poco:region", $profile["region"]);
741 if (trim($profile["country-name"]) != "") {
742 XML::addElement($doc, $element, "poco:country", $profile["country-name"]);
745 $author->appendChild($element);
753 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
755 * @param object $doc XML document
756 * @param string $element Element name for the author
757 * @param string $contact_url Link of the contact
758 * @param array $item Item elements
760 * @return object XML author object
761 * @todo Find proper type-hints
763 private static function addEntryAuthor($doc, $element, $contact_url, $item)
765 $contact = Contact::getDetailsByURL($contact_url, $item["uid"]);
767 $author = $doc->createElement($element);
768 XML::addElement($doc, $author, "name", $contact["name"]);
769 XML::addElement($doc, $author, "uri", $contact["url"]);
770 XML::addElement($doc, $author, "dfrn:handle", $contact["addr"]);
773 /// - Check real image type and image size
774 /// - Check which of these boths elements we should use
777 "type" => "image/jpeg",
779 "media:height" => 80,
780 "href" => $contact["photo"]];
781 XML::addElement($doc, $author, "link", "", $attributes);
785 "type" => "image/jpeg",
787 "media:height" => 80,
788 "href" => $contact["photo"]];
789 XML::addElement($doc, $author, "link", "", $attributes);
795 * @brief Adds the activity elements
797 * @param object $doc XML document
798 * @param string $element Element name for the activity
799 * @param string $activity activity value
801 * @return object XML activity object
802 * @todo Find proper type-hints
804 private static function createActivity($doc, $element, $activity)
807 $entry = $doc->createElement($element);
809 $r = XML::parseString($activity, false);
815 XML::addElement($doc, $entry, "activity:object-type", $r->type);
819 XML::addElement($doc, $entry, "id", $r->id);
823 XML::addElement($doc, $entry, "title", $r->title);
827 if (substr($r->link, 0, 1) == '<') {
828 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
829 $r->link = str_replace('&', '&', $r->link);
832 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
834 // XML does need a single element as root element so we add a dummy element here
835 $data = XML::parseString("<dummy>" . $r->link . "</dummy>", false);
836 if (is_object($data)) {
837 foreach ($data->link as $link) {
839 foreach ($link->attributes() as $parameter => $value) {
840 $attributes[$parameter] = $value;
842 XML::addElement($doc, $entry, "link", "", $attributes);
846 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
847 XML::addElement($doc, $entry, "link", "", $attributes);
851 XML::addElement($doc, $entry, "content", BBCode::convert($r->content), ["type" => "html"]);
861 * @brief Adds the elements for attachments
863 * @param object $doc XML document
864 * @param object $root XML root
865 * @param array $item Item element
867 * @return object XML attachment object
868 * @todo Find proper type-hints
870 private static function getAttachment($doc, $root, $item)
872 $arr = explode('[/attach],', $item['attach']);
874 foreach ($arr as $r) {
876 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
878 $attributes = ["rel" => "enclosure",
879 "href" => $matches[1],
880 "type" => $matches[3]];
882 if (intval($matches[2])) {
883 $attributes["length"] = intval($matches[2]);
886 if (trim($matches[4]) != "") {
887 $attributes["title"] = trim($matches[4]);
890 XML::addElement($doc, $root, "link", "", $attributes);
897 * @brief Adds the "entry" elements for the DFRN protocol
899 * @param object $doc XML document
900 * @param string $type "text" or "html"
901 * @param array $item Item element
902 * @param array $owner Owner record
903 * @param bool $comment Trigger the sending of the "comment" element
904 * @param int $cid Contact ID of the recipient
905 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
907 * @return object XML entry object
908 * @todo Find proper type-hints
910 private static function entry($doc, $type, array $item, array $owner, $comment = false, $cid = 0, $single = false)
914 if (!$item['parent']) {
918 if ($item['deleted']) {
919 $attributes = ["ref" => $item['uri'], "when" => DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM)];
920 return XML::createElement($doc, "at:deleted-entry", "", $attributes);
924 $entry = $doc->createElement("entry");
926 $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry');
927 $doc->appendChild($entry);
929 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
930 $entry->setAttribute("xmlns:at", NAMESPACE_TOMB);
931 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
932 $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
933 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
934 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
935 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
936 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
937 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
940 if ($item['private']) {
941 $body = Item::fixPrivatePhotos($item['body'], $owner['uid'], $item, $cid);
943 $body = $item['body'];
946 // Remove the abstract element. It is only locally important.
947 $body = BBCode::stripAbstract($body);
950 if ($type == 'html') {
953 if ($item['title'] != "") {
954 $htmlbody = "[b]" . $item['title'] . "[/b]\n\n" . $htmlbody;
957 $htmlbody = BBCode::convert($htmlbody, false, 7);
960 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
961 $entry->appendChild($author);
963 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
964 $entry->appendChild($dfrnowner);
966 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
967 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
968 $parent = Item::selectFirst(['guid', 'plink'], ['uri' => $parent_item, 'uid' => $item['uid']]);
969 $attributes = ["ref" => $parent_item, "type" => "text/html",
970 "href" => $parent['plink'],
971 "dfrn:diaspora_guid" => $parent['guid']];
972 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
975 // Add conversation data. This is used for OStatus
976 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
977 $conversation_uri = $conversation_href;
979 if (isset($parent_item)) {
980 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $item['parent-uri']]);
981 if (DBA::isResult($conversation)) {
982 if ($conversation['conversation-uri'] != '') {
983 $conversation_uri = $conversation['conversation-uri'];
985 if ($conversation['conversation-href'] != '') {
986 $conversation_href = $conversation['conversation-href'];
992 "href" => $conversation_href,
993 "ref" => $conversation_uri];
995 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
997 XML::addElement($doc, $entry, "id", $item["uri"]);
998 XML::addElement($doc, $entry, "title", $item["title"]);
1000 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"] . "+00:00", DateTimeFormat::ATOM));
1001 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"] . "+00:00", DateTimeFormat::ATOM));
1003 // "dfrn:env" is used to read the content
1004 XML::addElement($doc, $entry, "dfrn:env", base64url_encode($body, true));
1006 // The "content" field is not read by the receiver. We could remove it when the type is "text"
1007 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
1008 XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
1010 // We save this value in "plink". Maybe we should read it from there as well?
1016 ["rel" => "alternate", "type" => "text/html",
1017 "href" => System::baseUrl() . "/display/" . $item["guid"]]
1020 // "comment-allow" is some old fashioned stuff for old Friendica versions.
1021 // It is included in the rewritten code for completeness
1023 XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
1026 if ($item['location']) {
1027 XML::addElement($doc, $entry, "dfrn:location", $item['location']);
1030 if ($item['coord']) {
1031 XML::addElement($doc, $entry, "georss:point", $item['coord']);
1034 if ($item['private']) {
1035 XML::addElement($doc, $entry, "dfrn:private", ($item['private'] ? $item['private'] : 1));
1038 if ($item['extid']) {
1039 XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
1042 if ($item['post-type'] == Item::PT_PAGE) {
1043 XML::addElement($doc, $entry, "dfrn:bookmark", "true");
1047 XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
1050 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
1052 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
1053 // It is needed for relayed comments to Diaspora.
1054 if ($item['signed_text']) {
1055 $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer']]));
1056 XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
1059 XML::addElement($doc, $entry, "activity:verb", self::constructVerb($item));
1061 if ($item['object-type'] != "") {
1062 XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
1063 } elseif ($item['id'] == $item['parent']) {
1064 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1066 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
1069 $actobj = self::createActivity($doc, "activity:object", $item['object']);
1071 $entry->appendChild($actobj);
1074 $actarg = self::createActivity($doc, "activity:target", $item['target']);
1076 $entry->appendChild($actarg);
1079 $tags = Item::getFeedTags($item);
1081 /// @TODO Combine this with similar below if() block?
1083 foreach ($tags as $t) {
1084 if (($type != 'html') || ($t[0] != "@")) {
1085 XML::addElement($doc, $entry, "category", "", ["scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]]);
1091 foreach ($tags as $t) {
1093 $mentioned[$t[1]] = $t[1];
1098 foreach ($mentioned as $mention) {
1099 $condition = ['uid' => $owner["uid"], 'nurl' => normalise_link($mention)];
1100 $contact = DBA::selectFirst('contact', ['forum', 'prv'], $condition);
1102 if (DBA::isResult($contact) && ($contact["forum"] || $contact["prv"])) {
1108 ["rel" => "mentioned",
1109 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1118 ["rel" => "mentioned",
1119 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1125 self::getAttachment($doc, $entry, $item);
1131 * @brief encrypts data via AES
1133 * @param string $data The data that is to be encrypted
1134 * @param string $key The AES key
1136 * @return string encrypted data
1138 private static function aesEncrypt($data, $key)
1140 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1144 * @brief decrypts data via AES
1146 * @param string $encrypted The encrypted data
1147 * @param string $key The AES key
1149 * @return string decrypted data
1151 public static function aesDecrypt($encrypted, $key)
1153 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1157 * @brief Delivers the atom content to the contacts
1159 * @param array $owner Owner record
1160 * @param array $contact Contact record of the receiver
1161 * @param string $atom Content that will be transmitted
1162 * @param bool $dissolve (to be documented)
1164 * @return int Deliver status. Negative values mean an error.
1165 * @todo Add array type-hint for $owner, $contact
1167 public static function deliver($owner, $contact, $atom, $dissolve = false, $legacy_transport = false)
1171 // At first try the Diaspora transport layer
1172 if (!$dissolve && !$legacy_transport) {
1173 $curlResult = self::transmit($owner, $contact, $atom);
1174 if ($curlResult >= 200) {
1175 Logger::log('Delivery via Diaspora transport layer was successful with status ' . $curlResult);
1180 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1182 if ($contact['duplex'] && $contact['dfrn-id']) {
1183 $idtosend = '0:' . $orig_id;
1185 if ($contact['duplex'] && $contact['issued-id']) {
1186 $idtosend = '1:' . $orig_id;
1189 $rino = Config::get('system', 'rino_encrypt');
1190 $rino = intval($rino);
1192 Logger::log("Local rino version: ". $rino, Logger::DEBUG);
1194 $ssl_val = intval(Config::get('system', 'ssl_policy'));
1198 case SSL_POLICY_FULL:
1199 $ssl_policy = 'full';
1201 case SSL_POLICY_SELFSIGN:
1202 $ssl_policy = 'self';
1204 case SSL_POLICY_NONE:
1206 $ssl_policy = 'none';
1210 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1212 Logger::log('dfrn_deliver: ' . $url);
1214 $curlResult = Network::curl($url);
1216 if ($curlResult->isTimeout()) {
1217 Contact::markForArchival($contact);
1218 return -2; // timed out
1221 $xml = $curlResult->getBody();
1223 $curl_stat = $curlResult->getReturnCode();
1224 if (empty($curl_stat)) {
1225 Contact::markForArchival($contact);
1226 return -3; // timed out
1229 Logger::log('dfrn_deliver: ' . $xml, Logger::DATA);
1232 Contact::markForArchival($contact);
1236 if (strpos($xml, '<?xml') === false) {
1237 Logger::log('dfrn_deliver: no valid XML returned');
1238 Logger::log('dfrn_deliver: returned XML: ' . $xml, Logger::DATA);
1239 Contact::markForArchival($contact);
1243 $res = XML::parseString($xml);
1245 if (!is_object($res) || (intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
1246 Contact::markForArchival($contact);
1248 if (empty($res->status)) {
1251 $status = $res->status;
1258 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1259 $challenge = hex2bin((string) $res->challenge);
1260 $perm = (($res->perm) ? $res->perm : null);
1261 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1262 $rino_remote_version = intval($res->rino);
1263 $page = (($owner['page-flags'] == Contact::PAGE_COMMUNITY) ? 1 : 0);
1265 Logger::log("Remote rino version: ".$rino_remote_version." for ".$contact["url"], Logger::DEBUG);
1267 if ($owner['page-flags'] == Contact::PAGE_PRVGROUP) {
1271 $final_dfrn_id = '';
1274 if ((($perm == 'rw') && !intval($contact['writable']))
1275 || (($perm == 'r') && intval($contact['writable']))
1277 DBA::update('contact', ['writable' => ($perm == 'rw')], ['id' => $contact['id']]);
1279 $contact['writable'] = (string) 1 - intval($contact['writable']);
1283 if (($contact['duplex'] && strlen($contact['pubkey']))
1284 || ($owner['page-flags'] == Contact::PAGE_COMMUNITY && strlen($contact['pubkey']))
1285 || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
1287 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
1288 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
1290 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
1291 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
1294 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1296 if (strpos($final_dfrn_id, ':') == 1) {
1297 $final_dfrn_id = substr($final_dfrn_id, 2);
1300 if ($final_dfrn_id != $orig_id) {
1301 Logger::log('dfrn_deliver: wrong dfrn_id.');
1302 // did not decode properly - cannot trust this site
1303 Contact::markForArchival($contact);
1307 $postvars['dfrn_id'] = $idtosend;
1308 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1310 $postvars['dissolve'] = '1';
1313 if ((($contact['rel']) && ($contact['rel'] != Contact::SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == Contact::PAGE_COMMUNITY)) {
1314 $postvars['data'] = $atom;
1315 $postvars['perm'] = 'rw';
1317 $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
1318 $postvars['perm'] = 'r';
1321 $postvars['ssl_policy'] = $ssl_policy;
1324 $postvars['page'] = $page;
1328 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1329 Logger::log('rino version: '. $rino_remote_version);
1331 switch ($rino_remote_version) {
1333 $key = openssl_random_pseudo_bytes(16);
1334 $data = self::aesEncrypt($postvars['data'], $key);
1338 Logger::log("rino: invalid requested version '$rino_remote_version'");
1339 Contact::markForArchival($contact);
1343 $postvars['rino'] = $rino_remote_version;
1344 $postvars['data'] = bin2hex($data);
1346 if ($dfrn_version >= 2.1) {
1347 if (($contact['duplex'] && strlen($contact['pubkey']))
1348 || ($owner['page-flags'] == Contact::PAGE_COMMUNITY && strlen($contact['pubkey']))
1349 || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
1351 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1353 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1356 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == Contact::PAGE_COMMUNITY)) {
1357 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1359 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1363 Logger::log('md5 rawkey ' . md5($postvars['key']));
1365 $postvars['key'] = bin2hex($postvars['key']);
1369 Logger::log('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), Logger::DATA);
1371 $postResult = Network::post($contact['notify'], $postvars);
1373 $xml = $postResult->getBody();
1375 Logger::log('dfrn_deliver: ' . "RECEIVED: " . $xml, Logger::DATA);
1377 $curl_stat = $postResult->getReturnCode();
1378 if (empty($curl_stat) || empty($xml)) {
1379 Contact::markForArchival($contact);
1380 return -9; // timed out
1383 if (($curl_stat == 503) && stristr($postResult->getHeader(), 'retry-after')) {
1384 Contact::markForArchival($contact);
1388 if (strpos($xml, '<?xml') === false) {
1389 Logger::log('dfrn_deliver: phase 2: no valid XML returned');
1390 Logger::log('dfrn_deliver: phase 2: returned XML: ' . $xml, Logger::DATA);
1391 Contact::markForArchival($contact);
1395 $res = XML::parseString($xml);
1397 if (!isset($res->status)) {
1398 Contact::markForArchival($contact);
1402 // Possibly old servers had returned an empty value when everything was okay
1403 if (empty($res->status)) {
1407 if (!empty($res->message)) {
1408 Logger::log('Delivery returned status '.$res->status.' - '.$res->message, Logger::DEBUG);
1411 if (($res->status >= 200) && ($res->status <= 299)) {
1412 Contact::unmarkForArchival($contact);
1415 return intval($res->status);
1419 * @brief Transmits atom content to the contacts via the Diaspora transport layer
1421 * @param array $owner Owner record
1422 * @param array $contact Contact record of the receiver
1423 * @param string $atom Content that will be transmitted
1425 * @return int Deliver status. Negative values mean an error.
1427 public static function transmit($owner, $contact, $atom, $public_batch = false)
1431 if (!$public_batch) {
1432 if (empty($contact['addr'])) {
1433 Logger::log('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.');
1434 if (Contact::updateFromProbe($contact['id'])) {
1435 $new_contact = DBA::selectFirst('contact', ['addr'], ['id' => $contact['id']]);
1436 $contact['addr'] = $new_contact['addr'];
1439 if (empty($contact['addr'])) {
1440 Logger::log('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
1441 Contact::markForArchival($contact);
1446 $fcontact = Diaspora::personByHandle($contact['addr']);
1447 if (empty($fcontact)) {
1448 Logger::log('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
1449 Contact::markForArchival($contact);
1452 $pubkey = $fcontact['pubkey'];
1457 $envelope = Diaspora::buildMessage($atom, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
1459 // Create the endpoint for public posts. This is some WIP and should later be added to the probing
1460 if ($public_batch && empty($contact["batch"])) {
1461 $parts = parse_url($contact["notify"]);
1462 $path_parts = explode('/', $parts['path']);
1463 array_pop($path_parts);
1464 $parts['path'] = implode('/', $path_parts);
1465 $contact["batch"] = Network::unparseURL($parts);
1468 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
1470 $content_type = ($public_batch ? "application/magic-envelope+xml" : "application/json");
1472 $postResult = Network::post($dest_url, $envelope, ["Content-Type: ".$content_type]);
1473 $xml = $postResult->getBody();
1475 $curl_stat = $postResult->getReturnCode();
1476 if (empty($curl_stat) || empty($xml)) {
1477 Logger::log('Empty answer from ' . $contact['id'] . ' - ' . $dest_url);
1478 Contact::markForArchival($contact);
1479 return -9; // timed out
1482 if (($curl_stat == 503) && (stristr($postResult->getHeader(), 'retry-after'))) {
1483 Contact::markForArchival($contact);
1487 if (strpos($xml, '<?xml') === false) {
1488 Logger::log('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url);
1489 Logger::log('Returned XML: ' . $xml, Logger::DATA);
1490 Contact::markForArchival($contact);
1494 $res = XML::parseString($xml);
1496 if (empty($res->status)) {
1497 Contact::markForArchival($contact);
1501 if (!empty($res->message)) {
1502 Logger::log('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message, Logger::DEBUG);
1505 if (($res->status >= 200) && ($res->status <= 299)) {
1506 Contact::unmarkForArchival($contact);
1509 return intval($res->status);
1513 * @brief Add new birthday event for this person
1515 * @param array $contact Contact record
1516 * @param string $birthday Birthday of the contact
1518 * @todo Add array type-hint for $contact
1520 private static function birthdayEvent($contact, $birthday)
1522 // Check for duplicates
1523 $condition = ['uid' => $contact['uid'], 'cid' => $contact['id'],
1524 'start' => DateTimeFormat::utc($birthday), 'type' => 'birthday'];
1525 if (DBA::exists('event', $condition)) {
1529 Logger::log('updating birthday: ' . $birthday . ' for contact ' . $contact['id']);
1531 $bdtext = L10n::t('%s\'s birthday', $contact['name']);
1532 $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]');
1535 "INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1536 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1537 intval($contact['uid']),
1538 intval($contact['id']),
1539 DBA::escape(DateTimeFormat::utcNow()),
1540 DBA::escape(DateTimeFormat::utcNow()),
1541 DBA::escape(DateTimeFormat::utc($birthday)),
1542 DBA::escape(DateTimeFormat::utc($birthday . ' + 1 day ')),
1543 DBA::escape($bdtext),
1544 DBA::escape($bdtext2),
1545 DBA::escape('birthday')
1550 * @brief Fetch the author data from head or entry items
1552 * @param object $xpath XPath object
1553 * @param object $context In which context should the data be searched
1554 * @param array $importer Record of the importer user mixed with contact of the content
1555 * @param string $element Element name from which the data is fetched
1556 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1557 * @param string $xml optional, default empty
1559 * @return array Relevant data of the author
1560 * @todo Find good type-hints for all parameter
1562 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
1565 $author["name"] = XML::getFirstNodeValue($xpath, $element."/atom:name/text()", $context);
1566 $author["link"] = XML::getFirstNodeValue($xpath, $element."/atom:uri/text()", $context);
1568 $fields = ['id', 'uid', 'url', 'network', 'avatar-date', 'avatar', 'name-date', 'uri-date', 'addr',
1569 'name', 'nick', 'about', 'location', 'keywords', 'xmpp', 'bdyear', 'bd', 'hidden', 'contact-type'];
1570 $condition = ["`uid` = ? AND `nurl` = ? AND `network` != ?",
1571 $importer["importer_uid"], normalise_link($author["link"]), Protocol::STATUSNET];
1572 $contact_old = DBA::selectFirst('contact', $fields, $condition);
1574 if (DBA::isResult($contact_old)) {
1575 $author["contact-id"] = $contact_old["id"];
1576 $author["network"] = $contact_old["network"];
1579 Logger::log("Contact ".$author["link"]." wasn't found for user ".$importer["importer_uid"]." XML: ".$xml, Logger::DEBUG);
1582 $author["contact-unknown"] = true;
1583 $author["contact-id"] = $importer["id"];
1584 $author["network"] = $importer["network"];
1588 // Until now we aren't serving different sizes - but maybe later
1590 /// @todo check if "avatar" or "photo" would be the best field in the specification
1591 $avatars = $xpath->query($element . "/atom:link[@rel='avatar']", $context);
1592 foreach ($avatars as $avatar) {
1595 foreach ($avatar->attributes as $attributes) {
1596 /// @TODO Rewrite these similar if() to one switch
1597 if ($attributes->name == "href") {
1598 $href = $attributes->textContent;
1600 if ($attributes->name == "width") {
1601 $width = $attributes->textContent;
1603 if ($attributes->name == "updated") {
1604 $author["avatar-date"] = $attributes->textContent;
1607 if (($width > 0) && ($href != "")) {
1608 $avatarlist[$width] = $href;
1612 if (count($avatarlist) > 0) {
1613 krsort($avatarlist);
1614 $author["avatar"] = current($avatarlist);
1617 if (empty($author['avatar']) && !empty($author['link'])) {
1618 $cid = Contact::getIdForURL($author['link'], 0);
1620 $contact = DBA::selectFirst('contact', ['avatar'], ['id' => $cid]);
1621 if (DBA::isResult($contact)) {
1622 $author['avatar'] = $contact['avatar'];
1627 if (empty($author['avatar'])) {
1628 Logger::log('Empty author: ' . $xml);
1631 if (DBA::isResult($contact_old) && !$onlyfetch) {
1632 Logger::log("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", Logger::DEBUG);
1634 $poco = ["url" => $contact_old["url"]];
1636 // When was the last change to name or uri?
1637 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1638 foreach ($name_element->attributes as $attributes) {
1639 if ($attributes->name == "updated") {
1640 $poco["name-date"] = $attributes->textContent;
1644 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1645 foreach ($link_element->attributes as $attributes) {
1646 if ($attributes->name == "updated") {
1647 $poco["uri-date"] = $attributes->textContent;
1651 // Update contact data
1652 $value = XML::getFirstNodeValue($xpath, $element . "/dfrn:handle/text()", $context);
1654 $poco["addr"] = $value;
1657 $value = XML::getFirstNodeValue($xpath, $element . "/poco:displayName/text()", $context);
1659 $poco["name"] = $value;
1662 $value = XML::getFirstNodeValue($xpath, $element . "/poco:preferredUsername/text()", $context);
1664 $poco["nick"] = $value;
1667 $value = XML::getFirstNodeValue($xpath, $element . "/poco:note/text()", $context);
1669 $poco["about"] = $value;
1672 $value = XML::getFirstNodeValue($xpath, $element . "/poco:address/poco:formatted/text()", $context);
1674 $poco["location"] = $value;
1677 /// @todo Only search for elements with "poco:type" = "xmpp"
1678 $value = XML::getFirstNodeValue($xpath, $element . "/poco:ims/poco:value/text()", $context);
1680 $poco["xmpp"] = $value;
1683 /// @todo Add support for the following fields that we don't support by now in the contact table:
1684 /// - poco:utcOffset
1690 // If the "hide" element is present then the profile isn't searchable.
1691 $hide = intval(XML::getFirstNodeValue($xpath, $element . "/dfrn:hide/text()", $context) == "true");
1693 Logger::log("Hidden status for contact " . $contact_old["url"] . ": " . $hide, Logger::DEBUG);
1695 // If the contact isn't searchable then set the contact to "hidden".
1696 // Problem: This can be manually overridden by the user.
1698 $contact_old["hidden"] = true;
1701 // Save the keywords into the contact table
1703 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1704 foreach ($tagelements as $tag) {
1705 $tags[$tag->nodeValue] = $tag->nodeValue;
1709 $poco["keywords"] = implode(", ", $tags);
1712 // "dfrn:birthday" contains the birthday converted to UTC
1713 $birthday = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1715 if (strtotime($birthday) > time()) {
1716 $bd_timestamp = strtotime($birthday);
1718 $poco["bdyear"] = date("Y", $bd_timestamp);
1721 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1722 $value = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1724 if (!in_array($value, ["", "0000-00-00", "0001-01-01"])) {
1725 $bdyear = date("Y");
1726 $value = str_replace("0000", $bdyear, $value);
1728 if (strtotime($value) < time()) {
1729 $value = str_replace($bdyear, $bdyear + 1, $value);
1730 $bdyear = $bdyear + 1;
1733 $poco["bd"] = $value;
1736 $contact = array_merge($contact_old, $poco);
1738 if ($contact_old["bdyear"] != $contact["bdyear"]) {
1739 self::birthdayEvent($contact, $birthday);
1742 // Get all field names
1744 foreach ($contact_old as $field => $data) {
1745 $fields[$field] = $data;
1748 unset($fields["id"]);
1749 unset($fields["uid"]);
1750 unset($fields["url"]);
1751 unset($fields["avatar-date"]);
1752 unset($fields["avatar"]);
1753 unset($fields["name-date"]);
1754 unset($fields["uri-date"]);
1757 // Update check for this field has to be done differently
1758 $datefields = ["name-date", "uri-date"];
1759 foreach ($datefields as $field) {
1760 // The date fields arrives as '2018-07-17T10:44:45Z' - the database return '2018-07-17 10:44:45'
1761 // The fields have to be in the same format to be comparable, since strtotime does add timezones.
1762 $contact[$field] = DateTimeFormat::utc($contact[$field]);
1764 if (strtotime($contact[$field]) > strtotime($contact_old[$field])) {
1765 Logger::log("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", Logger::DEBUG);
1770 foreach ($fields as $field => $data) {
1771 if ($contact[$field] != $contact_old[$field]) {
1772 Logger::log("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", Logger::DEBUG);
1778 Logger::log("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", Logger::DEBUG);
1781 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1782 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1783 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1784 WHERE `id` = %d AND `network` = '%s'",
1785 DBA::escape($contact["name"]), DBA::escape($contact["nick"]), DBA::escape($contact["about"]), DBA::escape($contact["location"]),
1786 DBA::escape($contact["addr"]), DBA::escape($contact["keywords"]), DBA::escape($contact["bdyear"]),
1787 DBA::escape($contact["bd"]), intval($contact["hidden"]), DBA::escape($contact["xmpp"]),
1788 DBA::escape(DateTimeFormat::utc($contact["name-date"])), DBA::escape(DateTimeFormat::utc($contact["uri-date"])),
1789 intval($contact["id"]), DBA::escape($contact["network"])
1793 Contact::updateAvatar(
1795 $importer['importer_uid'],
1797 (strtotime($contact['avatar-date']) > strtotime($contact_old['avatar-date']) || ($author['avatar'] != $contact_old['avatar']))
1801 * The generation is a sign for the reliability of the provided data.
1802 * It is used in the socgraph.php to prevent that old contact data
1803 * that was relayed over several servers can overwrite contact
1804 * data that we received directly.
1807 $poco["generation"] = 2;
1808 $poco["photo"] = $author["avatar"];
1809 $poco["hide"] = $hide;
1810 $poco["contact-type"] = $contact["contact-type"];
1811 $gcid = GContact::update($poco);
1813 GContact::link($gcid, $importer["importer_uid"], $contact["id"]);
1820 * @brief Transforms activity objects into an XML string
1822 * @param object $xpath XPath object
1823 * @param object $activity Activity object
1824 * @param string $element element name
1826 * @return string XML string
1827 * @todo Find good type-hints for all parameter
1829 private static function transformActivity($xpath, $activity, $element)
1831 if (!is_object($activity)) {
1835 $obj_doc = new DOMDocument("1.0", "utf-8");
1836 $obj_doc->formatOutput = true;
1838 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1840 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1841 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1843 $id = $xpath->query("atom:id", $activity)->item(0);
1844 if (is_object($id)) {
1845 $obj_element->appendChild($obj_doc->importNode($id, true));
1848 $title = $xpath->query("atom:title", $activity)->item(0);
1849 if (is_object($title)) {
1850 $obj_element->appendChild($obj_doc->importNode($title, true));
1853 $links = $xpath->query("atom:link", $activity);
1854 if (is_object($links)) {
1855 foreach ($links as $link) {
1856 $obj_element->appendChild($obj_doc->importNode($link, true));
1860 $content = $xpath->query("atom:content", $activity)->item(0);
1861 if (is_object($content)) {
1862 $obj_element->appendChild($obj_doc->importNode($content, true));
1865 $obj_doc->appendChild($obj_element);
1867 $objxml = $obj_doc->saveXML($obj_element);
1869 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1870 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1875 * @brief Processes the mail elements
1877 * @param object $xpath XPath object
1878 * @param object $mail mail elements
1879 * @param array $importer Record of the importer user mixed with contact of the content
1881 * @todo Find good type-hints for all parameter
1883 private static function processMail($xpath, $mail, $importer)
1885 Logger::log("Processing mails");
1887 /// @TODO Rewrite this to one statement
1889 $msg["uid"] = $importer["importer_uid"];
1890 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1891 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1892 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1893 $msg["contact-id"] = $importer["id"];
1894 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1895 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1896 $msg["created"] = DateTimeFormat::utc($xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue);
1897 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1898 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1900 $msg["replied"] = 0;
1902 DBA::insert('mail', $msg);
1904 $msg["id"] = DBA::lastInsertId();
1906 // send notifications.
1907 /// @TODO Arange this mess
1909 "type" => NOTIFY_MAIL,
1910 "notify_flags" => $importer["notify-flags"],
1911 "language" => $importer["language"],
1912 "to_name" => $importer["username"],
1913 "to_email" => $importer["email"],
1914 "uid" => $importer["importer_uid"],
1916 "source_name" => $msg["from-name"],
1917 "source_link" => $importer["url"],
1918 "source_photo" => $importer["thumb"],
1919 "verb" => ACTIVITY_POST,
1923 notification($notif_params);
1925 Logger::log("Mail is processed, notification was sent.");
1929 * @brief Processes the suggestion elements
1931 * @param object $xpath XPath object
1932 * @param object $suggestion suggestion elements
1933 * @param array $importer Record of the importer user mixed with contact of the content
1935 * @todo Find good type-hints for all parameter
1937 private static function processSuggestion($xpath, $suggestion, $importer)
1941 Logger::log("Processing suggestions");
1943 /// @TODO Rewrite this to one statement
1945 $suggest["uid"] = $importer["importer_uid"];
1946 $suggest["cid"] = $importer["id"];
1947 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1948 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1949 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1950 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1951 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1953 // Does our member already have a friend matching this description?
1956 * The valid result means the friend we're about to send a friend
1957 * suggestion already has them in their contact, which means no further
1958 * action is required.
1960 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1962 $condition = ['name' => $suggest["name"], 'nurl' => normalise_link($suggest["url"]),
1963 'uid' => $suggest["uid"]];
1964 if (DBA::exists('contact', $condition)) {
1968 // Do we already have an fcontact record for this person?
1971 $condition = ['url' => $suggest["url"], 'name' => $suggest["name"], 'request' => $suggest["request"]];
1972 $fcontact = DBA::selectFirst('fcontact', ['id'], $condition);
1973 if (DBA::isResult($fcontact)) {
1974 $fid = $fcontact["id"];
1976 // OK, we do. Do we already have an introduction for this person?
1977 if (DBA::exists('intro', ['uid' => $suggest["uid"], 'fid' => $fid])) {
1979 * The valid result means the friend we're about to send a friend
1980 * suggestion already has them in their contact, which means no further
1981 * action is required.
1983 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1990 "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1991 DBA::escape($suggest["name"]),
1992 DBA::escape($suggest["url"]),
1993 DBA::escape($suggest["photo"]),
1994 DBA::escape($suggest["request"])
1998 $condition = ['url' => $suggest["url"], 'name' => $suggest["name"], 'request' => $suggest["request"]];
1999 $fcontact = DBA::selectFirst('fcontact', ['id'], $condition);
2002 * If no record in fcontact is found, below INSERT statement will not
2003 * link an introduction to it.
2005 if (!DBA::isResult($fcontact)) {
2006 // Database record did not get created. Quietly give up.
2012 $hash = random_string();
2015 "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
2016 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
2017 intval($suggest["uid"]),
2019 intval($suggest["cid"]),
2020 DBA::escape($suggest["body"]),
2022 DBA::escape(DateTimeFormat::utcNow()),
2028 "type" => NOTIFY_SUGGEST,
2029 "notify_flags" => $importer["notify-flags"],
2030 "language" => $importer["language"],
2031 "to_name" => $importer["username"],
2032 "to_email" => $importer["email"],
2033 "uid" => $importer["importer_uid"],
2035 "link" => System::baseUrl()."/notifications/intros",
2036 "source_name" => $importer["name"],
2037 "source_link" => $importer["url"],
2038 "source_photo" => $importer["photo"],
2039 "verb" => ACTIVITY_REQ_FRIEND,
2047 * @brief Processes the relocation elements
2049 * @param object $xpath XPath object
2050 * @param object $relocation relocation elements
2051 * @param array $importer Record of the importer user mixed with contact of the content
2053 * @todo Find good type-hints for all parameter
2055 private static function processRelocation($xpath, $relocation, $importer)
2057 Logger::log("Processing relocations");
2059 /// @TODO Rewrite this to one statement
2061 $relocate["uid"] = $importer["importer_uid"];
2062 $relocate["cid"] = $importer["id"];
2063 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
2064 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
2065 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
2066 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
2067 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
2068 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
2069 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
2070 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
2071 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
2072 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
2073 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
2074 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
2076 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
2077 $relocate["avatar"] = $relocate["photo"];
2080 if ($relocate["addr"] == "") {
2081 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
2086 "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d",
2087 intval($importer["id"]),
2088 intval($importer["importer_uid"])
2091 if (!DBA::isResult($r)) {
2092 Logger::log("Query failed to execute, no result returned in " . __FUNCTION__);
2098 // Update the gcontact entry
2099 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
2101 $fields = ['name' => $relocate["name"], 'photo' => $relocate["avatar"],
2102 'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2103 'addr' => $relocate["addr"], 'connect' => $relocate["addr"],
2104 'notify' => $relocate["notify"], 'server_url' => $relocate["server_url"]];
2105 DBA::update('gcontact', $fields, ['nurl' => normalise_link($old["url"])]);
2107 // Update the contact table. We try to find every entry.
2108 $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
2109 'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2110 'addr' => $relocate["addr"], 'request' => $relocate["request"],
2111 'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
2112 'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
2113 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], normalise_link($old["url"])];
2115 DBA::update('contact', $fields, $condition);
2117 Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
2119 Logger::log('Contacts are updated.');
2122 /// merge with current record, current contents have priority
2123 /// update record, set url-updated
2124 /// update profile photos
2125 /// schedule a scan?
2130 * @brief Updates an item
2132 * @param array $current the current item record
2133 * @param array $item the new item record
2134 * @param array $importer Record of the importer user mixed with contact of the content
2135 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2137 * @todo set proper type-hints (array?)
2139 private static function updateContent($current, $item, $importer, $entrytype)
2143 if (self::isEditedTimestampNewer($current, $item)) {
2144 // do not accept (ignore) an earlier edit than one we currently have.
2145 if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
2149 $fields = ['title' => defaults($item, 'title', ''), 'body' => defaults($item, 'body', ''),
2150 'tag' => defaults($item, 'tag', ''), 'changed' => DateTimeFormat::utcNow(),
2151 'edited' => DateTimeFormat::utc($item["edited"])];
2153 $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
2154 Item::update($fields, $condition);
2162 * @brief Detects the entry type of the item
2164 * @param array $importer Record of the importer user mixed with contact of the content
2165 * @param array $item the new item record
2167 * @return int Is it a toplevel entry, a comment or a relayed comment?
2168 * @todo set proper type-hints (array?)
2170 private static function getEntryType($importer, $item)
2172 if ($item["parent-uri"] != $item["uri"]) {
2175 if ($importer["page-flags"] == Contact::PAGE_COMMUNITY || $importer["page-flags"] == Contact::PAGE_PRVGROUP) {
2178 Logger::log("possible community action");
2180 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2183 // was the top-level post for this action written by somebody on this site?
2184 // Specifically, the recipient?
2186 $is_a_remote_action = false;
2188 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item["parent-uri"]]);
2189 if (DBA::isResult($parent)) {
2191 "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2192 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2193 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2194 AND `item`.`uid` = %d
2197 DBA::escape($parent["parent-uri"]),
2198 DBA::escape($parent["parent-uri"]),
2199 DBA::escape($parent["parent-uri"]),
2200 intval($importer["importer_uid"])
2202 if (DBA::isResult($r)) {
2203 $is_a_remote_action = true;
2208 * Does this have the characteristics of a community or private group action?
2209 * If it's an action to a wall post on a community/prvgroup page it's a
2210 * valid community action. Also forum_mode makes it valid for sure.
2211 * If neither, it's not.
2213 if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2214 $is_a_remote_action = false;
2215 Logger::log("not a community action");
2218 if ($is_a_remote_action) {
2219 return DFRN::REPLY_RC;
2224 return DFRN::TOP_LEVEL;
2229 * @brief Send a "poke"
2231 * @param array $item the new item record
2232 * @param array $importer Record of the importer user mixed with contact of the content
2233 * @param int $posted_id The record number of item record that was just posted
2235 * @todo set proper type-hints (array?)
2237 private static function doPoke($item, $importer, $posted_id)
2239 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2243 $xo = XML::parseString($item["object"], false);
2245 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2246 // somebody was poked/prodded. Was it me?
2247 foreach ($xo->link as $l) {
2248 $atts = $l->attributes();
2249 switch ($atts["rel"]) {
2251 $Blink = $atts["href"];
2258 if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2259 $author = DBA::selectFirst('contact', ['name', 'thumb', 'url'], ['id' => $item['author-id']]);
2261 $item['id'] = $posted_id;
2263 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => $importer["importer_uid"]]);
2264 $item["parent"] = $parent['id'];
2266 // send a notification
2269 "type" => NOTIFY_POKE,
2270 "notify_flags" => $importer["notify-flags"],
2271 "language" => $importer["language"],
2272 "to_name" => $importer["username"],
2273 "to_email" => $importer["email"],
2274 "uid" => $importer["importer_uid"],
2276 "link" => System::baseUrl()."/display/".urlencode(Item::getGuidById($posted_id)),
2277 "source_name" => $author["name"],
2278 "source_link" => $author["url"],
2279 "source_photo" => $author["thumb"],
2280 "verb" => $item["verb"],
2281 "otype" => "person",
2282 "activity" => $verb,
2283 "parent" => $item["parent"]]
2290 * @brief Processes several actions, depending on the verb
2292 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2293 * @param array $importer Record of the importer user mixed with contact of the content
2294 * @param array $item the new item record
2295 * @param bool $is_like Is the verb a "like"?
2297 * @return bool Should the processing of the entries be continued?
2298 * @todo set proper type-hints (array?)
2300 private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2302 Logger::log("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, Logger::DEBUG);
2304 if (($entrytype == DFRN::TOP_LEVEL)) {
2305 // The filling of the the "contact" variable is done for legcy reasons
2306 // The functions below are partly used by ostatus.php as well - where we have this variable
2307 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2309 $nickname = $contact["nick"];
2311 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2312 // This function once was responsible for DFRN and OStatus.
2313 if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2314 Logger::log("New follower");
2315 Contact::addRelationship($importer, $contact, $item, $nickname);
2318 if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2319 Logger::log("Lost follower");
2320 Contact::removeFollower($importer, $contact, $item);
2323 if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2324 Logger::log("New friend request");
2325 Contact::addRelationship($importer, $contact, $item, $nickname, true);
2328 if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2329 Logger::log("Lost sharer");
2330 Contact::removeSharer($importer, $contact, $item);
2334 if (($item["verb"] == ACTIVITY_LIKE)
2335 || ($item["verb"] == ACTIVITY_DISLIKE)
2336 || ($item["verb"] == ACTIVITY_ATTEND)
2337 || ($item["verb"] == ACTIVITY_ATTENDNO)
2338 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
2341 $item["gravity"] = GRAVITY_ACTIVITY;
2342 // only one like or dislike per person
2343 // splitted into two queries for performance issues
2344 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2345 'verb' => $item["verb"], 'parent-uri' => $item["parent-uri"]];
2346 if (Item::exists($condition)) {
2350 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2351 'verb' => $item["verb"], 'thr-parent' => $item["parent-uri"]];
2352 if (Item::exists($condition)) {
2356 // The owner of an activity must be the author
2357 $item["owner-name"] = $item["author-name"];
2358 $item["owner-link"] = $item["author-link"];
2359 $item["owner-avatar"] = $item["author-avatar"];
2360 $item["owner-id"] = $item["author-id"];
2365 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2366 $xo = XML::parseString($item["object"], false);
2367 $xt = XML::parseString($item["target"], false);
2369 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2370 $item_tag = Item::selectFirst(['id', 'tag'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]);
2372 if (!DBA::isResult($item_tag)) {
2373 Logger::log("Query failed to execute, no result returned in " . __FUNCTION__);
2377 // extract tag, if not duplicate, add to parent item
2379 if (!stristr($item_tag["tag"], trim($xo->content))) {
2380 $tag = $item_tag["tag"] . (strlen($item_tag["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2381 Item::update(['tag' => $tag], ['id' => $item_tag["id"]]);
2391 * @brief Processes the link elements
2393 * @param object $links link elements
2394 * @param array $item the item record
2396 * @todo set proper type-hints
2398 private static function parseLinks($links, &$item)
2405 foreach ($links as $link) {
2406 foreach ($link->attributes as $attributes) {
2407 switch ($attributes->name) {
2408 case "href" : $href = $attributes->textContent; break;
2409 case "rel" : $rel = $attributes->textContent; break;
2410 case "type" : $type = $attributes->textContent; break;
2411 case "length": $length = $attributes->textContent; break;
2412 case "title" : $title = $attributes->textContent; break;
2415 if (($rel != "") && ($href != "")) {
2418 $item["plink"] = $href;
2423 if (!empty($item["attach"])) {
2424 $item["attach"] .= ",";
2426 $item["attach"] = "";
2429 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2437 * @brief Processes the entry elements which contain the items and comments
2439 * @param array $header Array of the header elements that always stay the same
2440 * @param object $xpath XPath object
2441 * @param object $entry entry elements
2442 * @param array $importer Record of the importer user mixed with contact of the content
2443 * @param object $xml xml
2445 * @todo Add type-hints
2447 private static function processEntry($header, $xpath, $entry, $importer, $xml)
2449 Logger::log("Processing entries");
2453 $item["protocol"] = Conversation::PARCEL_DFRN;
2455 $item["source"] = $xml;
2458 $item["uri"] = XML::getFirstNodeValue($xpath, "atom:id/text()", $entry);
2460 $item["edited"] = XML::getFirstNodeValue($xpath, "atom:updated/text()", $entry);
2462 $current = Item::selectFirst(['id', 'uid', 'edited', 'body'],
2463 ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
2465 // Is there an existing item?
2466 if (DBA::isResult($current) && !self::isEditedTimestampNewer($current, $item)) {
2467 Logger::log("Item ".$item["uri"]." (".$item['edited'].") already existed.", Logger::DEBUG);
2472 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true, $xml);
2474 $owner_unknown = (isset($owner["contact-unknown"]) && $owner["contact-unknown"]);
2476 $item["owner-name"] = $owner["name"];
2477 $item["owner-link"] = $owner["link"];
2478 $item["owner-avatar"] = $owner["avatar"];
2479 $item["owner-id"] = Contact::getIdForURL($owner["link"], 0);
2482 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true, $xml);
2484 $item["author-name"] = $author["name"];
2485 $item["author-link"] = $author["link"];
2486 $item["author-avatar"] = $author["avatar"];
2487 $item["author-id"] = Contact::getIdForURL($author["link"], 0);
2489 $item["title"] = XML::getFirstNodeValue($xpath, "atom:title/text()", $entry);
2491 $item["created"] = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2493 $item["body"] = XML::getFirstNodeValue($xpath, "dfrn:env/text()", $entry);
2494 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2495 // make sure nobody is trying to sneak some html tags by us
2496 $item["body"] = notags(base64url_decode($item["body"]));
2498 $item["body"] = BBCode::limitBodySize($item["body"]);
2500 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2501 if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
2502 $base_url = get_app()->getBaseURL();
2503 $item['body'] = HTML::relToAbs($item['body'], $base_url);
2505 $item['body'] = HTML::toBBVideo($item['body']);
2507 $item['body'] = OEmbed::HTML2BBCode($item['body']);
2509 $config = HTMLPurifier_Config::createDefault();
2510 $config->set('Cache.DefinitionImpl', null);
2512 // we shouldn't need a whitelist, because the bbcode converter
2513 // will strip out any unsupported tags.
2515 $purifier = new HTMLPurifier($config);
2516 $item['body'] = $purifier->purify($item['body']);
2518 $item['body'] = @HTML::toBBCode($item['body']);
2521 /// @todo We should check for a repeated post and if we know the repeated author.
2523 // We don't need the content element since "dfrn:env" is always present
2524 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2526 $item["location"] = XML::getFirstNodeValue($xpath, "dfrn:location/text()", $entry);
2528 $item["coord"] = XML::getFirstNodeValue($xpath, "georss:point", $entry);
2530 $item["private"] = XML::getFirstNodeValue($xpath, "dfrn:private/text()", $entry);
2532 $item["extid"] = XML::getFirstNodeValue($xpath, "dfrn:extid/text()", $entry);
2534 if (XML::getFirstNodeValue($xpath, "dfrn:bookmark/text()", $entry) == "true") {
2535 $item["post-type"] = Item::PT_PAGE;
2538 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2539 if ($notice_info && ($notice_info->length > 0)) {
2540 foreach ($notice_info->item(0)->attributes as $attributes) {
2541 if ($attributes->name == "source") {
2542 $item["app"] = strip_tags($attributes->textContent);
2547 $item["guid"] = XML::getFirstNodeValue($xpath, "dfrn:diaspora_guid/text()", $entry);
2549 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
2550 $dsprsig = XML::unescape(XML::getFirstNodeValue($xpath, "dfrn:diaspora_signature/text()", $entry));
2551 if ($dsprsig != "") {
2552 $item["dsprsig"] = $dsprsig;
2555 $item["verb"] = XML::getFirstNodeValue($xpath, "activity:verb/text()", $entry);
2557 if (XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry) != "") {
2558 $item["object-type"] = XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry);
2561 $object = $xpath->query("activity:object", $entry)->item(0);
2562 $item["object"] = self::transformActivity($xpath, $object, "object");
2564 if (trim($item["object"]) != "") {
2565 $r = XML::parseString($item["object"], false);
2566 if (isset($r->type)) {
2567 $item["object-type"] = $r->type;
2571 $target = $xpath->query("activity:target", $entry)->item(0);
2572 $item["target"] = self::transformActivity($xpath, $target, "target");
2574 $categories = $xpath->query("atom:category", $entry);
2576 foreach ($categories as $category) {
2579 foreach ($category->attributes as $attributes) {
2580 if ($attributes->name == "term") {
2581 $term = $attributes->textContent;
2584 if ($attributes->name == "scheme") {
2585 $scheme = $attributes->textContent;
2589 if (($term != "") && ($scheme != "")) {
2590 $parts = explode(":", $scheme);
2591 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2592 $termhash = array_shift($parts);
2593 $termurl = implode(":", $parts);
2595 if (!empty($item["tag"])) {
2596 $item["tag"] .= ",";
2601 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2609 $links = $xpath->query("atom:link", $entry);
2611 self::parseLinks($links, $item);
2614 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
2616 $conv = $xpath->query('ostatus:conversation', $entry);
2617 if (is_object($conv->item(0))) {
2618 foreach ($conv->item(0)->attributes as $attributes) {
2619 if ($attributes->name == "ref") {
2620 $item['conversation-uri'] = $attributes->textContent;
2622 if ($attributes->name == "href") {
2623 $item['conversation-href'] = $attributes->textContent;
2628 // Is it a reply or a top level posting?
2629 $item["parent-uri"] = $item["uri"];
2631 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2632 if (is_object($inreplyto->item(0))) {
2633 foreach ($inreplyto->item(0)->attributes as $attributes) {
2634 if ($attributes->name == "ref") {
2635 $item["parent-uri"] = $attributes->textContent;
2640 // Get the type of the item (Top level post, reply or remote reply)
2641 $entrytype = self::getEntryType($importer, $item);
2643 // Now assign the rest of the values that depend on the type of the message
2644 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2645 if (!isset($item["object-type"])) {
2646 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2649 if ($item["contact-id"] != $owner["contact-id"]) {
2650 $item["contact-id"] = $owner["contact-id"];
2653 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2654 $item["network"] = $owner["network"];
2657 if ($item["contact-id"] != $author["contact-id"]) {
2658 $item["contact-id"] = $author["contact-id"];
2661 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2662 $item["network"] = $author["network"];
2666 if ($entrytype == DFRN::REPLY_RC) {
2668 } elseif ($entrytype == DFRN::TOP_LEVEL) {
2669 if (!isset($item["object-type"])) {
2670 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2674 if (($item["object-type"] == ACTIVITY_OBJ_EVENT) && !$owner_unknown) {
2675 Logger::log("Item ".$item["uri"]." seems to contain an event.", Logger::DEBUG);
2676 $ev = Event::fromBBCode($item["body"]);
2677 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2678 Logger::log("Event in item ".$item["uri"]." was found.", Logger::DEBUG);
2679 $ev["cid"] = $importer["id"];
2680 $ev["uid"] = $importer["importer_uid"];
2681 $ev["uri"] = $item["uri"];
2682 $ev["edited"] = $item["edited"];
2683 $ev["private"] = $item["private"];
2684 $ev["guid"] = $item["guid"];
2685 $ev["plink"] = $item["plink"];
2687 $condition = ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]];
2688 $event = DBA::selectFirst('event', ['id'], $condition);
2689 if (DBA::isResult($event)) {
2690 $ev["id"] = $event["id"];
2693 $event_id = Event::store($ev);
2694 Logger::log("Event ".$event_id." was stored", Logger::DEBUG);
2700 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2701 Logger::log("Exiting because 'processVerbs' told us so", Logger::DEBUG);
2705 // This check is done here to be able to receive connection requests in "processVerbs"
2706 if (($entrytype == DFRN::TOP_LEVEL) && $owner_unknown) {
2707 Logger::log("Item won't be stored because user " . $importer["importer_uid"] . " doesn't follow " . $item["owner-link"] . ".", Logger::DEBUG);
2712 // Update content if 'updated' changes
2713 if (DBA::isResult($current)) {
2714 if (self::updateContent($current, $item, $importer, $entrytype)) {
2715 Logger::log("Item ".$item["uri"]." was updated.", Logger::DEBUG);
2717 Logger::log("Item " . $item["uri"] . " already existed.", Logger::DEBUG);
2722 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2723 $posted_id = Item::insert($item);
2727 Logger::log("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, Logger::DEBUG);
2729 if ($item['uid'] == 0) {
2730 Item::distribute($posted_id);
2735 } else { // $entrytype == DFRN::TOP_LEVEL
2736 if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
2737 Logger::log("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", Logger::DEBUG);
2740 if (!link_compare($item["owner-link"], $importer["url"])) {
2742 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2743 * but otherwise there's a possible data mixup on the sender's system.
2744 * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2745 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2747 Logger::log('Correcting item owner.', Logger::DEBUG);
2748 $item["owner-link"] = $importer["url"];
2749 $item["owner-id"] = Contact::getIdForURL($importer["url"], 0);
2752 if (($importer["rel"] == Contact::FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2753 Logger::log("Contact ".$importer["id"]." is only follower and tgroup check was negative.", Logger::DEBUG);
2757 // This is my contact on another system, but it's really me.
2758 // Turn this into a wall post.
2759 $notify = Item::isRemoteSelf($importer, $item);
2761 $posted_id = Item::insert($item, false, $notify);
2764 $posted_id = $notify;
2767 Logger::log("Item was stored with id ".$posted_id, Logger::DEBUG);
2769 if ($item['uid'] == 0) {
2770 Item::distribute($posted_id);
2773 if (stristr($item["verb"], ACTIVITY_POKE)) {
2774 self::doPoke($item, $importer, $posted_id);
2780 * @brief Deletes items
2782 * @param object $xpath XPath object
2783 * @param object $deletion deletion elements
2784 * @param array $importer Record of the importer user mixed with contact of the content
2786 * @todo set proper type-hints
2788 private static function processDeletion($xpath, $deletion, $importer)
2790 Logger::log("Processing deletions");
2793 foreach ($deletion->attributes as $attributes) {
2794 if ($attributes->name == "ref") {
2795 $uri = $attributes->textContent;
2799 if (!$uri || !$importer["id"]) {
2803 $condition = ['uri' => $uri, 'uid' => $importer["importer_uid"]];
2804 $item = Item::selectFirst(['id', 'parent', 'contact-id', 'file', 'deleted'], $condition);
2805 if (!DBA::isResult($item)) {
2806 Logger::log("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", Logger::DEBUG);
2810 if (strstr($item['file'], '[')) {
2811 Logger::log("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " is filed. So it won't be deleted.", Logger::DEBUG);
2815 // When it is a starting post it has to belong to the person that wants to delete it
2816 if (($item['id'] == $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2817 Logger::log("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", Logger::DEBUG);
2821 // Comments can be deleted by the thread owner or comment owner
2822 if (($item['id'] != $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2823 $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2824 if (!Item::exists($condition)) {
2825 Logger::log("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", Logger::DEBUG);
2830 if ($item["deleted"]) {
2834 Logger::log('deleting item '.$item['id'].' uri='.$uri, Logger::DEBUG);
2836 Item::delete(['id' => $item['id']]);
2840 * @brief Imports a DFRN message
2842 * @param string $xml The DFRN message
2843 * @param array $importer Record of the importer user mixed with contact of the content
2844 * @param bool $sort_by_date Is used when feeds are polled
2845 * @return integer Import status
2846 * @todo set proper type-hints
2848 public static function import($xml, $importer, $sort_by_date = false)
2854 $doc = new DOMDocument();
2855 @$doc->loadXML($xml);
2857 $xpath = new DOMXPath($doc);
2858 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2859 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2860 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2861 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2862 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2863 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2864 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2865 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2866 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2867 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2870 $header["uid"] = $importer["importer_uid"];
2871 $header["network"] = Protocol::DFRN;
2872 $header["wall"] = 0;
2873 $header["origin"] = 0;
2874 $header["contact-id"] = $importer["id"];
2876 // Update the contact table if the data has changed
2878 // The "atom:author" is only present in feeds
2879 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2880 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2883 // Only the "dfrn:owner" in the head section contains all data
2884 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2885 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2888 Logger::log("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], Logger::DEBUG);
2890 // is it a public forum? Private forums aren't exposed with this method
2891 $forum = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:community/text()"));
2893 // The account type is new since 3.5.1
2894 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2895 $accounttype = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:account_type/text()"));
2897 if ($accounttype != $importer["contact-type"]) {
2898 DBA::update('contact', ['contact-type' => $accounttype], ['id' => $importer["id"]]);
2900 // A forum contact can either have set "forum" or "prv" - but not both
2901 if (($accounttype == Contact::ACCOUNT_TYPE_COMMUNITY) && (($forum != $importer["forum"]) || ($forum == $importer["prv"]))) {
2902 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer["id"]];
2903 DBA::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2905 } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
2906 $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2907 DBA::update('contact', ['forum' => $forum], $condition);
2911 // We are processing relocations even if we are ignoring a contact
2912 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2913 foreach ($relocations as $relocation) {
2914 self::processRelocation($xpath, $relocation, $importer);
2917 if (($importer["uid"] != 0) && !$importer["readonly"]) {
2918 $mails = $xpath->query("/atom:feed/dfrn:mail");
2919 foreach ($mails as $mail) {
2920 self::processMail($xpath, $mail, $importer);
2923 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2924 foreach ($suggestions as $suggestion) {
2925 self::processSuggestion($xpath, $suggestion, $importer);
2929 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2930 foreach ($deletions as $deletion) {
2931 self::processDeletion($xpath, $deletion, $importer);
2934 if (!$sort_by_date) {
2935 $entries = $xpath->query("/atom:feed/atom:entry");
2936 foreach ($entries as $entry) {
2937 self::processEntry($header, $xpath, $entry, $importer, $xml);
2941 $entries = $xpath->query("/atom:feed/atom:entry");
2942 foreach ($entries as $entry) {
2943 $created = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2944 $newentries[strtotime($created)] = $entry;
2947 // Now sort after the publishing date
2950 foreach ($newentries as $entry) {
2951 self::processEntry($header, $xpath, $entry, $importer, $xml);
2954 Logger::log("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], Logger::DEBUG);
2960 * @param string $contact_nick contact nickname
2962 public static function autoRedir(App $a, $contact_nick)
2965 if (x($_REQUEST, 'redir') && intval($_REQUEST['redir'])) {
2969 if ((! $contact_nick) || ($contact_nick === $a->user['nickname'])) {
2974 // We need to find out if $contact_nick is a user on this hub, and if so, if I
2975 // am a contact of that user. However, that user may have other contacts with the
2976 // same nickname as me on other hubs or other networks. Exclude these by requiring
2977 // that the contact have a local URL. I will be the only person with my nickname at
2978 // this URL, so if a result is found, then I am a contact of the $contact_nick user.
2980 // We also have to make sure that I'm a legitimate contact--I'm not blocked or pending.
2982 $baseurl = System::baseUrl();
2983 $domain_st = strpos($baseurl, "://");
2984 if ($domain_st === false) {
2987 $baseurl = substr($baseurl, $domain_st + 3);
2988 $nurl = normalise_link($baseurl);
2990 /// @todo Why is there a query for "url" *and* "nurl"? Especially this normalising is strange.
2991 $r = q("SELECT `id` FROM `contact` WHERE `uid` = (SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1)
2992 AND `nick` = '%s' AND NOT `self` AND (`url` LIKE '%%%s%%' OR `nurl` LIKE '%%%s%%') AND NOT `blocked` AND NOT `pending` LIMIT 1",
2993 DBA::escape($contact_nick),
2994 DBA::escape($a->user['nickname']),
2995 DBA::escape($baseurl),
2998 if ((! DBA::isResult($r)) || $r[0]['id'] == remote_user()) {
3002 $r = q("SELECT * FROM contact WHERE nick = '%s'
3003 AND network = '%s' AND uid = %d AND url LIKE '%%%s%%' LIMIT 1",
3004 DBA::escape($contact_nick),
3005 DBA::escape(Protocol::DFRN),
3006 intval(local_user()),
3007 DBA::escape($baseurl)
3009 if (! DBA::isResult($r)) {
3015 $dfrn_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
3017 if ($r[0]['duplex'] && $r[0]['issued-id']) {
3018 $orig_id = $r[0]['issued-id'];
3019 $dfrn_id = '1:' . $orig_id;
3021 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
3022 $orig_id = $r[0]['dfrn-id'];
3023 $dfrn_id = '0:' . $orig_id;
3026 // ensure that we've got a valid ID. There may be some edge cases with forums and non-duplex mode
3027 // that may have triggered some of the "went to {profile/intro} and got an RSS feed" issues
3029 if (strlen($dfrn_id) < 3) {
3033 $sec = random_string();
3035 DBA::insert('profile_check', ['uid' => local_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id, 'sec' => $sec, 'expire' => time() + 45]);
3037 $url = curPageURL();
3039 Logger::log('auto_redir: ' . $r[0]['name'] . ' ' . $sec, Logger::DEBUG);
3040 $dest = (($url) ? '&destination_url=' . $url : '');
3041 System::externalRedirect($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
3042 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest);
3049 * @brief Returns the activity verb
3051 * @param array $item Item array
3053 * @return string activity verb
3055 private static function constructVerb(array $item)
3057 if ($item['verb']) {
3058 return $item['verb'];
3060 return ACTIVITY_POST;
3063 private static function tgroupCheck($uid, $item)
3067 // check that the message originated elsewhere and is a top-level post
3069 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['parent-uri'])) {
3073 $user = DBA::selectFirst('user', ['page-flags', 'nickname'], ['uid' => $uid]);
3074 if (!DBA::isResult($user)) {
3078 $community_page = ($user['page-flags'] == Contact::PAGE_COMMUNITY);
3079 $prvgroup = ($user['page-flags'] == Contact::PAGE_PRVGROUP);
3081 $link = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
3084 * Diaspora uses their own hardwired link URL in @-tags
3085 * instead of the one we supply with webfinger
3087 $dlink = normalise_link(System::baseUrl() . '/u/' . $user['nickname']);
3089 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
3091 foreach ($matches as $mtch) {
3092 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
3094 Logger::log('mention found: ' . $mtch[2]);
3103 return $community_page || $prvgroup;
3107 * This function returns true if $update has an edited timestamp newer
3108 * than $existing, i.e. $update contains new data which should override
3109 * what's already there. If there is no timestamp yet, the update is
3110 * assumed to be newer. If the update has no timestamp, the existing
3111 * item is assumed to be up-to-date. If the timestamps are equal it
3112 * assumes the update has been seen before and should be ignored.
3115 private static function isEditedTimestampNewer($existing, $update)
3117 if (!x($existing, 'edited') || !$existing['edited']) {
3120 if (!x($update, 'edited') || !$update['edited']) {
3124 $existing_edited = DateTimeFormat::utc($existing['edited']);
3125 $update_edited = DateTimeFormat::utc($update['edited']);
3127 return (strcmp($existing_edited, $update_edited) < 0);