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\System;
21 use Friendica\Database\DBA;
22 use Friendica\Model\Contact;
23 use Friendica\Model\Event;
24 use Friendica\Model\GContact;
25 use Friendica\Model\Group;
26 use Friendica\Model\Item;
27 use Friendica\Model\Profile;
28 use Friendica\Model\PermissionSet;
29 use Friendica\Model\User;
30 use Friendica\Object\Image;
31 use Friendica\Util\Crypto;
32 use Friendica\Util\DateTimeFormat;
33 use Friendica\Util\Network;
34 use Friendica\Util\XML;
36 use HTMLPurifier_Config;
38 require_once 'boot.php';
39 require_once 'include/dba.php';
40 require_once "include/enotify.php";
41 require_once "include/items.php";
42 require_once "include/text.php";
45 * @brief This class contain functions to create and send DFRN XML files
50 const TOP_LEVEL = 0; // Top level posting
51 const REPLY = 1; // Regular reply that is stored locally
52 const REPLY_RC = 2; // Reply that will be relayed
55 * @brief Generates the atom entries for delivery.php
57 * This function is used whenever content is transmitted via DFRN.
59 * @param array $items Item elements
60 * @param array $owner Owner record
62 * @return string DFRN entries
63 * @todo Find proper type-hints
65 public static function entries($items, $owner)
67 $doc = new DOMDocument('1.0', 'utf-8');
68 $doc->formatOutput = true;
70 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
72 if (! count($items)) {
73 return trim($doc->saveXML());
76 foreach ($items as $item) {
77 // These values aren't sent when sending from the queue.
78 /// @todo Check if we can set these values from the queue or if they are needed at all.
79 $item["entry:comment-allow"] = defaults($item, "entry:comment-allow", true);
80 $item["entry:cid"] = defaults($item, "entry:cid", 0);
82 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
83 $root->appendChild($entry);
86 return trim($doc->saveXML());
90 * @brief Generate an atom feed for the given user
92 * This function is called when another server is pulling data from the user feed.
94 * @param string $dfrn_id DFRN ID from the requesting party
95 * @param string $owner_nick Owner nick name
96 * @param string $last_update Date of the last update
97 * @param int $direction Can be -1, 0 or 1.
98 * @param boolean $onlyheader Output only the header without content? (Default is "no")
100 * @return string DFRN feed entries
102 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false)
106 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
107 $public_feed = (($dfrn_id) ? false : true);
108 $starred = false; // not yet implemented, possible security issues
111 if ($public_feed && $a->argc > 2) {
112 for ($x = 2; $x < $a->argc; $x++) {
113 if ($a->argv[$x] == 'converse') {
116 if ($a->argv[$x] == 'starred') {
119 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
120 $category = $a->argv[$x+1];
125 // default permissions - anonymous user
127 $sql_extra = " AND NOT `item`.`private` ";
130 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
131 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
132 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
133 DBA::escape($owner_nick)
136 if (! DBA::isResult($r)) {
137 logger(sprintf('No contact found for nickname=%d', $owner_nick), LOGGER_WARNING);
142 $owner_id = $owner['uid'];
143 $owner_nick = $owner['nickname'];
145 $sql_post_table = "";
147 if (! $public_feed) {
149 switch ($direction) {
151 $sql_extra = sprintf(" AND `issued-id` = '%s' ", DBA::escape($dfrn_id));
155 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
156 $my_id = '1:' . $dfrn_id;
159 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
160 $my_id = '0:' . $dfrn_id;
168 "SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
172 if (! DBA::isResult($r)) {
173 logger(sprintf('No contact found for uid=%d', $owner_id), LOGGER_WARNING);
178 include_once 'include/security.php';
180 $set = PermissionSet::get($owner_id, $contact['id']);
183 $sql_extra = " AND `item`.`psid` IN (" . implode(',', $set) .")";
185 $sql_extra = " AND NOT `item`.`private`";
195 if (! strlen($last_update)) {
196 $last_update = 'now -30 days';
199 if (isset($category)) {
200 $sql_post_table = sprintf(
201 "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` ",
202 DBA::escape(protect_sprintf($category)),
203 intval(TERM_OBJ_POST),
204 intval(TERM_CATEGORY),
207 //$sql_extra .= file_tag_file_query('item',$category,'category');
210 if ($public_feed && ! $converse) {
211 $sql_extra .= " AND `contact`.`self` = 1 ";
214 $check_date = DateTimeFormat::utc($last_update);
218 FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
219 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
220 WHERE `item`.`uid` = %d AND `item`.`wall` AND `item`.`changed` > '%s'
222 ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
224 DBA::escape($check_date),
229 foreach ($r as $item) {
230 $ids[] = $item['id'];
234 $ret = Item::select(Item::DELIVER_FIELDLIST, ['id' => $ids]);
235 $items = Item::inArray($ret);
241 * Will check further below if this actually returned results.
242 * We will provide an empty feed if that is the case.
245 $doc = new DOMDocument('1.0', 'utf-8');
246 $doc->formatOutput = true;
248 $alternatelink = $owner['url'];
250 if (isset($category)) {
251 $alternatelink .= "/category/".$category;
255 $author = "dfrn:owner";
260 $root = self::addHeader($doc, $owner, $author, $alternatelink, true);
262 /// @TODO This hook can't work anymore
263 // Addon::callHooks('atom_feed', $atom);
265 if (!DBA::isResult($items) || $onlyheader) {
266 $atom = trim($doc->saveXML());
268 Addon::callHooks('atom_feed_end', $atom);
273 foreach ($items as $item) {
274 // prevent private email from leaking.
275 if ($item['network'] == NETWORK_MAIL) {
279 // public feeds get html, our own nodes use bbcode
283 // catch any email that's in a public conversation and make sure it doesn't leak
284 if ($item['private']) {
291 $entry = self::entry($doc, $type, $item, $owner, true);
292 $root->appendChild($entry);
295 $atom = trim($doc->saveXML());
297 Addon::callHooks('atom_feed_end', $atom);
303 * @brief Generate an atom entry for a given item id
305 * @param int $item_id The item id
306 * @param boolean $conversation Show the conversation. If false show the single post.
308 * @return string DFRN feed entry
310 public static function itemFeed($item_id, $conversation = false)
313 $condition = ['parent' => $item_id];
315 $condition = ['id' => $item_id];
318 $ret = Item::select(Item::DELIVER_FIELDLIST, $condition);
319 $items = Item::inArray($ret);
320 if (!DBA::isResult($items)) {
326 if ($item['uid'] != 0) {
327 $owner = User::getOwnerDataById($item['uid']);
332 $owner = ['uid' => 0, 'nick' => 'feed-item'];
335 $doc = new DOMDocument('1.0', 'utf-8');
336 $doc->formatOutput = true;
340 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
341 $doc->appendChild($root);
343 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
344 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
345 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
346 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
347 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
348 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
349 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
350 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
351 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
353 //$root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
355 foreach ($items as $item) {
356 $entry = self::entry($doc, $type, $item, $owner, true, 0);
357 $root->appendChild($entry);
360 $root = self::entry($doc, $type, $item, $owner, true, 0, true);
363 $atom = trim($doc->saveXML());
368 * @brief Create XML text for DFRN mails
370 * @param array $item message elements
371 * @param array $owner Owner record
373 * @return string DFRN mail
374 * @todo Find proper type-hints
376 public static function mail($item, $owner)
378 $doc = new DOMDocument('1.0', 'utf-8');
379 $doc->formatOutput = true;
381 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
383 $mail = $doc->createElement("dfrn:mail");
384 $sender = $doc->createElement("dfrn:sender");
386 XML::addElement($doc, $sender, "dfrn:name", $owner['name']);
387 XML::addElement($doc, $sender, "dfrn:uri", $owner['url']);
388 XML::addElement($doc, $sender, "dfrn:avatar", $owner['thumb']);
390 $mail->appendChild($sender);
392 XML::addElement($doc, $mail, "dfrn:id", $item['uri']);
393 XML::addElement($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
394 XML::addElement($doc, $mail, "dfrn:sentdate", DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
395 XML::addElement($doc, $mail, "dfrn:subject", $item['title']);
396 XML::addElement($doc, $mail, "dfrn:content", $item['body']);
398 $root->appendChild($mail);
400 return trim($doc->saveXML());
404 * @brief Create XML text for DFRN friend suggestions
406 * @param array $item suggestion elements
407 * @param array $owner Owner record
409 * @return string DFRN suggestions
410 * @todo Find proper type-hints
412 public static function fsuggest($item, $owner)
414 $doc = new DOMDocument('1.0', 'utf-8');
415 $doc->formatOutput = true;
417 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
419 $suggest = $doc->createElement("dfrn:suggest");
421 XML::addElement($doc, $suggest, "dfrn:url", $item['url']);
422 XML::addElement($doc, $suggest, "dfrn:name", $item['name']);
423 XML::addElement($doc, $suggest, "dfrn:photo", $item['photo']);
424 XML::addElement($doc, $suggest, "dfrn:request", $item['request']);
425 XML::addElement($doc, $suggest, "dfrn:note", $item['note']);
427 $root->appendChild($suggest);
429 return trim($doc->saveXML());
433 * @brief Create XML text for DFRN relocations
435 * @param array $owner Owner record
436 * @param int $uid User ID
438 * @return string DFRN relocations
439 * @todo Find proper type-hints
441 public static function relocate($owner, $uid)
444 /* get site pubkey. this could be a new installation with no site keys*/
445 $pubkey = Config::get('system', 'site_pubkey');
447 $res = Crypto::newKeypair(1024);
448 Config::set('system', 'site_prvkey', $res['prvkey']);
449 Config::set('system', 'site_pubkey', $res['pubkey']);
453 "SELECT `resource-id` , `scale`, type FROM `photo`
454 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;",
458 $ext = Image::supportedTypes();
460 foreach ($rp as $p) {
461 $photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
465 $doc = new DOMDocument('1.0', 'utf-8');
466 $doc->formatOutput = true;
468 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
470 $relocate = $doc->createElement("dfrn:relocate");
472 XML::addElement($doc, $relocate, "dfrn:url", $owner['url']);
473 XML::addElement($doc, $relocate, "dfrn:name", $owner['name']);
474 XML::addElement($doc, $relocate, "dfrn:addr", $owner['addr']);
475 XML::addElement($doc, $relocate, "dfrn:avatar", $owner['avatar']);
476 XML::addElement($doc, $relocate, "dfrn:photo", $photos[4]);
477 XML::addElement($doc, $relocate, "dfrn:thumb", $photos[5]);
478 XML::addElement($doc, $relocate, "dfrn:micro", $photos[6]);
479 XML::addElement($doc, $relocate, "dfrn:request", $owner['request']);
480 XML::addElement($doc, $relocate, "dfrn:confirm", $owner['confirm']);
481 XML::addElement($doc, $relocate, "dfrn:notify", $owner['notify']);
482 XML::addElement($doc, $relocate, "dfrn:poll", $owner['poll']);
483 XML::addElement($doc, $relocate, "dfrn:sitepubkey", Config::get('system', 'site_pubkey'));
485 $root->appendChild($relocate);
487 return trim($doc->saveXML());
491 * @brief Adds the header elements for the DFRN protocol
493 * @param object $doc XML document
494 * @param array $owner Owner record
495 * @param string $authorelement Element name for the author
496 * @param string $alternatelink link to profile or category
497 * @param bool $public Is it a header for public posts?
499 * @return object XML root object
500 * @todo Find proper type-hints
502 private static function addHeader($doc, $owner, $authorelement, $alternatelink = "", $public = false)
505 if ($alternatelink == "") {
506 $alternatelink = $owner['url'];
509 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
510 $doc->appendChild($root);
512 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
513 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
514 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
515 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
516 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
517 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
518 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
519 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
520 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
522 XML::addElement($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
523 XML::addElement($doc, $root, "title", $owner["name"]);
525 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION];
526 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
528 $attributes = ["rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/"];
529 XML::addElement($doc, $root, "link", "", $attributes);
531 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $alternatelink];
532 XML::addElement($doc, $root, "link", "", $attributes);
536 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
537 OStatus::hublinks($doc, $root, $owner["nick"]);
539 $attributes = ["rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
540 XML::addElement($doc, $root, "link", "", $attributes);
542 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
543 XML::addElement($doc, $root, "link", "", $attributes);
545 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
546 XML::addElement($doc, $root, "link", "", $attributes);
549 // For backward compatibility we keep this element
550 if ($owner['page-flags'] == PAGE_COMMUNITY) {
551 XML::addElement($doc, $root, "dfrn:community", 1);
554 // The former element is replaced by this one
555 XML::addElement($doc, $root, "dfrn:account_type", $owner["account-type"]);
557 /// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
559 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
561 $author = self::addAuthor($doc, $owner, $authorelement, $public);
562 $root->appendChild($author);
568 * @brief Adds the author element in the header for the DFRN protocol
570 * @param object $doc XML document
571 * @param array $owner Owner record
572 * @param string $authorelement Element name for the author
573 * @param boolean $public boolean
575 * @return object XML author object
576 * @todo Find proper type-hints
578 private static function addAuthor($doc, $owner, $authorelement, $public)
580 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
582 "SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
583 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
584 intval($owner['uid'])
586 if (DBA::isResult($r)) {
592 $author = $doc->createElement($authorelement);
594 $namdate = DateTimeFormat::utc($owner['name-date'].'+00:00', DateTimeFormat::ATOM);
595 $uridate = DateTimeFormat::utc($owner['uri-date'].'+00:00', DateTimeFormat::ATOM);
596 $picdate = DateTimeFormat::utc($owner['avatar-date'].'+00:00', DateTimeFormat::ATOM);
600 if (!$public || !$hidewall) {
601 $attributes = ["dfrn:updated" => $namdate];
604 XML::addElement($doc, $author, "name", $owner["name"], $attributes);
605 XML::addElement($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
606 XML::addElement($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
608 $attributes = ["rel" => "photo", "type" => "image/jpeg",
609 "media:width" => 175, "media:height" => 175, "href" => $owner['photo']];
611 if (!$public || !$hidewall) {
612 $attributes["dfrn:updated"] = $picdate;
615 XML::addElement($doc, $author, "link", "", $attributes);
617 $attributes["rel"] = "avatar";
618 XML::addElement($doc, $author, "link", "", $attributes);
621 XML::addElement($doc, $author, "dfrn:hide", "true");
624 // The following fields will only be generated if the data isn't meant for a public feed
629 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
632 XML::addElement($doc, $author, "dfrn:birthday", $birthday);
635 // Only show contact details when we are allowed to
637 "SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
638 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
639 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
641 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
642 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
643 intval($owner['uid'])
645 if (DBA::isResult($r)) {
648 XML::addElement($doc, $author, "poco:displayName", $profile["name"]);
649 XML::addElement($doc, $author, "poco:updated", $namdate);
651 if (trim($profile["dob"]) > '0001-01-01') {
652 XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
655 XML::addElement($doc, $author, "poco:note", $profile["about"]);
656 XML::addElement($doc, $author, "poco:preferredUsername", $profile["nickname"]);
658 $savetz = date_default_timezone_get();
659 date_default_timezone_set($profile["timezone"]);
660 XML::addElement($doc, $author, "poco:utcOffset", date("P"));
661 date_default_timezone_set($savetz);
663 if (trim($profile["homepage"]) != "") {
664 $urls = $doc->createElement("poco:urls");
665 XML::addElement($doc, $urls, "poco:type", "homepage");
666 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
667 XML::addElement($doc, $urls, "poco:primary", "true");
668 $author->appendChild($urls);
671 if (trim($profile["pub_keywords"]) != "") {
672 $keywords = explode(",", $profile["pub_keywords"]);
674 foreach ($keywords as $keyword) {
675 XML::addElement($doc, $author, "poco:tags", trim($keyword));
679 if (trim($profile["xmpp"]) != "") {
680 $ims = $doc->createElement("poco:ims");
681 XML::addElement($doc, $ims, "poco:type", "xmpp");
682 XML::addElement($doc, $ims, "poco:value", $profile["xmpp"]);
683 XML::addElement($doc, $ims, "poco:primary", "true");
684 $author->appendChild($ims);
687 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
688 $element = $doc->createElement("poco:address");
690 XML::addElement($doc, $element, "poco:formatted", Profile::formatLocation($profile));
692 if (trim($profile["locality"]) != "") {
693 XML::addElement($doc, $element, "poco:locality", $profile["locality"]);
696 if (trim($profile["region"]) != "") {
697 XML::addElement($doc, $element, "poco:region", $profile["region"]);
700 if (trim($profile["country-name"]) != "") {
701 XML::addElement($doc, $element, "poco:country", $profile["country-name"]);
704 $author->appendChild($element);
712 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
714 * @param object $doc XML document
715 * @param string $element Element name for the author
716 * @param string $contact_url Link of the contact
717 * @param array $item Item elements
719 * @return object XML author object
720 * @todo Find proper type-hints
722 private static function addEntryAuthor($doc, $element, $contact_url, $item)
724 $contact = Contact::getDetailsByURL($contact_url, $item["uid"]);
726 $author = $doc->createElement($element);
727 XML::addElement($doc, $author, "name", $contact["name"]);
728 XML::addElement($doc, $author, "uri", $contact["url"]);
729 XML::addElement($doc, $author, "dfrn:handle", $contact["addr"]);
732 /// - Check real image type and image size
733 /// - Check which of these boths elements we should use
736 "type" => "image/jpeg",
738 "media:height" => 80,
739 "href" => $contact["photo"]];
740 XML::addElement($doc, $author, "link", "", $attributes);
744 "type" => "image/jpeg",
746 "media:height" => 80,
747 "href" => $contact["photo"]];
748 XML::addElement($doc, $author, "link", "", $attributes);
754 * @brief Adds the activity elements
756 * @param object $doc XML document
757 * @param string $element Element name for the activity
758 * @param string $activity activity value
760 * @return object XML activity object
761 * @todo Find proper type-hints
763 private static function createActivity($doc, $element, $activity)
766 $entry = $doc->createElement($element);
768 $r = XML::parseString($activity, false);
774 XML::addElement($doc, $entry, "activity:object-type", $r->type);
778 XML::addElement($doc, $entry, "id", $r->id);
782 XML::addElement($doc, $entry, "title", $r->title);
786 if (substr($r->link, 0, 1) == '<') {
787 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
788 $r->link = str_replace('&', '&', $r->link);
791 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
793 // XML does need a single element as root element so we add a dummy element here
794 $data = XML::parseString("<dummy>" . $r->link . "</dummy>", false);
795 if (is_object($data)) {
796 foreach ($data->link as $link) {
798 foreach ($link->attributes() as $parameter => $value) {
799 $attributes[$parameter] = $value;
801 XML::addElement($doc, $entry, "link", "", $attributes);
805 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
806 XML::addElement($doc, $entry, "link", "", $attributes);
810 XML::addElement($doc, $entry, "content", BBCode::convert($r->content), ["type" => "html"]);
820 * @brief Adds the elements for attachments
822 * @param object $doc XML document
823 * @param object $root XML root
824 * @param array $item Item element
826 * @return object XML attachment object
827 * @todo Find proper type-hints
829 private static function getAttachment($doc, $root, $item)
831 $arr = explode('[/attach],', $item['attach']);
833 foreach ($arr as $r) {
835 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
837 $attributes = ["rel" => "enclosure",
838 "href" => $matches[1],
839 "type" => $matches[3]];
841 if (intval($matches[2])) {
842 $attributes["length"] = intval($matches[2]);
845 if (trim($matches[4]) != "") {
846 $attributes["title"] = trim($matches[4]);
849 XML::addElement($doc, $root, "link", "", $attributes);
856 * @brief Adds the "entry" elements for the DFRN protocol
858 * @param object $doc XML document
859 * @param string $type "text" or "html"
860 * @param array $item Item element
861 * @param array $owner Owner record
862 * @param bool $comment Trigger the sending of the "comment" element
863 * @param int $cid Contact ID of the recipient
864 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
866 * @return object XML entry object
867 * @todo Find proper type-hints
869 private static function entry($doc, $type, array $item, array $owner, $comment = false, $cid = 0, $single = false)
873 if (!$item['parent']) {
877 if ($item['deleted']) {
878 $attributes = ["ref" => $item['uri'], "when" => DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM)];
879 return XML::createElement($doc, "at:deleted-entry", "", $attributes);
883 $entry = $doc->createElement("entry");
885 $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry');
886 $doc->appendChild($entry);
888 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
889 $entry->setAttribute("xmlns:at", NAMESPACE_TOMB);
890 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
891 $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
892 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
893 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
894 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
895 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
896 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
899 if ($item['private']) {
900 $body = Item::fixPrivatePhotos($item['body'], $owner['uid'], $item, $cid);
902 $body = $item['body'];
905 // Remove the abstract element. It is only locally important.
906 $body = BBCode::stripAbstract($body);
909 if ($type == 'html') {
912 if ($item['title'] != "") {
913 $htmlbody = "[b]" . $item['title'] . "[/b]\n\n" . $htmlbody;
916 $htmlbody = BBCode::convert($htmlbody, false, 7);
919 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
920 $entry->appendChild($author);
922 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
923 $entry->appendChild($dfrnowner);
925 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
926 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
927 $parent = Item::selectFirst(['guid', 'plink'], ['uri' => $parent_item, 'uid' => $item['uid']]);
928 $attributes = ["ref" => $parent_item, "type" => "text/html",
929 "href" => $parent['plink'],
930 "dfrn:diaspora_guid" => $parent['guid']];
931 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
934 // Add conversation data. This is used for OStatus
935 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
936 $conversation_uri = $conversation_href;
938 if (isset($parent_item)) {
939 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $item['parent-uri']]);
940 if (DBA::isResult($conversation)) {
941 if ($conversation['conversation-uri'] != '') {
942 $conversation_uri = $conversation['conversation-uri'];
944 if ($conversation['conversation-href'] != '') {
945 $conversation_href = $conversation['conversation-href'];
951 "href" => $conversation_href,
952 "ref" => $conversation_uri];
954 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
956 XML::addElement($doc, $entry, "id", $item["uri"]);
957 XML::addElement($doc, $entry, "title", $item["title"]);
959 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"] . "+00:00", DateTimeFormat::ATOM));
960 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"] . "+00:00", DateTimeFormat::ATOM));
962 // "dfrn:env" is used to read the content
963 XML::addElement($doc, $entry, "dfrn:env", base64url_encode($body, true));
965 // The "content" field is not read by the receiver. We could remove it when the type is "text"
966 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
967 XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
969 // We save this value in "plink". Maybe we should read it from there as well?
975 ["rel" => "alternate", "type" => "text/html",
976 "href" => System::baseUrl() . "/display/" . $item["guid"]]
979 // "comment-allow" is some old fashioned stuff for old Friendica versions.
980 // It is included in the rewritten code for completeness
982 XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
985 if ($item['location']) {
986 XML::addElement($doc, $entry, "dfrn:location", $item['location']);
989 if ($item['coord']) {
990 XML::addElement($doc, $entry, "georss:point", $item['coord']);
993 if ($item['private']) {
994 XML::addElement($doc, $entry, "dfrn:private", ($item['private'] ? $item['private'] : 1));
997 if ($item['extid']) {
998 XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
1001 if ($item['post-type'] == Item::PT_PAGE) {
1002 XML::addElement($doc, $entry, "dfrn:bookmark", "true");
1006 XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
1009 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
1011 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
1012 // It is needed for relayed comments to Diaspora.
1013 if ($item['signed_text']) {
1014 $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer']]));
1015 XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
1018 XML::addElement($doc, $entry, "activity:verb", self::constructVerb($item));
1020 if ($item['object-type'] != "") {
1021 XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
1022 } elseif ($item['id'] == $item['parent']) {
1023 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1025 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
1028 $actobj = self::createActivity($doc, "activity:object", $item['object']);
1030 $entry->appendChild($actobj);
1033 $actarg = self::createActivity($doc, "activity:target", $item['target']);
1035 $entry->appendChild($actarg);
1038 $tags = Item::getFeedTags($item);
1040 /// @TODO Combine this with similar below if() block?
1042 foreach ($tags as $t) {
1043 if (($type != 'html') || ($t[0] != "@")) {
1044 XML::addElement($doc, $entry, "category", "", ["scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]]);
1050 foreach ($tags as $t) {
1052 $mentioned[$t[1]] = $t[1];
1057 foreach ($mentioned as $mention) {
1059 "SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1060 intval($owner["uid"]),
1061 DBA::escape(normalise_link($mention))
1064 if (DBA::isResult($r) && ($r[0]["forum"] || $r[0]["prv"])) {
1070 ["rel" => "mentioned",
1071 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1080 ["rel" => "mentioned",
1081 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1087 self::getAttachment($doc, $entry, $item);
1093 * @brief encrypts data via AES
1095 * @param string $data The data that is to be encrypted
1096 * @param string $key The AES key
1098 * @return string encrypted data
1100 private static function aesEncrypt($data, $key)
1102 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1106 * @brief decrypts data via AES
1108 * @param string $encrypted The encrypted data
1109 * @param string $key The AES key
1111 * @return string decrypted data
1113 public static function aesDecrypt($encrypted, $key)
1115 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1119 * @brief Delivers the atom content to the contacts
1121 * @param array $owner Owner record
1122 * @param array $contact Contact record of the receiver
1123 * @param string $atom Content that will be transmitted
1124 * @param bool $dissolve (to be documented)
1126 * @return int Deliver status. Negative values mean an error.
1127 * @todo Add array type-hint for $owner, $contact
1129 public static function deliver($owner, $contact, $atom, $dissolve = false)
1133 // At first try the Diaspora transport layer
1134 $ret = self::transmit($owner, $contact, $atom);
1136 logger('Delivery via Diaspora transport layer was successful with status ' . $ret);
1140 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1142 if ($contact['duplex'] && $contact['dfrn-id']) {
1143 $idtosend = '0:' . $orig_id;
1145 if ($contact['duplex'] && $contact['issued-id']) {
1146 $idtosend = '1:' . $orig_id;
1149 $rino = Config::get('system', 'rino_encrypt');
1150 $rino = intval($rino);
1152 logger("Local rino version: ". $rino, LOGGER_DEBUG);
1154 $ssl_val = intval(Config::get('system', 'ssl_policy'));
1158 case SSL_POLICY_FULL:
1159 $ssl_policy = 'full';
1161 case SSL_POLICY_SELFSIGN:
1162 $ssl_policy = 'self';
1164 case SSL_POLICY_NONE:
1166 $ssl_policy = 'none';
1170 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1172 logger('dfrn_deliver: ' . $url);
1174 $ret = Network::curl($url);
1176 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1177 Contact::markForArchival($contact);
1178 return -2; // timed out
1181 $xml = $ret['body'];
1183 $curl_stat = $a->get_curl_code();
1184 if (empty($curl_stat)) {
1185 Contact::markForArchival($contact);
1186 return -3; // timed out
1189 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1192 Contact::markForArchival($contact);
1196 if (strpos($xml, '<?xml') === false) {
1197 logger('dfrn_deliver: no valid XML returned');
1198 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1199 Contact::markForArchival($contact);
1203 $res = XML::parseString($xml);
1205 if (!is_object($res) || (intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
1206 Contact::markForArchival($contact);
1208 if (empty($res->status)) {
1211 $status = $res->status;
1218 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1219 $challenge = hex2bin((string) $res->challenge);
1220 $perm = (($res->perm) ? $res->perm : null);
1221 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1222 $rino_remote_version = intval($res->rino);
1223 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1225 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
1227 if ($owner['page-flags'] == PAGE_PRVGROUP) {
1231 $final_dfrn_id = '';
1234 if ((($perm == 'rw') && (! intval($contact['writable'])))
1235 || (($perm == 'r') && (intval($contact['writable'])))
1238 "update contact set writable = %d where id = %d",
1239 intval(($perm == 'rw') ? 1 : 0),
1240 intval($contact['id'])
1242 $contact['writable'] = (string) 1 - intval($contact['writable']);
1246 if (($contact['duplex'] && strlen($contact['pubkey']))
1247 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1248 || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
1250 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
1251 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
1253 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
1254 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
1257 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1259 if (strpos($final_dfrn_id, ':') == 1) {
1260 $final_dfrn_id = substr($final_dfrn_id, 2);
1263 if ($final_dfrn_id != $orig_id) {
1264 logger('dfrn_deliver: wrong dfrn_id.');
1265 // did not decode properly - cannot trust this site
1266 Contact::markForArchival($contact);
1270 $postvars['dfrn_id'] = $idtosend;
1271 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1273 $postvars['dissolve'] = '1';
1276 if ((($contact['rel']) && ($contact['rel'] != Contact::SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1277 $postvars['data'] = $atom;
1278 $postvars['perm'] = 'rw';
1280 $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
1281 $postvars['perm'] = 'r';
1284 $postvars['ssl_policy'] = $ssl_policy;
1287 $postvars['page'] = $page;
1291 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1292 logger('rino version: '. $rino_remote_version);
1294 switch ($rino_remote_version) {
1296 $key = openssl_random_pseudo_bytes(16);
1297 $data = self::aesEncrypt($postvars['data'], $key);
1300 logger("rino: invalid requested version '$rino_remote_version'");
1301 Contact::markForArchival($contact);
1305 $postvars['rino'] = $rino_remote_version;
1306 $postvars['data'] = bin2hex($data);
1308 if ($dfrn_version >= 2.1) {
1309 if (($contact['duplex'] && strlen($contact['pubkey']))
1310 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1311 || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
1313 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1315 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1318 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1319 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1321 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1325 logger('md5 rawkey ' . md5($postvars['key']));
1327 $postvars['key'] = bin2hex($postvars['key']);
1331 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), LOGGER_DATA);
1333 $xml = Network::post($contact['notify'], $postvars);
1335 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1337 $curl_stat = $a->get_curl_code();
1338 if (empty($curl_stat) || empty($xml)) {
1339 Contact::markForArchival($contact);
1340 return -9; // timed out
1343 if (($curl_stat == 503) && stristr($a->get_curl_headers(), 'retry-after')) {
1344 Contact::markForArchival($contact);
1348 if (strpos($xml, '<?xml') === false) {
1349 logger('dfrn_deliver: phase 2: no valid XML returned');
1350 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1351 Contact::markForArchival($contact);
1355 $res = XML::parseString($xml);
1357 if (!isset($res->status)) {
1358 Contact::markForArchival($contact);
1362 // Possibly old servers had returned an empty value when everything was okay
1363 if (empty($res->status)) {
1367 if (!empty($res->message)) {
1368 logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1371 if (($res->status >= 200) && ($res->status <= 299)) {
1372 Contact::unmarkForArchival($contact);
1375 return intval($res->status);
1379 * @brief Transmits atom content to the contacts via the Diaspora transport layer
1381 * @param array $owner Owner record
1382 * @param array $contact Contact record of the receiver
1383 * @param string $atom Content that will be transmitted
1385 * @return int Deliver status. Negative values mean an error.
1387 public static function transmit($owner, $contact, $atom, $public_batch = false)
1391 if (!$public_batch) {
1392 if (empty($contact['addr'])) {
1393 logger('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.');
1394 if (Contact::updateFromProbe($contact['id'])) {
1395 $new_contact = DBA::selectFirst('contact', ['addr'], ['id' => $contact['id']]);
1396 $contact['addr'] = $new_contact['addr'];
1399 if (empty($contact['addr'])) {
1400 logger('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
1401 Contact::markForArchival($contact);
1406 $fcontact = Diaspora::personByHandle($contact['addr']);
1407 if (empty($fcontact)) {
1408 logger('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
1409 Contact::markForArchival($contact);
1412 $pubkey = $fcontact['pubkey'];
1417 $envelope = Diaspora::buildMessage($atom, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
1419 // Create the endpoint for public posts. This is some WIP and should later be added to the probing
1420 if ($public_batch && empty($contact["batch"])) {
1421 $parts = parse_url($contact["notify"]);
1422 $path_parts = explode('/', $parts['path']);
1423 array_pop($path_parts);
1424 $parts['path'] = implode('/', $path_parts);
1425 $contact["batch"] = Network::unparseURL($parts);
1428 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
1430 $content_type = ($public_batch ? "application/magic-envelope+xml" : "application/json");
1432 $xml = Network::post($dest_url, $envelope, ["Content-Type: ".$content_type]);
1434 $curl_stat = $a->get_curl_code();
1435 if (empty($curl_stat) || empty($xml)) {
1436 logger('Empty answer from ' . $contact['id'] . ' - ' . $dest_url);
1437 Contact::markForArchival($contact);
1438 return -9; // timed out
1441 if (($curl_stat == 503) && (stristr($a->get_curl_headers(), 'retry-after'))) {
1442 Contact::markForArchival($contact);
1446 if (strpos($xml, '<?xml') === false) {
1447 logger('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url);
1448 logger('Returned XML: ' . $xml, LOGGER_DATA);
1449 Contact::markForArchival($contact);
1453 $res = XML::parseString($xml);
1455 if (empty($res->status)) {
1456 Contact::markForArchival($contact);
1460 if (!empty($res->message)) {
1461 logger('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1464 if (($res->status >= 200) && ($res->status <= 299)) {
1465 Contact::unmarkForArchival($contact);
1468 return intval($res->status);
1472 * @brief Add new birthday event for this person
1474 * @param array $contact Contact record
1475 * @param string $birthday Birthday of the contact
1477 * @todo Add array type-hint for $contact
1479 private static function birthdayEvent($contact, $birthday)
1481 // Check for duplicates
1483 "SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1484 intval($contact['uid']),
1485 intval($contact['id']),
1486 DBA::escape(DateTimeFormat::utc($birthday)),
1487 DBA::escape('birthday')
1490 if (DBA::isResult($r)) {
1494 logger('updating birthday: ' . $birthday . ' for contact ' . $contact['id']);
1496 $bdtext = L10n::t('%s\'s birthday', $contact['name']);
1497 $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]');
1500 "INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1501 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1502 intval($contact['uid']),
1503 intval($contact['id']),
1504 DBA::escape(DateTimeFormat::utcNow()),
1505 DBA::escape(DateTimeFormat::utcNow()),
1506 DBA::escape(DateTimeFormat::utc($birthday)),
1507 DBA::escape(DateTimeFormat::utc($birthday . ' + 1 day ')),
1508 DBA::escape($bdtext),
1509 DBA::escape($bdtext2),
1510 DBA::escape('birthday')
1515 * @brief Fetch the author data from head or entry items
1517 * @param object $xpath XPath object
1518 * @param object $context In which context should the data be searched
1519 * @param array $importer Record of the importer user mixed with contact of the content
1520 * @param string $element Element name from which the data is fetched
1521 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1522 * @param string $xml optional, default empty
1524 * @return array Relevant data of the author
1525 * @todo Find good type-hints for all parameter
1527 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
1530 $author["name"] = XML::getFirstNodeValue($xpath, $element."/atom:name/text()", $context);
1531 $author["link"] = XML::getFirstNodeValue($xpath, $element."/atom:uri/text()", $context);
1533 $fields = ['id', 'uid', 'url', 'network', 'avatar-date', 'avatar', 'name-date', 'uri-date', 'addr',
1534 'name', 'nick', 'about', 'location', 'keywords', 'xmpp', 'bdyear', 'bd', 'hidden', 'contact-type'];
1535 $condition = ["`uid` = ? AND `nurl` = ? AND `network` != ?",
1536 $importer["importer_uid"], normalise_link($author["link"]), NETWORK_STATUSNET];
1537 $contact_old = DBA::selectFirst('contact', $fields, $condition);
1539 if (DBA::isResult($contact_old)) {
1540 $author["contact-id"] = $contact_old["id"];
1541 $author["network"] = $contact_old["network"];
1544 logger("Contact ".$author["link"]." wasn't found for user ".$importer["importer_uid"]." XML: ".$xml, LOGGER_DEBUG);
1547 $author["contact-unknown"] = true;
1548 $author["contact-id"] = $importer["id"];
1549 $author["network"] = $importer["network"];
1553 // Until now we aren't serving different sizes - but maybe later
1555 /// @todo check if "avatar" or "photo" would be the best field in the specification
1556 $avatars = $xpath->query($element . "/atom:link[@rel='avatar']", $context);
1557 foreach ($avatars as $avatar) {
1560 foreach ($avatar->attributes as $attributes) {
1561 /// @TODO Rewrite these similar if() to one switch
1562 if ($attributes->name == "href") {
1563 $href = $attributes->textContent;
1565 if ($attributes->name == "width") {
1566 $width = $attributes->textContent;
1568 if ($attributes->name == "updated") {
1569 $author["avatar-date"] = $attributes->textContent;
1572 if (($width > 0) && ($href != "")) {
1573 $avatarlist[$width] = $href;
1577 if (count($avatarlist) > 0) {
1578 krsort($avatarlist);
1579 $author["avatar"] = current($avatarlist);
1582 if (DBA::isResult($contact_old) && !$onlyfetch) {
1583 logger("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", LOGGER_DEBUG);
1585 $poco = ["url" => $contact_old["url"]];
1587 // When was the last change to name or uri?
1588 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1589 foreach ($name_element->attributes as $attributes) {
1590 if ($attributes->name == "updated") {
1591 $poco["name-date"] = $attributes->textContent;
1595 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1596 foreach ($link_element->attributes as $attributes) {
1597 if ($attributes->name == "updated") {
1598 $poco["uri-date"] = $attributes->textContent;
1602 // Update contact data
1603 $value = XML::getFirstNodeValue($xpath, $element . "/dfrn:handle/text()", $context);
1605 $poco["addr"] = $value;
1608 $value = XML::getFirstNodeValue($xpath, $element . "/poco:displayName/text()", $context);
1610 $poco["name"] = $value;
1613 $value = XML::getFirstNodeValue($xpath, $element . "/poco:preferredUsername/text()", $context);
1615 $poco["nick"] = $value;
1618 $value = XML::getFirstNodeValue($xpath, $element . "/poco:note/text()", $context);
1620 $poco["about"] = $value;
1623 $value = XML::getFirstNodeValue($xpath, $element . "/poco:address/poco:formatted/text()", $context);
1625 $poco["location"] = $value;
1628 /// @todo Only search for elements with "poco:type" = "xmpp"
1629 $value = XML::getFirstNodeValue($xpath, $element . "/poco:ims/poco:value/text()", $context);
1631 $poco["xmpp"] = $value;
1634 /// @todo Add support for the following fields that we don't support by now in the contact table:
1635 /// - poco:utcOffset
1641 // If the "hide" element is present then the profile isn't searchable.
1642 $hide = intval(XML::getFirstNodeValue($xpath, $element . "/dfrn:hide/text()", $context) == "true");
1644 logger("Hidden status for contact " . $contact_old["url"] . ": " . $hide, LOGGER_DEBUG);
1646 // If the contact isn't searchable then set the contact to "hidden".
1647 // Problem: This can be manually overridden by the user.
1649 $contact_old["hidden"] = true;
1652 // Save the keywords into the contact table
1654 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1655 foreach ($tagelements as $tag) {
1656 $tags[$tag->nodeValue] = $tag->nodeValue;
1660 $poco["keywords"] = implode(", ", $tags);
1663 // "dfrn:birthday" contains the birthday converted to UTC
1664 $birthday = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1666 if (strtotime($birthday) > time()) {
1667 $bd_timestamp = strtotime($birthday);
1669 $poco["bdyear"] = date("Y", $bd_timestamp);
1672 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1673 $value = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1675 if (!in_array($value, ["", "0000-00-00", "0001-01-01"])) {
1676 $bdyear = date("Y");
1677 $value = str_replace("0000", $bdyear, $value);
1679 if (strtotime($value) < time()) {
1680 $value = str_replace($bdyear, $bdyear + 1, $value);
1681 $bdyear = $bdyear + 1;
1684 $poco["bd"] = $value;
1687 $contact = array_merge($contact_old, $poco);
1689 if ($contact_old["bdyear"] != $contact["bdyear"]) {
1690 self::birthdayEvent($contact, $birthday);
1693 // Get all field names
1695 foreach ($contact_old as $field => $data) {
1696 $fields[$field] = $data;
1699 unset($fields["id"]);
1700 unset($fields["uid"]);
1701 unset($fields["url"]);
1702 unset($fields["avatar-date"]);
1703 unset($fields["avatar"]);
1704 unset($fields["name-date"]);
1705 unset($fields["uri-date"]);
1708 // Update check for this field has to be done differently
1709 $datefields = ["name-date", "uri-date"];
1710 foreach ($datefields as $field) {
1711 if (strtotime($contact[$field]) > strtotime($contact_old[$field])) {
1712 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1717 foreach ($fields as $field => $data) {
1718 if ($contact[$field] != $contact_old[$field]) {
1719 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1725 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1728 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1729 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1730 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1731 WHERE `id` = %d AND `network` = '%s'",
1732 DBA::escape($contact["name"]), DBA::escape($contact["nick"]), DBA::escape($contact["about"]), DBA::escape($contact["location"]),
1733 DBA::escape($contact["addr"]), DBA::escape($contact["keywords"]), DBA::escape($contact["bdyear"]),
1734 DBA::escape($contact["bd"]), intval($contact["hidden"]), DBA::escape($contact["xmpp"]),
1735 DBA::escape(DateTimeFormat::utc($contact["name-date"])), DBA::escape(DateTimeFormat::utc($contact["uri-date"])),
1736 intval($contact["id"]), DBA::escape($contact["network"])
1740 Contact::updateAvatar(
1742 $importer['importer_uid'],
1744 (strtotime($contact['avatar-date']) > strtotime($contact_old['avatar-date']) || ($author['avatar'] != $contact_old['avatar']))
1748 * The generation is a sign for the reliability of the provided data.
1749 * It is used in the socgraph.php to prevent that old contact data
1750 * that was relayed over several servers can overwrite contact
1751 * data that we received directly.
1754 $poco["generation"] = 2;
1755 $poco["photo"] = $author["avatar"];
1756 $poco["hide"] = $hide;
1757 $poco["contact-type"] = $contact["contact-type"];
1758 $gcid = GContact::update($poco);
1760 GContact::link($gcid, $importer["importer_uid"], $contact["id"]);
1767 * @brief Transforms activity objects into an XML string
1769 * @param object $xpath XPath object
1770 * @param object $activity Activity object
1771 * @param string $element element name
1773 * @return string XML string
1774 * @todo Find good type-hints for all parameter
1776 private static function transformActivity($xpath, $activity, $element)
1778 if (!is_object($activity)) {
1782 $obj_doc = new DOMDocument("1.0", "utf-8");
1783 $obj_doc->formatOutput = true;
1785 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1787 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1788 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1790 $id = $xpath->query("atom:id", $activity)->item(0);
1791 if (is_object($id)) {
1792 $obj_element->appendChild($obj_doc->importNode($id, true));
1795 $title = $xpath->query("atom:title", $activity)->item(0);
1796 if (is_object($title)) {
1797 $obj_element->appendChild($obj_doc->importNode($title, true));
1800 $links = $xpath->query("atom:link", $activity);
1801 if (is_object($links)) {
1802 foreach ($links as $link) {
1803 $obj_element->appendChild($obj_doc->importNode($link, true));
1807 $content = $xpath->query("atom:content", $activity)->item(0);
1808 if (is_object($content)) {
1809 $obj_element->appendChild($obj_doc->importNode($content, true));
1812 $obj_doc->appendChild($obj_element);
1814 $objxml = $obj_doc->saveXML($obj_element);
1816 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1817 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1822 * @brief Processes the mail elements
1824 * @param object $xpath XPath object
1825 * @param object $mail mail elements
1826 * @param array $importer Record of the importer user mixed with contact of the content
1828 * @todo Find good type-hints for all parameter
1830 private static function processMail($xpath, $mail, $importer)
1832 logger("Processing mails");
1834 /// @TODO Rewrite this to one statement
1836 $msg["uid"] = $importer["importer_uid"];
1837 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1838 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1839 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1840 $msg["contact-id"] = $importer["id"];
1841 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1842 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1843 $msg["created"] = DateTimeFormat::utc($xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue);
1844 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1845 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1847 $msg["replied"] = 0;
1849 DBA::insert('mail', $msg);
1851 // send notifications.
1852 /// @TODO Arange this mess
1854 "type" => NOTIFY_MAIL,
1855 "notify_flags" => $importer["notify-flags"],
1856 "language" => $importer["language"],
1857 "to_name" => $importer["username"],
1858 "to_email" => $importer["email"],
1859 "uid" => $importer["importer_uid"],
1861 "source_name" => $msg["from-name"],
1862 "source_link" => $importer["url"],
1863 "source_photo" => $importer["thumb"],
1864 "verb" => ACTIVITY_POST,
1868 notification($notif_params);
1870 logger("Mail is processed, notification was sent.");
1874 * @brief Processes the suggestion elements
1876 * @param object $xpath XPath object
1877 * @param object $suggestion suggestion elements
1878 * @param array $importer Record of the importer user mixed with contact of the content
1880 * @todo Find good type-hints for all parameter
1882 private static function processSuggestion($xpath, $suggestion, $importer)
1886 logger("Processing suggestions");
1888 /// @TODO Rewrite this to one statement
1890 $suggest["uid"] = $importer["importer_uid"];
1891 $suggest["cid"] = $importer["id"];
1892 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1893 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1894 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1895 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1896 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1898 // Does our member already have a friend matching this description?
1901 "SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1902 DBA::escape($suggest["name"]),
1903 DBA::escape(normalise_link($suggest["url"])),
1904 intval($suggest["uid"])
1908 * The valid result means the friend we're about to send a friend
1909 * suggestion already has them in their contact, which means no further
1910 * action is required.
1912 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1914 if (DBA::isResult($r)) {
1918 // Do we already have an fcontact record for this person?
1922 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1923 DBA::escape($suggest["url"]),
1924 DBA::escape($suggest["name"]),
1925 DBA::escape($suggest["request"])
1927 if (DBA::isResult($r)) {
1930 // OK, we do. Do we already have an introduction for this person ?
1932 "SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1933 intval($suggest["uid"]),
1938 * The valid result means the friend we're about to send a friend
1939 * suggestion already has them in their contact, which means no further
1940 * action is required.
1942 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1944 if (DBA::isResult($r)) {
1950 "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1951 DBA::escape($suggest["name"]),
1952 DBA::escape($suggest["url"]),
1953 DBA::escape($suggest["photo"]),
1954 DBA::escape($suggest["request"])
1958 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1959 DBA::escape($suggest["url"]),
1960 DBA::escape($suggest["name"]),
1961 DBA::escape($suggest["request"])
1965 * If no record in fcontact is found, below INSERT statement will not
1966 * link an introduction to it.
1968 if (!DBA::isResult($r)) {
1969 // Database record did not get created. Quietly give up.
1975 $hash = random_string();
1978 "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1979 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1980 intval($suggest["uid"]),
1982 intval($suggest["cid"]),
1983 DBA::escape($suggest["body"]),
1985 DBA::escape(DateTimeFormat::utcNow()),
1991 "type" => NOTIFY_SUGGEST,
1992 "notify_flags" => $importer["notify-flags"],
1993 "language" => $importer["language"],
1994 "to_name" => $importer["username"],
1995 "to_email" => $importer["email"],
1996 "uid" => $importer["importer_uid"],
1998 "link" => System::baseUrl()."/notifications/intros",
1999 "source_name" => $importer["name"],
2000 "source_link" => $importer["url"],
2001 "source_photo" => $importer["photo"],
2002 "verb" => ACTIVITY_REQ_FRIEND,
2010 * @brief Processes the relocation elements
2012 * @param object $xpath XPath object
2013 * @param object $relocation relocation elements
2014 * @param array $importer Record of the importer user mixed with contact of the content
2016 * @todo Find good type-hints for all parameter
2018 private static function processRelocation($xpath, $relocation, $importer)
2020 logger("Processing relocations");
2022 /// @TODO Rewrite this to one statement
2024 $relocate["uid"] = $importer["importer_uid"];
2025 $relocate["cid"] = $importer["id"];
2026 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
2027 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
2028 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
2029 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
2030 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
2031 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
2032 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
2033 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
2034 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
2035 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
2036 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
2037 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
2039 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
2040 $relocate["avatar"] = $relocate["photo"];
2043 if ($relocate["addr"] == "") {
2044 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
2049 "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d",
2050 intval($importer["id"]),
2051 intval($importer["importer_uid"])
2054 if (!DBA::isResult($r)) {
2055 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2061 // Update the gcontact entry
2062 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
2064 $fields = ['name' => $relocate["name"], 'photo' => $relocate["avatar"],
2065 'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2066 'addr' => $relocate["addr"], 'connect' => $relocate["addr"],
2067 'notify' => $relocate["notify"], 'server_url' => $relocate["server_url"]];
2068 DBA::update('gcontact', $fields, ['nurl' => normalise_link($old["url"])]);
2070 // Update the contact table. We try to find every entry.
2071 $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
2072 'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2073 'addr' => $relocate["addr"], 'request' => $relocate["request"],
2074 'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
2075 'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
2076 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], normalise_link($old["url"])];
2078 DBA::update('contact', $fields, $condition);
2080 Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
2082 logger('Contacts are updated.');
2085 /// merge with current record, current contents have priority
2086 /// update record, set url-updated
2087 /// update profile photos
2088 /// schedule a scan?
2093 * @brief Updates an item
2095 * @param array $current the current item record
2096 * @param array $item the new item record
2097 * @param array $importer Record of the importer user mixed with contact of the content
2098 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2100 * @todo set proper type-hints (array?)
2102 private static function updateContent($current, $item, $importer, $entrytype)
2106 if (self::isEditedTimestampNewer($current, $item)) {
2107 // do not accept (ignore) an earlier edit than one we currently have.
2108 if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
2112 $fields = ['title' => defaults($item, 'title', ''), 'body' => defaults($item, 'body', ''),
2113 'tag' => defaults($item, 'tag', ''), 'changed' => DateTimeFormat::utcNow(),
2114 'edited' => DateTimeFormat::utc($item["edited"])];
2116 $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
2117 Item::update($fields, $condition);
2125 * @brief Detects the entry type of the item
2127 * @param array $importer Record of the importer user mixed with contact of the content
2128 * @param array $item the new item record
2130 * @return int Is it a toplevel entry, a comment or a relayed comment?
2131 * @todo set proper type-hints (array?)
2133 private static function getEntryType($importer, $item)
2135 if ($item["parent-uri"] != $item["uri"]) {
2138 if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
2141 logger("possible community action");
2143 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2146 // was the top-level post for this action written by somebody on this site?
2147 // Specifically, the recipient?
2149 $is_a_remote_action = false;
2151 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item["parent-uri"]]);
2152 if (DBA::isResult($parent)) {
2154 "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2155 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2156 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2157 AND `item`.`uid` = %d
2160 DBA::escape($parent["parent-uri"]),
2161 DBA::escape($parent["parent-uri"]),
2162 DBA::escape($parent["parent-uri"]),
2163 intval($importer["importer_uid"])
2165 if (DBA::isResult($r)) {
2166 $is_a_remote_action = true;
2171 * Does this have the characteristics of a community or private group action?
2172 * If it's an action to a wall post on a community/prvgroup page it's a
2173 * valid community action. Also forum_mode makes it valid for sure.
2174 * If neither, it's not.
2176 if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2177 $is_a_remote_action = false;
2178 logger("not a community action");
2181 if ($is_a_remote_action) {
2182 return DFRN::REPLY_RC;
2187 return DFRN::TOP_LEVEL;
2192 * @brief Send a "poke"
2194 * @param array $item the new item record
2195 * @param array $importer Record of the importer user mixed with contact of the content
2196 * @param int $posted_id The record number of item record that was just posted
2198 * @todo set proper type-hints (array?)
2200 private static function doPoke($item, $importer, $posted_id)
2202 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2206 $xo = XML::parseString($item["object"], false);
2208 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2209 // somebody was poked/prodded. Was it me?
2210 foreach ($xo->link as $l) {
2211 $atts = $l->attributes();
2212 switch ($atts["rel"]) {
2214 $Blink = $atts["href"];
2221 if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2222 $author = DBA::selectFirst('contact', ['name', 'thumb', 'url'], ['id' => $item['author-id']]);
2224 // send a notification
2227 "type" => NOTIFY_POKE,
2228 "notify_flags" => $importer["notify-flags"],
2229 "language" => $importer["language"],
2230 "to_name" => $importer["username"],
2231 "to_email" => $importer["email"],
2232 "uid" => $importer["importer_uid"],
2234 "link" => System::baseUrl()."/display/".urlencode(Item::getGuidById($posted_id)),
2235 "source_name" => $author["name"],
2236 "source_link" => $author["url"],
2237 "source_photo" => $author["thumb"],
2238 "verb" => $item["verb"],
2239 "otype" => "person",
2240 "activity" => $verb,
2241 "parent" => $item["parent"]]
2248 * @brief Processes several actions, depending on the verb
2250 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2251 * @param array $importer Record of the importer user mixed with contact of the content
2252 * @param array $item the new item record
2253 * @param bool $is_like Is the verb a "like"?
2255 * @return bool Should the processing of the entries be continued?
2256 * @todo set proper type-hints (array?)
2258 private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2260 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2262 if (($entrytype == DFRN::TOP_LEVEL)) {
2263 // The filling of the the "contact" variable is done for legcy reasons
2264 // The functions below are partly used by ostatus.php as well - where we have this variable
2265 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2267 $nickname = $contact["nick"];
2269 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2270 // This function once was responsible for DFRN and OStatus.
2271 if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2272 logger("New follower");
2273 Contact::addRelationship($importer, $contact, $item, $nickname);
2276 if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2277 logger("Lost follower");
2278 Contact::removeFollower($importer, $contact, $item);
2281 if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2282 logger("New friend request");
2283 Contact::addRelationship($importer, $contact, $item, $nickname, true);
2286 if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2287 logger("Lost sharer");
2288 Contact::removeSharer($importer, $contact, $item);
2292 if (($item["verb"] == ACTIVITY_LIKE)
2293 || ($item["verb"] == ACTIVITY_DISLIKE)
2294 || ($item["verb"] == ACTIVITY_ATTEND)
2295 || ($item["verb"] == ACTIVITY_ATTENDNO)
2296 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
2299 $item["gravity"] = GRAVITY_ACTIVITY;
2300 // only one like or dislike per person
2301 // splitted into two queries for performance issues
2302 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2303 'verb' => $item["verb"], 'parent-uri' => $item["parent-uri"]];
2304 if (Item::exists($condition)) {
2308 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2309 'verb' => $item["verb"], 'thr-parent' => $item["parent-uri"]];
2310 if (Item::exists($condition)) {
2317 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2318 $xo = XML::parseString($item["object"], false);
2319 $xt = XML::parseString($item["target"], false);
2321 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2322 $item_tag = Item::selectFirst(['id', 'tag'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]);
2324 if (!DBA::isResult($item_tag)) {
2325 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2329 // extract tag, if not duplicate, add to parent item
2331 if (!stristr($item_tag["tag"], trim($xo->content))) {
2332 $tag = $item_tag["tag"] . (strlen($item_tag["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2333 Item::update(['tag' => $tag], ['id' => $item_tag["id"]]);
2343 * @brief Processes the link elements
2345 * @param object $links link elements
2346 * @param array $item the item record
2348 * @todo set proper type-hints
2350 private static function parseLinks($links, &$item)
2357 foreach ($links as $link) {
2358 foreach ($link->attributes as $attributes) {
2359 switch ($attributes->name) {
2360 case "href" : $href = $attributes->textContent; break;
2361 case "rel" : $rel = $attributes->textContent; break;
2362 case "type" : $type = $attributes->textContent; break;
2363 case "length": $length = $attributes->textContent; break;
2364 case "title" : $title = $attributes->textContent; break;
2367 if (($rel != "") && ($href != "")) {
2370 $item["plink"] = $href;
2374 if (strlen($item["attach"])) {
2375 $item["attach"] .= ",";
2378 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2386 * @brief Processes the entry elements which contain the items and comments
2388 * @param array $header Array of the header elements that always stay the same
2389 * @param object $xpath XPath object
2390 * @param object $entry entry elements
2391 * @param array $importer Record of the importer user mixed with contact of the content
2392 * @param object $xml xml
2394 * @todo Add type-hints
2396 private static function processEntry($header, $xpath, $entry, $importer, $xml)
2398 logger("Processing entries");
2402 $item["protocol"] = PROTOCOL_DFRN;
2404 $item["source"] = $xml;
2407 $item["uri"] = XML::getFirstNodeValue($xpath, "atom:id/text()", $entry);
2409 $item["edited"] = XML::getFirstNodeValue($xpath, "atom:updated/text()", $entry);
2411 $current = Item::selectFirst(['id', 'uid', 'edited', 'body'],
2412 ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
2414 // Is there an existing item?
2415 if (DBA::isResult($current) && !self::isEditedTimestampNewer($current, $item)) {
2416 logger("Item ".$item["uri"]." (".$item['edited'].") already existed.", LOGGER_DEBUG);
2421 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2423 $owner_unknown = (isset($owner["contact-unknown"]) && $owner["contact-unknown"]);
2425 $item["owner-link"] = $owner["link"];
2426 $item["owner-id"] = Contact::getIdForURL($owner["link"], 0);
2429 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2431 $item["author-link"] = $author["link"];
2432 $item["author-id"] = Contact::getIdForURL($author["link"], 0);
2434 $item["title"] = XML::getFirstNodeValue($xpath, "atom:title/text()", $entry);
2436 $item["created"] = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2438 $item["body"] = XML::getFirstNodeValue($xpath, "dfrn:env/text()", $entry);
2439 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2440 // make sure nobody is trying to sneak some html tags by us
2441 $item["body"] = notags(base64url_decode($item["body"]));
2443 $item["body"] = BBCode::limitBodySize($item["body"]);
2445 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2446 if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
2447 $base_url = get_app()->get_baseurl();
2448 $item['body'] = reltoabs($item['body'], $base_url);
2450 $item['body'] = html2bb_video($item['body']);
2452 $item['body'] = OEmbed::HTML2BBCode($item['body']);
2454 $config = HTMLPurifier_Config::createDefault();
2455 $config->set('Cache.DefinitionImpl', null);
2457 // we shouldn't need a whitelist, because the bbcode converter
2458 // will strip out any unsupported tags.
2460 $purifier = new HTMLPurifier($config);
2461 $item['body'] = $purifier->purify($item['body']);
2463 $item['body'] = @HTML::toBBCode($item['body']);
2466 /// @todo We should check for a repeated post and if we know the repeated author.
2468 // We don't need the content element since "dfrn:env" is always present
2469 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2471 $item["location"] = XML::getFirstNodeValue($xpath, "dfrn:location/text()", $entry);
2473 $item["coord"] = XML::getFirstNodeValue($xpath, "georss:point", $entry);
2475 $item["private"] = XML::getFirstNodeValue($xpath, "dfrn:private/text()", $entry);
2477 $item["extid"] = XML::getFirstNodeValue($xpath, "dfrn:extid/text()", $entry);
2479 if (XML::getFirstNodeValue($xpath, "dfrn:bookmark/text()", $entry) == "true") {
2480 $item["post-type"] = Item::PT_PAGE;
2483 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2484 if ($notice_info && ($notice_info->length > 0)) {
2485 foreach ($notice_info->item(0)->attributes as $attributes) {
2486 if ($attributes->name == "source") {
2487 $item["app"] = strip_tags($attributes->textContent);
2492 $item["guid"] = XML::getFirstNodeValue($xpath, "dfrn:diaspora_guid/text()", $entry);
2494 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
2495 $dsprsig = unxmlify(XML::getFirstNodeValue($xpath, "dfrn:diaspora_signature/text()", $entry));
2496 if ($dsprsig != "") {
2497 $item["dsprsig"] = $dsprsig;
2500 $item["verb"] = XML::getFirstNodeValue($xpath, "activity:verb/text()", $entry);
2502 if (XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry) != "") {
2503 $item["object-type"] = XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry);
2506 $object = $xpath->query("activity:object", $entry)->item(0);
2507 $item["object"] = self::transformActivity($xpath, $object, "object");
2509 if (trim($item["object"]) != "") {
2510 $r = XML::parseString($item["object"], false);
2511 if (isset($r->type)) {
2512 $item["object-type"] = $r->type;
2516 $target = $xpath->query("activity:target", $entry)->item(0);
2517 $item["target"] = self::transformActivity($xpath, $target, "target");
2519 $categories = $xpath->query("atom:category", $entry);
2521 foreach ($categories as $category) {
2524 foreach ($category->attributes as $attributes) {
2525 if ($attributes->name == "term") {
2526 $term = $attributes->textContent;
2529 if ($attributes->name == "scheme") {
2530 $scheme = $attributes->textContent;
2534 if (($term != "") && ($scheme != "")) {
2535 $parts = explode(":", $scheme);
2536 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2537 $termhash = array_shift($parts);
2538 $termurl = implode(":", $parts);
2540 if (!empty($item["tag"])) {
2541 $item["tag"] .= ",";
2546 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2554 $links = $xpath->query("atom:link", $entry);
2556 self::parseLinks($links, $item);
2559 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
2561 $conv = $xpath->query('ostatus:conversation', $entry);
2562 if (is_object($conv->item(0))) {
2563 foreach ($conv->item(0)->attributes as $attributes) {
2564 if ($attributes->name == "ref") {
2565 $item['conversation-uri'] = $attributes->textContent;
2567 if ($attributes->name == "href") {
2568 $item['conversation-href'] = $attributes->textContent;
2573 // Is it a reply or a top level posting?
2574 $item["parent-uri"] = $item["uri"];
2576 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2577 if (is_object($inreplyto->item(0))) {
2578 foreach ($inreplyto->item(0)->attributes as $attributes) {
2579 if ($attributes->name == "ref") {
2580 $item["parent-uri"] = $attributes->textContent;
2585 // Get the type of the item (Top level post, reply or remote reply)
2586 $entrytype = self::getEntryType($importer, $item);
2588 // Now assign the rest of the values that depend on the type of the message
2589 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2590 if (!isset($item["object-type"])) {
2591 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2594 if ($item["contact-id"] != $owner["contact-id"]) {
2595 $item["contact-id"] = $owner["contact-id"];
2598 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2599 $item["network"] = $owner["network"];
2602 if ($item["contact-id"] != $author["contact-id"]) {
2603 $item["contact-id"] = $author["contact-id"];
2606 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2607 $item["network"] = $author["network"];
2611 if ($entrytype == DFRN::REPLY_RC) {
2613 } elseif ($entrytype == DFRN::TOP_LEVEL) {
2614 if (!isset($item["object-type"])) {
2615 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2619 if (($item["object-type"] == ACTIVITY_OBJ_EVENT) && !$owner_unknown) {
2620 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2621 $ev = Event::fromBBCode($item["body"]);
2622 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2623 logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2624 $ev["cid"] = $importer["id"];
2625 $ev["uid"] = $importer["importer_uid"];
2626 $ev["uri"] = $item["uri"];
2627 $ev["edited"] = $item["edited"];
2628 $ev["private"] = $item["private"];
2629 $ev["guid"] = $item["guid"];
2630 $ev["plink"] = $item["plink"];
2633 "SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2634 DBA::escape($item["uri"]),
2635 intval($importer["importer_uid"])
2637 if (DBA::isResult($r)) {
2638 $ev["id"] = $r[0]["id"];
2641 $event_id = Event::store($ev);
2642 logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2648 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2649 logger("Exiting because 'processVerbs' told us so", LOGGER_DEBUG);
2653 // This check is done here to be able to receive connection requests in "processVerbs"
2654 if (($entrytype == DFRN::TOP_LEVEL) && $owner_unknown) {
2655 logger("Item won't be stored because user " . $importer["importer_uid"] . " doesn't follow " . $item["owner-link"] . ".", LOGGER_DEBUG);
2660 // Update content if 'updated' changes
2661 if (DBA::isResult($current)) {
2662 if (self::updateContent($current, $item, $importer, $entrytype)) {
2663 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2665 logger("Item " . $item["uri"] . " already existed.", LOGGER_DEBUG);
2670 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2671 $posted_id = Item::insert($item);
2675 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2677 if ($item['uid'] == 0) {
2678 Item::distribute($posted_id);
2683 } else { // $entrytype == DFRN::TOP_LEVEL
2684 if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
2685 logger("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", LOGGER_DEBUG);
2688 if (!link_compare($item["owner-link"], $importer["url"])) {
2690 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2691 * but otherwise there's a possible data mixup on the sender's system.
2692 * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2693 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2695 logger('Correcting item owner.', LOGGER_DEBUG);
2696 $item["owner-link"] = $importer["url"];
2697 $item["owner-id"] = Contact::getIdForURL($importer["url"], 0);
2700 if (($importer["rel"] == Contact::FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2701 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2705 // This is my contact on another system, but it's really me.
2706 // Turn this into a wall post.
2707 $notify = Item::isRemoteSelf($importer, $item);
2709 $posted_id = Item::insert($item, false, $notify);
2712 $posted_id = $notify;
2715 logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2717 if ($item['uid'] == 0) {
2718 Item::distribute($posted_id);
2721 if (stristr($item["verb"], ACTIVITY_POKE)) {
2722 self::doPoke($item, $importer, $posted_id);
2728 * @brief Deletes items
2730 * @param object $xpath XPath object
2731 * @param object $deletion deletion elements
2732 * @param array $importer Record of the importer user mixed with contact of the content
2734 * @todo set proper type-hints
2736 private static function processDeletion($xpath, $deletion, $importer)
2738 logger("Processing deletions");
2741 foreach ($deletion->attributes as $attributes) {
2742 if ($attributes->name == "ref") {
2743 $uri = $attributes->textContent;
2747 if (!$uri || !$importer["id"]) {
2751 $condition = ['uri' => $uri, 'uid' => $importer["importer_uid"]];
2752 $item = Item::selectFirst(['id', 'parent', 'contact-id', 'file', 'deleted'], $condition);
2753 if (!DBA::isResult($item)) {
2754 logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", LOGGER_DEBUG);
2758 if (strstr($item['file'], '[')) {
2759 logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " is filed. So it won't be deleted.", LOGGER_DEBUG);
2763 // When it is a starting post it has to belong to the person that wants to delete it
2764 if (($item['id'] == $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2765 logger("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2769 // Comments can be deleted by the thread owner or comment owner
2770 if (($item['id'] != $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2771 $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2772 if (!Item::exists($condition)) {
2773 logger("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2778 if ($item["deleted"]) {
2782 logger('deleting item '.$item['id'].' uri='.$uri, LOGGER_DEBUG);
2784 Item::delete(['id' => $item['id']]);
2788 * @brief Imports a DFRN message
2790 * @param string $xml The DFRN message
2791 * @param array $importer Record of the importer user mixed with contact of the content
2792 * @param bool $sort_by_date Is used when feeds are polled
2793 * @return integer Import status
2794 * @todo set proper type-hints
2796 public static function import($xml, $importer, $sort_by_date = false)
2802 $doc = new DOMDocument();
2803 @$doc->loadXML($xml);
2805 $xpath = new DOMXPath($doc);
2806 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2807 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2808 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2809 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2810 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2811 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2812 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2813 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2814 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2815 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2818 $header["uid"] = $importer["importer_uid"];
2819 $header["network"] = NETWORK_DFRN;
2820 $header["wall"] = 0;
2821 $header["origin"] = 0;
2822 $header["contact-id"] = $importer["id"];
2824 // Update the contact table if the data has changed
2826 // The "atom:author" is only present in feeds
2827 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2828 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2831 // Only the "dfrn:owner" in the head section contains all data
2832 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2833 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2836 logger("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2838 // is it a public forum? Private forums aren't exposed with this method
2839 $forum = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:community/text()"));
2841 // The account type is new since 3.5.1
2842 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2843 $accounttype = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:account_type/text()"));
2845 if ($accounttype != $importer["contact-type"]) {
2846 DBA::update('contact', ['contact-type' => $accounttype], ['id' => $importer["id"]]);
2848 // A forum contact can either have set "forum" or "prv" - but not both
2849 if (($accounttype == ACCOUNT_TYPE_COMMUNITY) && (($forum != $importer["forum"]) || ($forum == $importer["prv"]))) {
2850 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer["id"]];
2851 DBA::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2853 } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
2854 $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2855 DBA::update('contact', ['forum' => $forum], $condition);
2859 // We are processing relocations even if we are ignoring a contact
2860 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2861 foreach ($relocations as $relocation) {
2862 self::processRelocation($xpath, $relocation, $importer);
2865 if (($importer["uid"] != 0) && !$importer["readonly"]) {
2866 $mails = $xpath->query("/atom:feed/dfrn:mail");
2867 foreach ($mails as $mail) {
2868 self::processMail($xpath, $mail, $importer);
2871 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2872 foreach ($suggestions as $suggestion) {
2873 self::processSuggestion($xpath, $suggestion, $importer);
2877 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2878 foreach ($deletions as $deletion) {
2879 self::processDeletion($xpath, $deletion, $importer);
2882 if (!$sort_by_date) {
2883 $entries = $xpath->query("/atom:feed/atom:entry");
2884 foreach ($entries as $entry) {
2885 self::processEntry($header, $xpath, $entry, $importer, $xml);
2889 $entries = $xpath->query("/atom:feed/atom:entry");
2890 foreach ($entries as $entry) {
2891 $created = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2892 $newentries[strtotime($created)] = $entry;
2895 // Now sort after the publishing date
2898 foreach ($newentries as $entry) {
2899 self::processEntry($header, $xpath, $entry, $importer, $xml);
2902 logger("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2908 * @param string $contact_nick contact nickname
2910 public static function autoRedir(App $a, $contact_nick)
2913 if (x($_REQUEST, 'redir') && intval($_REQUEST['redir'])) {
2917 if ((! $contact_nick) || ($contact_nick === $a->user['nickname'])) {
2922 // We need to find out if $contact_nick is a user on this hub, and if so, if I
2923 // am a contact of that user. However, that user may have other contacts with the
2924 // same nickname as me on other hubs or other networks. Exclude these by requiring
2925 // that the contact have a local URL. I will be the only person with my nickname at
2926 // this URL, so if a result is found, then I am a contact of the $contact_nick user.
2928 // We also have to make sure that I'm a legitimate contact--I'm not blocked or pending.
2930 $baseurl = System::baseUrl();
2931 $domain_st = strpos($baseurl, "://");
2932 if ($domain_st === false) {
2935 $baseurl = substr($baseurl, $domain_st + 3);
2936 $nurl = normalise_link($baseurl);
2938 /// @todo Why is there a query for "url" *and* "nurl"? Especially this normalising is strange.
2939 $r = q("SELECT `id` FROM `contact` WHERE `uid` = (SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1)
2940 AND `nick` = '%s' AND NOT `self` AND (`url` LIKE '%%%s%%' OR `nurl` LIKE '%%%s%%') AND NOT `blocked` AND NOT `pending` LIMIT 1",
2941 DBA::escape($contact_nick),
2942 DBA::escape($a->user['nickname']),
2943 DBA::escape($baseurl),
2946 if ((! DBA::isResult($r)) || $r[0]['id'] == remote_user()) {
2950 $r = q("SELECT * FROM contact WHERE nick = '%s'
2951 AND network = '%s' AND uid = %d AND url LIKE '%%%s%%' LIMIT 1",
2952 DBA::escape($contact_nick),
2953 DBA::escape(NETWORK_DFRN),
2954 intval(local_user()),
2955 DBA::escape($baseurl)
2957 if (! DBA::isResult($r)) {
2963 $dfrn_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2965 if ($r[0]['duplex'] && $r[0]['issued-id']) {
2966 $orig_id = $r[0]['issued-id'];
2967 $dfrn_id = '1:' . $orig_id;
2969 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
2970 $orig_id = $r[0]['dfrn-id'];
2971 $dfrn_id = '0:' . $orig_id;
2974 // ensure that we've got a valid ID. There may be some edge cases with forums and non-duplex mode
2975 // that may have triggered some of the "went to {profile/intro} and got an RSS feed" issues
2977 if (strlen($dfrn_id) < 3) {
2981 $sec = random_string();
2983 DBA::insert('profile_check', ['uid' => local_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id, 'sec' => $sec, 'expire' => time() + 45]);
2985 $url = curPageURL();
2987 logger('auto_redir: ' . $r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
2988 $dest = (($url) ? '&destination_url=' . $url : '');
2989 goaway($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
2990 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest);
2997 * @brief Returns the activity verb
2999 * @param array $item Item array
3001 * @return string activity verb
3003 private static function constructVerb(array $item)
3005 if ($item['verb']) {
3006 return $item['verb'];
3008 return ACTIVITY_POST;
3011 private static function tgroupCheck($uid, $item)
3015 // check that the message originated elsewhere and is a top-level post
3017 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['parent-uri'])) {
3021 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
3024 if (!DBA::isResult($u)) {
3028 $community_page = ($u[0]['page-flags'] == PAGE_COMMUNITY);
3029 $prvgroup = ($u[0]['page-flags'] == PAGE_PRVGROUP);
3031 $link = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
3034 * Diaspora uses their own hardwired link URL in @-tags
3035 * instead of the one we supply with webfinger
3037 $dlink = normalise_link(System::baseUrl() . '/u/' . $u[0]['nickname']);
3039 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
3041 foreach ($matches as $mtch) {
3042 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
3044 logger('mention found: ' . $mtch[2]);
3053 return $community_page || $prvgroup;
3057 * This function returns true if $update has an edited timestamp newer
3058 * than $existing, i.e. $update contains new data which should override
3059 * what's already there. If there is no timestamp yet, the update is
3060 * assumed to be newer. If the update has no timestamp, the existing
3061 * item is assumed to be up-to-date. If the timestamps are equal it
3062 * assumes the update has been seen before and should be ignored.
3065 private static function isEditedTimestampNewer($existing, $update)
3067 if (!x($existing, 'edited') || !$existing['edited']) {
3070 if (!x($update, 'edited') || !$update['edited']) {
3074 $existing_edited = DateTimeFormat::utc($existing['edited']);
3075 $update_edited = DateTimeFormat::utc($update['edited']);
3077 return (strcmp($existing_edited, $update_edited) < 0);