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;
12 use Friendica\Content\OEmbed;
13 use Friendica\Content\Text\BBCode;
14 use Friendica\Content\Text\HTML;
15 use Friendica\Core\Addon;
16 use Friendica\Core\Config;
17 use Friendica\Core\L10n;
18 use Friendica\Core\System;
19 use Friendica\Core\Worker;
20 use Friendica\Database\DBM;
21 use Friendica\Model\Contact;
22 use Friendica\Model\Event;
23 use Friendica\Model\GContact;
24 use Friendica\Model\Group;
25 use Friendica\Model\Item;
26 use Friendica\Model\Profile;
27 use Friendica\Model\User;
28 use Friendica\Object\Image;
29 use Friendica\Protocol\OStatus;
30 use Friendica\Util\Crypto;
31 use Friendica\Util\DateTimeFormat;
32 use Friendica\Util\Network;
33 use Friendica\Util\XML;
34 use Friendica\Protocol\Diaspora;
39 use HTMLPurifier_Config;
41 require_once 'boot.php';
42 require_once 'include/dba.php';
43 require_once "include/enotify.php";
44 require_once "include/items.php";
45 require_once "include/text.php";
48 * @brief This class contain functions to create and send DFRN XML files
53 const DFRN_TOP_LEVEL = 0; // Top level posting
54 const DFRN_REPLY = 1; // Regular reply that is stored locally
55 const DFRN_REPLY_RC = 2; // Reply that will be relayed
58 * @brief Generates the atom entries for delivery.php
60 * This function is used whenever content is transmitted via DFRN.
62 * @param array $items Item elements
63 * @param array $owner Owner record
65 * @return string DFRN entries
66 * @todo Add type-hints
68 public static function entries($items, $owner)
70 $doc = new DOMDocument('1.0', 'utf-8');
71 $doc->formatOutput = true;
73 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
75 if (! count($items)) {
76 return trim($doc->saveXML());
79 foreach ($items as $item) {
80 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
81 $root->appendChild($entry);
84 return(trim($doc->saveXML()));
88 * @brief Generate an atom feed for the given user
90 * This function is called when another server is pulling data from the user feed.
92 * @param string $dfrn_id DFRN ID from the requesting party
93 * @param string $owner_nick Owner nick name
94 * @param string $last_update Date of the last update
95 * @param int $direction Can be -1, 0 or 1.
96 * @param boolean $onlyheader Output only the header without content? (Default is "no")
98 * @return string DFRN feed entries
100 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false)
104 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
105 $public_feed = (($dfrn_id) ? false : true);
106 $starred = false; // not yet implemented, possible security issues
109 if ($public_feed && $a->argc > 2) {
110 for ($x = 2; $x < $a->argc; $x++) {
111 if ($a->argv[$x] == 'converse') {
114 if ($a->argv[$x] == 'starred') {
117 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
118 $category = $a->argv[$x+1];
125 // default permissions - anonymous user
127 $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = '' ";
130 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
131 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
132 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
136 if (! DBM::is_result($r)) {
141 $owner_id = $owner['uid'];
142 $owner_nick = $owner['nickname'];
144 $sql_post_table = "";
146 if (! $public_feed) {
148 switch ($direction) {
150 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
154 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
155 $my_id = '1:' . $dfrn_id;
158 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
159 $my_id = '0:' . $dfrn_id;
167 "SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
171 if (! DBM::is_result($r)) {
176 include_once 'include/security.php';
177 $groups = Group::getIdsByContactId($contact['id']);
179 if (count($groups)) {
180 for ($x = 0; $x < count($groups); $x ++)
181 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
182 $gs = implode('|', $groups);
184 $gs = '<<>>' ; // Impossible to match
187 $sql_extra = sprintf(
189 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
190 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
191 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
192 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
194 intval($contact['id']),
195 intval($contact['id']),
207 if (! strlen($last_update)) {
208 $last_update = 'now -30 days';
211 if (isset($category)) {
212 $sql_post_table = sprintf(
213 "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` ",
214 dbesc(protect_sprintf($category)),
215 intval(TERM_OBJ_POST),
216 intval(TERM_CATEGORY),
219 //$sql_extra .= file_tag_file_query('item',$category,'category');
224 $sql_extra .= " AND `contact`.`self` = 1 ";
228 $check_date = DateTimeFormat::utc($last_update);
231 "SELECT `item`.*, `item`.`id` AS `item_id`,
232 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
233 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
234 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
235 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
236 FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
237 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
238 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
239 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
240 WHERE `item`.`uid` = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
241 AND `item`.`wall` AND `item`.`changed` > '%s'
243 ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
250 * Will check further below if this actually returned results.
251 * We will provide an empty feed if that is the case.
256 $doc = new DOMDocument('1.0', 'utf-8');
257 $doc->formatOutput = true;
259 $alternatelink = $owner['url'];
261 if (isset($category)) {
262 $alternatelink .= "/category/".$category;
266 $author = "dfrn:owner";
271 $root = self::addHeader($doc, $owner, $author, $alternatelink, true);
273 /// @TODO This hook can't work anymore
274 // Addon::callHooks('atom_feed', $atom);
276 if (!DBM::is_result($items) || $onlyheader) {
277 $atom = trim($doc->saveXML());
279 Addon::callHooks('atom_feed_end', $atom);
284 foreach ($items as $item) {
285 // prevent private email from leaking.
286 if ($item['network'] == NETWORK_MAIL) {
290 // public feeds get html, our own nodes use bbcode
294 // catch any email that's in a public conversation and make sure it doesn't leak
295 if ($item['private']) {
302 $entry = self::entry($doc, $type, $item, $owner, true);
303 $root->appendChild($entry);
306 $atom = trim($doc->saveXML());
308 Addon::callHooks('atom_feed_end', $atom);
314 * @brief Generate an atom entry for a given item id
316 * @param int $item_id The item id
317 * @param boolean $conversation Show the conversation. If false show the single post.
319 * @return string DFRN feed entry
321 public static function itemFeed($item_id, $conversation = false)
324 $condition = '`item`.`parent`';
326 $condition = '`item`.`id`';
330 "SELECT `item`.*, `item`.`id` AS `item_id`,
331 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
332 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
333 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
334 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
336 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
337 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
338 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
339 WHERE %s = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
340 AND NOT `item`.`private`",
345 if (!DBM::is_result($r)) {
352 if ($item['uid'] != 0) {
353 $owner = User::getOwnerDataById($item['uid']);
358 $owner = ['uid' => 0, 'nick' => 'feed-item'];
361 $doc = new DOMDocument('1.0', 'utf-8');
362 $doc->formatOutput = true;
366 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
367 $doc->appendChild($root);
369 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
370 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
371 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
372 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
373 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
374 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
375 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
376 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
377 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
379 //$root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
381 foreach ($items as $item) {
382 $entry = self::entry($doc, $type, $item, $owner, true, 0);
383 $root->appendChild($entry);
386 $root = self::entry($doc, $type, $item, $owner, true, 0, true);
389 $atom = trim($doc->saveXML());
394 * @brief Create XML text for DFRN mails
396 * @param array $item message elements
397 * @param array $owner Owner record
399 * @return string DFRN mail
400 * @todo Add type-hints
402 public static function mail($item, $owner)
404 $doc = new DOMDocument('1.0', 'utf-8');
405 $doc->formatOutput = true;
407 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
409 $mail = $doc->createElement("dfrn:mail");
410 $sender = $doc->createElement("dfrn:sender");
412 XML::addElement($doc, $sender, "dfrn:name", $owner['name']);
413 XML::addElement($doc, $sender, "dfrn:uri", $owner['url']);
414 XML::addElement($doc, $sender, "dfrn:avatar", $owner['thumb']);
416 $mail->appendChild($sender);
418 XML::addElement($doc, $mail, "dfrn:id", $item['uri']);
419 XML::addElement($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
420 XML::addElement($doc, $mail, "dfrn:sentdate", DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
421 XML::addElement($doc, $mail, "dfrn:subject", $item['title']);
422 XML::addElement($doc, $mail, "dfrn:content", $item['body']);
424 $root->appendChild($mail);
426 return(trim($doc->saveXML()));
430 * @brief Create XML text for DFRN friend suggestions
432 * @param array $item suggestion elements
433 * @param array $owner Owner record
435 * @return string DFRN suggestions
436 * @todo Add type-hints
438 public static function fsuggest($item, $owner)
440 $doc = new DOMDocument('1.0', 'utf-8');
441 $doc->formatOutput = true;
443 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
445 $suggest = $doc->createElement("dfrn:suggest");
447 XML::addElement($doc, $suggest, "dfrn:url", $item['url']);
448 XML::addElement($doc, $suggest, "dfrn:name", $item['name']);
449 XML::addElement($doc, $suggest, "dfrn:photo", $item['photo']);
450 XML::addElement($doc, $suggest, "dfrn:request", $item['request']);
451 XML::addElement($doc, $suggest, "dfrn:note", $item['note']);
453 $root->appendChild($suggest);
455 return(trim($doc->saveXML()));
459 * @brief Create XML text for DFRN relocations
461 * @param array $owner Owner record
462 * @param int $uid User ID
464 * @return string DFRN relocations
465 * @todo Add type-hints
467 public static function relocate($owner, $uid)
470 /* get site pubkey. this could be a new installation with no site keys*/
471 $pubkey = Config::get('system', 'site_pubkey');
473 $res = Crypto::newKeypair(1024);
474 Config::set('system', 'site_prvkey', $res['prvkey']);
475 Config::set('system', 'site_pubkey', $res['pubkey']);
479 "SELECT `resource-id` , `scale`, type FROM `photo`
480 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;",
484 $ext = Image::supportedTypes();
486 foreach ($rp as $p) {
487 $photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
492 $doc = new DOMDocument('1.0', 'utf-8');
493 $doc->formatOutput = true;
495 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
497 $relocate = $doc->createElement("dfrn:relocate");
499 XML::addElement($doc, $relocate, "dfrn:url", $owner['url']);
500 XML::addElement($doc, $relocate, "dfrn:name", $owner['name']);
501 XML::addElement($doc, $relocate, "dfrn:addr", $owner['addr']);
502 XML::addElement($doc, $relocate, "dfrn:avatar", $owner['avatar']);
503 XML::addElement($doc, $relocate, "dfrn:photo", $photos[4]);
504 XML::addElement($doc, $relocate, "dfrn:thumb", $photos[5]);
505 XML::addElement($doc, $relocate, "dfrn:micro", $photos[6]);
506 XML::addElement($doc, $relocate, "dfrn:request", $owner['request']);
507 XML::addElement($doc, $relocate, "dfrn:confirm", $owner['confirm']);
508 XML::addElement($doc, $relocate, "dfrn:notify", $owner['notify']);
509 XML::addElement($doc, $relocate, "dfrn:poll", $owner['poll']);
510 XML::addElement($doc, $relocate, "dfrn:sitepubkey", Config::get('system', 'site_pubkey'));
512 $root->appendChild($relocate);
514 return(trim($doc->saveXML()));
518 * @brief Adds the header elements for the DFRN protocol
520 * @param object $doc XML document
521 * @param array $owner Owner record
522 * @param string $authorelement Element name for the author
523 * @param string $alternatelink link to profile or category
524 * @param bool $public Is it a header for public posts?
526 * @return object XML root object
527 * @todo Add type-hints
529 private static function addHeader($doc, $owner, $authorelement, $alternatelink = "", $public = false)
532 if ($alternatelink == "") {
533 $alternatelink = $owner['url'];
536 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
537 $doc->appendChild($root);
539 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
540 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
541 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
542 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
543 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
544 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
545 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
546 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
547 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
549 XML::addElement($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
550 XML::addElement($doc, $root, "title", $owner["name"]);
552 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION];
553 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
555 $attributes = ["rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/"];
556 XML::addElement($doc, $root, "link", "", $attributes);
558 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $alternatelink];
559 XML::addElement($doc, $root, "link", "", $attributes);
563 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
564 OStatus::hublinks($doc, $root, $owner["nick"]);
566 $attributes = ["rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
567 XML::addElement($doc, $root, "link", "", $attributes);
569 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
570 XML::addElement($doc, $root, "link", "", $attributes);
572 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
573 XML::addElement($doc, $root, "link", "", $attributes);
576 // For backward compatibility we keep this element
577 if ($owner['page-flags'] == PAGE_COMMUNITY) {
578 XML::addElement($doc, $root, "dfrn:community", 1);
581 // The former element is replaced by this one
582 XML::addElement($doc, $root, "dfrn:account_type", $owner["account-type"]);
584 /// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
586 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
588 $author = self::addAuthor($doc, $owner, $authorelement, $public);
589 $root->appendChild($author);
595 * @brief Adds the author element in the header for the DFRN protocol
597 * @param object $doc XML document
598 * @param array $owner Owner record
599 * @param string $authorelement Element name for the author
600 * @param boolean $public boolean
602 * @return object XML author object
603 * @todo Add type-hints
605 private static function addAuthor($doc, $owner, $authorelement, $public)
607 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
609 "SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
610 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
611 intval($owner['uid'])
613 if (DBM::is_result($r)) {
619 $author = $doc->createElement($authorelement);
621 $namdate = DateTimeFormat::utc($owner['name-date'].'+00:00', DateTimeFormat::ATOM);
622 $uridate = DateTimeFormat::utc($owner['uri-date'].'+00:00', DateTimeFormat::ATOM);
623 $picdate = DateTimeFormat::utc($owner['avatar-date'].'+00:00', DateTimeFormat::ATOM);
627 if (!$public || !$hidewall) {
628 $attributes = ["dfrn:updated" => $namdate];
631 XML::addElement($doc, $author, "name", $owner["name"], $attributes);
632 XML::addElement($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
633 XML::addElement($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
635 $attributes = ["rel" => "photo", "type" => "image/jpeg",
636 "media:width" => 175, "media:height" => 175, "href" => $owner['photo']];
638 if (!$public || !$hidewall) {
639 $attributes["dfrn:updated"] = $picdate;
642 XML::addElement($doc, $author, "link", "", $attributes);
644 $attributes["rel"] = "avatar";
645 XML::addElement($doc, $author, "link", "", $attributes);
648 XML::addElement($doc, $author, "dfrn:hide", "true");
651 // The following fields will only be generated if the data isn't meant for a public feed
656 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
659 XML::addElement($doc, $author, "dfrn:birthday", $birthday);
662 // Only show contact details when we are allowed to
664 "SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
665 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
666 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
668 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
669 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
670 intval($owner['uid'])
672 if (DBM::is_result($r)) {
675 XML::addElement($doc, $author, "poco:displayName", $profile["name"]);
676 XML::addElement($doc, $author, "poco:updated", $namdate);
678 if (trim($profile["dob"]) > '0001-01-01') {
679 XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
682 XML::addElement($doc, $author, "poco:note", $profile["about"]);
683 XML::addElement($doc, $author, "poco:preferredUsername", $profile["nickname"]);
685 $savetz = date_default_timezone_get();
686 date_default_timezone_set($profile["timezone"]);
687 XML::addElement($doc, $author, "poco:utcOffset", date("P"));
688 date_default_timezone_set($savetz);
690 if (trim($profile["homepage"]) != "") {
691 $urls = $doc->createElement("poco:urls");
692 XML::addElement($doc, $urls, "poco:type", "homepage");
693 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
694 XML::addElement($doc, $urls, "poco:primary", "true");
695 $author->appendChild($urls);
698 if (trim($profile["pub_keywords"]) != "") {
699 $keywords = explode(",", $profile["pub_keywords"]);
701 foreach ($keywords as $keyword) {
702 XML::addElement($doc, $author, "poco:tags", trim($keyword));
706 if (trim($profile["xmpp"]) != "") {
707 $ims = $doc->createElement("poco:ims");
708 XML::addElement($doc, $ims, "poco:type", "xmpp");
709 XML::addElement($doc, $ims, "poco:value", $profile["xmpp"]);
710 XML::addElement($doc, $ims, "poco:primary", "true");
711 $author->appendChild($ims);
714 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
715 $element = $doc->createElement("poco:address");
717 XML::addElement($doc, $element, "poco:formatted", Profile::formatLocation($profile));
719 if (trim($profile["locality"]) != "") {
720 XML::addElement($doc, $element, "poco:locality", $profile["locality"]);
723 if (trim($profile["region"]) != "") {
724 XML::addElement($doc, $element, "poco:region", $profile["region"]);
727 if (trim($profile["country-name"]) != "") {
728 XML::addElement($doc, $element, "poco:country", $profile["country-name"]);
731 $author->appendChild($element);
739 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
741 * @param object $doc XML document
742 * @param string $element Element name for the author
743 * @param string $contact_url Link of the contact
744 * @param array $item Item elements
746 * @return object XML author object
747 * @todo Add type-hints
749 private static function addEntryAuthor($doc, $element, $contact_url, $item)
751 $contact = Contact::getDetailsByURL($contact_url, $item["uid"]);
753 $author = $doc->createElement($element);
754 XML::addElement($doc, $author, "name", $contact["name"]);
755 XML::addElement($doc, $author, "uri", $contact["url"]);
756 XML::addElement($doc, $author, "dfrn:handle", $contact["addr"]);
759 /// - Check real image type and image size
760 /// - Check which of these boths elements we should use
763 "type" => "image/jpeg",
765 "media:height" => 80,
766 "href" => $contact["photo"]];
767 XML::addElement($doc, $author, "link", "", $attributes);
771 "type" => "image/jpeg",
773 "media:height" => 80,
774 "href" => $contact["photo"]];
775 XML::addElement($doc, $author, "link", "", $attributes);
781 * @brief Adds the activity elements
783 * @param object $doc XML document
784 * @param string $element Element name for the activity
785 * @param string $activity activity value
787 * @return object XML activity object
788 * @todo Add type-hints
790 private static function createActivity($doc, $element, $activity)
793 $entry = $doc->createElement($element);
795 $r = XML::parseString($activity, false);
800 XML::addElement($doc, $entry, "activity:object-type", $r->type);
803 XML::addElement($doc, $entry, "id", $r->id);
806 XML::addElement($doc, $entry, "title", $r->title);
810 if (substr($r->link, 0, 1) == '<') {
811 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
812 $r->link = str_replace('&', '&', $r->link);
815 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
817 // XML does need a single element as root element so we add a dummy element here
818 $data = XML::parseString("<dummy>" . $r->link . "</dummy>", false);
819 if (is_object($data)) {
820 foreach ($data->link as $link) {
822 foreach ($link->attributes() as $parameter => $value) {
823 $attributes[$parameter] = $value;
825 XML::addElement($doc, $entry, "link", "", $attributes);
829 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
830 XML::addElement($doc, $entry, "link", "", $attributes);
834 XML::addElement($doc, $entry, "content", BBCode::convert($r->content), ["type" => "html"]);
844 * @brief Adds the elements for attachments
846 * @param object $doc XML document
847 * @param object $root XML root
848 * @param array $item Item element
850 * @return object XML attachment object
851 * @todo Add type-hints
853 private static function getAttachment($doc, $root, $item)
855 $arr = explode('[/attach],', $item['attach']);
857 foreach ($arr as $r) {
859 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
861 $attributes = ["rel" => "enclosure",
862 "href" => $matches[1],
863 "type" => $matches[3]];
865 if (intval($matches[2])) {
866 $attributes["length"] = intval($matches[2]);
869 if (trim($matches[4]) != "") {
870 $attributes["title"] = trim($matches[4]);
873 XML::addElement($doc, $root, "link", "", $attributes);
880 * @brief Adds the "entry" elements for the DFRN protocol
882 * @param object $doc XML document
883 * @param string $type "text" or "html"
884 * @param array $item Item element
885 * @param array $owner Owner record
886 * @param bool $comment Trigger the sending of the "comment" element
887 * @param int $cid Contact ID of the recipient
888 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
890 * @return object XML entry object
891 * @todo Add type-hints
893 private static function entry($doc, $type, $item, $owner, $comment = false, $cid = 0, $single = false)
897 if (!$item['parent']) {
901 if ($item['deleted']) {
902 $attributes = ["ref" => $item['uri'], "when" => DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM)];
903 return XML::createElement($doc, "at:deleted-entry", "", $attributes);
907 $entry = $doc->createElement("entry");
909 $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry');
910 $doc->appendChild($entry);
912 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
913 $entry->setAttribute("xmlns:at", NAMESPACE_TOMB);
914 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
915 $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
916 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
917 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
918 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
919 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
920 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
923 if ($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid']) {
924 $body = Item::fixPrivatePhotos($item['body'], $owner['uid'], $item, $cid);
926 $body = $item['body'];
929 // Remove the abstract element. It is only locally important.
930 $body = BBCode::stripAbstract($body);
933 if ($type == 'html') {
936 if ($item['title'] != "") {
937 $htmlbody = "[b]".$item['title']."[/b]\n\n".$htmlbody;
940 $htmlbody = BBCode::convert($htmlbody, false, 7);
943 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
944 $entry->appendChild($author);
946 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
947 $entry->appendChild($dfrnowner);
949 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
950 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
951 $parent = q("SELECT `guid`,`plink` FROM `item` WHERE `uri` = '%s' AND `uid` = %d", dbesc($parent_item), intval($item['uid']));
952 $attributes = ["ref" => $parent_item, "type" => "text/html",
953 "href" => $parent[0]['plink'],
954 "dfrn:diaspora_guid" => $parent[0]['guid']];
955 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
958 // Add conversation data. This is used for OStatus
959 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
960 $conversation_uri = $conversation_href;
962 if (isset($parent_item)) {
963 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $item['parent-uri']);
964 if (DBM::is_result($r)) {
965 if ($r['conversation-uri'] != '') {
966 $conversation_uri = $r['conversation-uri'];
968 if ($r['conversation-href'] != '') {
969 $conversation_href = $r['conversation-href'];
975 "href" => $conversation_href,
976 "ref" => $conversation_uri];
978 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
980 XML::addElement($doc, $entry, "id", $item["uri"]);
981 XML::addElement($doc, $entry, "title", $item["title"]);
983 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"] . "+00:00", DateTimeFormat::ATOM));
984 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"] . "+00:00", DateTimeFormat::ATOM));
986 // "dfrn:env" is used to read the content
987 XML::addElement($doc, $entry, "dfrn:env", base64url_encode($body, true));
989 // The "content" field is not read by the receiver. We could remove it when the type is "text"
990 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
991 XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
993 // We save this value in "plink". Maybe we should read it from there as well?
999 ["rel" => "alternate", "type" => "text/html",
1000 "href" => System::baseUrl() . "/display/" . $item["guid"]]
1003 // "comment-allow" is some old fashioned stuff for old Friendica versions.
1004 // It is included in the rewritten code for completeness
1006 XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
1009 if ($item['location']) {
1010 XML::addElement($doc, $entry, "dfrn:location", $item['location']);
1013 if ($item['coord']) {
1014 XML::addElement($doc, $entry, "georss:point", $item['coord']);
1017 if (($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])) {
1018 XML::addElement($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
1021 if ($item['extid']) {
1022 XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
1025 if ($item['bookmark']) {
1026 XML::addElement($doc, $entry, "dfrn:bookmark", "true");
1030 XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
1033 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
1035 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
1036 // It is needed for relayed comments to Diaspora.
1037 if ($item['signed_text']) {
1038 $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer']]));
1039 XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
1042 XML::addElement($doc, $entry, "activity:verb", self::constructVerb($item));
1044 if ($item['object-type'] != "") {
1045 XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
1046 } elseif ($item['id'] == $item['parent']) {
1047 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1049 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
1052 $actobj = self::createActivity($doc, "activity:object", $item['object']);
1054 $entry->appendChild($actobj);
1057 $actarg = self::createActivity($doc, "activity:target", $item['target']);
1059 $entry->appendChild($actarg);
1062 $tags = Item::getFeedTags($item);
1065 foreach ($tags as $t) {
1066 if (($type != 'html') || ($t[0] != "@")) {
1067 XML::addElement($doc, $entry, "category", "", ["scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]]);
1073 foreach ($tags as $t) {
1075 $mentioned[$t[1]] = $t[1];
1080 foreach ($mentioned as $mention) {
1082 "SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1083 intval($owner["uid"]),
1084 dbesc(normalise_link($mention))
1087 if (DBM::is_result($r) && ($r[0]["forum"] || $r[0]["prv"])) {
1093 ["rel" => "mentioned",
1094 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1103 ["rel" => "mentioned",
1104 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1110 self::getAttachment($doc, $entry, $item);
1116 * @brief encrypts data via AES
1118 * @param string $data The data that is to be encrypted
1119 * @param string $key The AES key
1121 * @return string encrypted data
1123 private static function aesEncrypt($data, $key)
1125 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1129 * @brief decrypts data via AES
1131 * @param string $encrypted The encrypted data
1132 * @param string $key The AES key
1134 * @return string decrypted data
1136 public static function aesDecrypt($encrypted, $key)
1138 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1142 * @brief Delivers the atom content to the contacts
1144 * @param array $owner Owner record
1145 * @param array $contact Contact record of the receiver
1146 * @param string $atom Content that will be transmitted
1147 * @param bool $dissolve (to be documented)
1149 * @return int Deliver status. -1 means an error.
1150 * @todo Add array type-hint for $owner, $contact
1152 public static function deliver($owner, $contact, $atom, $dissolve = false)
1156 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1158 if ($contact['duplex'] && $contact['dfrn-id']) {
1159 $idtosend = '0:' . $orig_id;
1161 if ($contact['duplex'] && $contact['issued-id']) {
1162 $idtosend = '1:' . $orig_id;
1165 $rino = Config::get('system', 'rino_encrypt');
1166 $rino = intval($rino);
1168 logger("Local rino version: ". $rino, LOGGER_DEBUG);
1170 $ssl_val = intval(Config::get('system', 'ssl_policy'));
1174 case SSL_POLICY_FULL:
1175 $ssl_policy = 'full';
1177 case SSL_POLICY_SELFSIGN:
1178 $ssl_policy = 'self';
1180 case SSL_POLICY_NONE:
1182 $ssl_policy = 'none';
1186 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1188 logger('dfrn_deliver: ' . $url);
1190 $ret = Network::curl($url);
1192 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1193 return -2; // timed out
1196 $xml = $ret['body'];
1198 $curl_stat = $a->get_curl_code();
1200 return -3; // timed out
1203 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1209 if (strpos($xml, '<?xml') === false) {
1210 logger('dfrn_deliver: no valid XML returned');
1211 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1215 $res = XML::parseString($xml);
1217 if ((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id))) {
1218 return (($res->status) ? $res->status : 3);
1222 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1223 $challenge = hex2bin((string) $res->challenge);
1224 $perm = (($res->perm) ? $res->perm : null);
1225 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1226 $rino_remote_version = intval($res->rino);
1227 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1229 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
1231 if ($owner['page-flags'] == PAGE_PRVGROUP) {
1235 $final_dfrn_id = '';
1238 if ((($perm == 'rw') && (! intval($contact['writable'])))
1239 || (($perm == 'r') && (intval($contact['writable'])))
1242 "update contact set writable = %d where id = %d",
1243 intval(($perm == 'rw') ? 1 : 0),
1244 intval($contact['id'])
1246 $contact['writable'] = (string) 1 - intval($contact['writable']);
1250 if (($contact['duplex'] && strlen($contact['pubkey']))
1251 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1252 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
1254 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
1255 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
1257 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
1258 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
1261 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1263 if (strpos($final_dfrn_id, ':') == 1) {
1264 $final_dfrn_id = substr($final_dfrn_id, 2);
1267 if ($final_dfrn_id != $orig_id) {
1268 logger('dfrn_deliver: wrong dfrn_id.');
1269 // did not decode properly - cannot trust this site
1273 $postvars['dfrn_id'] = $idtosend;
1274 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1276 $postvars['dissolve'] = '1';
1280 if ((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1281 $postvars['data'] = $atom;
1282 $postvars['perm'] = 'rw';
1284 $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
1285 $postvars['perm'] = 'r';
1288 $postvars['ssl_policy'] = $ssl_policy;
1291 $postvars['page'] = $page;
1295 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1296 logger('rino version: '. $rino_remote_version);
1298 switch ($rino_remote_version) {
1300 $key = openssl_random_pseudo_bytes(16);
1301 $data = self::aesEncrypt($postvars['data'], $key);
1304 logger("rino: invalid requested version '$rino_remote_version'");
1308 $postvars['rino'] = $rino_remote_version;
1309 $postvars['data'] = bin2hex($data);
1311 if ($dfrn_version >= 2.1) {
1312 if (($contact['duplex'] && strlen($contact['pubkey']))
1313 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1314 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
1316 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1318 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1321 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1322 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1324 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1328 logger('md5 rawkey ' . md5($postvars['key']));
1330 $postvars['key'] = bin2hex($postvars['key']);
1334 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), LOGGER_DATA);
1336 $xml = Network::post($contact['notify'], $postvars);
1338 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1340 $curl_stat = $a->get_curl_code();
1341 if ((!$curl_stat) || (!strlen($xml))) {
1342 return -9; // timed out
1345 if (($curl_stat == 503) && (stristr($a->get_curl_headers(), 'retry-after'))) {
1349 if (strpos($xml, '<?xml') === false) {
1350 logger('dfrn_deliver: phase 2: no valid XML returned');
1351 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1355 $res = XML::parseString($xml);
1357 if (!isset($res->status)) {
1361 if (!empty($res->message)) {
1362 logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1365 if ($res->status == 200) {
1366 Contact::unmarkForArchival($contact);
1369 return intval($res->status);
1373 * @brief Delivers items to the contacts via the Diaspora transport layer
1375 * @param array $owner Owner record
1376 * @param array $contact Contact record of the receiver
1377 * @param array $items Items that will be transmitted
1379 * @return int HTTP Deliver status
1381 public static function buildAndTransmit($owner, $contact, $items)
1385 // Currently disabled, at first we will not use the batch delivery
1386 // $public_batch = !$items[0]['private'];
1387 $public_batch = false;
1389 $msg = DFRN::entries($items, $owner);
1391 $fcontact = Diaspora::personByHandle($contact['addr']);
1392 if (empty($fcontact)) {
1393 logger("unable to find contact details");
1397 $envelope = Diaspora::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $fcontact['pubkey'], $public_batch);
1399 $dest_url = ($public_batch ? $fcontact["batch"] : $contact["notify"]);
1401 $content_type = ($public_batch ? "application/magic-envelope+xml" : "application/json");
1403 $ret = Network::post($dest_url, $envelope, ["Content-Type: ".$content_type]);
1405 /// @ToDo: Add better treatment of return codes
1406 return $a->get_curl_code();
1410 * @brief Add new birthday event for this person
1412 * @param array $contact Contact record
1413 * @param string $birthday Birthday of the contact
1415 * @todo Add array type-hint for $contact
1417 private static function birthdayEvent($contact, $birthday)
1419 // Check for duplicates
1421 "SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1422 intval($contact["uid"]),
1423 intval($contact["id"]),
1424 dbesc(DateTimeFormat::utc($birthday)),
1428 if (DBM::is_result($r)) {
1432 logger("updating birthday: ".$birthday." for contact ".$contact["id"]);
1434 $bdtext = L10n::t("%s\'s birthday", $contact["name"]);
1435 $bdtext2 = L10n::t("Happy Birthday %s", " [url=".$contact["url"]."]".$contact["name"]."[/url]");
1438 "INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1439 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1440 intval($contact["uid"]),
1441 intval($contact["id"]),
1442 dbesc(DateTimeFormat::utcNow()),
1443 dbesc(DateTimeFormat::utcNow()),
1444 dbesc(DateTimeFormat::utc($birthday)),
1445 dbesc(DateTimeFormat::utc($birthday . " + 1 day ")),
1453 * @brief Fetch the author data from head or entry items
1455 * @param object $xpath XPath object
1456 * @param object $context In which context should the data be searched
1457 * @param array $importer Record of the importer user mixed with contact of the content
1458 * @param string $element Element name from which the data is fetched
1459 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1460 * @param string $xml optional, default empty
1462 * @return array Relevant data of the author
1463 * @todo Find good type-hints for all parameter
1465 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
1468 $author["name"] = $xpath->evaluate($element."/atom:name/text()", $context)->item(0)->nodeValue;
1469 $author["link"] = $xpath->evaluate($element."/atom:uri/text()", $context)->item(0)->nodeValue;
1471 $contact_old = dba::fetch_first("SELECT `id`, `uid`, `url`, `network`, `avatar-date`, `avatar`, `name-date`, `uri-date`, `addr`,
1472 `name`, `nick`, `about`, `location`, `keywords`, `xmpp`, `bdyear`, `bd`, `hidden`, `contact-type`
1473 FROM `contact` WHERE `uid` = ? AND `nurl` = ? AND `network` != ?",
1474 $importer["importer_uid"],
1475 normalise_link($author["link"]),
1479 if (DBM::is_result($contact_old)) {
1480 $author["contact-id"] = $contact_old["id"];
1481 $author["network"] = $contact_old["network"];
1484 logger("Contact ".$author["link"]." wasn't found for user ".$importer["importer_uid"]." XML: ".$xml, LOGGER_DEBUG);
1487 $author["contact-id"] = $importer["id"];
1488 $author["network"] = $importer["network"];
1492 // Until now we aren't serving different sizes - but maybe later
1494 /// @todo check if "avatar" or "photo" would be the best field in the specification
1495 $avatars = $xpath->query($element."/atom:link[@rel='avatar']", $context);
1496 foreach ($avatars as $avatar) {
1499 foreach ($avatar->attributes as $attributes) {
1500 /// @TODO Rewrite these similar if () to one switch
1501 if ($attributes->name == "href") {
1502 $href = $attributes->textContent;
1504 if ($attributes->name == "width") {
1505 $width = $attributes->textContent;
1507 if ($attributes->name == "updated") {
1508 $author["avatar-date"] = $attributes->textContent;
1511 if (($width > 0) && ($href != "")) {
1512 $avatarlist[$width] = $href;
1515 if (count($avatarlist) > 0) {
1516 krsort($avatarlist);
1517 $author["avatar"] = current($avatarlist);
1520 if (DBM::is_result($contact_old) && !$onlyfetch) {
1521 logger("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", LOGGER_DEBUG);
1523 $poco = ["url" => $contact_old["url"]];
1525 // When was the last change to name or uri?
1526 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1527 foreach ($name_element->attributes as $attributes) {
1528 if ($attributes->name == "updated") {
1529 $poco["name-date"] = $attributes->textContent;
1533 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1534 foreach ($link_element->attributes as $attributes) {
1535 if ($attributes->name == "updated") {
1536 $poco["uri-date"] = $attributes->textContent;
1540 // Update contact data
1541 $value = $xpath->evaluate($element . "/dfrn:handle/text()", $context)->item(0)->nodeValue;
1543 $poco["addr"] = $value;
1546 $value = $xpath->evaluate($element . "/poco:displayName/text()", $context)->item(0)->nodeValue;
1548 $poco["name"] = $value;
1551 $value = $xpath->evaluate($element . "/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
1553 $poco["nick"] = $value;
1556 $value = $xpath->evaluate($element . "/poco:note/text()", $context)->item(0)->nodeValue;
1558 $poco["about"] = $value;
1561 $value = $xpath->evaluate($element . "/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
1563 $poco["location"] = $value;
1566 /// @todo Only search for elements with "poco:type" = "xmpp"
1567 $value = $xpath->evaluate($element . "/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
1569 $poco["xmpp"] = $value;
1572 /// @todo Add support for the following fields that we don't support by now in the contact table:
1573 /// - poco:utcOffset
1579 // If the "hide" element is present then the profile isn't searchable.
1580 $hide = intval($xpath->evaluate($element . "/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
1582 logger("Hidden status for contact " . $contact_old["url"] . ": " . $hide, LOGGER_DEBUG);
1584 // If the contact isn't searchable then set the contact to "hidden".
1585 // Problem: This can be manually overridden by the user.
1587 $contact_old["hidden"] = true;
1590 // Save the keywords into the contact table
1592 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1593 foreach ($tagelements as $tag) {
1594 $tags[$tag->nodeValue] = $tag->nodeValue;
1598 $poco["keywords"] = implode(", ", $tags);
1601 // "dfrn:birthday" contains the birthday converted to UTC
1602 $birthday = $xpath->evaluate($element . "/dfrn:birthday/text()", $context)->item(0)->nodeValue;
1604 if (strtotime($birthday) > time()) {
1605 $bd_timestamp = strtotime($birthday);
1607 $poco["bdyear"] = date("Y", $bd_timestamp);
1610 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1611 $value = $xpath->evaluate($element . "/poco:birthday/text()", $context)->item(0)->nodeValue;
1613 if (!in_array($value, ["", "0000-00-00", "0001-01-01"])) {
1614 $bdyear = date("Y");
1615 $value = str_replace("0000", $bdyear, $value);
1617 if (strtotime($value) < time()) {
1618 $value = str_replace($bdyear, $bdyear + 1, $value);
1619 $bdyear = $bdyear + 1;
1622 $poco["bd"] = $value;
1625 $contact = array_merge($contact_old, $poco);
1627 if ($contact_old["bdyear"] != $contact["bdyear"]) {
1628 self::birthdayEvent($contact, $birthday);
1631 // Get all field names
1633 foreach ($contact_old as $field => $data) {
1634 $fields[$field] = $data;
1637 unset($fields["id"]);
1638 unset($fields["uid"]);
1639 unset($fields["url"]);
1640 unset($fields["avatar-date"]);
1641 unset($fields["avatar"]);
1642 unset($fields["name-date"]);
1643 unset($fields["uri-date"]);
1646 // Update check for this field has to be done differently
1647 $datefields = ["name-date", "uri-date"];
1648 foreach ($datefields as $field) {
1649 if (strtotime($contact[$field]) > strtotime($contact_old[$field])) {
1650 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1655 foreach ($fields as $field => $data) {
1656 if ($contact[$field] != $contact_old[$field]) {
1657 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1663 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1666 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1667 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1668 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1669 WHERE `id` = %d AND `network` = '%s'",
1670 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
1671 dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1672 dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
1673 dbesc(DBM::date($contact["name-date"])), dbesc(DBM::date($contact["uri-date"])),
1674 intval($contact["id"]), dbesc($contact["network"])
1678 Contact::updateAvatar(
1680 $importer['importer_uid'],
1682 (strtotime($contact['avatar-date']) > strtotime($contact_old['avatar-date']) || ($author['avatar'] != $contact_old['avatar']))
1686 * The generation is a sign for the reliability of the provided data.
1687 * It is used in the socgraph.php to prevent that old contact data
1688 * that was relayed over several servers can overwrite contact
1689 * data that we received directly.
1692 $poco["generation"] = 2;
1693 $poco["photo"] = $author["avatar"];
1694 $poco["hide"] = $hide;
1695 $poco["contact-type"] = $contact["contact-type"];
1696 $gcid = GContact::update($poco);
1698 GContact::link($gcid, $importer["importer_uid"], $contact["id"]);
1705 * @brief Transforms activity objects into an XML string
1707 * @param object $xpath XPath object
1708 * @param object $activity Activity object
1709 * @param string $element element name
1711 * @return string XML string
1712 * @todo Find good type-hints for all parameter
1714 private static function transformActivity($xpath, $activity, $element)
1716 if (!is_object($activity)) {
1720 $obj_doc = new DOMDocument("1.0", "utf-8");
1721 $obj_doc->formatOutput = true;
1723 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1725 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1726 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1728 $id = $xpath->query("atom:id", $activity)->item(0);
1729 if (is_object($id)) {
1730 $obj_element->appendChild($obj_doc->importNode($id, true));
1733 $title = $xpath->query("atom:title", $activity)->item(0);
1734 if (is_object($title)) {
1735 $obj_element->appendChild($obj_doc->importNode($title, true));
1738 $links = $xpath->query("atom:link", $activity);
1739 if (is_object($links)) {
1740 foreach ($links as $link) {
1741 $obj_element->appendChild($obj_doc->importNode($link, true));
1745 $content = $xpath->query("atom:content", $activity)->item(0);
1746 if (is_object($content)) {
1747 $obj_element->appendChild($obj_doc->importNode($content, true));
1750 $obj_doc->appendChild($obj_element);
1752 $objxml = $obj_doc->saveXML($obj_element);
1754 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1755 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1760 * @brief Processes the mail elements
1762 * @param object $xpath XPath object
1763 * @param object $mail mail elements
1764 * @param array $importer Record of the importer user mixed with contact of the content
1766 * @todo Find good type-hints for all parameter
1768 private static function processMail($xpath, $mail, $importer)
1770 logger("Processing mails");
1772 /// @TODO Rewrite this to one statement
1774 $msg["uid"] = $importer["importer_uid"];
1775 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1776 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1777 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1778 $msg["contact-id"] = $importer["id"];
1779 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1780 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1781 $msg["created"] = DateTimeFormat::utc($xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue);
1782 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1783 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1785 $msg["replied"] = 0;
1787 dba::insert('mail', $msg);
1789 // send notifications.
1790 /// @TODO Arange this mess
1792 "type" => NOTIFY_MAIL,
1793 "notify_flags" => $importer["notify-flags"],
1794 "language" => $importer["language"],
1795 "to_name" => $importer["username"],
1796 "to_email" => $importer["email"],
1797 "uid" => $importer["importer_uid"],
1799 "source_name" => $msg["from-name"],
1800 "source_link" => $importer["url"],
1801 "source_photo" => $importer["thumb"],
1802 "verb" => ACTIVITY_POST,
1806 notification($notif_params);
1808 logger("Mail is processed, notification was sent.");
1812 * @brief Processes the suggestion elements
1814 * @param object $xpath XPath object
1815 * @param object $suggestion suggestion elements
1816 * @param array $importer Record of the importer user mixed with contact of the content
1818 * @todo Find good type-hints for all parameter
1820 private static function processSuggestion($xpath, $suggestion, $importer)
1824 logger("Processing suggestions");
1826 /// @TODO Rewrite this to one statement
1828 $suggest["uid"] = $importer["importer_uid"];
1829 $suggest["cid"] = $importer["id"];
1830 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1831 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1832 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1833 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1834 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1836 // Does our member already have a friend matching this description?
1839 "SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1840 dbesc($suggest["name"]),
1841 dbesc(normalise_link($suggest["url"])),
1842 intval($suggest["uid"])
1846 * The valid result means the friend we're about to send a friend
1847 * suggestion already has them in their contact, which means no further
1848 * action is required.
1850 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1852 if (DBM::is_result($r)) {
1856 // Do we already have an fcontact record for this person?
1860 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1861 dbesc($suggest["url"]),
1862 dbesc($suggest["name"]),
1863 dbesc($suggest["request"])
1865 if (DBM::is_result($r)) {
1868 // OK, we do. Do we already have an introduction for this person ?
1870 "SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1871 intval($suggest["uid"]),
1876 * The valid result means the friend we're about to send a friend
1877 * suggestion already has them in their contact, which means no further
1878 * action is required.
1880 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1882 if (DBM::is_result($r)) {
1888 "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1889 dbesc($suggest["name"]),
1890 dbesc($suggest["url"]),
1891 dbesc($suggest["photo"]),
1892 dbesc($suggest["request"])
1896 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1897 dbesc($suggest["url"]),
1898 dbesc($suggest["name"]),
1899 dbesc($suggest["request"])
1903 * If no record in fcontact is found, below INSERT statement will not
1904 * link an introduction to it.
1906 if (!DBM::is_result($r)) {
1907 // database record did not get created. Quietly give up.
1913 $hash = random_string();
1916 "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1917 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1918 intval($suggest["uid"]),
1920 intval($suggest["cid"]),
1921 dbesc($suggest["body"]),
1923 dbesc(DateTimeFormat::utcNow()),
1929 "type" => NOTIFY_SUGGEST,
1930 "notify_flags" => $importer["notify-flags"],
1931 "language" => $importer["language"],
1932 "to_name" => $importer["username"],
1933 "to_email" => $importer["email"],
1934 "uid" => $importer["importer_uid"],
1936 "link" => System::baseUrl()."/notifications/intros",
1937 "source_name" => $importer["name"],
1938 "source_link" => $importer["url"],
1939 "source_photo" => $importer["photo"],
1940 "verb" => ACTIVITY_REQ_FRIEND,
1948 * @brief Processes the relocation elements
1950 * @param object $xpath XPath object
1951 * @param object $relocation relocation elements
1952 * @param array $importer Record of the importer user mixed with contact of the content
1954 * @todo Find good type-hints for all parameter
1956 private static function processRelocation($xpath, $relocation, $importer)
1958 logger("Processing relocations");
1960 /// @TODO Rewrite this to one statement
1962 $relocate["uid"] = $importer["importer_uid"];
1963 $relocate["cid"] = $importer["id"];
1964 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1965 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
1966 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1967 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
1968 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1969 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1970 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1971 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1972 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1973 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1974 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1975 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1977 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
1978 $relocate["avatar"] = $relocate["photo"];
1981 if ($relocate["addr"] == "") {
1982 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
1987 "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
1988 intval($importer["id"]),
1989 intval($importer["importer_uid"])
1992 if (!DBM::is_result($r)) {
1993 logger("Query failed to execute, no result returned in " . __FUNCTION__);
1999 // Update the gcontact entry
2000 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
2003 "UPDATE `gcontact` SET
2012 WHERE `nurl` = '%s';",
2013 dbesc($relocate["name"]),
2014 dbesc($relocate["avatar"]),
2015 dbesc($relocate["url"]),
2016 dbesc(normalise_link($relocate["url"])),
2017 dbesc($relocate["addr"]),
2018 dbesc($relocate["addr"]),
2019 dbesc($relocate["notify"]),
2020 dbesc($relocate["server_url"]),
2021 dbesc(normalise_link($old["url"]))
2024 // Update the contact table. We try to find every entry.
2026 "UPDATE `contact` SET
2036 `site-pubkey` = '%s'
2037 WHERE (`id` = %d AND `uid` = %d) OR (`nurl` = '%s');",
2038 dbesc($relocate["name"]),
2039 dbesc($relocate["avatar"]),
2040 dbesc($relocate["url"]),
2041 dbesc(normalise_link($relocate["url"])),
2042 dbesc($relocate["addr"]),
2043 dbesc($relocate["request"]),
2044 dbesc($relocate["confirm"]),
2045 dbesc($relocate["notify"]),
2046 dbesc($relocate["poll"]),
2047 dbesc($relocate["sitepubkey"]),
2048 intval($importer["id"]),
2049 intval($importer["importer_uid"]),
2050 dbesc(normalise_link($old["url"]))
2053 Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
2060 /// @todo This is an extreme performance killer
2062 'owner-link' => [$old["url"], $relocate["url"]],
2063 'author-link' => [$old["url"], $relocate["url"]],
2064 //'owner-avatar' => array($old["photo"], $relocate["photo"]),
2065 //'author-avatar' => array($old["photo"], $relocate["photo"]),
2067 foreach ($fields as $n => $f) {
2069 "SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
2072 intval($importer["importer_uid"])
2075 if (DBM::is_result($r)) {
2077 "UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
2082 intval($importer["importer_uid"])
2092 /// merge with current record, current contents have priority
2093 /// update record, set url-updated
2094 /// update profile photos
2095 /// schedule a scan?
2100 * @brief Updates an item
2102 * @param array $current the current item record
2103 * @param array $item the new item record
2104 * @param array $importer Record of the importer user mixed with contact of the content
2105 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2107 * @todo set proper type-hints (array?)
2109 private static function updateContent($current, $item, $importer, $entrytype)
2113 if (self::isEditedTimestampNewer($current, $item)) {
2114 // do not accept (ignore) an earlier edit than one we currently have.
2115 if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
2119 $fields = ['title' => defaults($item, 'title', ''), 'body' => defaults($item, 'body', ''),
2120 'tag' => defaults($item, 'tag', ''), 'changed' => DateTimeFormat::utcNow(),
2121 'edited' => DateTimeFormat::utc($item["edited"])];
2123 $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
2124 Item::update($fields, $condition);
2128 if ($entrytype == DFRN_REPLY_RC) {
2129 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $current["id"]);
2136 * @brief Detects the entry type of the item
2138 * @param array $importer Record of the importer user mixed with contact of the content
2139 * @param array $item the new item record
2141 * @return int Is it a toplevel entry, a comment or a relayed comment?
2142 * @todo set proper type-hints (array?)
2144 private static function getEntryType($importer, $item)
2146 if ($item["parent-uri"] != $item["uri"]) {
2149 if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
2152 logger("possible community action");
2154 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2157 // was the top-level post for this action written by somebody on this site?
2158 // Specifically, the recipient?
2160 $is_a_remote_action = false;
2163 "SELECT `item`.`parent-uri` FROM `item`
2164 WHERE `item`.`uri` = '%s'
2166 dbesc($item["parent-uri"])
2168 if (DBM::is_result($r)) {
2170 "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2171 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2172 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2173 AND `item`.`uid` = %d
2176 dbesc($r[0]["parent-uri"]),
2177 dbesc($r[0]["parent-uri"]),
2178 dbesc($r[0]["parent-uri"]),
2179 intval($importer["importer_uid"])
2181 if (DBM::is_result($r)) {
2182 $is_a_remote_action = true;
2187 * Does this have the characteristics of a community or private group action?
2188 * If it's an action to a wall post on a community/prvgroup page it's a
2189 * valid community action. Also forum_mode makes it valid for sure.
2190 * If neither, it's not.
2192 if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2193 $is_a_remote_action = false;
2194 logger("not a community action");
2197 if ($is_a_remote_action) {
2198 return DFRN_REPLY_RC;
2203 return DFRN_TOP_LEVEL;
2208 * @brief Send a "poke"
2210 * @param array $item the new item record
2211 * @param array $importer Record of the importer user mixed with contact of the content
2212 * @param int $posted_id The record number of item record that was just posted
2214 * @todo set proper type-hints (array?)
2216 private static function doPoke($item, $importer, $posted_id)
2218 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2222 $xo = XML::parseString($item["object"], false);
2224 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2225 // somebody was poked/prodded. Was it me?
2226 foreach ($xo->link as $l) {
2227 $atts = $l->attributes();
2228 switch ($atts["rel"]) {
2230 $Blink = $atts["href"];
2237 if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2238 // send a notification
2241 "type" => NOTIFY_POKE,
2242 "notify_flags" => $importer["notify-flags"],
2243 "language" => $importer["language"],
2244 "to_name" => $importer["username"],
2245 "to_email" => $importer["email"],
2246 "uid" => $importer["importer_uid"],
2248 "link" => System::baseUrl()."/display/".urlencode(Item::getGuidById($posted_id)),
2249 "source_name" => stripslashes($item["author-name"]),
2250 "source_link" => $item["author-link"],
2251 "source_photo" => ((link_compare($item["author-link"], $importer["url"]))
2252 ? $importer["thumb"] : $item["author-avatar"]),
2253 "verb" => $item["verb"],
2254 "otype" => "person",
2255 "activity" => $verb,
2256 "parent" => $item["parent"]]
2263 * @brief Processes several actions, depending on the verb
2265 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2266 * @param array $importer Record of the importer user mixed with contact of the content
2267 * @param array $item the new item record
2268 * @param bool $is_like Is the verb a "like"?
2270 * @return bool Should the processing of the entries be continued?
2271 * @todo set proper type-hints (array?)
2273 private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2275 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2277 if (($entrytype == DFRN_TOP_LEVEL)) {
2278 // The filling of the the "contact" variable is done for legcy reasons
2279 // The functions below are partly used by ostatus.php as well - where we have this variable
2280 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2282 $nickname = $contact["nick"];
2284 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2285 // This function once was responsible for DFRN and OStatus.
2286 if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2287 logger("New follower");
2288 Contact::addRelationship($importer, $contact, $item, $nickname);
2291 if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2292 logger("Lost follower");
2293 Contact::removeFollower($importer, $contact, $item);
2296 if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2297 logger("New friend request");
2298 Contact::addRelationship($importer, $contact, $item, $nickname, true);
2301 if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2302 logger("Lost sharer");
2303 Contact::removeSharer($importer, $contact, $item);
2307 if (($item["verb"] == ACTIVITY_LIKE)
2308 || ($item["verb"] == ACTIVITY_DISLIKE)
2309 || ($item["verb"] == ACTIVITY_ATTEND)
2310 || ($item["verb"] == ACTIVITY_ATTENDNO)
2311 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
2314 $item["type"] = "activity";
2315 $item["gravity"] = GRAVITY_LIKE;
2316 // only one like or dislike per person
2317 // splitted into two queries for performance issues
2319 "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `parent-uri` = '%s' AND NOT `deleted` LIMIT 1",
2320 intval($item["uid"]),
2321 dbesc($item["author-link"]),
2322 dbesc($item["verb"]),
2323 dbesc($item["parent-uri"])
2325 if (DBM::is_result($r)) {
2330 "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `thr-parent` = '%s' AND NOT `deleted` LIMIT 1",
2331 intval($item["uid"]),
2332 dbesc($item["author-link"]),
2333 dbesc($item["verb"]),
2334 dbesc($item["parent-uri"])
2336 if (DBM::is_result($r)) {
2343 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2344 $xo = XML::parseString($item["object"], false);
2345 $xt = XML::parseString($item["target"], false);
2347 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2349 "SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2351 intval($importer["importer_uid"])
2354 if (!DBM::is_result($r)) {
2355 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2359 // extract tag, if not duplicate, add to parent item
2361 if (!stristr($r[0]["tag"], trim($xo->content))) {
2362 $tag = $r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2363 Item::update(['tag' => $tag], ['id' => $r[0]["id"]]);
2373 * @brief Processes the link elements
2375 * @param object $links link elements
2376 * @param array $item the item record
2378 * @todo set proper type-hints
2380 private static function parseLinks($links, &$item)
2387 foreach ($links as $link) {
2388 foreach ($link->attributes as $attributes) {
2389 switch ($attributes->name) {
2390 case "href" : $href = $attributes->textContent; break;
2391 case "rel" : $rel = $attributes->textContent; break;
2392 case "type" : $type = $attributes->textContent; break;
2393 case "length": $length = $attributes->textContent; break;
2394 case "title" : $title = $attributes->textContent; break;
2397 if (($rel != "") && ($href != "")) {
2400 $item["plink"] = $href;
2404 if (strlen($item["attach"])) {
2405 $item["attach"] .= ",";
2408 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2416 * @brief Processes the entry elements which contain the items and comments
2418 * @param array $header Array of the header elements that always stay the same
2419 * @param object $xpath XPath object
2420 * @param object $entry entry elements
2421 * @param array $importer Record of the importer user mixed with contact of the content
2422 * @param object $xml xml
2424 * @todo Add type-hints
2426 private static function processEntry($header, $xpath, $entry, $importer, $xml)
2428 logger("Processing entries");
2432 $item["protocol"] = PROTOCOL_DFRN;
2434 $item["source"] = $xml;
2437 $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
2439 $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
2441 $current = dba::selectFirst('item',
2442 ['id', 'uid', 'edited', 'body'],
2443 ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
2445 // Is there an existing item?
2446 if (DBM::is_result($current) && !self::isEditedTimestampNewer($current, $item)) {
2447 logger("Item ".$item["uri"]." (".$item['edited'].") already existed.", LOGGER_DEBUG);
2452 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2454 $item["owner-name"] = $owner["name"];
2455 $item["owner-link"] = $owner["link"];
2456 $item["owner-avatar"] = $owner["avatar"];
2459 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2461 $item["author-name"] = $author["name"];
2462 $item["author-link"] = $author["link"];
2463 $item["author-avatar"] = $author["avatar"];
2465 $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
2467 $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2469 $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
2470 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2471 // make sure nobody is trying to sneak some html tags by us
2472 $item["body"] = notags(base64url_decode($item["body"]));
2474 $item["body"] = BBCode::limitBodySize($item["body"]);
2476 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2477 if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
2478 $base_url = get_app()->get_baseurl();
2479 $item['body'] = reltoabs($item['body'], $base_url);
2481 $item['body'] = html2bb_video($item['body']);
2483 $item['body'] = OEmbed::HTML2BBCode($item['body']);
2485 $config = HTMLPurifier_Config::createDefault();
2486 $config->set('Cache.DefinitionImpl', null);
2488 // we shouldn't need a whitelist, because the bbcode converter
2489 // will strip out any unsupported tags.
2491 $purifier = new HTMLPurifier($config);
2492 $item['body'] = $purifier->purify($item['body']);
2494 $item['body'] = @HTML::toBBCode($item['body']);
2497 /// @todo We should check for a repeated post and if we know the repeated author.
2499 // We don't need the content element since "dfrn:env" is always present
2500 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2502 $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
2504 $georsspoint = $xpath->query("georss:point", $entry);
2506 $item["coord"] = $georsspoint->item(0)->nodeValue;
2509 $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
2511 $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
2513 if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true") {
2514 $item["bookmark"] = true;
2517 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2518 if ($notice_info && ($notice_info->length > 0)) {
2519 foreach ($notice_info->item(0)->attributes as $attributes) {
2520 if ($attributes->name == "source") {
2521 $item["app"] = strip_tags($attributes->textContent);
2526 $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
2528 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
2529 $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
2530 if ($dsprsig != "") {
2531 $item["dsprsig"] = $dsprsig;
2534 $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
2536 if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "") {
2537 $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
2540 $object = $xpath->query("activity:object", $entry)->item(0);
2541 $item["object"] = self::transformActivity($xpath, $object, "object");
2543 if (trim($item["object"]) != "") {
2544 $r = XML::parseString($item["object"], false);
2545 if (isset($r->type)) {
2546 $item["object-type"] = $r->type;
2550 $target = $xpath->query("activity:target", $entry)->item(0);
2551 $item["target"] = self::transformActivity($xpath, $target, "target");
2553 $categories = $xpath->query("atom:category", $entry);
2555 foreach ($categories as $category) {
2558 foreach ($category->attributes as $attributes) {
2559 if ($attributes->name == "term") {
2560 $term = $attributes->textContent;
2563 if ($attributes->name == "scheme") {
2564 $scheme = $attributes->textContent;
2568 if (($term != "") && ($scheme != "")) {
2569 $parts = explode(":", $scheme);
2570 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2571 $termhash = array_shift($parts);
2572 $termurl = implode(":", $parts);
2574 if (strlen($item["tag"])) {
2575 $item["tag"] .= ",";
2578 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2586 $links = $xpath->query("atom:link", $entry);
2588 self::parseLinks($links, $item);
2591 $item['conversation-uri'] = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
2593 $conv = $xpath->query('ostatus:conversation', $entry);
2594 if (is_object($conv->item(0))) {
2595 foreach ($conv->item(0)->attributes as $attributes) {
2596 if ($attributes->name == "ref") {
2597 $item['conversation-uri'] = $attributes->textContent;
2599 if ($attributes->name == "href") {
2600 $item['conversation-href'] = $attributes->textContent;
2605 // Is it a reply or a top level posting?
2606 $item["parent-uri"] = $item["uri"];
2608 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2609 if (is_object($inreplyto->item(0))) {
2610 foreach ($inreplyto->item(0)->attributes as $attributes) {
2611 if ($attributes->name == "ref") {
2612 $item["parent-uri"] = $attributes->textContent;
2617 // Get the type of the item (Top level post, reply or remote reply)
2618 $entrytype = self::getEntryType($importer, $item);
2620 // Now assign the rest of the values that depend on the type of the message
2621 if (in_array($entrytype, [DFRN_REPLY, DFRN_REPLY_RC])) {
2622 if (!isset($item["object-type"])) {
2623 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2626 if ($item["contact-id"] != $owner["contact-id"]) {
2627 $item["contact-id"] = $owner["contact-id"];
2630 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2631 $item["network"] = $owner["network"];
2634 if ($item["contact-id"] != $author["contact-id"]) {
2635 $item["contact-id"] = $author["contact-id"];
2638 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2639 $item["network"] = $author["network"];
2643 if ($entrytype == DFRN_REPLY_RC) {
2644 $item["type"] = "remote-comment";
2646 } elseif ($entrytype == DFRN_TOP_LEVEL) {
2647 if (!isset($item["object-type"])) {
2648 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2652 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2653 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2654 $ev = Event::fromBBCode($item["body"]);
2655 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2656 logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2657 $ev["cid"] = $importer["id"];
2658 $ev["uid"] = $importer["importer_uid"];
2659 $ev["uri"] = $item["uri"];
2660 $ev["edited"] = $item["edited"];
2661 $ev["private"] = $item["private"];
2662 $ev["guid"] = $item["guid"];
2665 "SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2666 dbesc($item["uri"]),
2667 intval($importer["importer_uid"])
2669 if (DBM::is_result($r)) {
2670 $ev["id"] = $r[0]["id"];
2673 $event_id = Event::store($ev);
2674 logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2680 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2681 logger("Exiting because 'processVerbs' told us so", LOGGER_DEBUG);
2685 // Update content if 'updated' changes
2686 if (DBM::is_result($current)) {
2687 if (self::updateContent($current, $item, $importer, $entrytype)) {
2688 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2690 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2695 if (in_array($entrytype, [DFRN_REPLY, DFRN_REPLY_RC])) {
2696 $posted_id = Item::insert($item);
2700 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2702 $item["id"] = $posted_id;
2705 "SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2707 intval($importer["importer_uid"])
2709 if (DBM::is_result($r)) {
2710 $parent = $r[0]["parent"];
2711 $parent_uri = $r[0]["parent-uri"];
2714 if ($posted_id && $parent && ($entrytype == DFRN_REPLY_RC)) {
2715 logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
2716 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $posted_id);
2721 } else { // $entrytype == DFRN_TOP_LEVEL
2722 if ($importer["readonly"]) {
2723 logger('ignoring read-only contact '.$importer["id"]);
2726 if ($importer["uid"] == 0) {
2727 logger("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", LOGGER_DEBUG);
2730 if (!link_compare($item["owner-link"], $importer["url"])) {
2732 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2733 * but otherwise there's a possible data mixup on the sender's system.
2734 * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2735 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2737 logger('Correcting item owner.', LOGGER_DEBUG);
2738 $item["owner-name"] = $importer["senderName"];
2739 $item["owner-link"] = $importer["url"];
2740 $item["owner-avatar"] = $importer["thumb"];
2743 if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2744 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2748 // This is my contact on another system, but it's really me.
2749 // Turn this into a wall post.
2750 $notify = Item::isRemoteSelf($importer, $item);
2752 $posted_id = Item::insert($item, false, $notify);
2754 logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2756 if (stristr($item["verb"], ACTIVITY_POKE)) {
2757 self::doPoke($item, $importer, $posted_id);
2763 * @brief Deletes items
2765 * @param object $xpath XPath object
2766 * @param object $deletion deletion elements
2767 * @param array $importer Record of the importer user mixed with contact of the content
2769 * @todo set proper type-hints
2771 private static function processDeletion($xpath, $deletion, $importer)
2773 logger("Processing deletions");
2775 foreach ($deletion->attributes as $attributes) {
2776 if ($attributes->name == "ref") {
2777 $uri = $attributes->textContent;
2781 if (!$uri || !$importer["id"]) {
2785 $condition = ["`uri` = ? AND `uid` = ? AND NOT `file` LIKE '%[%'", $uri, $importer["importer_uid"]];
2786 $item = dba::selectFirst('item', ['id', 'parent', 'contact-id'], $condition);
2787 if (!DBM::is_result($item)) {
2788 logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", LOGGER_DEBUG);
2792 // When it is a starting post it has to belong to the person that wants to delete it
2793 if (($item['id'] == $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2794 logger("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2798 // Comments can be deleted by the thread owner or comment owner
2799 if (($item['id'] != $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2800 $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2801 if (!dba::exists('item', $condition)) {
2802 logger("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2807 $entrytype = self::getEntryType($importer, $item);
2809 if (!$item["deleted"]) {
2810 logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG);
2815 Item::deleteById($item["id"]);
2817 if ($entrytype != DFRN_TOP_LEVEL) {
2818 // if this is a relayed delete, propagate it to other recipients
2819 if ($entrytype == DFRN_REPLY_RC) {
2820 logger("Notifying followers about deletion of post " . $item["id"], LOGGER_DEBUG);
2821 Worker::add(PRIORITY_HIGH, "Notifier", "drop", $item["id"]);
2827 * @brief Imports a DFRN message
2829 * @param string $xml The DFRN message
2830 * @param array $importer Record of the importer user mixed with contact of the content
2831 * @param bool $sort_by_date Is used when feeds are polled
2832 * @return integer Import status
2833 * @todo set proper type-hints
2835 public static function import($xml, $importer, $sort_by_date = false)
2841 $doc = new DOMDocument();
2842 @$doc->loadXML($xml);
2844 $xpath = new DOMXPath($doc);
2845 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2846 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2847 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2848 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2849 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2850 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2851 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2852 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2853 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2854 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2857 $header["uid"] = $importer["importer_uid"];
2858 $header["network"] = NETWORK_DFRN;
2859 $header["type"] = "remote";
2860 $header["wall"] = 0;
2861 $header["origin"] = 0;
2862 $header["contact-id"] = $importer["id"];
2864 // Update the contact table if the data has changed
2866 // The "atom:author" is only present in feeds
2867 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2868 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2871 // Only the "dfrn:owner" in the head section contains all data
2872 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2873 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2876 logger("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2878 // The account type is new since 3.5.1
2879 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2880 $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()")->item(0)->nodeValue);
2882 if ($accounttype != $importer["contact-type"]) {
2883 dba::update('contact', ['contact-type' => $accounttype], ['id' => $importer["id"]]);
2887 // is it a public forum? Private forums aren't supported with this method
2888 // This is deprecated since 3.5.1
2889 $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()")->item(0)->nodeValue);
2891 if ($forum != $importer["forum"]) {
2892 $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2893 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 = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
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 dbesc($contact_nick),
2979 dbesc($a->user['nickname']),
2983 if ((! DBM::is_result($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 dbesc($contact_nick),
2990 dbesc(NETWORK_DFRN),
2991 intval(local_user()),
2994 if (! DBM::is_result($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 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
3061 if (!DBM::is_result($u)) {
3065 $community_page = ($u[0]['page-flags'] == PAGE_COMMUNITY);
3066 $prvgroup = ($u[0]['page-flags'] == PAGE_PRVGROUP);
3068 $link = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
3071 * Diaspora uses their own hardwired link URL in @-tags
3072 * instead of the one we supply with webfinger
3074 $dlink = normalise_link(System::baseUrl() . '/u/' . $u[0]['nickname']);
3076 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
3078 foreach ($matches as $mtch) {
3079 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
3081 logger('mention found: ' . $mtch[2]);
3090 return $community_page || $prvgroup;
3094 * This function returns true if $update has an edited timestamp newer
3095 * than $existing, i.e. $update contains new data which should override
3096 * what's already there. If there is no timestamp yet, the update is
3097 * assumed to be newer. If the update has no timestamp, the existing
3098 * item is assumed to be up-to-date. If the timestamps are equal it
3099 * assumes the update has been seen before and should be ignored.
3102 private static function isEditedTimestampNewer($existing, $update)
3104 if (!x($existing, 'edited') || !$existing['edited']) {
3107 if (!x($update, 'edited') || !$update['edited']) {
3111 $existing_edited = DateTimeFormat::utc($existing['edited']);
3112 $update_edited = DateTimeFormat::utc($update['edited']);
3114 return (strcmp($existing_edited, $update_edited) < 0);