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\Protocol;
21 use Friendica\Core\System;
22 use Friendica\Database\DBA;
23 use Friendica\Model\Contact;
24 use Friendica\Model\Conversation;
25 use Friendica\Model\Event;
26 use Friendica\Model\GContact;
27 use Friendica\Model\Item;
28 use Friendica\Model\PermissionSet;
29 use Friendica\Model\Profile;
30 use Friendica\Model\User;
31 use Friendica\Object\Image;
32 use Friendica\Util\Crypto;
33 use Friendica\Util\DateTimeFormat;
34 use Friendica\Util\Network;
35 use Friendica\Util\XML;
37 use HTMLPurifier_Config;
39 require_once 'boot.php';
40 require_once 'include/dba.php';
41 require_once "include/enotify.php";
42 require_once "include/items.php";
43 require_once "include/text.php";
46 * @brief This class contain functions to create and send DFRN XML files
51 const TOP_LEVEL = 0; // Top level posting
52 const REPLY = 1; // Regular reply that is stored locally
53 const REPLY_RC = 2; // Reply that will be relayed
56 * @brief Generates the atom entries for delivery.php
58 * This function is used whenever content is transmitted via DFRN.
60 * @param array $items Item elements
61 * @param array $owner Owner record
63 * @return string DFRN entries
64 * @todo Find proper type-hints
66 public static function entries($items, $owner)
68 $doc = new DOMDocument('1.0', 'utf-8');
69 $doc->formatOutput = true;
71 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
73 if (! count($items)) {
74 return trim($doc->saveXML());
77 foreach ($items as $item) {
78 // These values aren't sent when sending from the queue.
79 /// @todo Check if we can set these values from the queue or if they are needed at all.
80 $item["entry:comment-allow"] = defaults($item, "entry:comment-allow", true);
81 $item["entry:cid"] = defaults($item, "entry:cid", 0);
83 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
84 $root->appendChild($entry);
87 return trim($doc->saveXML());
91 * @brief Generate an atom feed for the given user
93 * This function is called when another server is pulling data from the user feed.
95 * @param string $dfrn_id DFRN ID from the requesting party
96 * @param string $owner_nick Owner nick name
97 * @param string $last_update Date of the last update
98 * @param int $direction Can be -1, 0 or 1.
99 * @param boolean $onlyheader Output only the header without content? (Default is "no")
101 * @return string DFRN feed entries
103 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false)
107 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
108 $public_feed = (($dfrn_id) ? false : true);
109 $starred = false; // not yet implemented, possible security issues
112 if ($public_feed && $a->argc > 2) {
113 for ($x = 2; $x < $a->argc; $x++) {
114 if ($a->argv[$x] == 'converse') {
117 if ($a->argv[$x] == 'starred') {
120 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
121 $category = $a->argv[$x+1];
126 // default permissions - anonymous user
128 $sql_extra = " AND NOT `item`.`private` ";
131 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
132 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
133 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
134 DBA::escape($owner_nick)
137 if (! DBA::isResult($r)) {
138 logger(sprintf('No contact found for nickname=%d', $owner_nick), LOGGER_WARNING);
143 $owner_id = $owner['uid'];
144 $owner_nick = $owner['nickname'];
146 $sql_post_table = "";
148 if (! $public_feed) {
150 switch ($direction) {
152 $sql_extra = sprintf(" AND `issued-id` = '%s' ", DBA::escape($dfrn_id));
156 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
157 $my_id = '1:' . $dfrn_id;
160 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
161 $my_id = '0:' . $dfrn_id;
169 "SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
173 if (! DBA::isResult($r)) {
174 logger(sprintf('No contact found for uid=%d', $owner_id), LOGGER_WARNING);
179 include_once 'include/security.php';
181 $set = PermissionSet::get($owner_id, $contact['id']);
184 $sql_extra = " AND `item`.`psid` IN (" . implode(',', $set) .")";
186 $sql_extra = " AND NOT `item`.`private`";
196 if (! strlen($last_update)) {
197 $last_update = 'now -30 days';
200 if (isset($category)) {
201 $sql_post_table = sprintf(
202 "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` ",
203 DBA::escape(protect_sprintf($category)),
204 intval(TERM_OBJ_POST),
205 intval(TERM_CATEGORY),
208 //$sql_extra .= file_tag_file_query('item',$category,'category');
211 if ($public_feed && ! $converse) {
212 $sql_extra .= " AND `contact`.`self` = 1 ";
215 $check_date = DateTimeFormat::utc($last_update);
219 FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
220 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
221 WHERE `item`.`uid` = %d AND `item`.`wall` AND `item`.`changed` > '%s'
223 ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
225 DBA::escape($check_date),
230 foreach ($r as $item) {
231 $ids[] = $item['id'];
235 $ret = Item::select(Item::DELIVER_FIELDLIST, ['id' => $ids]);
236 $items = Item::inArray($ret);
242 * Will check further below if this actually returned results.
243 * We will provide an empty feed if that is the case.
246 $doc = new DOMDocument('1.0', 'utf-8');
247 $doc->formatOutput = true;
249 $alternatelink = $owner['url'];
251 if (isset($category)) {
252 $alternatelink .= "/category/".$category;
256 $author = "dfrn:owner";
261 $root = self::addHeader($doc, $owner, $author, $alternatelink, true);
263 /// @TODO This hook can't work anymore
264 // Addon::callHooks('atom_feed', $atom);
266 if (!DBA::isResult($items) || $onlyheader) {
267 $atom = trim($doc->saveXML());
269 Addon::callHooks('atom_feed_end', $atom);
274 foreach ($items as $item) {
275 // prevent private email from leaking.
276 if ($item['network'] == Protocol::MAIL) {
280 // public feeds get html, our own nodes use bbcode
284 // catch any email that's in a public conversation and make sure it doesn't leak
285 if ($item['private']) {
292 $entry = self::entry($doc, $type, $item, $owner, true);
293 $root->appendChild($entry);
296 $atom = trim($doc->saveXML());
298 Addon::callHooks('atom_feed_end', $atom);
304 * @brief Generate an atom entry for a given item id
306 * @param int $item_id The item id
307 * @param boolean $conversation Show the conversation. If false show the single post.
309 * @return string DFRN feed entry
311 public static function itemFeed($item_id, $conversation = false)
314 $condition = ['parent' => $item_id];
316 $condition = ['id' => $item_id];
319 $ret = Item::select(Item::DELIVER_FIELDLIST, $condition);
320 $items = Item::inArray($ret);
321 if (!DBA::isResult($items)) {
327 if ($item['uid'] != 0) {
328 $owner = User::getOwnerDataById($item['uid']);
333 $owner = ['uid' => 0, 'nick' => 'feed-item'];
336 $doc = new DOMDocument('1.0', 'utf-8');
337 $doc->formatOutput = true;
341 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
342 $doc->appendChild($root);
344 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
345 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
346 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
347 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
348 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
349 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
350 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
351 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
352 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
354 //$root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
356 foreach ($items as $item) {
357 $entry = self::entry($doc, $type, $item, $owner, true, 0);
358 $root->appendChild($entry);
361 $root = self::entry($doc, $type, $item, $owner, true, 0, true);
364 $atom = trim($doc->saveXML());
369 * @brief Create XML text for DFRN mails
371 * @param array $item message elements
372 * @param array $owner Owner record
374 * @return string DFRN mail
375 * @todo Find proper type-hints
377 public static function mail($item, $owner)
379 $doc = new DOMDocument('1.0', 'utf-8');
380 $doc->formatOutput = true;
382 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
384 $mail = $doc->createElement("dfrn:mail");
385 $sender = $doc->createElement("dfrn:sender");
387 XML::addElement($doc, $sender, "dfrn:name", $owner['name']);
388 XML::addElement($doc, $sender, "dfrn:uri", $owner['url']);
389 XML::addElement($doc, $sender, "dfrn:avatar", $owner['thumb']);
391 $mail->appendChild($sender);
393 XML::addElement($doc, $mail, "dfrn:id", $item['uri']);
394 XML::addElement($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
395 XML::addElement($doc, $mail, "dfrn:sentdate", DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
396 XML::addElement($doc, $mail, "dfrn:subject", $item['title']);
397 XML::addElement($doc, $mail, "dfrn:content", $item['body']);
399 $root->appendChild($mail);
401 return trim($doc->saveXML());
405 * @brief Create XML text for DFRN friend suggestions
407 * @param array $item suggestion elements
408 * @param array $owner Owner record
410 * @return string DFRN suggestions
411 * @todo Find proper type-hints
413 public static function fsuggest($item, $owner)
415 $doc = new DOMDocument('1.0', 'utf-8');
416 $doc->formatOutput = true;
418 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
420 $suggest = $doc->createElement("dfrn:suggest");
422 XML::addElement($doc, $suggest, "dfrn:url", $item['url']);
423 XML::addElement($doc, $suggest, "dfrn:name", $item['name']);
424 XML::addElement($doc, $suggest, "dfrn:photo", $item['photo']);
425 XML::addElement($doc, $suggest, "dfrn:request", $item['request']);
426 XML::addElement($doc, $suggest, "dfrn:note", $item['note']);
428 $root->appendChild($suggest);
430 return trim($doc->saveXML());
434 * @brief Create XML text for DFRN relocations
436 * @param array $owner Owner record
437 * @param int $uid User ID
439 * @return string DFRN relocations
440 * @todo Find proper type-hints
442 public static function relocate($owner, $uid)
445 /* get site pubkey. this could be a new installation with no site keys*/
446 $pubkey = Config::get('system', 'site_pubkey');
448 $res = Crypto::newKeypair(1024);
449 Config::set('system', 'site_prvkey', $res['prvkey']);
450 Config::set('system', 'site_pubkey', $res['pubkey']);
454 "SELECT `resource-id` , `scale`, type FROM `photo`
455 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;",
459 $ext = Image::supportedTypes();
461 foreach ($rp as $p) {
462 $photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
466 $doc = new DOMDocument('1.0', 'utf-8');
467 $doc->formatOutput = true;
469 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
471 $relocate = $doc->createElement("dfrn:relocate");
473 XML::addElement($doc, $relocate, "dfrn:url", $owner['url']);
474 XML::addElement($doc, $relocate, "dfrn:name", $owner['name']);
475 XML::addElement($doc, $relocate, "dfrn:addr", $owner['addr']);
476 XML::addElement($doc, $relocate, "dfrn:avatar", $owner['avatar']);
477 XML::addElement($doc, $relocate, "dfrn:photo", $photos[4]);
478 XML::addElement($doc, $relocate, "dfrn:thumb", $photos[5]);
479 XML::addElement($doc, $relocate, "dfrn:micro", $photos[6]);
480 XML::addElement($doc, $relocate, "dfrn:request", $owner['request']);
481 XML::addElement($doc, $relocate, "dfrn:confirm", $owner['confirm']);
482 XML::addElement($doc, $relocate, "dfrn:notify", $owner['notify']);
483 XML::addElement($doc, $relocate, "dfrn:poll", $owner['poll']);
484 XML::addElement($doc, $relocate, "dfrn:sitepubkey", Config::get('system', 'site_pubkey'));
486 $root->appendChild($relocate);
488 return trim($doc->saveXML());
492 * @brief Adds the header elements for the DFRN protocol
494 * @param object $doc XML document
495 * @param array $owner Owner record
496 * @param string $authorelement Element name for the author
497 * @param string $alternatelink link to profile or category
498 * @param bool $public Is it a header for public posts?
500 * @return object XML root object
501 * @todo Find proper type-hints
503 private static function addHeader($doc, $owner, $authorelement, $alternatelink = "", $public = false)
506 if ($alternatelink == "") {
507 $alternatelink = $owner['url'];
510 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
511 $doc->appendChild($root);
513 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
514 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
515 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
516 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
517 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
518 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
519 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
520 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
521 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
523 XML::addElement($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
524 XML::addElement($doc, $root, "title", $owner["name"]);
526 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION];
527 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
529 $attributes = ["rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/"];
530 XML::addElement($doc, $root, "link", "", $attributes);
532 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $alternatelink];
533 XML::addElement($doc, $root, "link", "", $attributes);
537 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
538 OStatus::hublinks($doc, $root, $owner["nick"]);
540 $attributes = ["rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
541 XML::addElement($doc, $root, "link", "", $attributes);
543 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
544 XML::addElement($doc, $root, "link", "", $attributes);
546 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
547 XML::addElement($doc, $root, "link", "", $attributes);
550 // For backward compatibility we keep this element
551 if ($owner['page-flags'] == Contact::PAGE_COMMUNITY) {
552 XML::addElement($doc, $root, "dfrn:community", 1);
555 // The former element is replaced by this one
556 XML::addElement($doc, $root, "dfrn:account_type", $owner["account-type"]);
558 /// @todo We need a way to transmit the different page flags like "Contact::PAGE_PRVGROUP"
560 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
562 $author = self::addAuthor($doc, $owner, $authorelement, $public);
563 $root->appendChild($author);
569 * @brief Adds the author element in the header for the DFRN protocol
571 * @param object $doc XML document
572 * @param array $owner Owner record
573 * @param string $authorelement Element name for the author
574 * @param boolean $public boolean
576 * @return object XML author object
577 * @todo Find proper type-hints
579 private static function addAuthor($doc, $owner, $authorelement, $public)
581 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
583 "SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
584 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
585 intval($owner['uid'])
587 if (DBA::isResult($r)) {
593 $author = $doc->createElement($authorelement);
595 $namdate = DateTimeFormat::utc($owner['name-date'].'+00:00', DateTimeFormat::ATOM);
596 $uridate = DateTimeFormat::utc($owner['uri-date'].'+00:00', DateTimeFormat::ATOM);
597 $picdate = DateTimeFormat::utc($owner['avatar-date'].'+00:00', DateTimeFormat::ATOM);
601 if (!$public || !$hidewall) {
602 $attributes = ["dfrn:updated" => $namdate];
605 XML::addElement($doc, $author, "name", $owner["name"], $attributes);
606 XML::addElement($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
607 XML::addElement($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
609 $attributes = ["rel" => "photo", "type" => "image/jpeg",
610 "media:width" => 175, "media:height" => 175, "href" => $owner['photo']];
612 if (!$public || !$hidewall) {
613 $attributes["dfrn:updated"] = $picdate;
616 XML::addElement($doc, $author, "link", "", $attributes);
618 $attributes["rel"] = "avatar";
619 XML::addElement($doc, $author, "link", "", $attributes);
622 XML::addElement($doc, $author, "dfrn:hide", "true");
625 // The following fields will only be generated if the data isn't meant for a public feed
630 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
633 XML::addElement($doc, $author, "dfrn:birthday", $birthday);
636 // Only show contact details when we are allowed to
638 "SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
639 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
640 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
642 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
643 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
644 intval($owner['uid'])
646 if (DBA::isResult($r)) {
649 XML::addElement($doc, $author, "poco:displayName", $profile["name"]);
650 XML::addElement($doc, $author, "poco:updated", $namdate);
652 if (trim($profile["dob"]) > '0001-01-01') {
653 XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
656 XML::addElement($doc, $author, "poco:note", $profile["about"]);
657 XML::addElement($doc, $author, "poco:preferredUsername", $profile["nickname"]);
659 $savetz = date_default_timezone_get();
660 date_default_timezone_set($profile["timezone"]);
661 XML::addElement($doc, $author, "poco:utcOffset", date("P"));
662 date_default_timezone_set($savetz);
664 if (trim($profile["homepage"]) != "") {
665 $urls = $doc->createElement("poco:urls");
666 XML::addElement($doc, $urls, "poco:type", "homepage");
667 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
668 XML::addElement($doc, $urls, "poco:primary", "true");
669 $author->appendChild($urls);
672 if (trim($profile["pub_keywords"]) != "") {
673 $keywords = explode(",", $profile["pub_keywords"]);
675 foreach ($keywords as $keyword) {
676 XML::addElement($doc, $author, "poco:tags", trim($keyword));
680 if (trim($profile["xmpp"]) != "") {
681 $ims = $doc->createElement("poco:ims");
682 XML::addElement($doc, $ims, "poco:type", "xmpp");
683 XML::addElement($doc, $ims, "poco:value", $profile["xmpp"]);
684 XML::addElement($doc, $ims, "poco:primary", "true");
685 $author->appendChild($ims);
688 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
689 $element = $doc->createElement("poco:address");
691 XML::addElement($doc, $element, "poco:formatted", Profile::formatLocation($profile));
693 if (trim($profile["locality"]) != "") {
694 XML::addElement($doc, $element, "poco:locality", $profile["locality"]);
697 if (trim($profile["region"]) != "") {
698 XML::addElement($doc, $element, "poco:region", $profile["region"]);
701 if (trim($profile["country-name"]) != "") {
702 XML::addElement($doc, $element, "poco:country", $profile["country-name"]);
705 $author->appendChild($element);
713 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
715 * @param object $doc XML document
716 * @param string $element Element name for the author
717 * @param string $contact_url Link of the contact
718 * @param array $item Item elements
720 * @return object XML author object
721 * @todo Find proper type-hints
723 private static function addEntryAuthor($doc, $element, $contact_url, $item)
725 $contact = Contact::getDetailsByURL($contact_url, $item["uid"]);
727 $author = $doc->createElement($element);
728 XML::addElement($doc, $author, "name", $contact["name"]);
729 XML::addElement($doc, $author, "uri", $contact["url"]);
730 XML::addElement($doc, $author, "dfrn:handle", $contact["addr"]);
733 /// - Check real image type and image size
734 /// - Check which of these boths elements we should use
737 "type" => "image/jpeg",
739 "media:height" => 80,
740 "href" => $contact["photo"]];
741 XML::addElement($doc, $author, "link", "", $attributes);
745 "type" => "image/jpeg",
747 "media:height" => 80,
748 "href" => $contact["photo"]];
749 XML::addElement($doc, $author, "link", "", $attributes);
755 * @brief Adds the activity elements
757 * @param object $doc XML document
758 * @param string $element Element name for the activity
759 * @param string $activity activity value
761 * @return object XML activity object
762 * @todo Find proper type-hints
764 private static function createActivity($doc, $element, $activity)
767 $entry = $doc->createElement($element);
769 $r = XML::parseString($activity, false);
775 XML::addElement($doc, $entry, "activity:object-type", $r->type);
779 XML::addElement($doc, $entry, "id", $r->id);
783 XML::addElement($doc, $entry, "title", $r->title);
787 if (substr($r->link, 0, 1) == '<') {
788 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
789 $r->link = str_replace('&', '&', $r->link);
792 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
794 // XML does need a single element as root element so we add a dummy element here
795 $data = XML::parseString("<dummy>" . $r->link . "</dummy>", false);
796 if (is_object($data)) {
797 foreach ($data->link as $link) {
799 foreach ($link->attributes() as $parameter => $value) {
800 $attributes[$parameter] = $value;
802 XML::addElement($doc, $entry, "link", "", $attributes);
806 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
807 XML::addElement($doc, $entry, "link", "", $attributes);
811 XML::addElement($doc, $entry, "content", BBCode::convert($r->content), ["type" => "html"]);
821 * @brief Adds the elements for attachments
823 * @param object $doc XML document
824 * @param object $root XML root
825 * @param array $item Item element
827 * @return object XML attachment object
828 * @todo Find proper type-hints
830 private static function getAttachment($doc, $root, $item)
832 $arr = explode('[/attach],', $item['attach']);
834 foreach ($arr as $r) {
836 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
838 $attributes = ["rel" => "enclosure",
839 "href" => $matches[1],
840 "type" => $matches[3]];
842 if (intval($matches[2])) {
843 $attributes["length"] = intval($matches[2]);
846 if (trim($matches[4]) != "") {
847 $attributes["title"] = trim($matches[4]);
850 XML::addElement($doc, $root, "link", "", $attributes);
857 * @brief Adds the "entry" elements for the DFRN protocol
859 * @param object $doc XML document
860 * @param string $type "text" or "html"
861 * @param array $item Item element
862 * @param array $owner Owner record
863 * @param bool $comment Trigger the sending of the "comment" element
864 * @param int $cid Contact ID of the recipient
865 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
867 * @return object XML entry object
868 * @todo Find proper type-hints
870 private static function entry($doc, $type, array $item, array $owner, $comment = false, $cid = 0, $single = false)
874 if (!$item['parent']) {
878 if ($item['deleted']) {
879 $attributes = ["ref" => $item['uri'], "when" => DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM)];
880 return XML::createElement($doc, "at:deleted-entry", "", $attributes);
884 $entry = $doc->createElement("entry");
886 $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry');
887 $doc->appendChild($entry);
889 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
890 $entry->setAttribute("xmlns:at", NAMESPACE_TOMB);
891 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
892 $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
893 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
894 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
895 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
896 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
897 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
900 if ($item['private']) {
901 $body = Item::fixPrivatePhotos($item['body'], $owner['uid'], $item, $cid);
903 $body = $item['body'];
906 // Remove the abstract element. It is only locally important.
907 $body = BBCode::stripAbstract($body);
910 if ($type == 'html') {
913 if ($item['title'] != "") {
914 $htmlbody = "[b]" . $item['title'] . "[/b]\n\n" . $htmlbody;
917 $htmlbody = BBCode::convert($htmlbody, false, 7);
920 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
921 $entry->appendChild($author);
923 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
924 $entry->appendChild($dfrnowner);
926 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
927 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
928 $parent = Item::selectFirst(['guid', 'plink'], ['uri' => $parent_item, 'uid' => $item['uid']]);
929 $attributes = ["ref" => $parent_item, "type" => "text/html",
930 "href" => $parent['plink'],
931 "dfrn:diaspora_guid" => $parent['guid']];
932 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
935 // Add conversation data. This is used for OStatus
936 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
937 $conversation_uri = $conversation_href;
939 if (isset($parent_item)) {
940 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $item['parent-uri']]);
941 if (DBA::isResult($conversation)) {
942 if ($conversation['conversation-uri'] != '') {
943 $conversation_uri = $conversation['conversation-uri'];
945 if ($conversation['conversation-href'] != '') {
946 $conversation_href = $conversation['conversation-href'];
952 "href" => $conversation_href,
953 "ref" => $conversation_uri];
955 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
957 XML::addElement($doc, $entry, "id", $item["uri"]);
958 XML::addElement($doc, $entry, "title", $item["title"]);
960 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"] . "+00:00", DateTimeFormat::ATOM));
961 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"] . "+00:00", DateTimeFormat::ATOM));
963 // "dfrn:env" is used to read the content
964 XML::addElement($doc, $entry, "dfrn:env", base64url_encode($body, true));
966 // The "content" field is not read by the receiver. We could remove it when the type is "text"
967 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
968 XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
970 // We save this value in "plink". Maybe we should read it from there as well?
976 ["rel" => "alternate", "type" => "text/html",
977 "href" => System::baseUrl() . "/display/" . $item["guid"]]
980 // "comment-allow" is some old fashioned stuff for old Friendica versions.
981 // It is included in the rewritten code for completeness
983 XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
986 if ($item['location']) {
987 XML::addElement($doc, $entry, "dfrn:location", $item['location']);
990 if ($item['coord']) {
991 XML::addElement($doc, $entry, "georss:point", $item['coord']);
994 if ($item['private']) {
995 XML::addElement($doc, $entry, "dfrn:private", ($item['private'] ? $item['private'] : 1));
998 if ($item['extid']) {
999 XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
1002 if ($item['post-type'] == Item::PT_PAGE) {
1003 XML::addElement($doc, $entry, "dfrn:bookmark", "true");
1007 XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
1010 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
1012 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
1013 // It is needed for relayed comments to Diaspora.
1014 if ($item['signed_text']) {
1015 $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer']]));
1016 XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
1019 XML::addElement($doc, $entry, "activity:verb", self::constructVerb($item));
1021 if ($item['object-type'] != "") {
1022 XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
1023 } elseif ($item['id'] == $item['parent']) {
1024 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1026 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
1029 $actobj = self::createActivity($doc, "activity:object", $item['object']);
1031 $entry->appendChild($actobj);
1034 $actarg = self::createActivity($doc, "activity:target", $item['target']);
1036 $entry->appendChild($actarg);
1039 $tags = Item::getFeedTags($item);
1041 /// @TODO Combine this with similar below if() block?
1043 foreach ($tags as $t) {
1044 if (($type != 'html') || ($t[0] != "@")) {
1045 XML::addElement($doc, $entry, "category", "", ["scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]]);
1051 foreach ($tags as $t) {
1053 $mentioned[$t[1]] = $t[1];
1058 foreach ($mentioned as $mention) {
1059 $condition = ['uid' => $owner["uid"], 'nurl' => normalise_link($mention)];
1060 $contact = DBA::selectFirst('contact', ['forum', 'prv'], $condition);
1062 if (DBA::isResult($contact) && ($contact["forum"] || $contact["prv"])) {
1068 ["rel" => "mentioned",
1069 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1078 ["rel" => "mentioned",
1079 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1085 self::getAttachment($doc, $entry, $item);
1091 * @brief encrypts data via AES
1093 * @param string $data The data that is to be encrypted
1094 * @param string $key The AES key
1096 * @return string encrypted data
1098 private static function aesEncrypt($data, $key)
1100 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1104 * @brief decrypts data via AES
1106 * @param string $encrypted The encrypted data
1107 * @param string $key The AES key
1109 * @return string decrypted data
1111 public static function aesDecrypt($encrypted, $key)
1113 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1117 * @brief Delivers the atom content to the contacts
1119 * @param array $owner Owner record
1120 * @param array $contact Contact record of the receiver
1121 * @param string $atom Content that will be transmitted
1122 * @param bool $dissolve (to be documented)
1124 * @return int Deliver status. Negative values mean an error.
1125 * @todo Add array type-hint for $owner, $contact
1127 public static function deliver($owner, $contact, $atom, $dissolve = false)
1131 // At first try the Diaspora transport layer
1132 $ret = self::transmit($owner, $contact, $atom);
1134 logger('Delivery via Diaspora transport layer was successful with status ' . $ret);
1138 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1140 if ($contact['duplex'] && $contact['dfrn-id']) {
1141 $idtosend = '0:' . $orig_id;
1143 if ($contact['duplex'] && $contact['issued-id']) {
1144 $idtosend = '1:' . $orig_id;
1147 $rino = Config::get('system', 'rino_encrypt');
1148 $rino = intval($rino);
1150 logger("Local rino version: ". $rino, LOGGER_DEBUG);
1152 $ssl_val = intval(Config::get('system', 'ssl_policy'));
1156 case SSL_POLICY_FULL:
1157 $ssl_policy = 'full';
1159 case SSL_POLICY_SELFSIGN:
1160 $ssl_policy = 'self';
1162 case SSL_POLICY_NONE:
1164 $ssl_policy = 'none';
1168 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1170 logger('dfrn_deliver: ' . $url);
1172 $ret = Network::curl($url);
1174 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1175 Contact::markForArchival($contact);
1176 return -2; // timed out
1179 $xml = $ret['body'];
1181 $curl_stat = $a->get_curl_code();
1182 if (empty($curl_stat)) {
1183 Contact::markForArchival($contact);
1184 return -3; // timed out
1187 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1190 Contact::markForArchival($contact);
1194 if (strpos($xml, '<?xml') === false) {
1195 logger('dfrn_deliver: no valid XML returned');
1196 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1197 Contact::markForArchival($contact);
1201 $res = XML::parseString($xml);
1203 if (!is_object($res) || (intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
1204 Contact::markForArchival($contact);
1206 if (empty($res->status)) {
1209 $status = $res->status;
1216 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1217 $challenge = hex2bin((string) $res->challenge);
1218 $perm = (($res->perm) ? $res->perm : null);
1219 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1220 $rino_remote_version = intval($res->rino);
1221 $page = (($owner['page-flags'] == Contact::PAGE_COMMUNITY) ? 1 : 0);
1223 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
1225 if ($owner['page-flags'] == Contact::PAGE_PRVGROUP) {
1229 $final_dfrn_id = '';
1232 if ((($perm == 'rw') && !intval($contact['writable']))
1233 || (($perm == 'r') && intval($contact['writable']))
1235 DBA::update('contact', ['writable' => ($perm == 'rw')], ['id' => $contact['id']]);
1237 $contact['writable'] = (string) 1 - intval($contact['writable']);
1241 if (($contact['duplex'] && strlen($contact['pubkey']))
1242 || ($owner['page-flags'] == Contact::PAGE_COMMUNITY && strlen($contact['pubkey']))
1243 || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
1245 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
1246 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
1248 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
1249 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
1252 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1254 if (strpos($final_dfrn_id, ':') == 1) {
1255 $final_dfrn_id = substr($final_dfrn_id, 2);
1258 if ($final_dfrn_id != $orig_id) {
1259 logger('dfrn_deliver: wrong dfrn_id.');
1260 // did not decode properly - cannot trust this site
1261 Contact::markForArchival($contact);
1265 $postvars['dfrn_id'] = $idtosend;
1266 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1268 $postvars['dissolve'] = '1';
1271 if ((($contact['rel']) && ($contact['rel'] != Contact::SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == Contact::PAGE_COMMUNITY)) {
1272 $postvars['data'] = $atom;
1273 $postvars['perm'] = 'rw';
1275 $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
1276 $postvars['perm'] = 'r';
1279 $postvars['ssl_policy'] = $ssl_policy;
1282 $postvars['page'] = $page;
1286 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1287 logger('rino version: '. $rino_remote_version);
1289 switch ($rino_remote_version) {
1291 $key = openssl_random_pseudo_bytes(16);
1292 $data = self::aesEncrypt($postvars['data'], $key);
1295 logger("rino: invalid requested version '$rino_remote_version'");
1296 Contact::markForArchival($contact);
1300 $postvars['rino'] = $rino_remote_version;
1301 $postvars['data'] = bin2hex($data);
1303 if ($dfrn_version >= 2.1) {
1304 if (($contact['duplex'] && strlen($contact['pubkey']))
1305 || ($owner['page-flags'] == Contact::PAGE_COMMUNITY && strlen($contact['pubkey']))
1306 || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
1308 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1310 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1313 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == Contact::PAGE_COMMUNITY)) {
1314 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1316 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1320 logger('md5 rawkey ' . md5($postvars['key']));
1322 $postvars['key'] = bin2hex($postvars['key']);
1326 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), LOGGER_DATA);
1328 $xml = Network::post($contact['notify'], $postvars);
1330 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1332 $curl_stat = $a->get_curl_code();
1333 if (empty($curl_stat) || empty($xml)) {
1334 Contact::markForArchival($contact);
1335 return -9; // timed out
1338 if (($curl_stat == 503) && stristr($a->get_curl_headers(), 'retry-after')) {
1339 Contact::markForArchival($contact);
1343 if (strpos($xml, '<?xml') === false) {
1344 logger('dfrn_deliver: phase 2: no valid XML returned');
1345 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1346 Contact::markForArchival($contact);
1350 $res = XML::parseString($xml);
1352 if (!isset($res->status)) {
1353 Contact::markForArchival($contact);
1357 // Possibly old servers had returned an empty value when everything was okay
1358 if (empty($res->status)) {
1362 if (!empty($res->message)) {
1363 logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1366 if (($res->status >= 200) && ($res->status <= 299)) {
1367 Contact::unmarkForArchival($contact);
1370 return intval($res->status);
1374 * @brief Transmits atom content to the contacts via the Diaspora transport layer
1376 * @param array $owner Owner record
1377 * @param array $contact Contact record of the receiver
1378 * @param string $atom Content that will be transmitted
1380 * @return int Deliver status. Negative values mean an error.
1382 public static function transmit($owner, $contact, $atom, $public_batch = false)
1386 if (!$public_batch) {
1387 if (empty($contact['addr'])) {
1388 logger('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.');
1389 if (Contact::updateFromProbe($contact['id'])) {
1390 $new_contact = DBA::selectFirst('contact', ['addr'], ['id' => $contact['id']]);
1391 $contact['addr'] = $new_contact['addr'];
1394 if (empty($contact['addr'])) {
1395 logger('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
1396 Contact::markForArchival($contact);
1401 $fcontact = Diaspora::personByHandle($contact['addr']);
1402 if (empty($fcontact)) {
1403 logger('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
1404 Contact::markForArchival($contact);
1407 $pubkey = $fcontact['pubkey'];
1412 $envelope = Diaspora::buildMessage($atom, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
1414 // Create the endpoint for public posts. This is some WIP and should later be added to the probing
1415 if ($public_batch && empty($contact["batch"])) {
1416 $parts = parse_url($contact["notify"]);
1417 $path_parts = explode('/', $parts['path']);
1418 array_pop($path_parts);
1419 $parts['path'] = implode('/', $path_parts);
1420 $contact["batch"] = Network::unparseURL($parts);
1423 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
1425 $content_type = ($public_batch ? "application/magic-envelope+xml" : "application/json");
1427 $xml = Network::post($dest_url, $envelope, ["Content-Type: ".$content_type]);
1429 $curl_stat = $a->get_curl_code();
1430 if (empty($curl_stat) || empty($xml)) {
1431 logger('Empty answer from ' . $contact['id'] . ' - ' . $dest_url);
1432 Contact::markForArchival($contact);
1433 return -9; // timed out
1436 if (($curl_stat == 503) && (stristr($a->get_curl_headers(), 'retry-after'))) {
1437 Contact::markForArchival($contact);
1441 if (strpos($xml, '<?xml') === false) {
1442 logger('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url);
1443 logger('Returned XML: ' . $xml, LOGGER_DATA);
1444 Contact::markForArchival($contact);
1448 $res = XML::parseString($xml);
1450 if (empty($res->status)) {
1451 Contact::markForArchival($contact);
1455 if (!empty($res->message)) {
1456 logger('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1459 if (($res->status >= 200) && ($res->status <= 299)) {
1460 Contact::unmarkForArchival($contact);
1463 return intval($res->status);
1467 * @brief Add new birthday event for this person
1469 * @param array $contact Contact record
1470 * @param string $birthday Birthday of the contact
1472 * @todo Add array type-hint for $contact
1474 private static function birthdayEvent($contact, $birthday)
1476 // Check for duplicates
1477 $condition = ['uid' => $contact['uid'], 'cid' => $contact['id'],
1478 'start' => DateTimeFormat::utc($birthday), 'type' => 'birthday'];
1479 if (DBA::exists('event', $condition)) {
1483 logger('updating birthday: ' . $birthday . ' for contact ' . $contact['id']);
1485 $bdtext = L10n::t('%s\'s birthday', $contact['name']);
1486 $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]');
1489 "INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1490 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1491 intval($contact['uid']),
1492 intval($contact['id']),
1493 DBA::escape(DateTimeFormat::utcNow()),
1494 DBA::escape(DateTimeFormat::utcNow()),
1495 DBA::escape(DateTimeFormat::utc($birthday)),
1496 DBA::escape(DateTimeFormat::utc($birthday . ' + 1 day ')),
1497 DBA::escape($bdtext),
1498 DBA::escape($bdtext2),
1499 DBA::escape('birthday')
1504 * @brief Fetch the author data from head or entry items
1506 * @param object $xpath XPath object
1507 * @param object $context In which context should the data be searched
1508 * @param array $importer Record of the importer user mixed with contact of the content
1509 * @param string $element Element name from which the data is fetched
1510 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1511 * @param string $xml optional, default empty
1513 * @return array Relevant data of the author
1514 * @todo Find good type-hints for all parameter
1516 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
1519 $author["name"] = XML::getFirstNodeValue($xpath, $element."/atom:name/text()", $context);
1520 $author["link"] = XML::getFirstNodeValue($xpath, $element."/atom:uri/text()", $context);
1522 $fields = ['id', 'uid', 'url', 'network', 'avatar-date', 'avatar', 'name-date', 'uri-date', 'addr',
1523 'name', 'nick', 'about', 'location', 'keywords', 'xmpp', 'bdyear', 'bd', 'hidden', 'contact-type'];
1524 $condition = ["`uid` = ? AND `nurl` = ? AND `network` != ?",
1525 $importer["importer_uid"], normalise_link($author["link"]), Protocol::STATUSNET];
1526 $contact_old = DBA::selectFirst('contact', $fields, $condition);
1528 if (DBA::isResult($contact_old)) {
1529 $author["contact-id"] = $contact_old["id"];
1530 $author["network"] = $contact_old["network"];
1533 logger("Contact ".$author["link"]." wasn't found for user ".$importer["importer_uid"]." XML: ".$xml, LOGGER_DEBUG);
1536 $author["contact-unknown"] = true;
1537 $author["contact-id"] = $importer["id"];
1538 $author["network"] = $importer["network"];
1542 // Until now we aren't serving different sizes - but maybe later
1544 /// @todo check if "avatar" or "photo" would be the best field in the specification
1545 $avatars = $xpath->query($element . "/atom:link[@rel='avatar']", $context);
1546 foreach ($avatars as $avatar) {
1549 foreach ($avatar->attributes as $attributes) {
1550 /// @TODO Rewrite these similar if() to one switch
1551 if ($attributes->name == "href") {
1552 $href = $attributes->textContent;
1554 if ($attributes->name == "width") {
1555 $width = $attributes->textContent;
1557 if ($attributes->name == "updated") {
1558 $author["avatar-date"] = $attributes->textContent;
1561 if (($width > 0) && ($href != "")) {
1562 $avatarlist[$width] = $href;
1566 if (count($avatarlist) > 0) {
1567 krsort($avatarlist);
1568 $author["avatar"] = current($avatarlist);
1571 if (empty($author['avatar']) && !empty($author['link'])) {
1572 $cid = Contact::getIdForURL($author['link'], 0);
1574 $contact = DBA::selectFirst('contact', ['avatar'], ['id' => $cid]);
1575 if (DBA::isResult($contact)) {
1576 $author['avatar'] = $contact['avatar'];
1581 if (DBA::isResult($contact_old) && !$onlyfetch) {
1582 logger("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", LOGGER_DEBUG);
1584 $poco = ["url" => $contact_old["url"]];
1586 // When was the last change to name or uri?
1587 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1588 foreach ($name_element->attributes as $attributes) {
1589 if ($attributes->name == "updated") {
1590 $poco["name-date"] = $attributes->textContent;
1594 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1595 foreach ($link_element->attributes as $attributes) {
1596 if ($attributes->name == "updated") {
1597 $poco["uri-date"] = $attributes->textContent;
1601 // Update contact data
1602 $value = XML::getFirstNodeValue($xpath, $element . "/dfrn:handle/text()", $context);
1604 $poco["addr"] = $value;
1607 $value = XML::getFirstNodeValue($xpath, $element . "/poco:displayName/text()", $context);
1609 $poco["name"] = $value;
1612 $value = XML::getFirstNodeValue($xpath, $element . "/poco:preferredUsername/text()", $context);
1614 $poco["nick"] = $value;
1617 $value = XML::getFirstNodeValue($xpath, $element . "/poco:note/text()", $context);
1619 $poco["about"] = $value;
1622 $value = XML::getFirstNodeValue($xpath, $element . "/poco:address/poco:formatted/text()", $context);
1624 $poco["location"] = $value;
1627 /// @todo Only search for elements with "poco:type" = "xmpp"
1628 $value = XML::getFirstNodeValue($xpath, $element . "/poco:ims/poco:value/text()", $context);
1630 $poco["xmpp"] = $value;
1633 /// @todo Add support for the following fields that we don't support by now in the contact table:
1634 /// - poco:utcOffset
1640 // If the "hide" element is present then the profile isn't searchable.
1641 $hide = intval(XML::getFirstNodeValue($xpath, $element . "/dfrn:hide/text()", $context) == "true");
1643 logger("Hidden status for contact " . $contact_old["url"] . ": " . $hide, LOGGER_DEBUG);
1645 // If the contact isn't searchable then set the contact to "hidden".
1646 // Problem: This can be manually overridden by the user.
1648 $contact_old["hidden"] = true;
1651 // Save the keywords into the contact table
1653 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1654 foreach ($tagelements as $tag) {
1655 $tags[$tag->nodeValue] = $tag->nodeValue;
1659 $poco["keywords"] = implode(", ", $tags);
1662 // "dfrn:birthday" contains the birthday converted to UTC
1663 $birthday = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1665 if (strtotime($birthday) > time()) {
1666 $bd_timestamp = strtotime($birthday);
1668 $poco["bdyear"] = date("Y", $bd_timestamp);
1671 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1672 $value = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1674 if (!in_array($value, ["", "0000-00-00", "0001-01-01"])) {
1675 $bdyear = date("Y");
1676 $value = str_replace("0000", $bdyear, $value);
1678 if (strtotime($value) < time()) {
1679 $value = str_replace($bdyear, $bdyear + 1, $value);
1680 $bdyear = $bdyear + 1;
1683 $poco["bd"] = $value;
1686 $contact = array_merge($contact_old, $poco);
1688 if ($contact_old["bdyear"] != $contact["bdyear"]) {
1689 self::birthdayEvent($contact, $birthday);
1692 // Get all field names
1694 foreach ($contact_old as $field => $data) {
1695 $fields[$field] = $data;
1698 unset($fields["id"]);
1699 unset($fields["uid"]);
1700 unset($fields["url"]);
1701 unset($fields["avatar-date"]);
1702 unset($fields["avatar"]);
1703 unset($fields["name-date"]);
1704 unset($fields["uri-date"]);
1707 // Update check for this field has to be done differently
1708 $datefields = ["name-date", "uri-date"];
1709 foreach ($datefields as $field) {
1710 if (strtotime($contact[$field]) > strtotime($contact_old[$field])) {
1711 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1716 foreach ($fields as $field => $data) {
1717 if ($contact[$field] != $contact_old[$field]) {
1718 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1724 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1727 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1728 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1729 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1730 WHERE `id` = %d AND `network` = '%s'",
1731 DBA::escape($contact["name"]), DBA::escape($contact["nick"]), DBA::escape($contact["about"]), DBA::escape($contact["location"]),
1732 DBA::escape($contact["addr"]), DBA::escape($contact["keywords"]), DBA::escape($contact["bdyear"]),
1733 DBA::escape($contact["bd"]), intval($contact["hidden"]), DBA::escape($contact["xmpp"]),
1734 DBA::escape(DateTimeFormat::utc($contact["name-date"])), DBA::escape(DateTimeFormat::utc($contact["uri-date"])),
1735 intval($contact["id"]), DBA::escape($contact["network"])
1739 Contact::updateAvatar(
1741 $importer['importer_uid'],
1743 (strtotime($contact['avatar-date']) > strtotime($contact_old['avatar-date']) || ($author['avatar'] != $contact_old['avatar']))
1747 * The generation is a sign for the reliability of the provided data.
1748 * It is used in the socgraph.php to prevent that old contact data
1749 * that was relayed over several servers can overwrite contact
1750 * data that we received directly.
1753 $poco["generation"] = 2;
1754 $poco["photo"] = $author["avatar"];
1755 $poco["hide"] = $hide;
1756 $poco["contact-type"] = $contact["contact-type"];
1757 $gcid = GContact::update($poco);
1759 GContact::link($gcid, $importer["importer_uid"], $contact["id"]);
1766 * @brief Transforms activity objects into an XML string
1768 * @param object $xpath XPath object
1769 * @param object $activity Activity object
1770 * @param string $element element name
1772 * @return string XML string
1773 * @todo Find good type-hints for all parameter
1775 private static function transformActivity($xpath, $activity, $element)
1777 if (!is_object($activity)) {
1781 $obj_doc = new DOMDocument("1.0", "utf-8");
1782 $obj_doc->formatOutput = true;
1784 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1786 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1787 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1789 $id = $xpath->query("atom:id", $activity)->item(0);
1790 if (is_object($id)) {
1791 $obj_element->appendChild($obj_doc->importNode($id, true));
1794 $title = $xpath->query("atom:title", $activity)->item(0);
1795 if (is_object($title)) {
1796 $obj_element->appendChild($obj_doc->importNode($title, true));
1799 $links = $xpath->query("atom:link", $activity);
1800 if (is_object($links)) {
1801 foreach ($links as $link) {
1802 $obj_element->appendChild($obj_doc->importNode($link, true));
1806 $content = $xpath->query("atom:content", $activity)->item(0);
1807 if (is_object($content)) {
1808 $obj_element->appendChild($obj_doc->importNode($content, true));
1811 $obj_doc->appendChild($obj_element);
1813 $objxml = $obj_doc->saveXML($obj_element);
1815 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1816 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1821 * @brief Processes the mail elements
1823 * @param object $xpath XPath object
1824 * @param object $mail mail elements
1825 * @param array $importer Record of the importer user mixed with contact of the content
1827 * @todo Find good type-hints for all parameter
1829 private static function processMail($xpath, $mail, $importer)
1831 logger("Processing mails");
1833 /// @TODO Rewrite this to one statement
1835 $msg["uid"] = $importer["importer_uid"];
1836 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1837 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1838 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1839 $msg["contact-id"] = $importer["id"];
1840 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1841 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1842 $msg["created"] = DateTimeFormat::utc($xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue);
1843 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1844 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1846 $msg["replied"] = 0;
1848 DBA::insert('mail', $msg);
1850 $msg["id"] = DBA::lastInsertId();
1852 // send notifications.
1853 /// @TODO Arange this mess
1855 "type" => NOTIFY_MAIL,
1856 "notify_flags" => $importer["notify-flags"],
1857 "language" => $importer["language"],
1858 "to_name" => $importer["username"],
1859 "to_email" => $importer["email"],
1860 "uid" => $importer["importer_uid"],
1862 "source_name" => $msg["from-name"],
1863 "source_link" => $importer["url"],
1864 "source_photo" => $importer["thumb"],
1865 "verb" => ACTIVITY_POST,
1869 notification($notif_params);
1871 logger("Mail is processed, notification was sent.");
1875 * @brief Processes the suggestion elements
1877 * @param object $xpath XPath object
1878 * @param object $suggestion suggestion elements
1879 * @param array $importer Record of the importer user mixed with contact of the content
1881 * @todo Find good type-hints for all parameter
1883 private static function processSuggestion($xpath, $suggestion, $importer)
1887 logger("Processing suggestions");
1889 /// @TODO Rewrite this to one statement
1891 $suggest["uid"] = $importer["importer_uid"];
1892 $suggest["cid"] = $importer["id"];
1893 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1894 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1895 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1896 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1897 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1899 // Does our member already have a friend matching this description?
1902 * The valid result means the friend we're about to send a friend
1903 * suggestion already has them in their contact, which means no further
1904 * action is required.
1906 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1908 $condition = ['name' => $suggest["name"], 'nurl' => normalise_link($suggest["url"]),
1909 'uid' => $suggest["uid"]];
1910 if (DBA::exists('contact', $condition)) {
1914 // Do we already have an fcontact record for this person?
1917 $condition = ['url' => $suggest["url"], 'name' => $suggest["name"], 'request' => $suggest["request"]];
1918 $fcontact = DBA::selectFirst('fcontact', ['id'], $condition);
1919 if (DBA::isResult($fcontact)) {
1920 $fid = $fcontact["id"];
1922 // OK, we do. Do we already have an introduction for this person?
1923 if (DBA::exists('intro', ['uid' => $suggest["uid"], 'fid' => $fid])) {
1925 * The valid result means the friend we're about to send a friend
1926 * suggestion already has them in their contact, which means no further
1927 * action is required.
1929 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1936 "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1937 DBA::escape($suggest["name"]),
1938 DBA::escape($suggest["url"]),
1939 DBA::escape($suggest["photo"]),
1940 DBA::escape($suggest["request"])
1944 $condition = ['url' => $suggest["url"], 'name' => $suggest["name"], 'request' => $suggest["request"]];
1945 $fcontact = DBA::selectFirst('fcontact', ['id'], $condition);
1948 * If no record in fcontact is found, below INSERT statement will not
1949 * link an introduction to it.
1951 if (!DBA::isResult($fcontact)) {
1952 // Database record did not get created. Quietly give up.
1958 $hash = random_string();
1961 "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1962 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1963 intval($suggest["uid"]),
1965 intval($suggest["cid"]),
1966 DBA::escape($suggest["body"]),
1968 DBA::escape(DateTimeFormat::utcNow()),
1974 "type" => NOTIFY_SUGGEST,
1975 "notify_flags" => $importer["notify-flags"],
1976 "language" => $importer["language"],
1977 "to_name" => $importer["username"],
1978 "to_email" => $importer["email"],
1979 "uid" => $importer["importer_uid"],
1981 "link" => System::baseUrl()."/notifications/intros",
1982 "source_name" => $importer["name"],
1983 "source_link" => $importer["url"],
1984 "source_photo" => $importer["photo"],
1985 "verb" => ACTIVITY_REQ_FRIEND,
1993 * @brief Processes the relocation elements
1995 * @param object $xpath XPath object
1996 * @param object $relocation relocation elements
1997 * @param array $importer Record of the importer user mixed with contact of the content
1999 * @todo Find good type-hints for all parameter
2001 private static function processRelocation($xpath, $relocation, $importer)
2003 logger("Processing relocations");
2005 /// @TODO Rewrite this to one statement
2007 $relocate["uid"] = $importer["importer_uid"];
2008 $relocate["cid"] = $importer["id"];
2009 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
2010 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
2011 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
2012 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
2013 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
2014 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
2015 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
2016 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
2017 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
2018 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
2019 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
2020 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
2022 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
2023 $relocate["avatar"] = $relocate["photo"];
2026 if ($relocate["addr"] == "") {
2027 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
2032 "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d",
2033 intval($importer["id"]),
2034 intval($importer["importer_uid"])
2037 if (!DBA::isResult($r)) {
2038 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2044 // Update the gcontact entry
2045 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
2047 $fields = ['name' => $relocate["name"], 'photo' => $relocate["avatar"],
2048 'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2049 'addr' => $relocate["addr"], 'connect' => $relocate["addr"],
2050 'notify' => $relocate["notify"], 'server_url' => $relocate["server_url"]];
2051 DBA::update('gcontact', $fields, ['nurl' => normalise_link($old["url"])]);
2053 // Update the contact table. We try to find every entry.
2054 $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
2055 'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2056 'addr' => $relocate["addr"], 'request' => $relocate["request"],
2057 'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
2058 'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
2059 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], normalise_link($old["url"])];
2061 DBA::update('contact', $fields, $condition);
2063 Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
2065 logger('Contacts are updated.');
2068 /// merge with current record, current contents have priority
2069 /// update record, set url-updated
2070 /// update profile photos
2071 /// schedule a scan?
2076 * @brief Updates an item
2078 * @param array $current the current item record
2079 * @param array $item the new item record
2080 * @param array $importer Record of the importer user mixed with contact of the content
2081 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2083 * @todo set proper type-hints (array?)
2085 private static function updateContent($current, $item, $importer, $entrytype)
2089 if (self::isEditedTimestampNewer($current, $item)) {
2090 // do not accept (ignore) an earlier edit than one we currently have.
2091 if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
2095 $fields = ['title' => defaults($item, 'title', ''), 'body' => defaults($item, 'body', ''),
2096 'tag' => defaults($item, 'tag', ''), 'changed' => DateTimeFormat::utcNow(),
2097 'edited' => DateTimeFormat::utc($item["edited"])];
2099 $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
2100 Item::update($fields, $condition);
2108 * @brief Detects the entry type of the item
2110 * @param array $importer Record of the importer user mixed with contact of the content
2111 * @param array $item the new item record
2113 * @return int Is it a toplevel entry, a comment or a relayed comment?
2114 * @todo set proper type-hints (array?)
2116 private static function getEntryType($importer, $item)
2118 if ($item["parent-uri"] != $item["uri"]) {
2121 if ($importer["page-flags"] == Contact::PAGE_COMMUNITY || $importer["page-flags"] == Contact::PAGE_PRVGROUP) {
2124 logger("possible community action");
2126 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2129 // was the top-level post for this action written by somebody on this site?
2130 // Specifically, the recipient?
2132 $is_a_remote_action = false;
2134 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item["parent-uri"]]);
2135 if (DBA::isResult($parent)) {
2137 "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2138 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2139 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2140 AND `item`.`uid` = %d
2143 DBA::escape($parent["parent-uri"]),
2144 DBA::escape($parent["parent-uri"]),
2145 DBA::escape($parent["parent-uri"]),
2146 intval($importer["importer_uid"])
2148 if (DBA::isResult($r)) {
2149 $is_a_remote_action = true;
2154 * Does this have the characteristics of a community or private group action?
2155 * If it's an action to a wall post on a community/prvgroup page it's a
2156 * valid community action. Also forum_mode makes it valid for sure.
2157 * If neither, it's not.
2159 if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2160 $is_a_remote_action = false;
2161 logger("not a community action");
2164 if ($is_a_remote_action) {
2165 return DFRN::REPLY_RC;
2170 return DFRN::TOP_LEVEL;
2175 * @brief Send a "poke"
2177 * @param array $item the new item record
2178 * @param array $importer Record of the importer user mixed with contact of the content
2179 * @param int $posted_id The record number of item record that was just posted
2181 * @todo set proper type-hints (array?)
2183 private static function doPoke($item, $importer, $posted_id)
2185 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2189 $xo = XML::parseString($item["object"], false);
2191 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2192 // somebody was poked/prodded. Was it me?
2193 foreach ($xo->link as $l) {
2194 $atts = $l->attributes();
2195 switch ($atts["rel"]) {
2197 $Blink = $atts["href"];
2204 if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2205 $author = DBA::selectFirst('contact', ['name', 'thumb', 'url'], ['id' => $item['author-id']]);
2207 // send a notification
2210 "type" => NOTIFY_POKE,
2211 "notify_flags" => $importer["notify-flags"],
2212 "language" => $importer["language"],
2213 "to_name" => $importer["username"],
2214 "to_email" => $importer["email"],
2215 "uid" => $importer["importer_uid"],
2217 "link" => System::baseUrl()."/display/".urlencode(Item::getGuidById($posted_id)),
2218 "source_name" => $author["name"],
2219 "source_link" => $author["url"],
2220 "source_photo" => $author["thumb"],
2221 "verb" => $item["verb"],
2222 "otype" => "person",
2223 "activity" => $verb,
2224 "parent" => $item["parent"]]
2231 * @brief Processes several actions, depending on the verb
2233 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2234 * @param array $importer Record of the importer user mixed with contact of the content
2235 * @param array $item the new item record
2236 * @param bool $is_like Is the verb a "like"?
2238 * @return bool Should the processing of the entries be continued?
2239 * @todo set proper type-hints (array?)
2241 private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2243 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2245 if (($entrytype == DFRN::TOP_LEVEL)) {
2246 // The filling of the the "contact" variable is done for legcy reasons
2247 // The functions below are partly used by ostatus.php as well - where we have this variable
2248 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2250 $nickname = $contact["nick"];
2252 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2253 // This function once was responsible for DFRN and OStatus.
2254 if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2255 logger("New follower");
2256 Contact::addRelationship($importer, $contact, $item, $nickname);
2259 if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2260 logger("Lost follower");
2261 Contact::removeFollower($importer, $contact, $item);
2264 if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2265 logger("New friend request");
2266 Contact::addRelationship($importer, $contact, $item, $nickname, true);
2269 if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2270 logger("Lost sharer");
2271 Contact::removeSharer($importer, $contact, $item);
2275 if (($item["verb"] == ACTIVITY_LIKE)
2276 || ($item["verb"] == ACTIVITY_DISLIKE)
2277 || ($item["verb"] == ACTIVITY_ATTEND)
2278 || ($item["verb"] == ACTIVITY_ATTENDNO)
2279 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
2282 $item["gravity"] = GRAVITY_ACTIVITY;
2283 // only one like or dislike per person
2284 // splitted into two queries for performance issues
2285 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2286 'verb' => $item["verb"], 'parent-uri' => $item["parent-uri"]];
2287 if (Item::exists($condition)) {
2291 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2292 'verb' => $item["verb"], 'thr-parent' => $item["parent-uri"]];
2293 if (Item::exists($condition)) {
2300 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2301 $xo = XML::parseString($item["object"], false);
2302 $xt = XML::parseString($item["target"], false);
2304 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2305 $item_tag = Item::selectFirst(['id', 'tag'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]);
2307 if (!DBA::isResult($item_tag)) {
2308 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2312 // extract tag, if not duplicate, add to parent item
2314 if (!stristr($item_tag["tag"], trim($xo->content))) {
2315 $tag = $item_tag["tag"] . (strlen($item_tag["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2316 Item::update(['tag' => $tag], ['id' => $item_tag["id"]]);
2326 * @brief Processes the link elements
2328 * @param object $links link elements
2329 * @param array $item the item record
2331 * @todo set proper type-hints
2333 private static function parseLinks($links, &$item)
2340 foreach ($links as $link) {
2341 foreach ($link->attributes as $attributes) {
2342 switch ($attributes->name) {
2343 case "href" : $href = $attributes->textContent; break;
2344 case "rel" : $rel = $attributes->textContent; break;
2345 case "type" : $type = $attributes->textContent; break;
2346 case "length": $length = $attributes->textContent; break;
2347 case "title" : $title = $attributes->textContent; break;
2350 if (($rel != "") && ($href != "")) {
2353 $item["plink"] = $href;
2357 if (strlen($item["attach"])) {
2358 $item["attach"] .= ",";
2361 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2369 * @brief Processes the entry elements which contain the items and comments
2371 * @param array $header Array of the header elements that always stay the same
2372 * @param object $xpath XPath object
2373 * @param object $entry entry elements
2374 * @param array $importer Record of the importer user mixed with contact of the content
2375 * @param object $xml xml
2377 * @todo Add type-hints
2379 private static function processEntry($header, $xpath, $entry, $importer, $xml)
2381 logger("Processing entries");
2385 $item["protocol"] = Conversation::PARCEL_DFRN;
2387 $item["source"] = $xml;
2390 $item["uri"] = XML::getFirstNodeValue($xpath, "atom:id/text()", $entry);
2392 $item["edited"] = XML::getFirstNodeValue($xpath, "atom:updated/text()", $entry);
2394 $current = Item::selectFirst(['id', 'uid', 'edited', 'body'],
2395 ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
2397 // Is there an existing item?
2398 if (DBA::isResult($current) && !self::isEditedTimestampNewer($current, $item)) {
2399 logger("Item ".$item["uri"]." (".$item['edited'].") already existed.", LOGGER_DEBUG);
2404 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2406 $owner_unknown = (isset($owner["contact-unknown"]) && $owner["contact-unknown"]);
2408 $item["owner-name"] = $owner["name"];
2409 $item["owner-link"] = $owner["link"];
2410 $item["owner-avatar"] = $owner["avatar"];
2411 $item["owner-id"] = Contact::getIdForURL($owner["link"], 0);
2414 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2416 $item["author-name"] = $author["name"];
2417 $item["author-link"] = $author["link"];
2418 $item["author-avatar"] = $author["avatar"];
2419 $item["author-id"] = Contact::getIdForURL($author["link"], 0);
2421 $item["title"] = XML::getFirstNodeValue($xpath, "atom:title/text()", $entry);
2423 $item["created"] = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2425 $item["body"] = XML::getFirstNodeValue($xpath, "dfrn:env/text()", $entry);
2426 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2427 // make sure nobody is trying to sneak some html tags by us
2428 $item["body"] = notags(base64url_decode($item["body"]));
2430 $item["body"] = BBCode::limitBodySize($item["body"]);
2432 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2433 if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
2434 $base_url = get_app()->get_baseurl();
2435 $item['body'] = reltoabs($item['body'], $base_url);
2437 $item['body'] = html2bb_video($item['body']);
2439 $item['body'] = OEmbed::HTML2BBCode($item['body']);
2441 $config = HTMLPurifier_Config::createDefault();
2442 $config->set('Cache.DefinitionImpl', null);
2444 // we shouldn't need a whitelist, because the bbcode converter
2445 // will strip out any unsupported tags.
2447 $purifier = new HTMLPurifier($config);
2448 $item['body'] = $purifier->purify($item['body']);
2450 $item['body'] = @HTML::toBBCode($item['body']);
2453 /// @todo We should check for a repeated post and if we know the repeated author.
2455 // We don't need the content element since "dfrn:env" is always present
2456 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2458 $item["location"] = XML::getFirstNodeValue($xpath, "dfrn:location/text()", $entry);
2460 $item["coord"] = XML::getFirstNodeValue($xpath, "georss:point", $entry);
2462 $item["private"] = XML::getFirstNodeValue($xpath, "dfrn:private/text()", $entry);
2464 $item["extid"] = XML::getFirstNodeValue($xpath, "dfrn:extid/text()", $entry);
2466 if (XML::getFirstNodeValue($xpath, "dfrn:bookmark/text()", $entry) == "true") {
2467 $item["post-type"] = Item::PT_PAGE;
2470 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2471 if ($notice_info && ($notice_info->length > 0)) {
2472 foreach ($notice_info->item(0)->attributes as $attributes) {
2473 if ($attributes->name == "source") {
2474 $item["app"] = strip_tags($attributes->textContent);
2479 $item["guid"] = XML::getFirstNodeValue($xpath, "dfrn:diaspora_guid/text()", $entry);
2481 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
2482 $dsprsig = unxmlify(XML::getFirstNodeValue($xpath, "dfrn:diaspora_signature/text()", $entry));
2483 if ($dsprsig != "") {
2484 $item["dsprsig"] = $dsprsig;
2487 $item["verb"] = XML::getFirstNodeValue($xpath, "activity:verb/text()", $entry);
2489 if (XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry) != "") {
2490 $item["object-type"] = XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry);
2493 $object = $xpath->query("activity:object", $entry)->item(0);
2494 $item["object"] = self::transformActivity($xpath, $object, "object");
2496 if (trim($item["object"]) != "") {
2497 $r = XML::parseString($item["object"], false);
2498 if (isset($r->type)) {
2499 $item["object-type"] = $r->type;
2503 $target = $xpath->query("activity:target", $entry)->item(0);
2504 $item["target"] = self::transformActivity($xpath, $target, "target");
2506 $categories = $xpath->query("atom:category", $entry);
2508 foreach ($categories as $category) {
2511 foreach ($category->attributes as $attributes) {
2512 if ($attributes->name == "term") {
2513 $term = $attributes->textContent;
2516 if ($attributes->name == "scheme") {
2517 $scheme = $attributes->textContent;
2521 if (($term != "") && ($scheme != "")) {
2522 $parts = explode(":", $scheme);
2523 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2524 $termhash = array_shift($parts);
2525 $termurl = implode(":", $parts);
2527 if (!empty($item["tag"])) {
2528 $item["tag"] .= ",";
2533 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2541 $links = $xpath->query("atom:link", $entry);
2543 self::parseLinks($links, $item);
2546 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
2548 $conv = $xpath->query('ostatus:conversation', $entry);
2549 if (is_object($conv->item(0))) {
2550 foreach ($conv->item(0)->attributes as $attributes) {
2551 if ($attributes->name == "ref") {
2552 $item['conversation-uri'] = $attributes->textContent;
2554 if ($attributes->name == "href") {
2555 $item['conversation-href'] = $attributes->textContent;
2560 // Is it a reply or a top level posting?
2561 $item["parent-uri"] = $item["uri"];
2563 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2564 if (is_object($inreplyto->item(0))) {
2565 foreach ($inreplyto->item(0)->attributes as $attributes) {
2566 if ($attributes->name == "ref") {
2567 $item["parent-uri"] = $attributes->textContent;
2572 // Get the type of the item (Top level post, reply or remote reply)
2573 $entrytype = self::getEntryType($importer, $item);
2575 // Now assign the rest of the values that depend on the type of the message
2576 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2577 if (!isset($item["object-type"])) {
2578 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2581 if ($item["contact-id"] != $owner["contact-id"]) {
2582 $item["contact-id"] = $owner["contact-id"];
2585 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2586 $item["network"] = $owner["network"];
2589 if ($item["contact-id"] != $author["contact-id"]) {
2590 $item["contact-id"] = $author["contact-id"];
2593 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2594 $item["network"] = $author["network"];
2598 if ($entrytype == DFRN::REPLY_RC) {
2600 } elseif ($entrytype == DFRN::TOP_LEVEL) {
2601 if (!isset($item["object-type"])) {
2602 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2606 if (($item["object-type"] == ACTIVITY_OBJ_EVENT) && !$owner_unknown) {
2607 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2608 $ev = Event::fromBBCode($item["body"]);
2609 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2610 logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2611 $ev["cid"] = $importer["id"];
2612 $ev["uid"] = $importer["importer_uid"];
2613 $ev["uri"] = $item["uri"];
2614 $ev["edited"] = $item["edited"];
2615 $ev["private"] = $item["private"];
2616 $ev["guid"] = $item["guid"];
2617 $ev["plink"] = $item["plink"];
2619 $condition = ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]];
2620 $event = DBA::selectFirst('event', ['id'], $condition);
2621 if (DBA::isResult($event)) {
2622 $ev["id"] = $event["id"];
2625 $event_id = Event::store($ev);
2626 logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2632 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2633 logger("Exiting because 'processVerbs' told us so", LOGGER_DEBUG);
2637 // This check is done here to be able to receive connection requests in "processVerbs"
2638 if (($entrytype == DFRN::TOP_LEVEL) && $owner_unknown) {
2639 logger("Item won't be stored because user " . $importer["importer_uid"] . " doesn't follow " . $item["owner-link"] . ".", LOGGER_DEBUG);
2644 // Update content if 'updated' changes
2645 if (DBA::isResult($current)) {
2646 if (self::updateContent($current, $item, $importer, $entrytype)) {
2647 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2649 logger("Item " . $item["uri"] . " already existed.", LOGGER_DEBUG);
2654 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2655 $posted_id = Item::insert($item);
2659 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2661 if ($item['uid'] == 0) {
2662 Item::distribute($posted_id);
2667 } else { // $entrytype == DFRN::TOP_LEVEL
2668 if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
2669 logger("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", LOGGER_DEBUG);
2672 if (!link_compare($item["owner-link"], $importer["url"])) {
2674 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2675 * but otherwise there's a possible data mixup on the sender's system.
2676 * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2677 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2679 logger('Correcting item owner.', LOGGER_DEBUG);
2680 $item["owner-link"] = $importer["url"];
2681 $item["owner-id"] = Contact::getIdForURL($importer["url"], 0);
2684 if (($importer["rel"] == Contact::FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2685 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2689 // This is my contact on another system, but it's really me.
2690 // Turn this into a wall post.
2691 $notify = Item::isRemoteSelf($importer, $item);
2693 $posted_id = Item::insert($item, false, $notify);
2696 $posted_id = $notify;
2699 logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2701 if ($item['uid'] == 0) {
2702 Item::distribute($posted_id);
2705 if (stristr($item["verb"], ACTIVITY_POKE)) {
2706 self::doPoke($item, $importer, $posted_id);
2712 * @brief Deletes items
2714 * @param object $xpath XPath object
2715 * @param object $deletion deletion elements
2716 * @param array $importer Record of the importer user mixed with contact of the content
2718 * @todo set proper type-hints
2720 private static function processDeletion($xpath, $deletion, $importer)
2722 logger("Processing deletions");
2725 foreach ($deletion->attributes as $attributes) {
2726 if ($attributes->name == "ref") {
2727 $uri = $attributes->textContent;
2731 if (!$uri || !$importer["id"]) {
2735 $condition = ['uri' => $uri, 'uid' => $importer["importer_uid"]];
2736 $item = Item::selectFirst(['id', 'parent', 'contact-id', 'file', 'deleted'], $condition);
2737 if (!DBA::isResult($item)) {
2738 logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", LOGGER_DEBUG);
2742 if (strstr($item['file'], '[')) {
2743 logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " is filed. So it won't be deleted.", LOGGER_DEBUG);
2747 // When it is a starting post it has to belong to the person that wants to delete it
2748 if (($item['id'] == $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2749 logger("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2753 // Comments can be deleted by the thread owner or comment owner
2754 if (($item['id'] != $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2755 $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2756 if (!Item::exists($condition)) {
2757 logger("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2762 if ($item["deleted"]) {
2766 logger('deleting item '.$item['id'].' uri='.$uri, LOGGER_DEBUG);
2768 Item::delete(['id' => $item['id']]);
2772 * @brief Imports a DFRN message
2774 * @param string $xml The DFRN message
2775 * @param array $importer Record of the importer user mixed with contact of the content
2776 * @param bool $sort_by_date Is used when feeds are polled
2777 * @return integer Import status
2778 * @todo set proper type-hints
2780 public static function import($xml, $importer, $sort_by_date = false)
2786 $doc = new DOMDocument();
2787 @$doc->loadXML($xml);
2789 $xpath = new DOMXPath($doc);
2790 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2791 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2792 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2793 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2794 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2795 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2796 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2797 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2798 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2799 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2802 $header["uid"] = $importer["importer_uid"];
2803 $header["network"] = Protocol::DFRN;
2804 $header["wall"] = 0;
2805 $header["origin"] = 0;
2806 $header["contact-id"] = $importer["id"];
2808 // Update the contact table if the data has changed
2810 // The "atom:author" is only present in feeds
2811 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2812 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2815 // Only the "dfrn:owner" in the head section contains all data
2816 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2817 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2820 logger("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2822 // is it a public forum? Private forums aren't exposed with this method
2823 $forum = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:community/text()"));
2825 // The account type is new since 3.5.1
2826 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2827 $accounttype = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:account_type/text()"));
2829 if ($accounttype != $importer["contact-type"]) {
2830 DBA::update('contact', ['contact-type' => $accounttype], ['id' => $importer["id"]]);
2832 // A forum contact can either have set "forum" or "prv" - but not both
2833 if (($accounttype == Contact::ACCOUNT_TYPE_COMMUNITY) && (($forum != $importer["forum"]) || ($forum == $importer["prv"]))) {
2834 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer["id"]];
2835 DBA::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2837 } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
2838 $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2839 DBA::update('contact', ['forum' => $forum], $condition);
2843 // We are processing relocations even if we are ignoring a contact
2844 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2845 foreach ($relocations as $relocation) {
2846 self::processRelocation($xpath, $relocation, $importer);
2849 if (($importer["uid"] != 0) && !$importer["readonly"]) {
2850 $mails = $xpath->query("/atom:feed/dfrn:mail");
2851 foreach ($mails as $mail) {
2852 self::processMail($xpath, $mail, $importer);
2855 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2856 foreach ($suggestions as $suggestion) {
2857 self::processSuggestion($xpath, $suggestion, $importer);
2861 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2862 foreach ($deletions as $deletion) {
2863 self::processDeletion($xpath, $deletion, $importer);
2866 if (!$sort_by_date) {
2867 $entries = $xpath->query("/atom:feed/atom:entry");
2868 foreach ($entries as $entry) {
2869 self::processEntry($header, $xpath, $entry, $importer, $xml);
2873 $entries = $xpath->query("/atom:feed/atom:entry");
2874 foreach ($entries as $entry) {
2875 $created = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2876 $newentries[strtotime($created)] = $entry;
2879 // Now sort after the publishing date
2882 foreach ($newentries as $entry) {
2883 self::processEntry($header, $xpath, $entry, $importer, $xml);
2886 logger("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2892 * @param string $contact_nick contact nickname
2894 public static function autoRedir(App $a, $contact_nick)
2897 if (x($_REQUEST, 'redir') && intval($_REQUEST['redir'])) {
2901 if ((! $contact_nick) || ($contact_nick === $a->user['nickname'])) {
2906 // We need to find out if $contact_nick is a user on this hub, and if so, if I
2907 // am a contact of that user. However, that user may have other contacts with the
2908 // same nickname as me on other hubs or other networks. Exclude these by requiring
2909 // that the contact have a local URL. I will be the only person with my nickname at
2910 // this URL, so if a result is found, then I am a contact of the $contact_nick user.
2912 // We also have to make sure that I'm a legitimate contact--I'm not blocked or pending.
2914 $baseurl = System::baseUrl();
2915 $domain_st = strpos($baseurl, "://");
2916 if ($domain_st === false) {
2919 $baseurl = substr($baseurl, $domain_st + 3);
2920 $nurl = normalise_link($baseurl);
2922 /// @todo Why is there a query for "url" *and* "nurl"? Especially this normalising is strange.
2923 $r = q("SELECT `id` FROM `contact` WHERE `uid` = (SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1)
2924 AND `nick` = '%s' AND NOT `self` AND (`url` LIKE '%%%s%%' OR `nurl` LIKE '%%%s%%') AND NOT `blocked` AND NOT `pending` LIMIT 1",
2925 DBA::escape($contact_nick),
2926 DBA::escape($a->user['nickname']),
2927 DBA::escape($baseurl),
2930 if ((! DBA::isResult($r)) || $r[0]['id'] == remote_user()) {
2934 $r = q("SELECT * FROM contact WHERE nick = '%s'
2935 AND network = '%s' AND uid = %d AND url LIKE '%%%s%%' LIMIT 1",
2936 DBA::escape($contact_nick),
2937 DBA::escape(Protocol::DFRN),
2938 intval(local_user()),
2939 DBA::escape($baseurl)
2941 if (! DBA::isResult($r)) {
2947 $dfrn_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2949 if ($r[0]['duplex'] && $r[0]['issued-id']) {
2950 $orig_id = $r[0]['issued-id'];
2951 $dfrn_id = '1:' . $orig_id;
2953 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
2954 $orig_id = $r[0]['dfrn-id'];
2955 $dfrn_id = '0:' . $orig_id;
2958 // ensure that we've got a valid ID. There may be some edge cases with forums and non-duplex mode
2959 // that may have triggered some of the "went to {profile/intro} and got an RSS feed" issues
2961 if (strlen($dfrn_id) < 3) {
2965 $sec = random_string();
2967 DBA::insert('profile_check', ['uid' => local_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id, 'sec' => $sec, 'expire' => time() + 45]);
2969 $url = curPageURL();
2971 logger('auto_redir: ' . $r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
2972 $dest = (($url) ? '&destination_url=' . $url : '');
2973 goaway($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
2974 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest);
2981 * @brief Returns the activity verb
2983 * @param array $item Item array
2985 * @return string activity verb
2987 private static function constructVerb(array $item)
2989 if ($item['verb']) {
2990 return $item['verb'];
2992 return ACTIVITY_POST;
2995 private static function tgroupCheck($uid, $item)
2999 // check that the message originated elsewhere and is a top-level post
3001 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['parent-uri'])) {
3005 $user = DBA::selectFirst('user', ['page-flags', 'nickname'], ['uid' => $uid]);
3006 if (!DBA::isResult($user)) {
3010 $community_page = ($user['page-flags'] == Contact::PAGE_COMMUNITY);
3011 $prvgroup = ($user['page-flags'] == Contact::PAGE_PRVGROUP);
3013 $link = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
3016 * Diaspora uses their own hardwired link URL in @-tags
3017 * instead of the one we supply with webfinger
3019 $dlink = normalise_link(System::baseUrl() . '/u/' . $user['nickname']);
3021 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
3023 foreach ($matches as $mtch) {
3024 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
3026 logger('mention found: ' . $mtch[2]);
3035 return $community_page || $prvgroup;
3039 * This function returns true if $update has an edited timestamp newer
3040 * than $existing, i.e. $update contains new data which should override
3041 * what's already there. If there is no timestamp yet, the update is
3042 * assumed to be newer. If the update has no timestamp, the existing
3043 * item is assumed to be up-to-date. If the timestamps are equal it
3044 * assumes the update has been seen before and should be ignored.
3047 private static function isEditedTimestampNewer($existing, $update)
3049 if (!x($existing, 'edited') || !$existing['edited']) {
3052 if (!x($update, 'edited') || !$update['edited']) {
3056 $existing_edited = DateTimeFormat::utc($existing['edited']);
3057 $update_edited = DateTimeFormat::utc($update['edited']);
3059 return (strcmp($existing_edited, $update_edited) < 0);