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 an array of contact and user for DFRN imports
58 * This array contains not only the receiver but also the sender of the message.
60 * @param integer $cid Contact id
61 * @param integer $uid User id
63 * @return array importer
65 public static function getImporter($cid, $uid = 0)
67 $condition = ['id' => $cid, 'blocked' => false, 'pending' => false];
68 $contact = DBA::selectFirst('contact', [], $condition);
69 if (!DBA::isResult($contact)) {
73 $contact['cpubkey'] = $contact['pubkey'];
74 $contact['cprvkey'] = $contact['prvkey'];
75 $contact['senderName'] = $contact['name'];
78 $condition = ['uid' => $uid, 'account_expired' => false, 'account_removed' => false];
79 $user = DBA::selectFirst('user', [], $condition);
80 if (!DBA::isResult($user)) {
84 $user['importer_uid'] = $user['uid'];
86 $user = ['importer_uid' => 0, 'uprvkey' => '', 'timezone' => 'UTC',
87 'nickname' => '', 'sprvkey' => '', 'spubkey' => '',
88 'page-flags' => 0, 'account-type' => 0, 'prvnets' => 0];
91 return array_merge($contact, $user);
95 * @brief Generates the atom entries for delivery.php
97 * This function is used whenever content is transmitted via DFRN.
99 * @param array $items Item elements
100 * @param array $owner Owner record
102 * @return string DFRN entries
103 * @todo Find proper type-hints
105 public static function entries($items, $owner)
107 $doc = new DOMDocument('1.0', 'utf-8');
108 $doc->formatOutput = true;
110 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
112 if (! count($items)) {
113 return trim($doc->saveXML());
116 foreach ($items as $item) {
117 // These values aren't sent when sending from the queue.
118 /// @todo Check if we can set these values from the queue or if they are needed at all.
119 $item["entry:comment-allow"] = defaults($item, "entry:comment-allow", true);
120 $item["entry:cid"] = defaults($item, "entry:cid", 0);
122 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
123 $root->appendChild($entry);
126 return trim($doc->saveXML());
130 * @brief Generate an atom feed for the given user
132 * This function is called when another server is pulling data from the user feed.
134 * @param string $dfrn_id DFRN ID from the requesting party
135 * @param string $owner_nick Owner nick name
136 * @param string $last_update Date of the last update
137 * @param int $direction Can be -1, 0 or 1.
138 * @param boolean $onlyheader Output only the header without content? (Default is "no")
140 * @return string DFRN feed entries
142 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false)
146 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
147 $public_feed = (($dfrn_id) ? false : true);
148 $starred = false; // not yet implemented, possible security issues
151 if ($public_feed && $a->argc > 2) {
152 for ($x = 2; $x < $a->argc; $x++) {
153 if ($a->argv[$x] == 'converse') {
156 if ($a->argv[$x] == 'starred') {
159 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
160 $category = $a->argv[$x+1];
165 // default permissions - anonymous user
167 $sql_extra = " AND NOT `item`.`private` ";
170 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
171 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
172 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
173 DBA::escape($owner_nick)
176 if (! DBA::isResult($r)) {
177 logger(sprintf('No contact found for nickname=%d', $owner_nick), LOGGER_WARNING);
182 $owner_id = $owner['uid'];
183 $owner_nick = $owner['nickname'];
185 $sql_post_table = "";
187 if (! $public_feed) {
189 switch ($direction) {
191 $sql_extra = sprintf(" AND `issued-id` = '%s' ", DBA::escape($dfrn_id));
195 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
196 $my_id = '1:' . $dfrn_id;
199 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
200 $my_id = '0:' . $dfrn_id;
208 "SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
212 if (! DBA::isResult($r)) {
213 logger(sprintf('No contact found for uid=%d', $owner_id), LOGGER_WARNING);
218 include_once 'include/security.php';
220 $set = PermissionSet::get($owner_id, $contact['id']);
223 $sql_extra = " AND `item`.`psid` IN (" . implode(',', $set) .")";
225 $sql_extra = " AND NOT `item`.`private`";
235 if (! strlen($last_update)) {
236 $last_update = 'now -30 days';
239 if (isset($category)) {
240 $sql_post_table = sprintf(
241 "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` ",
242 DBA::escape(protect_sprintf($category)),
243 intval(TERM_OBJ_POST),
244 intval(TERM_CATEGORY),
247 //$sql_extra .= file_tag_file_query('item',$category,'category');
250 if ($public_feed && ! $converse) {
251 $sql_extra .= " AND `contact`.`self` = 1 ";
254 $check_date = DateTimeFormat::utc($last_update);
258 FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
259 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
260 WHERE `item`.`uid` = %d AND `item`.`wall` AND `item`.`changed` > '%s'
262 ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
264 DBA::escape($check_date),
269 foreach ($r as $item) {
270 $ids[] = $item['id'];
274 $ret = Item::select(Item::DELIVER_FIELDLIST, ['id' => $ids]);
275 $items = Item::inArray($ret);
281 * Will check further below if this actually returned results.
282 * We will provide an empty feed if that is the case.
285 $doc = new DOMDocument('1.0', 'utf-8');
286 $doc->formatOutput = true;
288 $alternatelink = $owner['url'];
290 if (isset($category)) {
291 $alternatelink .= "/category/".$category;
295 $author = "dfrn:owner";
300 $root = self::addHeader($doc, $owner, $author, $alternatelink, true);
302 /// @TODO This hook can't work anymore
303 // Addon::callHooks('atom_feed', $atom);
305 if (!DBA::isResult($items) || $onlyheader) {
306 $atom = trim($doc->saveXML());
308 Addon::callHooks('atom_feed_end', $atom);
313 foreach ($items as $item) {
314 // prevent private email from leaking.
315 if ($item['network'] == Protocol::MAIL) {
319 // public feeds get html, our own nodes use bbcode
323 // catch any email that's in a public conversation and make sure it doesn't leak
324 if ($item['private']) {
331 $entry = self::entry($doc, $type, $item, $owner, true);
332 $root->appendChild($entry);
335 $atom = trim($doc->saveXML());
337 Addon::callHooks('atom_feed_end', $atom);
343 * @brief Generate an atom entry for a given item id
345 * @param int $item_id The item id
346 * @param boolean $conversation Show the conversation. If false show the single post.
348 * @return string DFRN feed entry
350 public static function itemFeed($item_id, $conversation = false)
353 $condition = ['parent' => $item_id];
355 $condition = ['id' => $item_id];
358 $ret = Item::select(Item::DELIVER_FIELDLIST, $condition);
359 $items = Item::inArray($ret);
360 if (!DBA::isResult($items)) {
366 if ($item['uid'] != 0) {
367 $owner = User::getOwnerDataById($item['uid']);
372 $owner = ['uid' => 0, 'nick' => 'feed-item'];
375 $doc = new DOMDocument('1.0', 'utf-8');
376 $doc->formatOutput = true;
380 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
381 $doc->appendChild($root);
383 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
384 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
385 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
386 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
387 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
388 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
389 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
390 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
391 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
393 //$root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
395 foreach ($items as $item) {
396 $entry = self::entry($doc, $type, $item, $owner, true, 0);
397 $root->appendChild($entry);
400 $root = self::entry($doc, $type, $item, $owner, true, 0, true);
403 $atom = trim($doc->saveXML());
408 * @brief Create XML text for DFRN mails
410 * @param array $item message elements
411 * @param array $owner Owner record
413 * @return string DFRN mail
414 * @todo Find proper type-hints
416 public static function mail($item, $owner)
418 $doc = new DOMDocument('1.0', 'utf-8');
419 $doc->formatOutput = true;
421 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
423 $mail = $doc->createElement("dfrn:mail");
424 $sender = $doc->createElement("dfrn:sender");
426 XML::addElement($doc, $sender, "dfrn:name", $owner['name']);
427 XML::addElement($doc, $sender, "dfrn:uri", $owner['url']);
428 XML::addElement($doc, $sender, "dfrn:avatar", $owner['thumb']);
430 $mail->appendChild($sender);
432 XML::addElement($doc, $mail, "dfrn:id", $item['uri']);
433 XML::addElement($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
434 XML::addElement($doc, $mail, "dfrn:sentdate", DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
435 XML::addElement($doc, $mail, "dfrn:subject", $item['title']);
436 XML::addElement($doc, $mail, "dfrn:content", $item['body']);
438 $root->appendChild($mail);
440 return trim($doc->saveXML());
444 * @brief Create XML text for DFRN friend suggestions
446 * @param array $item suggestion elements
447 * @param array $owner Owner record
449 * @return string DFRN suggestions
450 * @todo Find proper type-hints
452 public static function fsuggest($item, $owner)
454 $doc = new DOMDocument('1.0', 'utf-8');
455 $doc->formatOutput = true;
457 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
459 $suggest = $doc->createElement("dfrn:suggest");
461 XML::addElement($doc, $suggest, "dfrn:url", $item['url']);
462 XML::addElement($doc, $suggest, "dfrn:name", $item['name']);
463 XML::addElement($doc, $suggest, "dfrn:photo", $item['photo']);
464 XML::addElement($doc, $suggest, "dfrn:request", $item['request']);
465 XML::addElement($doc, $suggest, "dfrn:note", $item['note']);
467 $root->appendChild($suggest);
469 return trim($doc->saveXML());
473 * @brief Create XML text for DFRN relocations
475 * @param array $owner Owner record
476 * @param int $uid User ID
478 * @return string DFRN relocations
479 * @todo Find proper type-hints
481 public static function relocate($owner, $uid)
484 /* get site pubkey. this could be a new installation with no site keys*/
485 $pubkey = Config::get('system', 'site_pubkey');
487 $res = Crypto::newKeypair(1024);
488 Config::set('system', 'site_prvkey', $res['prvkey']);
489 Config::set('system', 'site_pubkey', $res['pubkey']);
493 "SELECT `resource-id` , `scale`, type FROM `photo`
494 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;",
498 $ext = Image::supportedTypes();
500 foreach ($rp as $p) {
501 $photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
505 $doc = new DOMDocument('1.0', 'utf-8');
506 $doc->formatOutput = true;
508 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
510 $relocate = $doc->createElement("dfrn:relocate");
512 XML::addElement($doc, $relocate, "dfrn:url", $owner['url']);
513 XML::addElement($doc, $relocate, "dfrn:name", $owner['name']);
514 XML::addElement($doc, $relocate, "dfrn:addr", $owner['addr']);
515 XML::addElement($doc, $relocate, "dfrn:avatar", $owner['avatar']);
516 XML::addElement($doc, $relocate, "dfrn:photo", $photos[4]);
517 XML::addElement($doc, $relocate, "dfrn:thumb", $photos[5]);
518 XML::addElement($doc, $relocate, "dfrn:micro", $photos[6]);
519 XML::addElement($doc, $relocate, "dfrn:request", $owner['request']);
520 XML::addElement($doc, $relocate, "dfrn:confirm", $owner['confirm']);
521 XML::addElement($doc, $relocate, "dfrn:notify", $owner['notify']);
522 XML::addElement($doc, $relocate, "dfrn:poll", $owner['poll']);
523 XML::addElement($doc, $relocate, "dfrn:sitepubkey", Config::get('system', 'site_pubkey'));
525 $root->appendChild($relocate);
527 return trim($doc->saveXML());
531 * @brief Adds the header elements for the DFRN protocol
533 * @param object $doc XML document
534 * @param array $owner Owner record
535 * @param string $authorelement Element name for the author
536 * @param string $alternatelink link to profile or category
537 * @param bool $public Is it a header for public posts?
539 * @return object XML root object
540 * @todo Find proper type-hints
542 private static function addHeader($doc, $owner, $authorelement, $alternatelink = "", $public = false)
545 if ($alternatelink == "") {
546 $alternatelink = $owner['url'];
549 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
550 $doc->appendChild($root);
552 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
553 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
554 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
555 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
556 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
557 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
558 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
559 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
560 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
562 XML::addElement($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
563 XML::addElement($doc, $root, "title", $owner["name"]);
565 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION];
566 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
568 $attributes = ["rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/"];
569 XML::addElement($doc, $root, "link", "", $attributes);
571 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $alternatelink];
572 XML::addElement($doc, $root, "link", "", $attributes);
576 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
577 OStatus::hublinks($doc, $root, $owner["nick"]);
579 $attributes = ["rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
580 XML::addElement($doc, $root, "link", "", $attributes);
582 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
583 XML::addElement($doc, $root, "link", "", $attributes);
585 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
586 XML::addElement($doc, $root, "link", "", $attributes);
589 // For backward compatibility we keep this element
590 if ($owner['page-flags'] == Contact::PAGE_COMMUNITY) {
591 XML::addElement($doc, $root, "dfrn:community", 1);
594 // The former element is replaced by this one
595 XML::addElement($doc, $root, "dfrn:account_type", $owner["account-type"]);
597 /// @todo We need a way to transmit the different page flags like "Contact::PAGE_PRVGROUP"
599 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
601 $author = self::addAuthor($doc, $owner, $authorelement, $public);
602 $root->appendChild($author);
608 * @brief Adds the author element in the header for the DFRN protocol
610 * @param object $doc XML document
611 * @param array $owner Owner record
612 * @param string $authorelement Element name for the author
613 * @param boolean $public boolean
615 * @return object XML author object
616 * @todo Find proper type-hints
618 private static function addAuthor($doc, $owner, $authorelement, $public)
620 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
622 "SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
623 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
624 intval($owner['uid'])
626 if (DBA::isResult($r)) {
632 $author = $doc->createElement($authorelement);
634 $namdate = DateTimeFormat::utc($owner['name-date'].'+00:00', DateTimeFormat::ATOM);
635 $uridate = DateTimeFormat::utc($owner['uri-date'].'+00:00', DateTimeFormat::ATOM);
636 $picdate = DateTimeFormat::utc($owner['avatar-date'].'+00:00', DateTimeFormat::ATOM);
640 if (!$public || !$hidewall) {
641 $attributes = ["dfrn:updated" => $namdate];
644 XML::addElement($doc, $author, "name", $owner["name"], $attributes);
645 XML::addElement($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
646 XML::addElement($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
648 $attributes = ["rel" => "photo", "type" => "image/jpeg",
649 "media:width" => 175, "media:height" => 175, "href" => $owner['photo']];
651 if (!$public || !$hidewall) {
652 $attributes["dfrn:updated"] = $picdate;
655 XML::addElement($doc, $author, "link", "", $attributes);
657 $attributes["rel"] = "avatar";
658 XML::addElement($doc, $author, "link", "", $attributes);
661 XML::addElement($doc, $author, "dfrn:hide", "true");
664 // The following fields will only be generated if the data isn't meant for a public feed
669 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
672 XML::addElement($doc, $author, "dfrn:birthday", $birthday);
675 // Only show contact details when we are allowed to
677 "SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
678 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
679 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
681 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
682 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
683 intval($owner['uid'])
685 if (DBA::isResult($r)) {
688 XML::addElement($doc, $author, "poco:displayName", $profile["name"]);
689 XML::addElement($doc, $author, "poco:updated", $namdate);
691 if (trim($profile["dob"]) > '0001-01-01') {
692 XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
695 XML::addElement($doc, $author, "poco:note", $profile["about"]);
696 XML::addElement($doc, $author, "poco:preferredUsername", $profile["nickname"]);
698 $savetz = date_default_timezone_get();
699 date_default_timezone_set($profile["timezone"]);
700 XML::addElement($doc, $author, "poco:utcOffset", date("P"));
701 date_default_timezone_set($savetz);
703 if (trim($profile["homepage"]) != "") {
704 $urls = $doc->createElement("poco:urls");
705 XML::addElement($doc, $urls, "poco:type", "homepage");
706 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
707 XML::addElement($doc, $urls, "poco:primary", "true");
708 $author->appendChild($urls);
711 if (trim($profile["pub_keywords"]) != "") {
712 $keywords = explode(",", $profile["pub_keywords"]);
714 foreach ($keywords as $keyword) {
715 XML::addElement($doc, $author, "poco:tags", trim($keyword));
719 if (trim($profile["xmpp"]) != "") {
720 $ims = $doc->createElement("poco:ims");
721 XML::addElement($doc, $ims, "poco:type", "xmpp");
722 XML::addElement($doc, $ims, "poco:value", $profile["xmpp"]);
723 XML::addElement($doc, $ims, "poco:primary", "true");
724 $author->appendChild($ims);
727 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
728 $element = $doc->createElement("poco:address");
730 XML::addElement($doc, $element, "poco:formatted", Profile::formatLocation($profile));
732 if (trim($profile["locality"]) != "") {
733 XML::addElement($doc, $element, "poco:locality", $profile["locality"]);
736 if (trim($profile["region"]) != "") {
737 XML::addElement($doc, $element, "poco:region", $profile["region"]);
740 if (trim($profile["country-name"]) != "") {
741 XML::addElement($doc, $element, "poco:country", $profile["country-name"]);
744 $author->appendChild($element);
752 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
754 * @param object $doc XML document
755 * @param string $element Element name for the author
756 * @param string $contact_url Link of the contact
757 * @param array $item Item elements
759 * @return object XML author object
760 * @todo Find proper type-hints
762 private static function addEntryAuthor($doc, $element, $contact_url, $item)
764 $contact = Contact::getDetailsByURL($contact_url, $item["uid"]);
766 $author = $doc->createElement($element);
767 XML::addElement($doc, $author, "name", $contact["name"]);
768 XML::addElement($doc, $author, "uri", $contact["url"]);
769 XML::addElement($doc, $author, "dfrn:handle", $contact["addr"]);
772 /// - Check real image type and image size
773 /// - Check which of these boths elements we should use
776 "type" => "image/jpeg",
778 "media:height" => 80,
779 "href" => $contact["photo"]];
780 XML::addElement($doc, $author, "link", "", $attributes);
784 "type" => "image/jpeg",
786 "media:height" => 80,
787 "href" => $contact["photo"]];
788 XML::addElement($doc, $author, "link", "", $attributes);
794 * @brief Adds the activity elements
796 * @param object $doc XML document
797 * @param string $element Element name for the activity
798 * @param string $activity activity value
800 * @return object XML activity object
801 * @todo Find proper type-hints
803 private static function createActivity($doc, $element, $activity)
806 $entry = $doc->createElement($element);
808 $r = XML::parseString($activity, false);
814 XML::addElement($doc, $entry, "activity:object-type", $r->type);
818 XML::addElement($doc, $entry, "id", $r->id);
822 XML::addElement($doc, $entry, "title", $r->title);
826 if (substr($r->link, 0, 1) == '<') {
827 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
828 $r->link = str_replace('&', '&', $r->link);
831 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
833 // XML does need a single element as root element so we add a dummy element here
834 $data = XML::parseString("<dummy>" . $r->link . "</dummy>", false);
835 if (is_object($data)) {
836 foreach ($data->link as $link) {
838 foreach ($link->attributes() as $parameter => $value) {
839 $attributes[$parameter] = $value;
841 XML::addElement($doc, $entry, "link", "", $attributes);
845 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
846 XML::addElement($doc, $entry, "link", "", $attributes);
850 XML::addElement($doc, $entry, "content", BBCode::convert($r->content), ["type" => "html"]);
860 * @brief Adds the elements for attachments
862 * @param object $doc XML document
863 * @param object $root XML root
864 * @param array $item Item element
866 * @return object XML attachment object
867 * @todo Find proper type-hints
869 private static function getAttachment($doc, $root, $item)
871 $arr = explode('[/attach],', $item['attach']);
873 foreach ($arr as $r) {
875 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
877 $attributes = ["rel" => "enclosure",
878 "href" => $matches[1],
879 "type" => $matches[3]];
881 if (intval($matches[2])) {
882 $attributes["length"] = intval($matches[2]);
885 if (trim($matches[4]) != "") {
886 $attributes["title"] = trim($matches[4]);
889 XML::addElement($doc, $root, "link", "", $attributes);
896 * @brief Adds the "entry" elements for the DFRN protocol
898 * @param object $doc XML document
899 * @param string $type "text" or "html"
900 * @param array $item Item element
901 * @param array $owner Owner record
902 * @param bool $comment Trigger the sending of the "comment" element
903 * @param int $cid Contact ID of the recipient
904 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
906 * @return object XML entry object
907 * @todo Find proper type-hints
909 private static function entry($doc, $type, array $item, array $owner, $comment = false, $cid = 0, $single = false)
913 if (!$item['parent']) {
917 if ($item['deleted']) {
918 $attributes = ["ref" => $item['uri'], "when" => DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM)];
919 return XML::createElement($doc, "at:deleted-entry", "", $attributes);
923 $entry = $doc->createElement("entry");
925 $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry');
926 $doc->appendChild($entry);
928 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
929 $entry->setAttribute("xmlns:at", NAMESPACE_TOMB);
930 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
931 $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
932 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
933 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
934 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
935 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
936 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
939 if ($item['private']) {
940 $body = Item::fixPrivatePhotos($item['body'], $owner['uid'], $item, $cid);
942 $body = $item['body'];
945 // Remove the abstract element. It is only locally important.
946 $body = BBCode::stripAbstract($body);
949 if ($type == 'html') {
952 if ($item['title'] != "") {
953 $htmlbody = "[b]" . $item['title'] . "[/b]\n\n" . $htmlbody;
956 $htmlbody = BBCode::convert($htmlbody, false, 7);
959 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
960 $entry->appendChild($author);
962 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
963 $entry->appendChild($dfrnowner);
965 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
966 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
967 $parent = Item::selectFirst(['guid', 'plink'], ['uri' => $parent_item, 'uid' => $item['uid']]);
968 $attributes = ["ref" => $parent_item, "type" => "text/html",
969 "href" => $parent['plink'],
970 "dfrn:diaspora_guid" => $parent['guid']];
971 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
974 // Add conversation data. This is used for OStatus
975 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
976 $conversation_uri = $conversation_href;
978 if (isset($parent_item)) {
979 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $item['parent-uri']]);
980 if (DBA::isResult($conversation)) {
981 if ($conversation['conversation-uri'] != '') {
982 $conversation_uri = $conversation['conversation-uri'];
984 if ($conversation['conversation-href'] != '') {
985 $conversation_href = $conversation['conversation-href'];
991 "href" => $conversation_href,
992 "ref" => $conversation_uri];
994 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
996 XML::addElement($doc, $entry, "id", $item["uri"]);
997 XML::addElement($doc, $entry, "title", $item["title"]);
999 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"] . "+00:00", DateTimeFormat::ATOM));
1000 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"] . "+00:00", DateTimeFormat::ATOM));
1002 // "dfrn:env" is used to read the content
1003 XML::addElement($doc, $entry, "dfrn:env", base64url_encode($body, true));
1005 // The "content" field is not read by the receiver. We could remove it when the type is "text"
1006 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
1007 XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
1009 // We save this value in "plink". Maybe we should read it from there as well?
1015 ["rel" => "alternate", "type" => "text/html",
1016 "href" => System::baseUrl() . "/display/" . $item["guid"]]
1019 // "comment-allow" is some old fashioned stuff for old Friendica versions.
1020 // It is included in the rewritten code for completeness
1022 XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
1025 if ($item['location']) {
1026 XML::addElement($doc, $entry, "dfrn:location", $item['location']);
1029 if ($item['coord']) {
1030 XML::addElement($doc, $entry, "georss:point", $item['coord']);
1033 if ($item['private']) {
1034 XML::addElement($doc, $entry, "dfrn:private", ($item['private'] ? $item['private'] : 1));
1037 if ($item['extid']) {
1038 XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
1041 if ($item['post-type'] == Item::PT_PAGE) {
1042 XML::addElement($doc, $entry, "dfrn:bookmark", "true");
1046 XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
1049 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
1051 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
1052 // It is needed for relayed comments to Diaspora.
1053 if ($item['signed_text']) {
1054 $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer']]));
1055 XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
1058 XML::addElement($doc, $entry, "activity:verb", self::constructVerb($item));
1060 if ($item['object-type'] != "") {
1061 XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
1062 } elseif ($item['id'] == $item['parent']) {
1063 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1065 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
1068 $actobj = self::createActivity($doc, "activity:object", $item['object']);
1070 $entry->appendChild($actobj);
1073 $actarg = self::createActivity($doc, "activity:target", $item['target']);
1075 $entry->appendChild($actarg);
1078 $tags = Item::getFeedTags($item);
1080 /// @TODO Combine this with similar below if() block?
1082 foreach ($tags as $t) {
1083 if (($type != 'html') || ($t[0] != "@")) {
1084 XML::addElement($doc, $entry, "category", "", ["scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]]);
1090 foreach ($tags as $t) {
1092 $mentioned[$t[1]] = $t[1];
1097 foreach ($mentioned as $mention) {
1098 $condition = ['uid' => $owner["uid"], 'nurl' => normalise_link($mention)];
1099 $contact = DBA::selectFirst('contact', ['forum', 'prv'], $condition);
1101 if (DBA::isResult($contact) && ($contact["forum"] || $contact["prv"])) {
1107 ["rel" => "mentioned",
1108 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1117 ["rel" => "mentioned",
1118 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1124 self::getAttachment($doc, $entry, $item);
1130 * @brief encrypts data via AES
1132 * @param string $data The data that is to be encrypted
1133 * @param string $key The AES key
1135 * @return string encrypted data
1137 private static function aesEncrypt($data, $key)
1139 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1143 * @brief decrypts data via AES
1145 * @param string $encrypted The encrypted data
1146 * @param string $key The AES key
1148 * @return string decrypted data
1150 public static function aesDecrypt($encrypted, $key)
1152 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1156 * @brief Delivers the atom content to the contacts
1158 * @param array $owner Owner record
1159 * @param array $contact Contact record of the receiver
1160 * @param string $atom Content that will be transmitted
1161 * @param bool $dissolve (to be documented)
1163 * @return int Deliver status. Negative values mean an error.
1164 * @todo Add array type-hint for $owner, $contact
1166 public static function deliver($owner, $contact, $atom, $dissolve = false)
1170 // At first try the Diaspora transport layer
1171 $ret = self::transmit($owner, $contact, $atom);
1173 logger('Delivery via Diaspora transport layer was successful with status ' . $ret);
1177 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1179 if ($contact['duplex'] && $contact['dfrn-id']) {
1180 $idtosend = '0:' . $orig_id;
1182 if ($contact['duplex'] && $contact['issued-id']) {
1183 $idtosend = '1:' . $orig_id;
1186 $rino = Config::get('system', 'rino_encrypt');
1187 $rino = intval($rino);
1189 logger("Local rino version: ". $rino, LOGGER_DEBUG);
1191 $ssl_val = intval(Config::get('system', 'ssl_policy'));
1195 case SSL_POLICY_FULL:
1196 $ssl_policy = 'full';
1198 case SSL_POLICY_SELFSIGN:
1199 $ssl_policy = 'self';
1201 case SSL_POLICY_NONE:
1203 $ssl_policy = 'none';
1207 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1209 logger('dfrn_deliver: ' . $url);
1211 $ret = Network::curl($url);
1213 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1214 Contact::markForArchival($contact);
1215 return -2; // timed out
1218 $xml = $ret['body'];
1220 $curl_stat = $a->get_curl_code();
1221 if (empty($curl_stat)) {
1222 Contact::markForArchival($contact);
1223 return -3; // timed out
1226 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1229 Contact::markForArchival($contact);
1233 if (strpos($xml, '<?xml') === false) {
1234 logger('dfrn_deliver: no valid XML returned');
1235 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1236 Contact::markForArchival($contact);
1240 $res = XML::parseString($xml);
1242 if (!is_object($res) || (intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
1243 Contact::markForArchival($contact);
1245 if (empty($res->status)) {
1248 $status = $res->status;
1255 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1256 $challenge = hex2bin((string) $res->challenge);
1257 $perm = (($res->perm) ? $res->perm : null);
1258 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1259 $rino_remote_version = intval($res->rino);
1260 $page = (($owner['page-flags'] == Contact::PAGE_COMMUNITY) ? 1 : 0);
1262 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
1264 if ($owner['page-flags'] == Contact::PAGE_PRVGROUP) {
1268 $final_dfrn_id = '';
1271 if ((($perm == 'rw') && !intval($contact['writable']))
1272 || (($perm == 'r') && intval($contact['writable']))
1274 DBA::update('contact', ['writable' => ($perm == 'rw')], ['id' => $contact['id']]);
1276 $contact['writable'] = (string) 1 - intval($contact['writable']);
1280 if (($contact['duplex'] && strlen($contact['pubkey']))
1281 || ($owner['page-flags'] == Contact::PAGE_COMMUNITY && strlen($contact['pubkey']))
1282 || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
1284 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
1285 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
1287 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
1288 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
1291 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1293 if (strpos($final_dfrn_id, ':') == 1) {
1294 $final_dfrn_id = substr($final_dfrn_id, 2);
1297 if ($final_dfrn_id != $orig_id) {
1298 logger('dfrn_deliver: wrong dfrn_id.');
1299 // did not decode properly - cannot trust this site
1300 Contact::markForArchival($contact);
1304 $postvars['dfrn_id'] = $idtosend;
1305 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1307 $postvars['dissolve'] = '1';
1310 if ((($contact['rel']) && ($contact['rel'] != Contact::SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == Contact::PAGE_COMMUNITY)) {
1311 $postvars['data'] = $atom;
1312 $postvars['perm'] = 'rw';
1314 $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
1315 $postvars['perm'] = 'r';
1318 $postvars['ssl_policy'] = $ssl_policy;
1321 $postvars['page'] = $page;
1325 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1326 logger('rino version: '. $rino_remote_version);
1328 switch ($rino_remote_version) {
1330 $key = openssl_random_pseudo_bytes(16);
1331 $data = self::aesEncrypt($postvars['data'], $key);
1335 logger("rino: invalid requested version '$rino_remote_version'");
1336 Contact::markForArchival($contact);
1340 $postvars['rino'] = $rino_remote_version;
1341 $postvars['data'] = bin2hex($data);
1343 if ($dfrn_version >= 2.1) {
1344 if (($contact['duplex'] && strlen($contact['pubkey']))
1345 || ($owner['page-flags'] == Contact::PAGE_COMMUNITY && strlen($contact['pubkey']))
1346 || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
1348 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1350 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1353 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == Contact::PAGE_COMMUNITY)) {
1354 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1356 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1360 logger('md5 rawkey ' . md5($postvars['key']));
1362 $postvars['key'] = bin2hex($postvars['key']);
1366 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), LOGGER_DATA);
1368 $xml = Network::post($contact['notify'], $postvars);
1370 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1372 $curl_stat = $a->get_curl_code();
1373 if (empty($curl_stat) || empty($xml)) {
1374 Contact::markForArchival($contact);
1375 return -9; // timed out
1378 if (($curl_stat == 503) && stristr($a->get_curl_headers(), 'retry-after')) {
1379 Contact::markForArchival($contact);
1383 if (strpos($xml, '<?xml') === false) {
1384 logger('dfrn_deliver: phase 2: no valid XML returned');
1385 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1386 Contact::markForArchival($contact);
1390 $res = XML::parseString($xml);
1392 if (!isset($res->status)) {
1393 Contact::markForArchival($contact);
1397 // Possibly old servers had returned an empty value when everything was okay
1398 if (empty($res->status)) {
1402 if (!empty($res->message)) {
1403 logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1406 if (($res->status >= 200) && ($res->status <= 299)) {
1407 Contact::unmarkForArchival($contact);
1410 return intval($res->status);
1414 * @brief Transmits atom content to the contacts via the Diaspora transport layer
1416 * @param array $owner Owner record
1417 * @param array $contact Contact record of the receiver
1418 * @param string $atom Content that will be transmitted
1420 * @return int Deliver status. Negative values mean an error.
1422 public static function transmit($owner, $contact, $atom, $public_batch = false)
1426 if (!$public_batch) {
1427 if (empty($contact['addr'])) {
1428 logger('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.');
1429 if (Contact::updateFromProbe($contact['id'])) {
1430 $new_contact = DBA::selectFirst('contact', ['addr'], ['id' => $contact['id']]);
1431 $contact['addr'] = $new_contact['addr'];
1434 if (empty($contact['addr'])) {
1435 logger('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
1436 Contact::markForArchival($contact);
1441 $fcontact = Diaspora::personByHandle($contact['addr']);
1442 if (empty($fcontact)) {
1443 logger('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
1444 Contact::markForArchival($contact);
1447 $pubkey = $fcontact['pubkey'];
1452 $envelope = Diaspora::buildMessage($atom, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
1454 // Create the endpoint for public posts. This is some WIP and should later be added to the probing
1455 if ($public_batch && empty($contact["batch"])) {
1456 $parts = parse_url($contact["notify"]);
1457 $path_parts = explode('/', $parts['path']);
1458 array_pop($path_parts);
1459 $parts['path'] = implode('/', $path_parts);
1460 $contact["batch"] = Network::unparseURL($parts);
1463 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
1465 $content_type = ($public_batch ? "application/magic-envelope+xml" : "application/json");
1467 $xml = Network::post($dest_url, $envelope, ["Content-Type: ".$content_type]);
1469 $curl_stat = $a->get_curl_code();
1470 if (empty($curl_stat) || empty($xml)) {
1471 logger('Empty answer from ' . $contact['id'] . ' - ' . $dest_url);
1472 Contact::markForArchival($contact);
1473 return -9; // timed out
1476 if (($curl_stat == 503) && (stristr($a->get_curl_headers(), 'retry-after'))) {
1477 Contact::markForArchival($contact);
1481 if (strpos($xml, '<?xml') === false) {
1482 logger('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url);
1483 logger('Returned XML: ' . $xml, LOGGER_DATA);
1484 Contact::markForArchival($contact);
1488 $res = XML::parseString($xml);
1490 if (empty($res->status)) {
1491 Contact::markForArchival($contact);
1495 if (!empty($res->message)) {
1496 logger('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1499 if (($res->status >= 200) && ($res->status <= 299)) {
1500 Contact::unmarkForArchival($contact);
1503 return intval($res->status);
1507 * @brief Add new birthday event for this person
1509 * @param array $contact Contact record
1510 * @param string $birthday Birthday of the contact
1512 * @todo Add array type-hint for $contact
1514 private static function birthdayEvent($contact, $birthday)
1516 // Check for duplicates
1517 $condition = ['uid' => $contact['uid'], 'cid' => $contact['id'],
1518 'start' => DateTimeFormat::utc($birthday), 'type' => 'birthday'];
1519 if (DBA::exists('event', $condition)) {
1523 logger('updating birthday: ' . $birthday . ' for contact ' . $contact['id']);
1525 $bdtext = L10n::t('%s\'s birthday', $contact['name']);
1526 $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]');
1529 "INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1530 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1531 intval($contact['uid']),
1532 intval($contact['id']),
1533 DBA::escape(DateTimeFormat::utcNow()),
1534 DBA::escape(DateTimeFormat::utcNow()),
1535 DBA::escape(DateTimeFormat::utc($birthday)),
1536 DBA::escape(DateTimeFormat::utc($birthday . ' + 1 day ')),
1537 DBA::escape($bdtext),
1538 DBA::escape($bdtext2),
1539 DBA::escape('birthday')
1544 * @brief Fetch the author data from head or entry items
1546 * @param object $xpath XPath object
1547 * @param object $context In which context should the data be searched
1548 * @param array $importer Record of the importer user mixed with contact of the content
1549 * @param string $element Element name from which the data is fetched
1550 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1551 * @param string $xml optional, default empty
1553 * @return array Relevant data of the author
1554 * @todo Find good type-hints for all parameter
1556 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
1559 $author["name"] = XML::getFirstNodeValue($xpath, $element."/atom:name/text()", $context);
1560 $author["link"] = XML::getFirstNodeValue($xpath, $element."/atom:uri/text()", $context);
1562 $fields = ['id', 'uid', 'url', 'network', 'avatar-date', 'avatar', 'name-date', 'uri-date', 'addr',
1563 'name', 'nick', 'about', 'location', 'keywords', 'xmpp', 'bdyear', 'bd', 'hidden', 'contact-type'];
1564 $condition = ["`uid` = ? AND `nurl` = ? AND `network` != ?",
1565 $importer["importer_uid"], normalise_link($author["link"]), Protocol::STATUSNET];
1566 $contact_old = DBA::selectFirst('contact', $fields, $condition);
1568 if (DBA::isResult($contact_old)) {
1569 $author["contact-id"] = $contact_old["id"];
1570 $author["network"] = $contact_old["network"];
1573 logger("Contact ".$author["link"]." wasn't found for user ".$importer["importer_uid"]." XML: ".$xml, LOGGER_DEBUG);
1576 $author["contact-unknown"] = true;
1577 $author["contact-id"] = $importer["id"];
1578 $author["network"] = $importer["network"];
1582 // Until now we aren't serving different sizes - but maybe later
1584 /// @todo check if "avatar" or "photo" would be the best field in the specification
1585 $avatars = $xpath->query($element . "/atom:link[@rel='avatar']", $context);
1586 foreach ($avatars as $avatar) {
1589 foreach ($avatar->attributes as $attributes) {
1590 /// @TODO Rewrite these similar if() to one switch
1591 if ($attributes->name == "href") {
1592 $href = $attributes->textContent;
1594 if ($attributes->name == "width") {
1595 $width = $attributes->textContent;
1597 if ($attributes->name == "updated") {
1598 $author["avatar-date"] = $attributes->textContent;
1601 if (($width > 0) && ($href != "")) {
1602 $avatarlist[$width] = $href;
1606 if (count($avatarlist) > 0) {
1607 krsort($avatarlist);
1608 $author["avatar"] = current($avatarlist);
1611 if (empty($author['avatar']) && !empty($author['link'])) {
1612 $cid = Contact::getIdForURL($author['link'], 0);
1614 $contact = DBA::selectFirst('contact', ['avatar'], ['id' => $cid]);
1615 if (DBA::isResult($contact)) {
1616 $author['avatar'] = $contact['avatar'];
1621 if (empty($author['avatar'])) {
1622 logger('Empty author: ' . $xml);
1625 if (DBA::isResult($contact_old) && !$onlyfetch) {
1626 logger("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", LOGGER_DEBUG);
1628 $poco = ["url" => $contact_old["url"]];
1630 // When was the last change to name or uri?
1631 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1632 foreach ($name_element->attributes as $attributes) {
1633 if ($attributes->name == "updated") {
1634 $poco["name-date"] = $attributes->textContent;
1638 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1639 foreach ($link_element->attributes as $attributes) {
1640 if ($attributes->name == "updated") {
1641 $poco["uri-date"] = $attributes->textContent;
1645 // Update contact data
1646 $value = XML::getFirstNodeValue($xpath, $element . "/dfrn:handle/text()", $context);
1648 $poco["addr"] = $value;
1651 $value = XML::getFirstNodeValue($xpath, $element . "/poco:displayName/text()", $context);
1653 $poco["name"] = $value;
1656 $value = XML::getFirstNodeValue($xpath, $element . "/poco:preferredUsername/text()", $context);
1658 $poco["nick"] = $value;
1661 $value = XML::getFirstNodeValue($xpath, $element . "/poco:note/text()", $context);
1663 $poco["about"] = $value;
1666 $value = XML::getFirstNodeValue($xpath, $element . "/poco:address/poco:formatted/text()", $context);
1668 $poco["location"] = $value;
1671 /// @todo Only search for elements with "poco:type" = "xmpp"
1672 $value = XML::getFirstNodeValue($xpath, $element . "/poco:ims/poco:value/text()", $context);
1674 $poco["xmpp"] = $value;
1677 /// @todo Add support for the following fields that we don't support by now in the contact table:
1678 /// - poco:utcOffset
1684 // If the "hide" element is present then the profile isn't searchable.
1685 $hide = intval(XML::getFirstNodeValue($xpath, $element . "/dfrn:hide/text()", $context) == "true");
1687 logger("Hidden status for contact " . $contact_old["url"] . ": " . $hide, LOGGER_DEBUG);
1689 // If the contact isn't searchable then set the contact to "hidden".
1690 // Problem: This can be manually overridden by the user.
1692 $contact_old["hidden"] = true;
1695 // Save the keywords into the contact table
1697 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1698 foreach ($tagelements as $tag) {
1699 $tags[$tag->nodeValue] = $tag->nodeValue;
1703 $poco["keywords"] = implode(", ", $tags);
1706 // "dfrn:birthday" contains the birthday converted to UTC
1707 $birthday = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1709 if (strtotime($birthday) > time()) {
1710 $bd_timestamp = strtotime($birthday);
1712 $poco["bdyear"] = date("Y", $bd_timestamp);
1715 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1716 $value = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1718 if (!in_array($value, ["", "0000-00-00", "0001-01-01"])) {
1719 $bdyear = date("Y");
1720 $value = str_replace("0000", $bdyear, $value);
1722 if (strtotime($value) < time()) {
1723 $value = str_replace($bdyear, $bdyear + 1, $value);
1724 $bdyear = $bdyear + 1;
1727 $poco["bd"] = $value;
1730 $contact = array_merge($contact_old, $poco);
1732 if ($contact_old["bdyear"] != $contact["bdyear"]) {
1733 self::birthdayEvent($contact, $birthday);
1736 // Get all field names
1738 foreach ($contact_old as $field => $data) {
1739 $fields[$field] = $data;
1742 unset($fields["id"]);
1743 unset($fields["uid"]);
1744 unset($fields["url"]);
1745 unset($fields["avatar-date"]);
1746 unset($fields["avatar"]);
1747 unset($fields["name-date"]);
1748 unset($fields["uri-date"]);
1751 // Update check for this field has to be done differently
1752 $datefields = ["name-date", "uri-date"];
1753 foreach ($datefields as $field) {
1754 // The date fields arrives as '2018-07-17T10:44:45Z' - the database return '2018-07-17 10:44:45'
1755 // The fields have to be in the same format to be comparable, since strtotime does add timezones.
1756 $contact[$field] = DateTimeFormat::utc($contact[$field]);
1758 if (strtotime($contact[$field]) > strtotime($contact_old[$field])) {
1759 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1764 foreach ($fields as $field => $data) {
1765 if ($contact[$field] != $contact_old[$field]) {
1766 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1772 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1775 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1776 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1777 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1778 WHERE `id` = %d AND `network` = '%s'",
1779 DBA::escape($contact["name"]), DBA::escape($contact["nick"]), DBA::escape($contact["about"]), DBA::escape($contact["location"]),
1780 DBA::escape($contact["addr"]), DBA::escape($contact["keywords"]), DBA::escape($contact["bdyear"]),
1781 DBA::escape($contact["bd"]), intval($contact["hidden"]), DBA::escape($contact["xmpp"]),
1782 DBA::escape(DateTimeFormat::utc($contact["name-date"])), DBA::escape(DateTimeFormat::utc($contact["uri-date"])),
1783 intval($contact["id"]), DBA::escape($contact["network"])
1787 Contact::updateAvatar(
1789 $importer['importer_uid'],
1791 (strtotime($contact['avatar-date']) > strtotime($contact_old['avatar-date']) || ($author['avatar'] != $contact_old['avatar']))
1795 * The generation is a sign for the reliability of the provided data.
1796 * It is used in the socgraph.php to prevent that old contact data
1797 * that was relayed over several servers can overwrite contact
1798 * data that we received directly.
1801 $poco["generation"] = 2;
1802 $poco["photo"] = $author["avatar"];
1803 $poco["hide"] = $hide;
1804 $poco["contact-type"] = $contact["contact-type"];
1805 $gcid = GContact::update($poco);
1807 GContact::link($gcid, $importer["importer_uid"], $contact["id"]);
1814 * @brief Transforms activity objects into an XML string
1816 * @param object $xpath XPath object
1817 * @param object $activity Activity object
1818 * @param string $element element name
1820 * @return string XML string
1821 * @todo Find good type-hints for all parameter
1823 private static function transformActivity($xpath, $activity, $element)
1825 if (!is_object($activity)) {
1829 $obj_doc = new DOMDocument("1.0", "utf-8");
1830 $obj_doc->formatOutput = true;
1832 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1834 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1835 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1837 $id = $xpath->query("atom:id", $activity)->item(0);
1838 if (is_object($id)) {
1839 $obj_element->appendChild($obj_doc->importNode($id, true));
1842 $title = $xpath->query("atom:title", $activity)->item(0);
1843 if (is_object($title)) {
1844 $obj_element->appendChild($obj_doc->importNode($title, true));
1847 $links = $xpath->query("atom:link", $activity);
1848 if (is_object($links)) {
1849 foreach ($links as $link) {
1850 $obj_element->appendChild($obj_doc->importNode($link, true));
1854 $content = $xpath->query("atom:content", $activity)->item(0);
1855 if (is_object($content)) {
1856 $obj_element->appendChild($obj_doc->importNode($content, true));
1859 $obj_doc->appendChild($obj_element);
1861 $objxml = $obj_doc->saveXML($obj_element);
1863 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1864 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1869 * @brief Processes the mail elements
1871 * @param object $xpath XPath object
1872 * @param object $mail mail elements
1873 * @param array $importer Record of the importer user mixed with contact of the content
1875 * @todo Find good type-hints for all parameter
1877 private static function processMail($xpath, $mail, $importer)
1879 logger("Processing mails");
1881 /// @TODO Rewrite this to one statement
1883 $msg["uid"] = $importer["importer_uid"];
1884 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1885 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1886 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1887 $msg["contact-id"] = $importer["id"];
1888 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1889 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1890 $msg["created"] = DateTimeFormat::utc($xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue);
1891 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1892 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1894 $msg["replied"] = 0;
1896 DBA::insert('mail', $msg);
1898 $msg["id"] = DBA::lastInsertId();
1900 // send notifications.
1901 /// @TODO Arange this mess
1903 "type" => NOTIFY_MAIL,
1904 "notify_flags" => $importer["notify-flags"],
1905 "language" => $importer["language"],
1906 "to_name" => $importer["username"],
1907 "to_email" => $importer["email"],
1908 "uid" => $importer["importer_uid"],
1910 "source_name" => $msg["from-name"],
1911 "source_link" => $importer["url"],
1912 "source_photo" => $importer["thumb"],
1913 "verb" => ACTIVITY_POST,
1917 notification($notif_params);
1919 logger("Mail is processed, notification was sent.");
1923 * @brief Processes the suggestion elements
1925 * @param object $xpath XPath object
1926 * @param object $suggestion suggestion elements
1927 * @param array $importer Record of the importer user mixed with contact of the content
1929 * @todo Find good type-hints for all parameter
1931 private static function processSuggestion($xpath, $suggestion, $importer)
1935 logger("Processing suggestions");
1937 /// @TODO Rewrite this to one statement
1939 $suggest["uid"] = $importer["importer_uid"];
1940 $suggest["cid"] = $importer["id"];
1941 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1942 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1943 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1944 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1945 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1947 // Does our member already have a friend matching this description?
1950 * The valid result means the friend we're about to send a friend
1951 * suggestion already has them in their contact, which means no further
1952 * action is required.
1954 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1956 $condition = ['name' => $suggest["name"], 'nurl' => normalise_link($suggest["url"]),
1957 'uid' => $suggest["uid"]];
1958 if (DBA::exists('contact', $condition)) {
1962 // Do we already have an fcontact record for this person?
1965 $condition = ['url' => $suggest["url"], 'name' => $suggest["name"], 'request' => $suggest["request"]];
1966 $fcontact = DBA::selectFirst('fcontact', ['id'], $condition);
1967 if (DBA::isResult($fcontact)) {
1968 $fid = $fcontact["id"];
1970 // OK, we do. Do we already have an introduction for this person?
1971 if (DBA::exists('intro', ['uid' => $suggest["uid"], 'fid' => $fid])) {
1973 * The valid result means the friend we're about to send a friend
1974 * suggestion already has them in their contact, which means no further
1975 * action is required.
1977 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1984 "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1985 DBA::escape($suggest["name"]),
1986 DBA::escape($suggest["url"]),
1987 DBA::escape($suggest["photo"]),
1988 DBA::escape($suggest["request"])
1992 $condition = ['url' => $suggest["url"], 'name' => $suggest["name"], 'request' => $suggest["request"]];
1993 $fcontact = DBA::selectFirst('fcontact', ['id'], $condition);
1996 * If no record in fcontact is found, below INSERT statement will not
1997 * link an introduction to it.
1999 if (!DBA::isResult($fcontact)) {
2000 // Database record did not get created. Quietly give up.
2006 $hash = random_string();
2009 "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
2010 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
2011 intval($suggest["uid"]),
2013 intval($suggest["cid"]),
2014 DBA::escape($suggest["body"]),
2016 DBA::escape(DateTimeFormat::utcNow()),
2022 "type" => NOTIFY_SUGGEST,
2023 "notify_flags" => $importer["notify-flags"],
2024 "language" => $importer["language"],
2025 "to_name" => $importer["username"],
2026 "to_email" => $importer["email"],
2027 "uid" => $importer["importer_uid"],
2029 "link" => System::baseUrl()."/notifications/intros",
2030 "source_name" => $importer["name"],
2031 "source_link" => $importer["url"],
2032 "source_photo" => $importer["photo"],
2033 "verb" => ACTIVITY_REQ_FRIEND,
2041 * @brief Processes the relocation elements
2043 * @param object $xpath XPath object
2044 * @param object $relocation relocation elements
2045 * @param array $importer Record of the importer user mixed with contact of the content
2047 * @todo Find good type-hints for all parameter
2049 private static function processRelocation($xpath, $relocation, $importer)
2051 logger("Processing relocations");
2053 /// @TODO Rewrite this to one statement
2055 $relocate["uid"] = $importer["importer_uid"];
2056 $relocate["cid"] = $importer["id"];
2057 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
2058 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
2059 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
2060 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
2061 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
2062 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
2063 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
2064 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
2065 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
2066 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
2067 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
2068 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
2070 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
2071 $relocate["avatar"] = $relocate["photo"];
2074 if ($relocate["addr"] == "") {
2075 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
2080 "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d",
2081 intval($importer["id"]),
2082 intval($importer["importer_uid"])
2085 if (!DBA::isResult($r)) {
2086 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2092 // Update the gcontact entry
2093 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
2095 $fields = ['name' => $relocate["name"], 'photo' => $relocate["avatar"],
2096 'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2097 'addr' => $relocate["addr"], 'connect' => $relocate["addr"],
2098 'notify' => $relocate["notify"], 'server_url' => $relocate["server_url"]];
2099 DBA::update('gcontact', $fields, ['nurl' => normalise_link($old["url"])]);
2101 // Update the contact table. We try to find every entry.
2102 $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
2103 'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2104 'addr' => $relocate["addr"], 'request' => $relocate["request"],
2105 'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
2106 'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
2107 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], normalise_link($old["url"])];
2109 DBA::update('contact', $fields, $condition);
2111 Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
2113 logger('Contacts are updated.');
2116 /// merge with current record, current contents have priority
2117 /// update record, set url-updated
2118 /// update profile photos
2119 /// schedule a scan?
2124 * @brief Updates an item
2126 * @param array $current the current item record
2127 * @param array $item the new item record
2128 * @param array $importer Record of the importer user mixed with contact of the content
2129 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2131 * @todo set proper type-hints (array?)
2133 private static function updateContent($current, $item, $importer, $entrytype)
2137 if (self::isEditedTimestampNewer($current, $item)) {
2138 // do not accept (ignore) an earlier edit than one we currently have.
2139 if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
2143 $fields = ['title' => defaults($item, 'title', ''), 'body' => defaults($item, 'body', ''),
2144 'tag' => defaults($item, 'tag', ''), 'changed' => DateTimeFormat::utcNow(),
2145 'edited' => DateTimeFormat::utc($item["edited"])];
2147 $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
2148 Item::update($fields, $condition);
2156 * @brief Detects the entry type of the item
2158 * @param array $importer Record of the importer user mixed with contact of the content
2159 * @param array $item the new item record
2161 * @return int Is it a toplevel entry, a comment or a relayed comment?
2162 * @todo set proper type-hints (array?)
2164 private static function getEntryType($importer, $item)
2166 if ($item["parent-uri"] != $item["uri"]) {
2169 if ($importer["page-flags"] == Contact::PAGE_COMMUNITY || $importer["page-flags"] == Contact::PAGE_PRVGROUP) {
2172 logger("possible community action");
2174 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2177 // was the top-level post for this action written by somebody on this site?
2178 // Specifically, the recipient?
2180 $is_a_remote_action = false;
2182 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item["parent-uri"]]);
2183 if (DBA::isResult($parent)) {
2185 "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2186 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2187 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2188 AND `item`.`uid` = %d
2191 DBA::escape($parent["parent-uri"]),
2192 DBA::escape($parent["parent-uri"]),
2193 DBA::escape($parent["parent-uri"]),
2194 intval($importer["importer_uid"])
2196 if (DBA::isResult($r)) {
2197 $is_a_remote_action = true;
2202 * Does this have the characteristics of a community or private group action?
2203 * If it's an action to a wall post on a community/prvgroup page it's a
2204 * valid community action. Also forum_mode makes it valid for sure.
2205 * If neither, it's not.
2207 if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2208 $is_a_remote_action = false;
2209 logger("not a community action");
2212 if ($is_a_remote_action) {
2213 return DFRN::REPLY_RC;
2218 return DFRN::TOP_LEVEL;
2223 * @brief Send a "poke"
2225 * @param array $item the new item record
2226 * @param array $importer Record of the importer user mixed with contact of the content
2227 * @param int $posted_id The record number of item record that was just posted
2229 * @todo set proper type-hints (array?)
2231 private static function doPoke($item, $importer, $posted_id)
2233 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2237 $xo = XML::parseString($item["object"], false);
2239 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2240 // somebody was poked/prodded. Was it me?
2241 foreach ($xo->link as $l) {
2242 $atts = $l->attributes();
2243 switch ($atts["rel"]) {
2245 $Blink = $atts["href"];
2252 if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2253 $author = DBA::selectFirst('contact', ['name', 'thumb', 'url'], ['id' => $item['author-id']]);
2255 $item['id'] = $posted_id;
2257 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => $importer["importer_uid"]]);
2258 $item["parent"] = $parent['id'];
2260 // send a notification
2263 "type" => NOTIFY_POKE,
2264 "notify_flags" => $importer["notify-flags"],
2265 "language" => $importer["language"],
2266 "to_name" => $importer["username"],
2267 "to_email" => $importer["email"],
2268 "uid" => $importer["importer_uid"],
2270 "link" => System::baseUrl()."/display/".urlencode(Item::getGuidById($posted_id)),
2271 "source_name" => $author["name"],
2272 "source_link" => $author["url"],
2273 "source_photo" => $author["thumb"],
2274 "verb" => $item["verb"],
2275 "otype" => "person",
2276 "activity" => $verb,
2277 "parent" => $item["parent"]]
2284 * @brief Processes several actions, depending on the verb
2286 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2287 * @param array $importer Record of the importer user mixed with contact of the content
2288 * @param array $item the new item record
2289 * @param bool $is_like Is the verb a "like"?
2291 * @return bool Should the processing of the entries be continued?
2292 * @todo set proper type-hints (array?)
2294 private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2296 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2298 if (($entrytype == DFRN::TOP_LEVEL)) {
2299 // The filling of the the "contact" variable is done for legcy reasons
2300 // The functions below are partly used by ostatus.php as well - where we have this variable
2301 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2303 $nickname = $contact["nick"];
2305 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2306 // This function once was responsible for DFRN and OStatus.
2307 if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2308 logger("New follower");
2309 Contact::addRelationship($importer, $contact, $item, $nickname);
2312 if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2313 logger("Lost follower");
2314 Contact::removeFollower($importer, $contact, $item);
2317 if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2318 logger("New friend request");
2319 Contact::addRelationship($importer, $contact, $item, $nickname, true);
2322 if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2323 logger("Lost sharer");
2324 Contact::removeSharer($importer, $contact, $item);
2328 if (($item["verb"] == ACTIVITY_LIKE)
2329 || ($item["verb"] == ACTIVITY_DISLIKE)
2330 || ($item["verb"] == ACTIVITY_ATTEND)
2331 || ($item["verb"] == ACTIVITY_ATTENDNO)
2332 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
2335 $item["gravity"] = GRAVITY_ACTIVITY;
2336 // only one like or dislike per person
2337 // splitted into two queries for performance issues
2338 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2339 'verb' => $item["verb"], 'parent-uri' => $item["parent-uri"]];
2340 if (Item::exists($condition)) {
2344 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2345 'verb' => $item["verb"], 'thr-parent' => $item["parent-uri"]];
2346 if (Item::exists($condition)) {
2353 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2354 $xo = XML::parseString($item["object"], false);
2355 $xt = XML::parseString($item["target"], false);
2357 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2358 $item_tag = Item::selectFirst(['id', 'tag'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]);
2360 if (!DBA::isResult($item_tag)) {
2361 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2365 // extract tag, if not duplicate, add to parent item
2367 if (!stristr($item_tag["tag"], trim($xo->content))) {
2368 $tag = $item_tag["tag"] . (strlen($item_tag["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2369 Item::update(['tag' => $tag], ['id' => $item_tag["id"]]);
2379 * @brief Processes the link elements
2381 * @param object $links link elements
2382 * @param array $item the item record
2384 * @todo set proper type-hints
2386 private static function parseLinks($links, &$item)
2393 foreach ($links as $link) {
2394 foreach ($link->attributes as $attributes) {
2395 switch ($attributes->name) {
2396 case "href" : $href = $attributes->textContent; break;
2397 case "rel" : $rel = $attributes->textContent; break;
2398 case "type" : $type = $attributes->textContent; break;
2399 case "length": $length = $attributes->textContent; break;
2400 case "title" : $title = $attributes->textContent; break;
2403 if (($rel != "") && ($href != "")) {
2406 $item["plink"] = $href;
2410 if (strlen($item["attach"])) {
2411 $item["attach"] .= ",";
2414 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2422 * @brief Processes the entry elements which contain the items and comments
2424 * @param array $header Array of the header elements that always stay the same
2425 * @param object $xpath XPath object
2426 * @param object $entry entry elements
2427 * @param array $importer Record of the importer user mixed with contact of the content
2428 * @param object $xml xml
2430 * @todo Add type-hints
2432 private static function processEntry($header, $xpath, $entry, $importer, $xml)
2434 logger("Processing entries");
2438 $item["protocol"] = Conversation::PARCEL_DFRN;
2440 $item["source"] = $xml;
2443 $item["uri"] = XML::getFirstNodeValue($xpath, "atom:id/text()", $entry);
2445 $item["edited"] = XML::getFirstNodeValue($xpath, "atom:updated/text()", $entry);
2447 $current = Item::selectFirst(['id', 'uid', 'edited', 'body'],
2448 ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
2450 // Is there an existing item?
2451 if (DBA::isResult($current) && !self::isEditedTimestampNewer($current, $item)) {
2452 logger("Item ".$item["uri"]." (".$item['edited'].") already existed.", LOGGER_DEBUG);
2457 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true, $xml);
2459 $owner_unknown = (isset($owner["contact-unknown"]) && $owner["contact-unknown"]);
2461 $item["owner-name"] = $owner["name"];
2462 $item["owner-link"] = $owner["link"];
2463 $item["owner-avatar"] = $owner["avatar"];
2464 $item["owner-id"] = Contact::getIdForURL($owner["link"], 0);
2467 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true, $xml);
2469 $item["author-name"] = $author["name"];
2470 $item["author-link"] = $author["link"];
2471 $item["author-avatar"] = $author["avatar"];
2472 $item["author-id"] = Contact::getIdForURL($author["link"], 0);
2474 $item["title"] = XML::getFirstNodeValue($xpath, "atom:title/text()", $entry);
2476 $item["created"] = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2478 $item["body"] = XML::getFirstNodeValue($xpath, "dfrn:env/text()", $entry);
2479 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2480 // make sure nobody is trying to sneak some html tags by us
2481 $item["body"] = notags(base64url_decode($item["body"]));
2483 $item["body"] = BBCode::limitBodySize($item["body"]);
2485 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2486 if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
2487 $base_url = get_app()->get_baseurl();
2488 $item['body'] = reltoabs($item['body'], $base_url);
2490 $item['body'] = html2bb_video($item['body']);
2492 $item['body'] = OEmbed::HTML2BBCode($item['body']);
2494 $config = HTMLPurifier_Config::createDefault();
2495 $config->set('Cache.DefinitionImpl', null);
2497 // we shouldn't need a whitelist, because the bbcode converter
2498 // will strip out any unsupported tags.
2500 $purifier = new HTMLPurifier($config);
2501 $item['body'] = $purifier->purify($item['body']);
2503 $item['body'] = @HTML::toBBCode($item['body']);
2506 /// @todo We should check for a repeated post and if we know the repeated author.
2508 // We don't need the content element since "dfrn:env" is always present
2509 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2511 $item["location"] = XML::getFirstNodeValue($xpath, "dfrn:location/text()", $entry);
2513 $item["coord"] = XML::getFirstNodeValue($xpath, "georss:point", $entry);
2515 $item["private"] = XML::getFirstNodeValue($xpath, "dfrn:private/text()", $entry);
2517 $item["extid"] = XML::getFirstNodeValue($xpath, "dfrn:extid/text()", $entry);
2519 if (XML::getFirstNodeValue($xpath, "dfrn:bookmark/text()", $entry) == "true") {
2520 $item["post-type"] = Item::PT_PAGE;
2523 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2524 if ($notice_info && ($notice_info->length > 0)) {
2525 foreach ($notice_info->item(0)->attributes as $attributes) {
2526 if ($attributes->name == "source") {
2527 $item["app"] = strip_tags($attributes->textContent);
2532 $item["guid"] = XML::getFirstNodeValue($xpath, "dfrn:diaspora_guid/text()", $entry);
2534 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
2535 $dsprsig = unxmlify(XML::getFirstNodeValue($xpath, "dfrn:diaspora_signature/text()", $entry));
2536 if ($dsprsig != "") {
2537 $item["dsprsig"] = $dsprsig;
2540 $item["verb"] = XML::getFirstNodeValue($xpath, "activity:verb/text()", $entry);
2542 if (XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry) != "") {
2543 $item["object-type"] = XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry);
2546 $object = $xpath->query("activity:object", $entry)->item(0);
2547 $item["object"] = self::transformActivity($xpath, $object, "object");
2549 if (trim($item["object"]) != "") {
2550 $r = XML::parseString($item["object"], false);
2551 if (isset($r->type)) {
2552 $item["object-type"] = $r->type;
2556 $target = $xpath->query("activity:target", $entry)->item(0);
2557 $item["target"] = self::transformActivity($xpath, $target, "target");
2559 $categories = $xpath->query("atom:category", $entry);
2561 foreach ($categories as $category) {
2564 foreach ($category->attributes as $attributes) {
2565 if ($attributes->name == "term") {
2566 $term = $attributes->textContent;
2569 if ($attributes->name == "scheme") {
2570 $scheme = $attributes->textContent;
2574 if (($term != "") && ($scheme != "")) {
2575 $parts = explode(":", $scheme);
2576 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2577 $termhash = array_shift($parts);
2578 $termurl = implode(":", $parts);
2580 if (!empty($item["tag"])) {
2581 $item["tag"] .= ",";
2586 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2594 $links = $xpath->query("atom:link", $entry);
2596 self::parseLinks($links, $item);
2599 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
2601 $conv = $xpath->query('ostatus:conversation', $entry);
2602 if (is_object($conv->item(0))) {
2603 foreach ($conv->item(0)->attributes as $attributes) {
2604 if ($attributes->name == "ref") {
2605 $item['conversation-uri'] = $attributes->textContent;
2607 if ($attributes->name == "href") {
2608 $item['conversation-href'] = $attributes->textContent;
2613 // Is it a reply or a top level posting?
2614 $item["parent-uri"] = $item["uri"];
2616 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2617 if (is_object($inreplyto->item(0))) {
2618 foreach ($inreplyto->item(0)->attributes as $attributes) {
2619 if ($attributes->name == "ref") {
2620 $item["parent-uri"] = $attributes->textContent;
2625 // Get the type of the item (Top level post, reply or remote reply)
2626 $entrytype = self::getEntryType($importer, $item);
2628 // Now assign the rest of the values that depend on the type of the message
2629 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2630 if (!isset($item["object-type"])) {
2631 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2634 if ($item["contact-id"] != $owner["contact-id"]) {
2635 $item["contact-id"] = $owner["contact-id"];
2638 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2639 $item["network"] = $owner["network"];
2642 if ($item["contact-id"] != $author["contact-id"]) {
2643 $item["contact-id"] = $author["contact-id"];
2646 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2647 $item["network"] = $author["network"];
2651 if ($entrytype == DFRN::REPLY_RC) {
2653 } elseif ($entrytype == DFRN::TOP_LEVEL) {
2654 if (!isset($item["object-type"])) {
2655 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2659 if (($item["object-type"] == ACTIVITY_OBJ_EVENT) && !$owner_unknown) {
2660 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2661 $ev = Event::fromBBCode($item["body"]);
2662 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2663 logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2664 $ev["cid"] = $importer["id"];
2665 $ev["uid"] = $importer["importer_uid"];
2666 $ev["uri"] = $item["uri"];
2667 $ev["edited"] = $item["edited"];
2668 $ev["private"] = $item["private"];
2669 $ev["guid"] = $item["guid"];
2670 $ev["plink"] = $item["plink"];
2672 $condition = ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]];
2673 $event = DBA::selectFirst('event', ['id'], $condition);
2674 if (DBA::isResult($event)) {
2675 $ev["id"] = $event["id"];
2678 $event_id = Event::store($ev);
2679 logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2685 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2686 logger("Exiting because 'processVerbs' told us so", LOGGER_DEBUG);
2690 // This check is done here to be able to receive connection requests in "processVerbs"
2691 if (($entrytype == DFRN::TOP_LEVEL) && $owner_unknown) {
2692 logger("Item won't be stored because user " . $importer["importer_uid"] . " doesn't follow " . $item["owner-link"] . ".", LOGGER_DEBUG);
2697 // Update content if 'updated' changes
2698 if (DBA::isResult($current)) {
2699 if (self::updateContent($current, $item, $importer, $entrytype)) {
2700 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2702 logger("Item " . $item["uri"] . " already existed.", LOGGER_DEBUG);
2707 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2708 $posted_id = Item::insert($item);
2712 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2714 if ($item['uid'] == 0) {
2715 Item::distribute($posted_id);
2720 } else { // $entrytype == DFRN::TOP_LEVEL
2721 if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
2722 logger("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", LOGGER_DEBUG);
2725 if (!link_compare($item["owner-link"], $importer["url"])) {
2727 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2728 * but otherwise there's a possible data mixup on the sender's system.
2729 * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2730 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2732 logger('Correcting item owner.', LOGGER_DEBUG);
2733 $item["owner-link"] = $importer["url"];
2734 $item["owner-id"] = Contact::getIdForURL($importer["url"], 0);
2737 if (($importer["rel"] == Contact::FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2738 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2742 // This is my contact on another system, but it's really me.
2743 // Turn this into a wall post.
2744 $notify = Item::isRemoteSelf($importer, $item);
2746 $posted_id = Item::insert($item, false, $notify);
2749 $posted_id = $notify;
2752 logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2754 if ($item['uid'] == 0) {
2755 Item::distribute($posted_id);
2758 if (stristr($item["verb"], ACTIVITY_POKE)) {
2759 self::doPoke($item, $importer, $posted_id);
2765 * @brief Deletes items
2767 * @param object $xpath XPath object
2768 * @param object $deletion deletion elements
2769 * @param array $importer Record of the importer user mixed with contact of the content
2771 * @todo set proper type-hints
2773 private static function processDeletion($xpath, $deletion, $importer)
2775 logger("Processing deletions");
2778 foreach ($deletion->attributes as $attributes) {
2779 if ($attributes->name == "ref") {
2780 $uri = $attributes->textContent;
2784 if (!$uri || !$importer["id"]) {
2788 $condition = ['uri' => $uri, 'uid' => $importer["importer_uid"]];
2789 $item = Item::selectFirst(['id', 'parent', 'contact-id', 'file', 'deleted'], $condition);
2790 if (!DBA::isResult($item)) {
2791 logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", LOGGER_DEBUG);
2795 if (strstr($item['file'], '[')) {
2796 logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " is filed. So it won't be deleted.", LOGGER_DEBUG);
2800 // When it is a starting post it has to belong to the person that wants to delete it
2801 if (($item['id'] == $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2802 logger("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2806 // Comments can be deleted by the thread owner or comment owner
2807 if (($item['id'] != $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2808 $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2809 if (!Item::exists($condition)) {
2810 logger("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2815 if ($item["deleted"]) {
2819 logger('deleting item '.$item['id'].' uri='.$uri, LOGGER_DEBUG);
2821 Item::delete(['id' => $item['id']]);
2825 * @brief Imports a DFRN message
2827 * @param string $xml The DFRN message
2828 * @param array $importer Record of the importer user mixed with contact of the content
2829 * @param bool $sort_by_date Is used when feeds are polled
2830 * @return integer Import status
2831 * @todo set proper type-hints
2833 public static function import($xml, $importer, $sort_by_date = false)
2839 $doc = new DOMDocument();
2840 @$doc->loadXML($xml);
2842 $xpath = new DOMXPath($doc);
2843 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2844 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2845 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2846 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2847 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2848 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2849 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2850 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2851 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2852 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2855 $header["uid"] = $importer["importer_uid"];
2856 $header["network"] = Protocol::DFRN;
2857 $header["wall"] = 0;
2858 $header["origin"] = 0;
2859 $header["contact-id"] = $importer["id"];
2861 // Update the contact table if the data has changed
2863 // The "atom:author" is only present in feeds
2864 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2865 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2868 // Only the "dfrn:owner" in the head section contains all data
2869 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2870 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2873 logger("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2875 // is it a public forum? Private forums aren't exposed with this method
2876 $forum = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:community/text()"));
2878 // The account type is new since 3.5.1
2879 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2880 $accounttype = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:account_type/text()"));
2882 if ($accounttype != $importer["contact-type"]) {
2883 DBA::update('contact', ['contact-type' => $accounttype], ['id' => $importer["id"]]);
2885 // A forum contact can either have set "forum" or "prv" - but not both
2886 if (($accounttype == Contact::ACCOUNT_TYPE_COMMUNITY) && (($forum != $importer["forum"]) || ($forum == $importer["prv"]))) {
2887 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer["id"]];
2888 DBA::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2890 } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
2891 $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2892 DBA::update('contact', ['forum' => $forum], $condition);
2896 // We are processing relocations even if we are ignoring a contact
2897 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2898 foreach ($relocations as $relocation) {
2899 self::processRelocation($xpath, $relocation, $importer);
2902 if (($importer["uid"] != 0) && !$importer["readonly"]) {
2903 $mails = $xpath->query("/atom:feed/dfrn:mail");
2904 foreach ($mails as $mail) {
2905 self::processMail($xpath, $mail, $importer);
2908 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2909 foreach ($suggestions as $suggestion) {
2910 self::processSuggestion($xpath, $suggestion, $importer);
2914 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2915 foreach ($deletions as $deletion) {
2916 self::processDeletion($xpath, $deletion, $importer);
2919 if (!$sort_by_date) {
2920 $entries = $xpath->query("/atom:feed/atom:entry");
2921 foreach ($entries as $entry) {
2922 self::processEntry($header, $xpath, $entry, $importer, $xml);
2926 $entries = $xpath->query("/atom:feed/atom:entry");
2927 foreach ($entries as $entry) {
2928 $created = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2929 $newentries[strtotime($created)] = $entry;
2932 // Now sort after the publishing date
2935 foreach ($newentries as $entry) {
2936 self::processEntry($header, $xpath, $entry, $importer, $xml);
2939 logger("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2945 * @param string $contact_nick contact nickname
2947 public static function autoRedir(App $a, $contact_nick)
2950 if (x($_REQUEST, 'redir') && intval($_REQUEST['redir'])) {
2954 if ((! $contact_nick) || ($contact_nick === $a->user['nickname'])) {
2959 // We need to find out if $contact_nick is a user on this hub, and if so, if I
2960 // am a contact of that user. However, that user may have other contacts with the
2961 // same nickname as me on other hubs or other networks. Exclude these by requiring
2962 // that the contact have a local URL. I will be the only person with my nickname at
2963 // this URL, so if a result is found, then I am a contact of the $contact_nick user.
2965 // We also have to make sure that I'm a legitimate contact--I'm not blocked or pending.
2967 $baseurl = System::baseUrl();
2968 $domain_st = strpos($baseurl, "://");
2969 if ($domain_st === false) {
2972 $baseurl = substr($baseurl, $domain_st + 3);
2973 $nurl = normalise_link($baseurl);
2975 /// @todo Why is there a query for "url" *and* "nurl"? Especially this normalising is strange.
2976 $r = q("SELECT `id` FROM `contact` WHERE `uid` = (SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1)
2977 AND `nick` = '%s' AND NOT `self` AND (`url` LIKE '%%%s%%' OR `nurl` LIKE '%%%s%%') AND NOT `blocked` AND NOT `pending` LIMIT 1",
2978 DBA::escape($contact_nick),
2979 DBA::escape($a->user['nickname']),
2980 DBA::escape($baseurl),
2983 if ((! DBA::isResult($r)) || $r[0]['id'] == remote_user()) {
2987 $r = q("SELECT * FROM contact WHERE nick = '%s'
2988 AND network = '%s' AND uid = %d AND url LIKE '%%%s%%' LIMIT 1",
2989 DBA::escape($contact_nick),
2990 DBA::escape(Protocol::DFRN),
2991 intval(local_user()),
2992 DBA::escape($baseurl)
2994 if (! DBA::isResult($r)) {
3000 $dfrn_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
3002 if ($r[0]['duplex'] && $r[0]['issued-id']) {
3003 $orig_id = $r[0]['issued-id'];
3004 $dfrn_id = '1:' . $orig_id;
3006 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
3007 $orig_id = $r[0]['dfrn-id'];
3008 $dfrn_id = '0:' . $orig_id;
3011 // ensure that we've got a valid ID. There may be some edge cases with forums and non-duplex mode
3012 // that may have triggered some of the "went to {profile/intro} and got an RSS feed" issues
3014 if (strlen($dfrn_id) < 3) {
3018 $sec = random_string();
3020 DBA::insert('profile_check', ['uid' => local_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id, 'sec' => $sec, 'expire' => time() + 45]);
3022 $url = curPageURL();
3024 logger('auto_redir: ' . $r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
3025 $dest = (($url) ? '&destination_url=' . $url : '');
3026 goaway($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
3027 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest);
3034 * @brief Returns the activity verb
3036 * @param array $item Item array
3038 * @return string activity verb
3040 private static function constructVerb(array $item)
3042 if ($item['verb']) {
3043 return $item['verb'];
3045 return ACTIVITY_POST;
3048 private static function tgroupCheck($uid, $item)
3052 // check that the message originated elsewhere and is a top-level post
3054 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['parent-uri'])) {
3058 $user = DBA::selectFirst('user', ['page-flags', 'nickname'], ['uid' => $uid]);
3059 if (!DBA::isResult($user)) {
3063 $community_page = ($user['page-flags'] == Contact::PAGE_COMMUNITY);
3064 $prvgroup = ($user['page-flags'] == Contact::PAGE_PRVGROUP);
3066 $link = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
3069 * Diaspora uses their own hardwired link URL in @-tags
3070 * instead of the one we supply with webfinger
3072 $dlink = normalise_link(System::baseUrl() . '/u/' . $user['nickname']);
3074 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
3076 foreach ($matches as $mtch) {
3077 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
3079 logger('mention found: ' . $mtch[2]);
3088 return $community_page || $prvgroup;
3092 * This function returns true if $update has an edited timestamp newer
3093 * than $existing, i.e. $update contains new data which should override
3094 * what's already there. If there is no timestamp yet, the update is
3095 * assumed to be newer. If the update has no timestamp, the existing
3096 * item is assumed to be up-to-date. If the timestamps are equal it
3097 * assumes the update has been seen before and should be ignored.
3100 private static function isEditedTimestampNewer($existing, $update)
3102 if (!x($existing, 'edited') || !$existing['edited']) {
3105 if (!x($update, 'edited') || !$update['edited']) {
3109 $existing_edited = DateTimeFormat::utc($existing['edited']);
3110 $update_edited = DateTimeFormat::utc($update['edited']);
3112 return (strcmp($existing_edited, $update_edited) < 0);