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 TOP_LEVEL = 0; // Top level posting
54 const REPLY = 1; // Regular reply that is stored locally
55 const 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 Find proper 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];
123 // default permissions - anonymous user
125 $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = '' ";
128 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
129 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
130 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
134 if (! DBM::is_result($r)) {
135 logger(sprintf('No contact found for nickname=%d', $owner_nick), LOGGER_WARNING);
140 $owner_id = $owner['uid'];
141 $owner_nick = $owner['nickname'];
143 $sql_post_table = "";
145 if (! $public_feed) {
147 switch ($direction) {
149 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
153 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
154 $my_id = '1:' . $dfrn_id;
157 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
158 $my_id = '0:' . $dfrn_id;
166 "SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
170 if (! DBM::is_result($r)) {
171 logger(sprintf('No contact found for uid=%d', $owner_id), LOGGER_WARNING);
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]) . '>' ;
184 $gs = implode('|', $groups);
186 $gs = '<<>>' ; // Impossible to match
189 $sql_extra = sprintf(
191 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
192 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
193 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
194 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
196 intval($contact['id']),
197 intval($contact['id']),
209 if (! strlen($last_update)) {
210 $last_update = 'now -30 days';
213 if (isset($category)) {
214 $sql_post_table = sprintf(
215 "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` ",
216 dbesc(protect_sprintf($category)),
217 intval(TERM_OBJ_POST),
218 intval(TERM_CATEGORY),
221 //$sql_extra .= file_tag_file_query('item',$category,'category');
224 if ($public_feed && ! $converse) {
225 $sql_extra .= " AND `contact`.`self` = 1 ";
228 $check_date = DateTimeFormat::utc($last_update);
232 FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
233 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
234 WHERE `item`.`uid` = %d AND `item`.`wall` AND `item`.`changed` > '%s'
236 ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
243 foreach ($r as $item) {
244 $ids[] = $item['id'];
247 $condition = ['id' => $ids];
248 $fields = ['author-id', 'uid', 'id', 'parent', 'uri', 'thr-parent',
249 'parent-uri', 'created', 'edited', 'verb', 'object-type',
250 'guid', 'private', 'title', 'body', 'location', 'coord', 'app',
251 'attach', 'object', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
252 'extid', 'target', 'tag', 'bookmark', 'deleted',
253 'author-link', 'owner-link', 'signed_text', 'signature', 'signer'];
254 $ret = Item::select($owner_id, $fields, $condition);
255 $items = dba::inArray($ret);
258 * Will check further below if this actually returned results.
259 * We will provide an empty feed if that is the case.
262 $doc = new DOMDocument('1.0', 'utf-8');
263 $doc->formatOutput = true;
265 $alternatelink = $owner['url'];
267 if (isset($category)) {
268 $alternatelink .= "/category/".$category;
272 $author = "dfrn:owner";
277 $root = self::addHeader($doc, $owner, $author, $alternatelink, true);
279 /// @TODO This hook can't work anymore
280 // Addon::callHooks('atom_feed', $atom);
282 if (!DBM::is_result($items) || $onlyheader) {
283 $atom = trim($doc->saveXML());
285 Addon::callHooks('atom_feed_end', $atom);
290 foreach ($items as $item) {
291 // prevent private email from leaking.
292 if ($item['network'] == NETWORK_MAIL) {
296 // public feeds get html, our own nodes use bbcode
300 // catch any email that's in a public conversation and make sure it doesn't leak
301 if ($item['private']) {
308 $entry = self::entry($doc, $type, $item, $owner, true);
309 $root->appendChild($entry);
312 $atom = trim($doc->saveXML());
314 Addon::callHooks('atom_feed_end', $atom);
320 * @brief Generate an atom entry for a given item id
322 * @param int $item_id The item id
323 * @param boolean $conversation Show the conversation. If false show the single post.
325 * @return string DFRN feed entry
327 public static function itemFeed($item_id, $conversation = false)
330 $condition = ['parent' => $item_id];
332 $condition = ['id' => $item_id];
335 $fields = ['author-id', 'uid', 'id', 'parent', 'uri', 'thr-parent',
336 'parent-uri', 'created', 'edited', 'verb', 'object-type',
337 'guid', 'private', 'title', 'body', 'location', 'coord', 'app',
338 'attach', 'object', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
339 'extid', 'target', 'tag', 'bookmark', 'deleted',
340 'author-link', 'owner-link', 'signed_text', 'signature', 'signer'];
341 $ret = Item::select(0, $fields, $condition);
342 $items = dba::inArray($ret);
343 if (!DBM::is_result($items)) {
349 if ($item['uid'] != 0) {
350 $owner = User::getOwnerDataById($item['uid']);
355 $owner = ['uid' => 0, 'nick' => 'feed-item'];
358 $doc = new DOMDocument('1.0', 'utf-8');
359 $doc->formatOutput = true;
363 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
364 $doc->appendChild($root);
366 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
367 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
368 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
369 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
370 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
371 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
372 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
373 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
374 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
376 //$root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
378 foreach ($items as $item) {
379 $entry = self::entry($doc, $type, $item, $owner, true, 0);
380 $root->appendChild($entry);
383 $root = self::entry($doc, $type, $item, $owner, true, 0, true);
386 $atom = trim($doc->saveXML());
391 * @brief Create XML text for DFRN mails
393 * @param array $item message elements
394 * @param array $owner Owner record
396 * @return string DFRN mail
397 * @todo Find proper type-hints
399 public static function mail($item, $owner)
401 $doc = new DOMDocument('1.0', 'utf-8');
402 $doc->formatOutput = true;
404 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
406 $mail = $doc->createElement("dfrn:mail");
407 $sender = $doc->createElement("dfrn:sender");
409 XML::addElement($doc, $sender, "dfrn:name", $owner['name']);
410 XML::addElement($doc, $sender, "dfrn:uri", $owner['url']);
411 XML::addElement($doc, $sender, "dfrn:avatar", $owner['thumb']);
413 $mail->appendChild($sender);
415 XML::addElement($doc, $mail, "dfrn:id", $item['uri']);
416 XML::addElement($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
417 XML::addElement($doc, $mail, "dfrn:sentdate", DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
418 XML::addElement($doc, $mail, "dfrn:subject", $item['title']);
419 XML::addElement($doc, $mail, "dfrn:content", $item['body']);
421 $root->appendChild($mail);
423 return trim($doc->saveXML());
427 * @brief Create XML text for DFRN friend suggestions
429 * @param array $item suggestion elements
430 * @param array $owner Owner record
432 * @return string DFRN suggestions
433 * @todo Find proper type-hints
435 public static function fsuggest($item, $owner)
437 $doc = new DOMDocument('1.0', 'utf-8');
438 $doc->formatOutput = true;
440 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
442 $suggest = $doc->createElement("dfrn:suggest");
444 XML::addElement($doc, $suggest, "dfrn:url", $item['url']);
445 XML::addElement($doc, $suggest, "dfrn:name", $item['name']);
446 XML::addElement($doc, $suggest, "dfrn:photo", $item['photo']);
447 XML::addElement($doc, $suggest, "dfrn:request", $item['request']);
448 XML::addElement($doc, $suggest, "dfrn:note", $item['note']);
450 $root->appendChild($suggest);
452 return trim($doc->saveXML());
456 * @brief Create XML text for DFRN relocations
458 * @param array $owner Owner record
459 * @param int $uid User ID
461 * @return string DFRN relocations
462 * @todo Find proper type-hints
464 public static function relocate($owner, $uid)
467 /* get site pubkey. this could be a new installation with no site keys*/
468 $pubkey = Config::get('system', 'site_pubkey');
470 $res = Crypto::newKeypair(1024);
471 Config::set('system', 'site_prvkey', $res['prvkey']);
472 Config::set('system', 'site_pubkey', $res['pubkey']);
476 "SELECT `resource-id` , `scale`, type FROM `photo`
477 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;",
481 $ext = Image::supportedTypes();
483 foreach ($rp as $p) {
484 $photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
488 $doc = new DOMDocument('1.0', 'utf-8');
489 $doc->formatOutput = true;
491 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
493 $relocate = $doc->createElement("dfrn:relocate");
495 XML::addElement($doc, $relocate, "dfrn:url", $owner['url']);
496 XML::addElement($doc, $relocate, "dfrn:name", $owner['name']);
497 XML::addElement($doc, $relocate, "dfrn:addr", $owner['addr']);
498 XML::addElement($doc, $relocate, "dfrn:avatar", $owner['avatar']);
499 XML::addElement($doc, $relocate, "dfrn:photo", $photos[4]);
500 XML::addElement($doc, $relocate, "dfrn:thumb", $photos[5]);
501 XML::addElement($doc, $relocate, "dfrn:micro", $photos[6]);
502 XML::addElement($doc, $relocate, "dfrn:request", $owner['request']);
503 XML::addElement($doc, $relocate, "dfrn:confirm", $owner['confirm']);
504 XML::addElement($doc, $relocate, "dfrn:notify", $owner['notify']);
505 XML::addElement($doc, $relocate, "dfrn:poll", $owner['poll']);
506 XML::addElement($doc, $relocate, "dfrn:sitepubkey", Config::get('system', 'site_pubkey'));
508 $root->appendChild($relocate);
510 return trim($doc->saveXML());
514 * @brief Adds the header elements for the DFRN protocol
516 * @param object $doc XML document
517 * @param array $owner Owner record
518 * @param string $authorelement Element name for the author
519 * @param string $alternatelink link to profile or category
520 * @param bool $public Is it a header for public posts?
522 * @return object XML root object
523 * @todo Find proper type-hints
525 private static function addHeader($doc, $owner, $authorelement, $alternatelink = "", $public = false)
528 if ($alternatelink == "") {
529 $alternatelink = $owner['url'];
532 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
533 $doc->appendChild($root);
535 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
536 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
537 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
538 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
539 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
540 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
541 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
542 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
543 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
545 XML::addElement($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
546 XML::addElement($doc, $root, "title", $owner["name"]);
548 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION];
549 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
551 $attributes = ["rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/"];
552 XML::addElement($doc, $root, "link", "", $attributes);
554 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $alternatelink];
555 XML::addElement($doc, $root, "link", "", $attributes);
559 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
560 OStatus::hublinks($doc, $root, $owner["nick"]);
562 $attributes = ["rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
563 XML::addElement($doc, $root, "link", "", $attributes);
565 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
566 XML::addElement($doc, $root, "link", "", $attributes);
568 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
569 XML::addElement($doc, $root, "link", "", $attributes);
572 // For backward compatibility we keep this element
573 if ($owner['page-flags'] == PAGE_COMMUNITY) {
574 XML::addElement($doc, $root, "dfrn:community", 1);
577 // The former element is replaced by this one
578 XML::addElement($doc, $root, "dfrn:account_type", $owner["account-type"]);
580 /// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
582 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
584 $author = self::addAuthor($doc, $owner, $authorelement, $public);
585 $root->appendChild($author);
591 * @brief Adds the author element in the header for the DFRN protocol
593 * @param object $doc XML document
594 * @param array $owner Owner record
595 * @param string $authorelement Element name for the author
596 * @param boolean $public boolean
598 * @return object XML author object
599 * @todo Find proper type-hints
601 private static function addAuthor($doc, $owner, $authorelement, $public)
603 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
605 "SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
606 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
607 intval($owner['uid'])
609 if (DBM::is_result($r)) {
615 $author = $doc->createElement($authorelement);
617 $namdate = DateTimeFormat::utc($owner['name-date'].'+00:00', DateTimeFormat::ATOM);
618 $uridate = DateTimeFormat::utc($owner['uri-date'].'+00:00', DateTimeFormat::ATOM);
619 $picdate = DateTimeFormat::utc($owner['avatar-date'].'+00:00', DateTimeFormat::ATOM);
623 if (!$public || !$hidewall) {
624 $attributes = ["dfrn:updated" => $namdate];
627 XML::addElement($doc, $author, "name", $owner["name"], $attributes);
628 XML::addElement($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
629 XML::addElement($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
631 $attributes = ["rel" => "photo", "type" => "image/jpeg",
632 "media:width" => 175, "media:height" => 175, "href" => $owner['photo']];
634 if (!$public || !$hidewall) {
635 $attributes["dfrn:updated"] = $picdate;
638 XML::addElement($doc, $author, "link", "", $attributes);
640 $attributes["rel"] = "avatar";
641 XML::addElement($doc, $author, "link", "", $attributes);
644 XML::addElement($doc, $author, "dfrn:hide", "true");
647 // The following fields will only be generated if the data isn't meant for a public feed
652 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
655 XML::addElement($doc, $author, "dfrn:birthday", $birthday);
658 // Only show contact details when we are allowed to
660 "SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
661 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
662 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
664 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
665 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
666 intval($owner['uid'])
668 if (DBM::is_result($r)) {
671 XML::addElement($doc, $author, "poco:displayName", $profile["name"]);
672 XML::addElement($doc, $author, "poco:updated", $namdate);
674 if (trim($profile["dob"]) > '0001-01-01') {
675 XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
678 XML::addElement($doc, $author, "poco:note", $profile["about"]);
679 XML::addElement($doc, $author, "poco:preferredUsername", $profile["nickname"]);
681 $savetz = date_default_timezone_get();
682 date_default_timezone_set($profile["timezone"]);
683 XML::addElement($doc, $author, "poco:utcOffset", date("P"));
684 date_default_timezone_set($savetz);
686 if (trim($profile["homepage"]) != "") {
687 $urls = $doc->createElement("poco:urls");
688 XML::addElement($doc, $urls, "poco:type", "homepage");
689 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
690 XML::addElement($doc, $urls, "poco:primary", "true");
691 $author->appendChild($urls);
694 if (trim($profile["pub_keywords"]) != "") {
695 $keywords = explode(",", $profile["pub_keywords"]);
697 foreach ($keywords as $keyword) {
698 XML::addElement($doc, $author, "poco:tags", trim($keyword));
702 if (trim($profile["xmpp"]) != "") {
703 $ims = $doc->createElement("poco:ims");
704 XML::addElement($doc, $ims, "poco:type", "xmpp");
705 XML::addElement($doc, $ims, "poco:value", $profile["xmpp"]);
706 XML::addElement($doc, $ims, "poco:primary", "true");
707 $author->appendChild($ims);
710 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
711 $element = $doc->createElement("poco:address");
713 XML::addElement($doc, $element, "poco:formatted", Profile::formatLocation($profile));
715 if (trim($profile["locality"]) != "") {
716 XML::addElement($doc, $element, "poco:locality", $profile["locality"]);
719 if (trim($profile["region"]) != "") {
720 XML::addElement($doc, $element, "poco:region", $profile["region"]);
723 if (trim($profile["country-name"]) != "") {
724 XML::addElement($doc, $element, "poco:country", $profile["country-name"]);
727 $author->appendChild($element);
735 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
737 * @param object $doc XML document
738 * @param string $element Element name for the author
739 * @param string $contact_url Link of the contact
740 * @param array $item Item elements
742 * @return object XML author object
743 * @todo Find proper type-hints
745 private static function addEntryAuthor($doc, $element, $contact_url, $item)
747 $contact = Contact::getDetailsByURL($contact_url, $item["uid"]);
749 $author = $doc->createElement($element);
750 XML::addElement($doc, $author, "name", $contact["name"]);
751 XML::addElement($doc, $author, "uri", $contact["url"]);
752 XML::addElement($doc, $author, "dfrn:handle", $contact["addr"]);
755 /// - Check real image type and image size
756 /// - Check which of these boths elements we should use
759 "type" => "image/jpeg",
761 "media:height" => 80,
762 "href" => $contact["photo"]];
763 XML::addElement($doc, $author, "link", "", $attributes);
767 "type" => "image/jpeg",
769 "media:height" => 80,
770 "href" => $contact["photo"]];
771 XML::addElement($doc, $author, "link", "", $attributes);
777 * @brief Adds the activity elements
779 * @param object $doc XML document
780 * @param string $element Element name for the activity
781 * @param string $activity activity value
783 * @return object XML activity object
784 * @todo Find proper type-hints
786 private static function createActivity($doc, $element, $activity)
789 $entry = $doc->createElement($element);
791 $r = XML::parseString($activity, false);
797 XML::addElement($doc, $entry, "activity:object-type", $r->type);
801 XML::addElement($doc, $entry, "id", $r->id);
805 XML::addElement($doc, $entry, "title", $r->title);
809 if (substr($r->link, 0, 1) == '<') {
810 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
811 $r->link = str_replace('&', '&', $r->link);
814 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
816 // XML does need a single element as root element so we add a dummy element here
817 $data = XML::parseString("<dummy>" . $r->link . "</dummy>", false);
818 if (is_object($data)) {
819 foreach ($data->link as $link) {
821 foreach ($link->attributes() as $parameter => $value) {
822 $attributes[$parameter] = $value;
824 XML::addElement($doc, $entry, "link", "", $attributes);
828 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
829 XML::addElement($doc, $entry, "link", "", $attributes);
833 XML::addElement($doc, $entry, "content", BBCode::convert($r->content), ["type" => "html"]);
843 * @brief Adds the elements for attachments
845 * @param object $doc XML document
846 * @param object $root XML root
847 * @param array $item Item element
849 * @return object XML attachment object
850 * @todo Find proper type-hints
852 private static function getAttachment($doc, $root, $item)
854 $arr = explode('[/attach],', $item['attach']);
856 foreach ($arr as $r) {
858 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
860 $attributes = ["rel" => "enclosure",
861 "href" => $matches[1],
862 "type" => $matches[3]];
864 if (intval($matches[2])) {
865 $attributes["length"] = intval($matches[2]);
868 if (trim($matches[4]) != "") {
869 $attributes["title"] = trim($matches[4]);
872 XML::addElement($doc, $root, "link", "", $attributes);
879 * @brief Adds the "entry" elements for the DFRN protocol
881 * @param object $doc XML document
882 * @param string $type "text" or "html"
883 * @param array $item Item element
884 * @param array $owner Owner record
885 * @param bool $comment Trigger the sending of the "comment" element
886 * @param int $cid Contact ID of the recipient
887 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
889 * @return object XML entry object
890 * @todo Find proper type-hints
892 private static function entry($doc, $type, array $item, array $owner, $comment = false, $cid = 0, $single = false)
896 if (!$item['parent']) {
900 if ($item['deleted']) {
901 $attributes = ["ref" => $item['uri'], "when" => DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM)];
902 return XML::createElement($doc, "at:deleted-entry", "", $attributes);
906 $entry = $doc->createElement("entry");
908 $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry');
909 $doc->appendChild($entry);
911 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
912 $entry->setAttribute("xmlns:at", NAMESPACE_TOMB);
913 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
914 $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
915 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
916 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
917 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
918 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
919 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
922 if ($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid']) {
923 $body = Item::fixPrivatePhotos($item['body'], $owner['uid'], $item, $cid);
925 $body = $item['body'];
928 // Remove the abstract element. It is only locally important.
929 $body = BBCode::stripAbstract($body);
932 if ($type == 'html') {
935 if ($item['title'] != "") {
936 $htmlbody = "[b]" . $item['title'] . "[/b]\n\n" . $htmlbody;
939 $htmlbody = BBCode::convert($htmlbody, false, 7);
942 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
943 $entry->appendChild($author);
945 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
946 $entry->appendChild($dfrnowner);
948 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
949 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
950 $parent = q("SELECT `guid`,`plink` FROM `item` WHERE `uri` = '%s' AND `uid` = %d", dbesc($parent_item), intval($item['uid']));
951 $attributes = ["ref" => $parent_item, "type" => "text/html",
952 "href" => $parent[0]['plink'],
953 "dfrn:diaspora_guid" => $parent[0]['guid']];
954 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
957 // Add conversation data. This is used for OStatus
958 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
959 $conversation_uri = $conversation_href;
961 if (isset($parent_item)) {
962 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $item['parent-uri']);
963 if (DBM::is_result($r)) {
964 if ($r['conversation-uri'] != '') {
965 $conversation_uri = $r['conversation-uri'];
967 if ($r['conversation-href'] != '') {
968 $conversation_href = $r['conversation-href'];
974 "href" => $conversation_href,
975 "ref" => $conversation_uri];
977 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
979 XML::addElement($doc, $entry, "id", $item["uri"]);
980 XML::addElement($doc, $entry, "title", $item["title"]);
982 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"] . "+00:00", DateTimeFormat::ATOM));
983 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"] . "+00:00", DateTimeFormat::ATOM));
985 // "dfrn:env" is used to read the content
986 XML::addElement($doc, $entry, "dfrn:env", base64url_encode($body, true));
988 // The "content" field is not read by the receiver. We could remove it when the type is "text"
989 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
990 XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
992 // We save this value in "plink". Maybe we should read it from there as well?
998 ["rel" => "alternate", "type" => "text/html",
999 "href" => System::baseUrl() . "/display/" . $item["guid"]]
1002 // "comment-allow" is some old fashioned stuff for old Friendica versions.
1003 // It is included in the rewritten code for completeness
1005 XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
1008 if ($item['location']) {
1009 XML::addElement($doc, $entry, "dfrn:location", $item['location']);
1012 if ($item['coord']) {
1013 XML::addElement($doc, $entry, "georss:point", $item['coord']);
1016 if (($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])) {
1017 XML::addElement($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
1020 if ($item['extid']) {
1021 XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
1024 if ($item['bookmark']) {
1025 XML::addElement($doc, $entry, "dfrn:bookmark", "true");
1029 XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
1032 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
1034 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
1035 // It is needed for relayed comments to Diaspora.
1036 if ($item['signed_text']) {
1037 $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer']]));
1038 XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
1041 XML::addElement($doc, $entry, "activity:verb", self::constructVerb($item));
1043 if ($item['object-type'] != "") {
1044 XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
1045 } elseif ($item['id'] == $item['parent']) {
1046 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1048 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
1051 $actobj = self::createActivity($doc, "activity:object", $item['object']);
1053 $entry->appendChild($actobj);
1056 $actarg = self::createActivity($doc, "activity:target", $item['target']);
1058 $entry->appendChild($actarg);
1061 $tags = Item::getFeedTags($item);
1063 /// @TODO Combine this with similar below if() block?
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. Negative values mean an error.
1150 * @todo Add array type-hint for $owner, $contact
1152 public static function deliver($owner, $contact, $atom, $dissolve = false)
1156 // At first try the Diaspora transport layer
1157 $ret = self::transmit($owner, $contact, $atom);
1159 logger('Delivery via Diaspora transport layer was successful with status ' . $ret);
1163 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1165 if ($contact['duplex'] && $contact['dfrn-id']) {
1166 $idtosend = '0:' . $orig_id;
1168 if ($contact['duplex'] && $contact['issued-id']) {
1169 $idtosend = '1:' . $orig_id;
1172 $rino = Config::get('system', 'rino_encrypt');
1173 $rino = intval($rino);
1175 logger("Local rino version: ". $rino, LOGGER_DEBUG);
1177 $ssl_val = intval(Config::get('system', 'ssl_policy'));
1181 case SSL_POLICY_FULL:
1182 $ssl_policy = 'full';
1184 case SSL_POLICY_SELFSIGN:
1185 $ssl_policy = 'self';
1187 case SSL_POLICY_NONE:
1189 $ssl_policy = 'none';
1193 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1195 logger('dfrn_deliver: ' . $url);
1197 $ret = Network::curl($url);
1199 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1200 Contact::markForArchival($contact);
1201 return -2; // timed out
1204 $xml = $ret['body'];
1206 $curl_stat = $a->get_curl_code();
1207 if (empty($curl_stat)) {
1208 Contact::markForArchival($contact);
1209 return -3; // timed out
1212 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1215 Contact::markForArchival($contact);
1219 if (strpos($xml, '<?xml') === false) {
1220 logger('dfrn_deliver: no valid XML returned');
1221 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1222 Contact::markForArchival($contact);
1226 $res = XML::parseString($xml);
1228 if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
1229 Contact::markForArchival($contact);
1230 return ($res->status ? $res->status : 3);
1234 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1235 $challenge = hex2bin((string) $res->challenge);
1236 $perm = (($res->perm) ? $res->perm : null);
1237 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1238 $rino_remote_version = intval($res->rino);
1239 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1241 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
1243 if ($owner['page-flags'] == PAGE_PRVGROUP) {
1247 $final_dfrn_id = '';
1250 if ((($perm == 'rw') && (! intval($contact['writable'])))
1251 || (($perm == 'r') && (intval($contact['writable'])))
1254 "update contact set writable = %d where id = %d",
1255 intval(($perm == 'rw') ? 1 : 0),
1256 intval($contact['id'])
1258 $contact['writable'] = (string) 1 - intval($contact['writable']);
1262 if (($contact['duplex'] && strlen($contact['pubkey']))
1263 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1264 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
1266 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
1267 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
1269 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
1270 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
1273 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1275 if (strpos($final_dfrn_id, ':') == 1) {
1276 $final_dfrn_id = substr($final_dfrn_id, 2);
1279 if ($final_dfrn_id != $orig_id) {
1280 logger('dfrn_deliver: wrong dfrn_id.');
1281 // did not decode properly - cannot trust this site
1282 Contact::markForArchival($contact);
1286 $postvars['dfrn_id'] = $idtosend;
1287 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1289 $postvars['dissolve'] = '1';
1292 if ((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1293 $postvars['data'] = $atom;
1294 $postvars['perm'] = 'rw';
1296 $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
1297 $postvars['perm'] = 'r';
1300 $postvars['ssl_policy'] = $ssl_policy;
1303 $postvars['page'] = $page;
1307 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1308 logger('rino version: '. $rino_remote_version);
1310 switch ($rino_remote_version) {
1312 $key = openssl_random_pseudo_bytes(16);
1313 $data = self::aesEncrypt($postvars['data'], $key);
1316 logger("rino: invalid requested version '$rino_remote_version'");
1317 Contact::markForArchival($contact);
1321 $postvars['rino'] = $rino_remote_version;
1322 $postvars['data'] = bin2hex($data);
1324 if ($dfrn_version >= 2.1) {
1325 if (($contact['duplex'] && strlen($contact['pubkey']))
1326 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1327 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
1329 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1331 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1334 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1335 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1337 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1341 logger('md5 rawkey ' . md5($postvars['key']));
1343 $postvars['key'] = bin2hex($postvars['key']);
1347 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), LOGGER_DATA);
1349 $xml = Network::post($contact['notify'], $postvars);
1351 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1353 $curl_stat = $a->get_curl_code();
1354 if (empty($curl_stat) || empty($xml)) {
1355 Contact::markForArchival($contact);
1356 return -9; // timed out
1359 if (($curl_stat == 503) && stristr($a->get_curl_headers(), 'retry-after')) {
1360 Contact::markForArchival($contact);
1364 if (strpos($xml, '<?xml') === false) {
1365 logger('dfrn_deliver: phase 2: no valid XML returned');
1366 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1367 Contact::markForArchival($contact);
1371 $res = XML::parseString($xml);
1373 if (!isset($res->status)) {
1374 Contact::markForArchival($contact);
1378 // Possibly old servers had returned an empty value when everything was okay
1379 if (empty($res->status)) {
1383 if (!empty($res->message)) {
1384 logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1387 if (($res->status >= 200) && ($res->status <= 299)) {
1388 Contact::unmarkForArchival($contact);
1391 return intval($res->status);
1395 * @brief Transmits atom content to the contacts via the Diaspora transport layer
1397 * @param array $owner Owner record
1398 * @param array $contact Contact record of the receiver
1399 * @param string $atom Content that will be transmitted
1401 * @return int Deliver status. Negative values mean an error.
1403 public static function transmit($owner, $contact, $atom, $public_batch = false)
1407 if (!$public_batch) {
1408 if (empty($contact['addr'])) {
1409 logger('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.');
1410 if (Contact::updateFromProbe($contact['id'])) {
1411 $new_contact = dba::selectFirst('contact', ['addr'], ['id' => $contact['id']]);
1412 $contact['addr'] = $new_contact['addr'];
1415 if (empty($contact['addr'])) {
1416 logger('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
1417 Contact::markForArchival($contact);
1422 $fcontact = Diaspora::personByHandle($contact['addr']);
1423 if (empty($fcontact)) {
1424 logger('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
1425 Contact::markForArchival($contact);
1428 $pubkey = $fcontact['pubkey'];
1433 $envelope = Diaspora::buildMessage($atom, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
1435 // Create the endpoint for public posts. This is some WIP and should later be added to the probing
1436 if ($public_batch && empty($contact["batch"])) {
1437 $parts = parse_url($contact["notify"]);
1438 $path_parts = explode('/', $parts['path']);
1439 array_pop($path_parts);
1440 $parts['path'] = implode('/', $path_parts);
1441 $contact["batch"] = Network::unparseURL($parts);
1444 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
1446 $content_type = ($public_batch ? "application/magic-envelope+xml" : "application/json");
1448 $xml = Network::post($dest_url, $envelope, ["Content-Type: ".$content_type]);
1450 $curl_stat = $a->get_curl_code();
1451 if (empty($curl_stat) || empty($xml)) {
1452 logger('Empty answer from ' . $contact['id'] . ' - ' . $dest_url);
1453 Contact::markForArchival($contact);
1454 return -9; // timed out
1457 if (($curl_stat == 503) && (stristr($a->get_curl_headers(), 'retry-after'))) {
1458 Contact::markForArchival($contact);
1462 if (strpos($xml, '<?xml') === false) {
1463 logger('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url);
1464 logger('Returned XML: ' . $xml, LOGGER_DATA);
1465 Contact::markForArchival($contact);
1469 $res = XML::parseString($xml);
1471 if (empty($res->status)) {
1472 Contact::markForArchival($contact);
1476 if (!empty($res->message)) {
1477 logger('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1480 if (($res->status >= 200) && ($res->status <= 299)) {
1481 Contact::unmarkForArchival($contact);
1484 return intval($res->status);
1488 * @brief Add new birthday event for this person
1490 * @param array $contact Contact record
1491 * @param string $birthday Birthday of the contact
1493 * @todo Add array type-hint for $contact
1495 private static function birthdayEvent($contact, $birthday)
1497 // Check for duplicates
1499 "SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1500 intval($contact['uid']),
1501 intval($contact['id']),
1502 dbesc(DateTimeFormat::utc($birthday)),
1506 if (DBM::is_result($r)) {
1510 logger('updating birthday: ' . $birthday . ' for contact ' . $contact['id']);
1512 $bdtext = L10n::t('%s\'s birthday', $contact['name']);
1513 $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]');
1516 "INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1517 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1518 intval($contact['uid']),
1519 intval($contact['id']),
1520 dbesc(DateTimeFormat::utcNow()),
1521 dbesc(DateTimeFormat::utcNow()),
1522 dbesc(DateTimeFormat::utc($birthday)),
1523 dbesc(DateTimeFormat::utc($birthday . ' + 1 day ')),
1531 * @brief Fetch the author data from head or entry items
1533 * @param object $xpath XPath object
1534 * @param object $context In which context should the data be searched
1535 * @param array $importer Record of the importer user mixed with contact of the content
1536 * @param string $element Element name from which the data is fetched
1537 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1538 * @param string $xml optional, default empty
1540 * @return array Relevant data of the author
1541 * @todo Find good type-hints for all parameter
1543 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
1546 $author["name"] = $xpath->evaluate($element."/atom:name/text()", $context)->item(0)->nodeValue;
1547 $author["link"] = $xpath->evaluate($element."/atom:uri/text()", $context)->item(0)->nodeValue;
1549 $contact_old = dba::fetch_first("SELECT `id`, `uid`, `url`, `network`, `avatar-date`, `avatar`, `name-date`, `uri-date`, `addr`,
1550 `name`, `nick`, `about`, `location`, `keywords`, `xmpp`, `bdyear`, `bd`, `hidden`, `contact-type`
1551 FROM `contact` WHERE `uid` = ? AND `nurl` = ? AND `network` != ?",
1552 $importer["importer_uid"],
1553 normalise_link($author["link"]),
1557 if (DBM::is_result($contact_old)) {
1558 $author["contact-id"] = $contact_old["id"];
1559 $author["network"] = $contact_old["network"];
1562 logger("Contact ".$author["link"]." wasn't found for user ".$importer["importer_uid"]." XML: ".$xml, LOGGER_DEBUG);
1565 $author["contact-id"] = $importer["id"];
1566 $author["network"] = $importer["network"];
1570 // Until now we aren't serving different sizes - but maybe later
1572 /// @todo check if "avatar" or "photo" would be the best field in the specification
1573 $avatars = $xpath->query($element . "/atom:link[@rel='avatar']", $context);
1574 foreach ($avatars as $avatar) {
1577 foreach ($avatar->attributes as $attributes) {
1578 /// @TODO Rewrite these similar if() to one switch
1579 if ($attributes->name == "href") {
1580 $href = $attributes->textContent;
1582 if ($attributes->name == "width") {
1583 $width = $attributes->textContent;
1585 if ($attributes->name == "updated") {
1586 $author["avatar-date"] = $attributes->textContent;
1589 if (($width > 0) && ($href != "")) {
1590 $avatarlist[$width] = $href;
1594 if (count($avatarlist) > 0) {
1595 krsort($avatarlist);
1596 $author["avatar"] = current($avatarlist);
1599 if (DBM::is_result($contact_old) && !$onlyfetch) {
1600 logger("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", LOGGER_DEBUG);
1602 $poco = ["url" => $contact_old["url"]];
1604 // When was the last change to name or uri?
1605 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1606 foreach ($name_element->attributes as $attributes) {
1607 if ($attributes->name == "updated") {
1608 $poco["name-date"] = $attributes->textContent;
1612 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1613 foreach ($link_element->attributes as $attributes) {
1614 if ($attributes->name == "updated") {
1615 $poco["uri-date"] = $attributes->textContent;
1619 // Update contact data
1620 $value = $xpath->evaluate($element . "/dfrn:handle/text()", $context)->item(0)->nodeValue;
1622 $poco["addr"] = $value;
1625 $value = $xpath->evaluate($element . "/poco:displayName/text()", $context)->item(0)->nodeValue;
1627 $poco["name"] = $value;
1630 $value = $xpath->evaluate($element . "/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
1632 $poco["nick"] = $value;
1635 $value = $xpath->evaluate($element . "/poco:note/text()", $context)->item(0)->nodeValue;
1637 $poco["about"] = $value;
1640 $value = $xpath->evaluate($element . "/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
1642 $poco["location"] = $value;
1645 /// @todo Only search for elements with "poco:type" = "xmpp"
1646 $value = $xpath->evaluate($element . "/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
1648 $poco["xmpp"] = $value;
1651 /// @todo Add support for the following fields that we don't support by now in the contact table:
1652 /// - poco:utcOffset
1658 // If the "hide" element is present then the profile isn't searchable.
1659 $hide = intval($xpath->evaluate($element . "/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
1661 logger("Hidden status for contact " . $contact_old["url"] . ": " . $hide, LOGGER_DEBUG);
1663 // If the contact isn't searchable then set the contact to "hidden".
1664 // Problem: This can be manually overridden by the user.
1666 $contact_old["hidden"] = true;
1669 // Save the keywords into the contact table
1671 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1672 foreach ($tagelements as $tag) {
1673 $tags[$tag->nodeValue] = $tag->nodeValue;
1677 $poco["keywords"] = implode(", ", $tags);
1680 // "dfrn:birthday" contains the birthday converted to UTC
1681 $birthday = $xpath->evaluate($element . "/dfrn:birthday/text()", $context)->item(0)->nodeValue;
1683 if (strtotime($birthday) > time()) {
1684 $bd_timestamp = strtotime($birthday);
1686 $poco["bdyear"] = date("Y", $bd_timestamp);
1689 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1690 $value = $xpath->evaluate($element . "/poco:birthday/text()", $context)->item(0)->nodeValue;
1692 if (!in_array($value, ["", "0000-00-00", "0001-01-01"])) {
1693 $bdyear = date("Y");
1694 $value = str_replace("0000", $bdyear, $value);
1696 if (strtotime($value) < time()) {
1697 $value = str_replace($bdyear, $bdyear + 1, $value);
1698 $bdyear = $bdyear + 1;
1701 $poco["bd"] = $value;
1704 $contact = array_merge($contact_old, $poco);
1706 if ($contact_old["bdyear"] != $contact["bdyear"]) {
1707 self::birthdayEvent($contact, $birthday);
1710 // Get all field names
1712 foreach ($contact_old as $field => $data) {
1713 $fields[$field] = $data;
1716 unset($fields["id"]);
1717 unset($fields["uid"]);
1718 unset($fields["url"]);
1719 unset($fields["avatar-date"]);
1720 unset($fields["avatar"]);
1721 unset($fields["name-date"]);
1722 unset($fields["uri-date"]);
1725 // Update check for this field has to be done differently
1726 $datefields = ["name-date", "uri-date"];
1727 foreach ($datefields as $field) {
1728 if (strtotime($contact[$field]) > strtotime($contact_old[$field])) {
1729 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1734 foreach ($fields as $field => $data) {
1735 if ($contact[$field] != $contact_old[$field]) {
1736 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1742 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1745 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1746 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1747 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1748 WHERE `id` = %d AND `network` = '%s'",
1749 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
1750 dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1751 dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
1752 dbesc(DBM::date($contact["name-date"])), dbesc(DBM::date($contact["uri-date"])),
1753 intval($contact["id"]), dbesc($contact["network"])
1757 Contact::updateAvatar(
1759 $importer['importer_uid'],
1761 (strtotime($contact['avatar-date']) > strtotime($contact_old['avatar-date']) || ($author['avatar'] != $contact_old['avatar']))
1765 * The generation is a sign for the reliability of the provided data.
1766 * It is used in the socgraph.php to prevent that old contact data
1767 * that was relayed over several servers can overwrite contact
1768 * data that we received directly.
1771 $poco["generation"] = 2;
1772 $poco["photo"] = $author["avatar"];
1773 $poco["hide"] = $hide;
1774 $poco["contact-type"] = $contact["contact-type"];
1775 $gcid = GContact::update($poco);
1777 GContact::link($gcid, $importer["importer_uid"], $contact["id"]);
1784 * @brief Transforms activity objects into an XML string
1786 * @param object $xpath XPath object
1787 * @param object $activity Activity object
1788 * @param string $element element name
1790 * @return string XML string
1791 * @todo Find good type-hints for all parameter
1793 private static function transformActivity($xpath, $activity, $element)
1795 if (!is_object($activity)) {
1799 $obj_doc = new DOMDocument("1.0", "utf-8");
1800 $obj_doc->formatOutput = true;
1802 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1804 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1805 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1807 $id = $xpath->query("atom:id", $activity)->item(0);
1808 if (is_object($id)) {
1809 $obj_element->appendChild($obj_doc->importNode($id, true));
1812 $title = $xpath->query("atom:title", $activity)->item(0);
1813 if (is_object($title)) {
1814 $obj_element->appendChild($obj_doc->importNode($title, true));
1817 $links = $xpath->query("atom:link", $activity);
1818 if (is_object($links)) {
1819 foreach ($links as $link) {
1820 $obj_element->appendChild($obj_doc->importNode($link, true));
1824 $content = $xpath->query("atom:content", $activity)->item(0);
1825 if (is_object($content)) {
1826 $obj_element->appendChild($obj_doc->importNode($content, true));
1829 $obj_doc->appendChild($obj_element);
1831 $objxml = $obj_doc->saveXML($obj_element);
1833 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1834 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1839 * @brief Processes the mail elements
1841 * @param object $xpath XPath object
1842 * @param object $mail mail elements
1843 * @param array $importer Record of the importer user mixed with contact of the content
1845 * @todo Find good type-hints for all parameter
1847 private static function processMail($xpath, $mail, $importer)
1849 logger("Processing mails");
1851 /// @TODO Rewrite this to one statement
1853 $msg["uid"] = $importer["importer_uid"];
1854 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1855 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1856 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1857 $msg["contact-id"] = $importer["id"];
1858 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1859 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1860 $msg["created"] = DateTimeFormat::utc($xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue);
1861 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1862 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1864 $msg["replied"] = 0;
1866 dba::insert('mail', $msg);
1868 // send notifications.
1869 /// @TODO Arange this mess
1871 "type" => NOTIFY_MAIL,
1872 "notify_flags" => $importer["notify-flags"],
1873 "language" => $importer["language"],
1874 "to_name" => $importer["username"],
1875 "to_email" => $importer["email"],
1876 "uid" => $importer["importer_uid"],
1878 "source_name" => $msg["from-name"],
1879 "source_link" => $importer["url"],
1880 "source_photo" => $importer["thumb"],
1881 "verb" => ACTIVITY_POST,
1885 notification($notif_params);
1887 logger("Mail is processed, notification was sent.");
1891 * @brief Processes the suggestion elements
1893 * @param object $xpath XPath object
1894 * @param object $suggestion suggestion elements
1895 * @param array $importer Record of the importer user mixed with contact of the content
1897 * @todo Find good type-hints for all parameter
1899 private static function processSuggestion($xpath, $suggestion, $importer)
1903 logger("Processing suggestions");
1905 /// @TODO Rewrite this to one statement
1907 $suggest["uid"] = $importer["importer_uid"];
1908 $suggest["cid"] = $importer["id"];
1909 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1910 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1911 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1912 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1913 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1915 // Does our member already have a friend matching this description?
1918 "SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1919 dbesc($suggest["name"]),
1920 dbesc(normalise_link($suggest["url"])),
1921 intval($suggest["uid"])
1925 * The valid result means the friend we're about to send a friend
1926 * suggestion already has them in their contact, which means no further
1927 * action is required.
1929 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1931 if (DBM::is_result($r)) {
1935 // Do we already have an fcontact record for this person?
1939 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1940 dbesc($suggest["url"]),
1941 dbesc($suggest["name"]),
1942 dbesc($suggest["request"])
1944 if (DBM::is_result($r)) {
1947 // OK, we do. Do we already have an introduction for this person ?
1949 "SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1950 intval($suggest["uid"]),
1955 * The valid result means the friend we're about to send a friend
1956 * suggestion already has them in their contact, which means no further
1957 * action is required.
1959 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1961 if (DBM::is_result($r)) {
1967 "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1968 dbesc($suggest["name"]),
1969 dbesc($suggest["url"]),
1970 dbesc($suggest["photo"]),
1971 dbesc($suggest["request"])
1975 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1976 dbesc($suggest["url"]),
1977 dbesc($suggest["name"]),
1978 dbesc($suggest["request"])
1982 * If no record in fcontact is found, below INSERT statement will not
1983 * link an introduction to it.
1985 if (!DBM::is_result($r)) {
1986 // database record did not get created. Quietly give up.
1992 $hash = random_string();
1995 "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1996 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1997 intval($suggest["uid"]),
1999 intval($suggest["cid"]),
2000 dbesc($suggest["body"]),
2002 dbesc(DateTimeFormat::utcNow()),
2008 "type" => NOTIFY_SUGGEST,
2009 "notify_flags" => $importer["notify-flags"],
2010 "language" => $importer["language"],
2011 "to_name" => $importer["username"],
2012 "to_email" => $importer["email"],
2013 "uid" => $importer["importer_uid"],
2015 "link" => System::baseUrl()."/notifications/intros",
2016 "source_name" => $importer["name"],
2017 "source_link" => $importer["url"],
2018 "source_photo" => $importer["photo"],
2019 "verb" => ACTIVITY_REQ_FRIEND,
2027 * @brief Processes the relocation elements
2029 * @param object $xpath XPath object
2030 * @param object $relocation relocation elements
2031 * @param array $importer Record of the importer user mixed with contact of the content
2033 * @todo Find good type-hints for all parameter
2035 private static function processRelocation($xpath, $relocation, $importer)
2037 logger("Processing relocations");
2039 /// @TODO Rewrite this to one statement
2041 $relocate["uid"] = $importer["importer_uid"];
2042 $relocate["cid"] = $importer["id"];
2043 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
2044 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
2045 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
2046 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
2047 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
2048 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
2049 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
2050 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
2051 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
2052 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
2053 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
2054 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
2056 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
2057 $relocate["avatar"] = $relocate["photo"];
2060 if ($relocate["addr"] == "") {
2061 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
2066 "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
2067 intval($importer["id"]),
2068 intval($importer["importer_uid"])
2071 if (!DBM::is_result($r)) {
2072 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2078 // Update the gcontact entry
2079 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
2081 $fields = ['name' => $relocate["name"], 'photo' => $relocate["avatar"],
2082 'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2083 'addr' => $relocate["addr"], 'connect' => $relocate["addr"],
2084 'notify' => $relocate["notify"], 'server_url' => $relocate["server_url"]];
2085 dba::update('gcontact', $fields, ['nurl' => normalise_link($old["url"])]);
2087 // Update the contact table. We try to find every entry.
2088 $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
2089 'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2090 'addr' => $relocate["addr"], 'request' => $relocate["request"],
2091 'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
2092 'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
2093 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], normalise_link($old["url"])];
2094 dba::update('contact', $fields, $condition);
2096 // @TODO No dba:update here?
2097 dba::update('contact', $fields, $condition);
2099 Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
2101 logger('Contacts are updated.');
2104 // This is an extreme performance killer
2105 Item::update(['owner-link' => $relocate["url"]], ['owner-link' => $old["url"], 'uid' => $importer["importer_uid"]]);
2106 Item::update(['author-link' => $relocate["url"]], ['author-link' => $old["url"], 'uid' => $importer["importer_uid"]]);
2108 logger('Items are updated.');
2111 /// merge with current record, current contents have priority
2112 /// update record, set url-updated
2113 /// update profile photos
2114 /// schedule a scan?
2119 * @brief Updates an item
2121 * @param array $current the current item record
2122 * @param array $item the new item record
2123 * @param array $importer Record of the importer user mixed with contact of the content
2124 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2126 * @todo set proper type-hints (array?)
2128 private static function updateContent($current, $item, $importer, $entrytype)
2132 if (self::isEditedTimestampNewer($current, $item)) {
2133 // do not accept (ignore) an earlier edit than one we currently have.
2134 if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
2138 $fields = ['title' => defaults($item, 'title', ''), 'body' => defaults($item, 'body', ''),
2139 'tag' => defaults($item, 'tag', ''), 'changed' => DateTimeFormat::utcNow(),
2140 'edited' => DateTimeFormat::utc($item["edited"])];
2142 $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
2143 Item::update($fields, $condition);
2151 * @brief Detects the entry type of the item
2153 * @param array $importer Record of the importer user mixed with contact of the content
2154 * @param array $item the new item record
2156 * @return int Is it a toplevel entry, a comment or a relayed comment?
2157 * @todo set proper type-hints (array?)
2159 private static function getEntryType($importer, $item)
2161 if ($item["parent-uri"] != $item["uri"]) {
2164 if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
2167 logger("possible community action");
2169 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2172 // was the top-level post for this action written by somebody on this site?
2173 // Specifically, the recipient?
2175 $is_a_remote_action = false;
2178 "SELECT `item`.`parent-uri` FROM `item`
2179 WHERE `item`.`uri` = '%s'
2181 dbesc($item["parent-uri"])
2183 if (DBM::is_result($r)) {
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 dbesc($r[0]["parent-uri"]),
2192 dbesc($r[0]["parent-uri"]),
2193 dbesc($r[0]["parent-uri"]),
2194 intval($importer["importer_uid"])
2196 if (DBM::is_result($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 // send a notification
2258 "type" => NOTIFY_POKE,
2259 "notify_flags" => $importer["notify-flags"],
2260 "language" => $importer["language"],
2261 "to_name" => $importer["username"],
2262 "to_email" => $importer["email"],
2263 "uid" => $importer["importer_uid"],
2265 "link" => System::baseUrl()."/display/".urlencode(Item::getGuidById($posted_id)),
2266 "source_name" => $author["name"],
2267 "source_link" => $author["url"],
2268 "source_photo" => $author["thumb"],
2269 "verb" => $item["verb"],
2270 "otype" => "person",
2271 "activity" => $verb,
2272 "parent" => $item["parent"]]
2279 * @brief Processes several actions, depending on the verb
2281 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2282 * @param array $importer Record of the importer user mixed with contact of the content
2283 * @param array $item the new item record
2284 * @param bool $is_like Is the verb a "like"?
2286 * @return bool Should the processing of the entries be continued?
2287 * @todo set proper type-hints (array?)
2289 private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2291 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2293 if (($entrytype == DFRN::TOP_LEVEL)) {
2294 // The filling of the the "contact" variable is done for legcy reasons
2295 // The functions below are partly used by ostatus.php as well - where we have this variable
2296 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2298 $nickname = $contact["nick"];
2300 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2301 // This function once was responsible for DFRN and OStatus.
2302 if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2303 logger("New follower");
2304 Contact::addRelationship($importer, $contact, $item, $nickname);
2307 if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2308 logger("Lost follower");
2309 Contact::removeFollower($importer, $contact, $item);
2312 if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2313 logger("New friend request");
2314 Contact::addRelationship($importer, $contact, $item, $nickname, true);
2317 if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2318 logger("Lost sharer");
2319 Contact::removeSharer($importer, $contact, $item);
2323 if (($item["verb"] == ACTIVITY_LIKE)
2324 || ($item["verb"] == ACTIVITY_DISLIKE)
2325 || ($item["verb"] == ACTIVITY_ATTEND)
2326 || ($item["verb"] == ACTIVITY_ATTENDNO)
2327 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
2330 $item["type"] = "activity";
2331 $item["gravity"] = GRAVITY_LIKE;
2332 // only one like or dislike per person
2333 // splitted into two queries for performance issues
2335 "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-id` = %d AND `verb` = '%s' AND `parent-uri` = '%s' AND NOT `deleted` LIMIT 1",
2336 intval($item["uid"]),
2337 intval($item["author-id"]),
2338 dbesc($item["verb"]),
2339 dbesc($item["parent-uri"])
2341 if (DBM::is_result($r)) {
2346 "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-id` = %d AND `verb` = '%s' AND `thr-parent` = '%s' AND NOT `deleted` LIMIT 1",
2347 intval($item["uid"]),
2348 intval($item["author-id"]),
2349 dbesc($item["verb"]),
2350 dbesc($item["parent-uri"])
2352 if (DBM::is_result($r)) {
2359 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2360 $xo = XML::parseString($item["object"], false);
2361 $xt = XML::parseString($item["target"], false);
2363 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2365 "SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2367 intval($importer["importer_uid"])
2370 if (!DBM::is_result($r)) {
2371 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2375 // extract tag, if not duplicate, add to parent item
2377 if (!stristr($r[0]["tag"], trim($xo->content))) {
2378 $tag = $r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2379 Item::update(['tag' => $tag], ['id' => $r[0]["id"]]);
2389 * @brief Processes the link elements
2391 * @param object $links link elements
2392 * @param array $item the item record
2394 * @todo set proper type-hints
2396 private static function parseLinks($links, &$item)
2403 foreach ($links as $link) {
2404 foreach ($link->attributes as $attributes) {
2405 switch ($attributes->name) {
2406 case "href" : $href = $attributes->textContent; break;
2407 case "rel" : $rel = $attributes->textContent; break;
2408 case "type" : $type = $attributes->textContent; break;
2409 case "length": $length = $attributes->textContent; break;
2410 case "title" : $title = $attributes->textContent; break;
2413 if (($rel != "") && ($href != "")) {
2416 $item["plink"] = $href;
2420 if (strlen($item["attach"])) {
2421 $item["attach"] .= ",";
2424 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2432 * @brief Processes the entry elements which contain the items and comments
2434 * @param array $header Array of the header elements that always stay the same
2435 * @param object $xpath XPath object
2436 * @param object $entry entry elements
2437 * @param array $importer Record of the importer user mixed with contact of the content
2438 * @param object $xml xml
2440 * @todo Add type-hints
2442 private static function processEntry($header, $xpath, $entry, $importer, $xml)
2444 logger("Processing entries");
2448 $item["protocol"] = PROTOCOL_DFRN;
2450 $item["source"] = $xml;
2453 $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
2455 $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
2457 $current = dba::selectFirst('item',
2458 ['id', 'uid', 'edited', 'body'],
2459 ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
2461 // Is there an existing item?
2462 if (DBM::is_result($current) && !self::isEditedTimestampNewer($current, $item)) {
2463 logger("Item ".$item["uri"]." (".$item['edited'].") already existed.", LOGGER_DEBUG);
2468 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2470 $item["owner-link"] = $owner["link"];
2471 $item["owner-id"] = Contact::getIdForURL($owner["link"], 0);
2474 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2476 $item["author-link"] = $author["link"];
2477 $item["author-id"] = Contact::getIdForURL($author["link"], 0);
2479 $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
2481 $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2483 $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
2484 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2485 // make sure nobody is trying to sneak some html tags by us
2486 $item["body"] = notags(base64url_decode($item["body"]));
2488 $item["body"] = BBCode::limitBodySize($item["body"]);
2490 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2491 if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
2492 $base_url = get_app()->get_baseurl();
2493 $item['body'] = reltoabs($item['body'], $base_url);
2495 $item['body'] = html2bb_video($item['body']);
2497 $item['body'] = OEmbed::HTML2BBCode($item['body']);
2499 $config = HTMLPurifier_Config::createDefault();
2500 $config->set('Cache.DefinitionImpl', null);
2502 // we shouldn't need a whitelist, because the bbcode converter
2503 // will strip out any unsupported tags.
2505 $purifier = new HTMLPurifier($config);
2506 $item['body'] = $purifier->purify($item['body']);
2508 $item['body'] = @HTML::toBBCode($item['body']);
2511 /// @todo We should check for a repeated post and if we know the repeated author.
2513 // We don't need the content element since "dfrn:env" is always present
2514 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2516 $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
2518 $georsspoint = $xpath->query("georss:point", $entry);
2520 $item["coord"] = $georsspoint->item(0)->nodeValue;
2523 $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
2525 $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
2527 if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true") {
2528 $item["bookmark"] = true;
2531 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2532 if ($notice_info && ($notice_info->length > 0)) {
2533 foreach ($notice_info->item(0)->attributes as $attributes) {
2534 if ($attributes->name == "source") {
2535 $item["app"] = strip_tags($attributes->textContent);
2540 $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
2542 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
2543 $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
2544 if ($dsprsig != "") {
2545 $item["dsprsig"] = $dsprsig;
2548 $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
2550 if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "") {
2551 $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
2554 $object = $xpath->query("activity:object", $entry)->item(0);
2555 $item["object"] = self::transformActivity($xpath, $object, "object");
2557 if (trim($item["object"]) != "") {
2558 $r = XML::parseString($item["object"], false);
2559 if (isset($r->type)) {
2560 $item["object-type"] = $r->type;
2564 $target = $xpath->query("activity:target", $entry)->item(0);
2565 $item["target"] = self::transformActivity($xpath, $target, "target");
2567 $categories = $xpath->query("atom:category", $entry);
2569 foreach ($categories as $category) {
2572 foreach ($category->attributes as $attributes) {
2573 if ($attributes->name == "term") {
2574 $term = $attributes->textContent;
2577 if ($attributes->name == "scheme") {
2578 $scheme = $attributes->textContent;
2582 if (($term != "") && ($scheme != "")) {
2583 $parts = explode(":", $scheme);
2584 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2585 $termhash = array_shift($parts);
2586 $termurl = implode(":", $parts);
2588 if (strlen($item["tag"])) {
2589 $item["tag"] .= ",";
2592 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2600 $links = $xpath->query("atom:link", $entry);
2602 self::parseLinks($links, $item);
2605 $item['conversation-uri'] = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
2607 $conv = $xpath->query('ostatus:conversation', $entry);
2608 if (is_object($conv->item(0))) {
2609 foreach ($conv->item(0)->attributes as $attributes) {
2610 if ($attributes->name == "ref") {
2611 $item['conversation-uri'] = $attributes->textContent;
2613 if ($attributes->name == "href") {
2614 $item['conversation-href'] = $attributes->textContent;
2619 // Is it a reply or a top level posting?
2620 $item["parent-uri"] = $item["uri"];
2622 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2623 if (is_object($inreplyto->item(0))) {
2624 foreach ($inreplyto->item(0)->attributes as $attributes) {
2625 if ($attributes->name == "ref") {
2626 $item["parent-uri"] = $attributes->textContent;
2631 // Get the type of the item (Top level post, reply or remote reply)
2632 $entrytype = self::getEntryType($importer, $item);
2634 // Now assign the rest of the values that depend on the type of the message
2635 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2636 if (!isset($item["object-type"])) {
2637 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2640 if ($item["contact-id"] != $owner["contact-id"]) {
2641 $item["contact-id"] = $owner["contact-id"];
2644 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2645 $item["network"] = $owner["network"];
2648 if ($item["contact-id"] != $author["contact-id"]) {
2649 $item["contact-id"] = $author["contact-id"];
2652 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2653 $item["network"] = $author["network"];
2657 if ($entrytype == DFRN::REPLY_RC) {
2658 $item["type"] = "remote-comment";
2660 } elseif ($entrytype == DFRN::TOP_LEVEL) {
2661 if (!isset($item["object-type"])) {
2662 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2666 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2667 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2668 $ev = Event::fromBBCode($item["body"]);
2669 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2670 logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2671 $ev["cid"] = $importer["id"];
2672 $ev["uid"] = $importer["importer_uid"];
2673 $ev["uri"] = $item["uri"];
2674 $ev["edited"] = $item["edited"];
2675 $ev["private"] = $item["private"];
2676 $ev["guid"] = $item["guid"];
2679 "SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2680 dbesc($item["uri"]),
2681 intval($importer["importer_uid"])
2683 if (DBM::is_result($r)) {
2684 $ev["id"] = $r[0]["id"];
2687 $event_id = Event::store($ev);
2688 logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2694 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2695 logger("Exiting because 'processVerbs' told us so", LOGGER_DEBUG);
2699 // Update content if 'updated' changes
2700 if (DBM::is_result($current)) {
2701 if (self::updateContent($current, $item, $importer, $entrytype)) {
2702 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2704 logger("Item " . $item["uri"] . " already existed.", LOGGER_DEBUG);
2709 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2710 $posted_id = Item::insert($item);
2714 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2716 if ($item['uid'] == 0) {
2717 Item::distribute($posted_id);
2722 } else { // $entrytype == DFRN::TOP_LEVEL
2723 if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
2724 logger("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", LOGGER_DEBUG);
2727 if (!link_compare($item["owner-link"], $importer["url"])) {
2729 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2730 * but otherwise there's a possible data mixup on the sender's system.
2731 * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2732 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2734 logger('Correcting item owner.', LOGGER_DEBUG);
2735 $item["owner-link"] = $importer["url"];
2736 $item["owner-id"] = Contact::getIdForURL($importer["url"], 0);
2739 if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2740 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2744 // This is my contact on another system, but it's really me.
2745 // Turn this into a wall post.
2746 $notify = Item::isRemoteSelf($importer, $item);
2748 $posted_id = Item::insert($item, false, $notify);
2751 $posted_id = $notify;
2754 logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2756 if ($item['uid'] == 0) {
2757 Item::distribute($posted_id);
2760 if (stristr($item["verb"], ACTIVITY_POKE)) {
2761 self::doPoke($item, $importer, $posted_id);
2767 * @brief Deletes items
2769 * @param object $xpath XPath object
2770 * @param object $deletion deletion elements
2771 * @param array $importer Record of the importer user mixed with contact of the content
2773 * @todo set proper type-hints
2775 private static function processDeletion($xpath, $deletion, $importer)
2777 logger("Processing deletions");
2780 foreach ($deletion->attributes as $attributes) {
2781 if ($attributes->name == "ref") {
2782 $uri = $attributes->textContent;
2786 if (!$uri || !$importer["id"]) {
2790 $condition = ["`uri` = ? AND `uid` = ? AND NOT `file` LIKE '%[%'", $uri, $importer["importer_uid"]];
2791 $item = dba::selectFirst('item', ['id', 'parent', 'contact-id'], $condition);
2792 if (!DBM::is_result($item)) {
2793 logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", LOGGER_DEBUG);
2797 // When it is a starting post it has to belong to the person that wants to delete it
2798 if (($item['id'] == $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2799 logger("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2803 // Comments can be deleted by the thread owner or comment owner
2804 if (($item['id'] != $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2805 $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2806 if (!dba::exists('item', $condition)) {
2807 logger("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2812 if ($item["deleted"]) {
2816 logger('deleting item '.$item['id'].' uri='.$uri, LOGGER_DEBUG);
2818 Item::delete(['id' => $item['id']]);
2822 * @brief Imports a DFRN message
2824 * @param string $xml The DFRN message
2825 * @param array $importer Record of the importer user mixed with contact of the content
2826 * @param bool $sort_by_date Is used when feeds are polled
2827 * @return integer Import status
2828 * @todo set proper type-hints
2830 public static function import($xml, $importer, $sort_by_date = false)
2836 $doc = new DOMDocument();
2837 @$doc->loadXML($xml);
2839 $xpath = new DOMXPath($doc);
2840 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2841 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2842 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2843 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2844 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2845 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2846 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2847 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2848 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2849 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2852 $header["uid"] = $importer["importer_uid"];
2853 $header["network"] = NETWORK_DFRN;
2854 $header["type"] = "remote";
2855 $header["wall"] = 0;
2856 $header["origin"] = 0;
2857 $header["contact-id"] = $importer["id"];
2859 // Update the contact table if the data has changed
2861 // The "atom:author" is only present in feeds
2862 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2863 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2866 // Only the "dfrn:owner" in the head section contains all data
2867 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2868 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2871 logger("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2873 // is it a public forum? Private forums aren't exposed with this method
2874 $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()")->item(0)->nodeValue);
2876 // The account type is new since 3.5.1
2877 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2878 $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()")->item(0)->nodeValue);
2880 if ($accounttype != $importer["contact-type"]) {
2881 dba::update('contact', ['contact-type' => $accounttype], ['id' => $importer["id"]]);
2883 // A forum contact can either have set "forum" or "prv" - but not both
2884 if (($accounttype == ACCOUNT_TYPE_COMMUNITY) && (($forum != $importer["forum"]) || ($forum == $importer["prv"]))) {
2885 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer["id"]];
2886 dba::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2888 } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
2889 $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2890 dba::update('contact', ['forum' => $forum], $condition);
2894 // We are processing relocations even if we are ignoring a contact
2895 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2896 foreach ($relocations as $relocation) {
2897 self::processRelocation($xpath, $relocation, $importer);
2900 if (($importer["uid"] != 0) && !$importer["readonly"]) {
2901 $mails = $xpath->query("/atom:feed/dfrn:mail");
2902 foreach ($mails as $mail) {
2903 self::processMail($xpath, $mail, $importer);
2906 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2907 foreach ($suggestions as $suggestion) {
2908 self::processSuggestion($xpath, $suggestion, $importer);
2912 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2913 foreach ($deletions as $deletion) {
2914 self::processDeletion($xpath, $deletion, $importer);
2917 if (!$sort_by_date) {
2918 $entries = $xpath->query("/atom:feed/atom:entry");
2919 foreach ($entries as $entry) {
2920 self::processEntry($header, $xpath, $entry, $importer, $xml);
2924 $entries = $xpath->query("/atom:feed/atom:entry");
2925 foreach ($entries as $entry) {
2926 $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2927 $newentries[strtotime($created)] = $entry;
2930 // Now sort after the publishing date
2933 foreach ($newentries as $entry) {
2934 self::processEntry($header, $xpath, $entry, $importer, $xml);
2937 logger("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2943 * @param string $contact_nick contact nickname
2945 public static function autoRedir(App $a, $contact_nick)
2948 if (x($_REQUEST, 'redir') && intval($_REQUEST['redir'])) {
2952 if ((! $contact_nick) || ($contact_nick === $a->user['nickname'])) {
2957 // We need to find out if $contact_nick is a user on this hub, and if so, if I
2958 // am a contact of that user. However, that user may have other contacts with the
2959 // same nickname as me on other hubs or other networks. Exclude these by requiring
2960 // that the contact have a local URL. I will be the only person with my nickname at
2961 // this URL, so if a result is found, then I am a contact of the $contact_nick user.
2963 // We also have to make sure that I'm a legitimate contact--I'm not blocked or pending.
2965 $baseurl = System::baseUrl();
2966 $domain_st = strpos($baseurl, "://");
2967 if ($domain_st === false) {
2970 $baseurl = substr($baseurl, $domain_st + 3);
2971 $nurl = normalise_link($baseurl);
2973 /// @todo Why is there a query for "url" *and* "nurl"? Especially this normalising is strange.
2974 $r = q("SELECT `id` FROM `contact` WHERE `uid` = (SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1)
2975 AND `nick` = '%s' AND NOT `self` AND (`url` LIKE '%%%s%%' OR `nurl` LIKE '%%%s%%') AND NOT `blocked` AND NOT `pending` LIMIT 1",
2976 dbesc($contact_nick),
2977 dbesc($a->user['nickname']),
2981 if ((! DBM::is_result($r)) || $r[0]['id'] == remote_user()) {
2985 $r = q("SELECT * FROM contact WHERE nick = '%s'
2986 AND network = '%s' AND uid = %d AND url LIKE '%%%s%%' LIMIT 1",
2987 dbesc($contact_nick),
2988 dbesc(NETWORK_DFRN),
2989 intval(local_user()),
2992 if (! DBM::is_result($r)) {
2998 $dfrn_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
3000 if ($r[0]['duplex'] && $r[0]['issued-id']) {
3001 $orig_id = $r[0]['issued-id'];
3002 $dfrn_id = '1:' . $orig_id;
3004 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
3005 $orig_id = $r[0]['dfrn-id'];
3006 $dfrn_id = '0:' . $orig_id;
3009 // ensure that we've got a valid ID. There may be some edge cases with forums and non-duplex mode
3010 // that may have triggered some of the "went to {profile/intro} and got an RSS feed" issues
3012 if (strlen($dfrn_id) < 3) {
3016 $sec = random_string();
3018 dba::insert('profile_check', ['uid' => local_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id, 'sec' => $sec, 'expire' => time() + 45]);
3020 $url = curPageURL();
3022 logger('auto_redir: ' . $r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
3023 $dest = (($url) ? '&destination_url=' . $url : '');
3024 goaway($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
3025 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest);
3032 * @brief Returns the activity verb
3034 * @param array $item Item array
3036 * @return string activity verb
3038 private static function constructVerb(array $item)
3040 if ($item['verb']) {
3041 return $item['verb'];
3043 return ACTIVITY_POST;
3046 private static function tgroupCheck($uid, $item)
3050 // check that the message originated elsewhere and is a top-level post
3052 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['parent-uri'])) {
3056 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
3059 if (!DBM::is_result($u)) {
3063 $community_page = ($u[0]['page-flags'] == PAGE_COMMUNITY);
3064 $prvgroup = ($u[0]['page-flags'] == PAGE_PRVGROUP);
3066 $link = normalise_link(System::baseUrl() . '/profile/' . $u[0]['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/' . $u[0]['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);