3 * @file include/dfrn.php
4 * @brief The implementation of the dfrn protocol
6 * @see https://github.com/friendica/friendica/wiki/Protocol and
7 * https://github.com/friendica/friendica/blob/master/spec/dfrn2.pdf
9 namespace Friendica\Protocol;
14 use Friendica\Content\OEmbed;
15 use Friendica\Content\Text\BBCode;
16 use Friendica\Content\Text\HTML;
17 use Friendica\Core\Addon;
18 use Friendica\Core\Config;
19 use Friendica\Core\L10n;
20 use Friendica\Core\System;
21 use Friendica\Database\DBA;
22 use Friendica\Database\DBM;
23 use Friendica\Model\Contact;
24 use Friendica\Model\Event;
25 use Friendica\Model\GContact;
26 use Friendica\Model\Group;
27 use Friendica\Model\Item;
28 use Friendica\Model\Profile;
29 use Friendica\Model\User;
30 use Friendica\Object\Image;
31 use Friendica\Util\Crypto;
32 use Friendica\Util\DateTimeFormat;
33 use Friendica\Util\Network;
34 use Friendica\Util\XML;
36 use HTMLPurifier_Config;
38 require_once 'boot.php';
39 require_once 'include/dba.php';
40 require_once "include/enotify.php";
41 require_once "include/items.php";
42 require_once "include/text.php";
45 * @brief This class contain functions to create and send DFRN XML files
50 const TOP_LEVEL = 0; // Top level posting
51 const REPLY = 1; // Regular reply that is stored locally
52 const REPLY_RC = 2; // Reply that will be relayed
55 * @brief Generates the atom entries for delivery.php
57 * This function is used whenever content is transmitted via DFRN.
59 * @param array $items Item elements
60 * @param array $owner Owner record
62 * @return string DFRN entries
63 * @todo Find proper type-hints
65 public static function entries($items, $owner)
67 $doc = new DOMDocument('1.0', 'utf-8');
68 $doc->formatOutput = true;
70 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
72 if (! count($items)) {
73 return trim($doc->saveXML());
76 foreach ($items as $item) {
77 // These values aren't sent when sending from the queue.
78 /// @todo Check if we can set these values from the queue or if they are needed at all.
79 $item["entry:comment-allow"] = defaults($item, "entry:comment-allow", true);
80 $item["entry:cid"] = defaults($item, "entry:cid", 0);
82 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
83 $root->appendChild($entry);
86 return trim($doc->saveXML());
90 * @brief Generate an atom feed for the given user
92 * This function is called when another server is pulling data from the user feed.
94 * @param string $dfrn_id DFRN ID from the requesting party
95 * @param string $owner_nick Owner nick name
96 * @param string $last_update Date of the last update
97 * @param int $direction Can be -1, 0 or 1.
98 * @param boolean $onlyheader Output only the header without content? (Default is "no")
100 * @return string DFRN feed entries
102 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false)
106 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
107 $public_feed = (($dfrn_id) ? false : true);
108 $starred = false; // not yet implemented, possible security issues
111 if ($public_feed && $a->argc > 2) {
112 for ($x = 2; $x < $a->argc; $x++) {
113 if ($a->argv[$x] == 'converse') {
116 if ($a->argv[$x] == 'starred') {
119 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
120 $category = $a->argv[$x+1];
125 // default permissions - anonymous user
127 $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = '' ";
130 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
131 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
132 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
136 if (! DBM::is_result($r)) {
137 logger(sprintf('No contact found for nickname=%d', $owner_nick), LOGGER_WARNING);
142 $owner_id = $owner['uid'];
143 $owner_nick = $owner['nickname'];
145 $sql_post_table = "";
147 if (! $public_feed) {
149 switch ($direction) {
151 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
155 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
156 $my_id = '1:' . $dfrn_id;
159 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
160 $my_id = '0:' . $dfrn_id;
168 "SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
172 if (! DBM::is_result($r)) {
173 logger(sprintf('No contact found for uid=%d', $owner_id), LOGGER_WARNING);
178 include_once 'include/security.php';
179 $groups = Group::getIdsByContactId($contact['id']);
181 if (count($groups)) {
182 for ($x = 0; $x < count($groups); $x ++) {
183 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
186 $gs = implode('|', $groups);
188 $gs = '<<>>' ; // Impossible to match
191 $sql_extra = sprintf(
193 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
194 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
195 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
196 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
198 intval($contact['id']),
199 intval($contact['id']),
211 if (! strlen($last_update)) {
212 $last_update = 'now -30 days';
215 if (isset($category)) {
216 $sql_post_table = sprintf(
217 "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` ",
218 dbesc(protect_sprintf($category)),
219 intval(TERM_OBJ_POST),
220 intval(TERM_CATEGORY),
223 //$sql_extra .= file_tag_file_query('item',$category,'category');
226 if ($public_feed && ! $converse) {
227 $sql_extra .= " AND `contact`.`self` = 1 ";
230 $check_date = DateTimeFormat::utc($last_update);
234 FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
235 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
236 WHERE `item`.`uid` = %d AND `item`.`wall` AND `item`.`changed` > '%s'
238 ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
245 foreach ($r as $item) {
246 $ids[] = $item['id'];
250 $ret = Item::select(Item::DELIVER_FIELDLIST, ['id' => $ids]);
251 $items = Item::inArray($ret);
257 * Will check further below if this actually returned results.
258 * We will provide an empty feed if that is the case.
261 $doc = new DOMDocument('1.0', 'utf-8');
262 $doc->formatOutput = true;
264 $alternatelink = $owner['url'];
266 if (isset($category)) {
267 $alternatelink .= "/category/".$category;
271 $author = "dfrn:owner";
276 $root = self::addHeader($doc, $owner, $author, $alternatelink, true);
278 /// @TODO This hook can't work anymore
279 // Addon::callHooks('atom_feed', $atom);
281 if (!DBM::is_result($items) || $onlyheader) {
282 $atom = trim($doc->saveXML());
284 Addon::callHooks('atom_feed_end', $atom);
289 foreach ($items as $item) {
290 // prevent private email from leaking.
291 if ($item['network'] == NETWORK_MAIL) {
295 // public feeds get html, our own nodes use bbcode
299 // catch any email that's in a public conversation and make sure it doesn't leak
300 if ($item['private']) {
307 $entry = self::entry($doc, $type, $item, $owner, true);
308 $root->appendChild($entry);
311 $atom = trim($doc->saveXML());
313 Addon::callHooks('atom_feed_end', $atom);
319 * @brief Generate an atom entry for a given item id
321 * @param int $item_id The item id
322 * @param boolean $conversation Show the conversation. If false show the single post.
324 * @return string DFRN feed entry
326 public static function itemFeed($item_id, $conversation = false)
329 $condition = ['parent' => $item_id];
331 $condition = ['id' => $item_id];
334 $ret = Item::select(Item::DELIVER_FIELDLIST, $condition);
335 $items = Item::inArray($ret);
336 if (!DBM::is_result($items)) {
342 if ($item['uid'] != 0) {
343 $owner = User::getOwnerDataById($item['uid']);
348 $owner = ['uid' => 0, 'nick' => 'feed-item'];
351 $doc = new DOMDocument('1.0', 'utf-8');
352 $doc->formatOutput = true;
356 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
357 $doc->appendChild($root);
359 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
360 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
361 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
362 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
363 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
364 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
365 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
366 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
367 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
369 //$root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
371 foreach ($items as $item) {
372 $entry = self::entry($doc, $type, $item, $owner, true, 0);
373 $root->appendChild($entry);
376 $root = self::entry($doc, $type, $item, $owner, true, 0, true);
379 $atom = trim($doc->saveXML());
384 * @brief Create XML text for DFRN mails
386 * @param array $item message elements
387 * @param array $owner Owner record
389 * @return string DFRN mail
390 * @todo Find proper type-hints
392 public static function mail($item, $owner)
394 $doc = new DOMDocument('1.0', 'utf-8');
395 $doc->formatOutput = true;
397 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
399 $mail = $doc->createElement("dfrn:mail");
400 $sender = $doc->createElement("dfrn:sender");
402 XML::addElement($doc, $sender, "dfrn:name", $owner['name']);
403 XML::addElement($doc, $sender, "dfrn:uri", $owner['url']);
404 XML::addElement($doc, $sender, "dfrn:avatar", $owner['thumb']);
406 $mail->appendChild($sender);
408 XML::addElement($doc, $mail, "dfrn:id", $item['uri']);
409 XML::addElement($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
410 XML::addElement($doc, $mail, "dfrn:sentdate", DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
411 XML::addElement($doc, $mail, "dfrn:subject", $item['title']);
412 XML::addElement($doc, $mail, "dfrn:content", $item['body']);
414 $root->appendChild($mail);
416 return trim($doc->saveXML());
420 * @brief Create XML text for DFRN friend suggestions
422 * @param array $item suggestion elements
423 * @param array $owner Owner record
425 * @return string DFRN suggestions
426 * @todo Find proper type-hints
428 public static function fsuggest($item, $owner)
430 $doc = new DOMDocument('1.0', 'utf-8');
431 $doc->formatOutput = true;
433 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
435 $suggest = $doc->createElement("dfrn:suggest");
437 XML::addElement($doc, $suggest, "dfrn:url", $item['url']);
438 XML::addElement($doc, $suggest, "dfrn:name", $item['name']);
439 XML::addElement($doc, $suggest, "dfrn:photo", $item['photo']);
440 XML::addElement($doc, $suggest, "dfrn:request", $item['request']);
441 XML::addElement($doc, $suggest, "dfrn:note", $item['note']);
443 $root->appendChild($suggest);
445 return trim($doc->saveXML());
449 * @brief Create XML text for DFRN relocations
451 * @param array $owner Owner record
452 * @param int $uid User ID
454 * @return string DFRN relocations
455 * @todo Find proper type-hints
457 public static function relocate($owner, $uid)
460 /* get site pubkey. this could be a new installation with no site keys*/
461 $pubkey = Config::get('system', 'site_pubkey');
463 $res = Crypto::newKeypair(1024);
464 Config::set('system', 'site_prvkey', $res['prvkey']);
465 Config::set('system', 'site_pubkey', $res['pubkey']);
469 "SELECT `resource-id` , `scale`, type FROM `photo`
470 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;",
474 $ext = Image::supportedTypes();
476 foreach ($rp as $p) {
477 $photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
481 $doc = new DOMDocument('1.0', 'utf-8');
482 $doc->formatOutput = true;
484 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
486 $relocate = $doc->createElement("dfrn:relocate");
488 XML::addElement($doc, $relocate, "dfrn:url", $owner['url']);
489 XML::addElement($doc, $relocate, "dfrn:name", $owner['name']);
490 XML::addElement($doc, $relocate, "dfrn:addr", $owner['addr']);
491 XML::addElement($doc, $relocate, "dfrn:avatar", $owner['avatar']);
492 XML::addElement($doc, $relocate, "dfrn:photo", $photos[4]);
493 XML::addElement($doc, $relocate, "dfrn:thumb", $photos[5]);
494 XML::addElement($doc, $relocate, "dfrn:micro", $photos[6]);
495 XML::addElement($doc, $relocate, "dfrn:request", $owner['request']);
496 XML::addElement($doc, $relocate, "dfrn:confirm", $owner['confirm']);
497 XML::addElement($doc, $relocate, "dfrn:notify", $owner['notify']);
498 XML::addElement($doc, $relocate, "dfrn:poll", $owner['poll']);
499 XML::addElement($doc, $relocate, "dfrn:sitepubkey", Config::get('system', 'site_pubkey'));
501 $root->appendChild($relocate);
503 return trim($doc->saveXML());
507 * @brief Adds the header elements for the DFRN protocol
509 * @param object $doc XML document
510 * @param array $owner Owner record
511 * @param string $authorelement Element name for the author
512 * @param string $alternatelink link to profile or category
513 * @param bool $public Is it a header for public posts?
515 * @return object XML root object
516 * @todo Find proper type-hints
518 private static function addHeader($doc, $owner, $authorelement, $alternatelink = "", $public = false)
521 if ($alternatelink == "") {
522 $alternatelink = $owner['url'];
525 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
526 $doc->appendChild($root);
528 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
529 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
530 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
531 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
532 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
533 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
534 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
535 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
536 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
538 XML::addElement($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
539 XML::addElement($doc, $root, "title", $owner["name"]);
541 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION];
542 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
544 $attributes = ["rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/"];
545 XML::addElement($doc, $root, "link", "", $attributes);
547 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $alternatelink];
548 XML::addElement($doc, $root, "link", "", $attributes);
552 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
553 OStatus::hublinks($doc, $root, $owner["nick"]);
555 $attributes = ["rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
556 XML::addElement($doc, $root, "link", "", $attributes);
558 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
559 XML::addElement($doc, $root, "link", "", $attributes);
561 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
562 XML::addElement($doc, $root, "link", "", $attributes);
565 // For backward compatibility we keep this element
566 if ($owner['page-flags'] == PAGE_COMMUNITY) {
567 XML::addElement($doc, $root, "dfrn:community", 1);
570 // The former element is replaced by this one
571 XML::addElement($doc, $root, "dfrn:account_type", $owner["account-type"]);
573 /// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
575 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
577 $author = self::addAuthor($doc, $owner, $authorelement, $public);
578 $root->appendChild($author);
584 * @brief Adds the author element in the header for the DFRN protocol
586 * @param object $doc XML document
587 * @param array $owner Owner record
588 * @param string $authorelement Element name for the author
589 * @param boolean $public boolean
591 * @return object XML author object
592 * @todo Find proper type-hints
594 private static function addAuthor($doc, $owner, $authorelement, $public)
596 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
598 "SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
599 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
600 intval($owner['uid'])
602 if (DBM::is_result($r)) {
608 $author = $doc->createElement($authorelement);
610 $namdate = DateTimeFormat::utc($owner['name-date'].'+00:00', DateTimeFormat::ATOM);
611 $uridate = DateTimeFormat::utc($owner['uri-date'].'+00:00', DateTimeFormat::ATOM);
612 $picdate = DateTimeFormat::utc($owner['avatar-date'].'+00:00', DateTimeFormat::ATOM);
616 if (!$public || !$hidewall) {
617 $attributes = ["dfrn:updated" => $namdate];
620 XML::addElement($doc, $author, "name", $owner["name"], $attributes);
621 XML::addElement($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
622 XML::addElement($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
624 $attributes = ["rel" => "photo", "type" => "image/jpeg",
625 "media:width" => 175, "media:height" => 175, "href" => $owner['photo']];
627 if (!$public || !$hidewall) {
628 $attributes["dfrn:updated"] = $picdate;
631 XML::addElement($doc, $author, "link", "", $attributes);
633 $attributes["rel"] = "avatar";
634 XML::addElement($doc, $author, "link", "", $attributes);
637 XML::addElement($doc, $author, "dfrn:hide", "true");
640 // The following fields will only be generated if the data isn't meant for a public feed
645 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
648 XML::addElement($doc, $author, "dfrn:birthday", $birthday);
651 // Only show contact details when we are allowed to
653 "SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
654 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
655 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
657 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
658 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
659 intval($owner['uid'])
661 if (DBM::is_result($r)) {
664 XML::addElement($doc, $author, "poco:displayName", $profile["name"]);
665 XML::addElement($doc, $author, "poco:updated", $namdate);
667 if (trim($profile["dob"]) > '0001-01-01') {
668 XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
671 XML::addElement($doc, $author, "poco:note", $profile["about"]);
672 XML::addElement($doc, $author, "poco:preferredUsername", $profile["nickname"]);
674 $savetz = date_default_timezone_get();
675 date_default_timezone_set($profile["timezone"]);
676 XML::addElement($doc, $author, "poco:utcOffset", date("P"));
677 date_default_timezone_set($savetz);
679 if (trim($profile["homepage"]) != "") {
680 $urls = $doc->createElement("poco:urls");
681 XML::addElement($doc, $urls, "poco:type", "homepage");
682 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
683 XML::addElement($doc, $urls, "poco:primary", "true");
684 $author->appendChild($urls);
687 if (trim($profile["pub_keywords"]) != "") {
688 $keywords = explode(",", $profile["pub_keywords"]);
690 foreach ($keywords as $keyword) {
691 XML::addElement($doc, $author, "poco:tags", trim($keyword));
695 if (trim($profile["xmpp"]) != "") {
696 $ims = $doc->createElement("poco:ims");
697 XML::addElement($doc, $ims, "poco:type", "xmpp");
698 XML::addElement($doc, $ims, "poco:value", $profile["xmpp"]);
699 XML::addElement($doc, $ims, "poco:primary", "true");
700 $author->appendChild($ims);
703 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
704 $element = $doc->createElement("poco:address");
706 XML::addElement($doc, $element, "poco:formatted", Profile::formatLocation($profile));
708 if (trim($profile["locality"]) != "") {
709 XML::addElement($doc, $element, "poco:locality", $profile["locality"]);
712 if (trim($profile["region"]) != "") {
713 XML::addElement($doc, $element, "poco:region", $profile["region"]);
716 if (trim($profile["country-name"]) != "") {
717 XML::addElement($doc, $element, "poco:country", $profile["country-name"]);
720 $author->appendChild($element);
728 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
730 * @param object $doc XML document
731 * @param string $element Element name for the author
732 * @param string $contact_url Link of the contact
733 * @param array $item Item elements
735 * @return object XML author object
736 * @todo Find proper type-hints
738 private static function addEntryAuthor($doc, $element, $contact_url, $item)
740 $contact = Contact::getDetailsByURL($contact_url, $item["uid"]);
742 $author = $doc->createElement($element);
743 XML::addElement($doc, $author, "name", $contact["name"]);
744 XML::addElement($doc, $author, "uri", $contact["url"]);
745 XML::addElement($doc, $author, "dfrn:handle", $contact["addr"]);
748 /// - Check real image type and image size
749 /// - Check which of these boths elements we should use
752 "type" => "image/jpeg",
754 "media:height" => 80,
755 "href" => $contact["photo"]];
756 XML::addElement($doc, $author, "link", "", $attributes);
760 "type" => "image/jpeg",
762 "media:height" => 80,
763 "href" => $contact["photo"]];
764 XML::addElement($doc, $author, "link", "", $attributes);
770 * @brief Adds the activity elements
772 * @param object $doc XML document
773 * @param string $element Element name for the activity
774 * @param string $activity activity value
776 * @return object XML activity object
777 * @todo Find proper type-hints
779 private static function createActivity($doc, $element, $activity)
782 $entry = $doc->createElement($element);
784 $r = XML::parseString($activity, false);
790 XML::addElement($doc, $entry, "activity:object-type", $r->type);
794 XML::addElement($doc, $entry, "id", $r->id);
798 XML::addElement($doc, $entry, "title", $r->title);
802 if (substr($r->link, 0, 1) == '<') {
803 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
804 $r->link = str_replace('&', '&', $r->link);
807 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
809 // XML does need a single element as root element so we add a dummy element here
810 $data = XML::parseString("<dummy>" . $r->link . "</dummy>", false);
811 if (is_object($data)) {
812 foreach ($data->link as $link) {
814 foreach ($link->attributes() as $parameter => $value) {
815 $attributes[$parameter] = $value;
817 XML::addElement($doc, $entry, "link", "", $attributes);
821 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
822 XML::addElement($doc, $entry, "link", "", $attributes);
826 XML::addElement($doc, $entry, "content", BBCode::convert($r->content), ["type" => "html"]);
836 * @brief Adds the elements for attachments
838 * @param object $doc XML document
839 * @param object $root XML root
840 * @param array $item Item element
842 * @return object XML attachment object
843 * @todo Find proper type-hints
845 private static function getAttachment($doc, $root, $item)
847 $arr = explode('[/attach],', $item['attach']);
849 foreach ($arr as $r) {
851 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
853 $attributes = ["rel" => "enclosure",
854 "href" => $matches[1],
855 "type" => $matches[3]];
857 if (intval($matches[2])) {
858 $attributes["length"] = intval($matches[2]);
861 if (trim($matches[4]) != "") {
862 $attributes["title"] = trim($matches[4]);
865 XML::addElement($doc, $root, "link", "", $attributes);
872 * @brief Adds the "entry" elements for the DFRN protocol
874 * @param object $doc XML document
875 * @param string $type "text" or "html"
876 * @param array $item Item element
877 * @param array $owner Owner record
878 * @param bool $comment Trigger the sending of the "comment" element
879 * @param int $cid Contact ID of the recipient
880 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
882 * @return object XML entry object
883 * @todo Find proper type-hints
885 private static function entry($doc, $type, array $item, array $owner, $comment = false, $cid = 0, $single = false)
889 if (!$item['parent']) {
893 if ($item['deleted']) {
894 $attributes = ["ref" => $item['uri'], "when" => DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM)];
895 return XML::createElement($doc, "at:deleted-entry", "", $attributes);
899 $entry = $doc->createElement("entry");
901 $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry');
902 $doc->appendChild($entry);
904 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
905 $entry->setAttribute("xmlns:at", NAMESPACE_TOMB);
906 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
907 $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
908 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
909 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
910 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
911 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
912 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
915 if ($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid']) {
916 $body = Item::fixPrivatePhotos($item['body'], $owner['uid'], $item, $cid);
918 $body = $item['body'];
921 // Remove the abstract element. It is only locally important.
922 $body = BBCode::stripAbstract($body);
925 if ($type == 'html') {
928 if ($item['title'] != "") {
929 $htmlbody = "[b]" . $item['title'] . "[/b]\n\n" . $htmlbody;
932 $htmlbody = BBCode::convert($htmlbody, false, 7);
935 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
936 $entry->appendChild($author);
938 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
939 $entry->appendChild($dfrnowner);
941 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
942 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
943 $parent = Item::selectFirst(['guid', 'plink'], ['uri' => $parent_item, 'uid' => $item['uid']]);
944 $attributes = ["ref" => $parent_item, "type" => "text/html",
945 "href" => $parent['plink'],
946 "dfrn:diaspora_guid" => $parent['guid']];
947 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
950 // Add conversation data. This is used for OStatus
951 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
952 $conversation_uri = $conversation_href;
954 if (isset($parent_item)) {
955 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $item['parent-uri']]);
956 if (DBM::is_result($conversation)) {
957 if ($conversation['conversation-uri'] != '') {
958 $conversation_uri = $conversation['conversation-uri'];
960 if ($conversation['conversation-href'] != '') {
961 $conversation_href = $conversation['conversation-href'];
967 "href" => $conversation_href,
968 "ref" => $conversation_uri];
970 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
972 XML::addElement($doc, $entry, "id", $item["uri"]);
973 XML::addElement($doc, $entry, "title", $item["title"]);
975 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"] . "+00:00", DateTimeFormat::ATOM));
976 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"] . "+00:00", DateTimeFormat::ATOM));
978 // "dfrn:env" is used to read the content
979 XML::addElement($doc, $entry, "dfrn:env", base64url_encode($body, true));
981 // The "content" field is not read by the receiver. We could remove it when the type is "text"
982 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
983 XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
985 // We save this value in "plink". Maybe we should read it from there as well?
991 ["rel" => "alternate", "type" => "text/html",
992 "href" => System::baseUrl() . "/display/" . $item["guid"]]
995 // "comment-allow" is some old fashioned stuff for old Friendica versions.
996 // It is included in the rewritten code for completeness
998 XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
1001 if ($item['location']) {
1002 XML::addElement($doc, $entry, "dfrn:location", $item['location']);
1005 if ($item['coord']) {
1006 XML::addElement($doc, $entry, "georss:point", $item['coord']);
1009 if (($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])) {
1010 XML::addElement($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
1013 if ($item['extid']) {
1014 XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
1017 if ($item['post-type'] == Item::PT_PAGE) {
1018 XML::addElement($doc, $entry, "dfrn:bookmark", "true");
1022 XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
1025 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
1027 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
1028 // It is needed for relayed comments to Diaspora.
1029 if ($item['signed_text']) {
1030 $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer']]));
1031 XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
1034 XML::addElement($doc, $entry, "activity:verb", self::constructVerb($item));
1036 if ($item['object-type'] != "") {
1037 XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
1038 } elseif ($item['id'] == $item['parent']) {
1039 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1041 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
1044 $actobj = self::createActivity($doc, "activity:object", $item['object']);
1046 $entry->appendChild($actobj);
1049 $actarg = self::createActivity($doc, "activity:target", $item['target']);
1051 $entry->appendChild($actarg);
1054 $tags = Item::getFeedTags($item);
1056 /// @TODO Combine this with similar below if() block?
1058 foreach ($tags as $t) {
1059 if (($type != 'html') || ($t[0] != "@")) {
1060 XML::addElement($doc, $entry, "category", "", ["scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]]);
1066 foreach ($tags as $t) {
1068 $mentioned[$t[1]] = $t[1];
1073 foreach ($mentioned as $mention) {
1075 "SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1076 intval($owner["uid"]),
1077 dbesc(normalise_link($mention))
1080 if (DBM::is_result($r) && ($r[0]["forum"] || $r[0]["prv"])) {
1086 ["rel" => "mentioned",
1087 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1096 ["rel" => "mentioned",
1097 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1103 self::getAttachment($doc, $entry, $item);
1109 * @brief encrypts data via AES
1111 * @param string $data The data that is to be encrypted
1112 * @param string $key The AES key
1114 * @return string encrypted data
1116 private static function aesEncrypt($data, $key)
1118 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1122 * @brief decrypts data via AES
1124 * @param string $encrypted The encrypted data
1125 * @param string $key The AES key
1127 * @return string decrypted data
1129 public static function aesDecrypt($encrypted, $key)
1131 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1135 * @brief Delivers the atom content to the contacts
1137 * @param array $owner Owner record
1138 * @param array $contact Contact record of the receiver
1139 * @param string $atom Content that will be transmitted
1140 * @param bool $dissolve (to be documented)
1142 * @return int Deliver status. Negative values mean an error.
1143 * @todo Add array type-hint for $owner, $contact
1145 public static function deliver($owner, $contact, $atom, $dissolve = false)
1149 // At first try the Diaspora transport layer
1150 $ret = self::transmit($owner, $contact, $atom);
1152 logger('Delivery via Diaspora transport layer was successful with status ' . $ret);
1156 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1158 if ($contact['duplex'] && $contact['dfrn-id']) {
1159 $idtosend = '0:' . $orig_id;
1161 if ($contact['duplex'] && $contact['issued-id']) {
1162 $idtosend = '1:' . $orig_id;
1165 $rino = Config::get('system', 'rino_encrypt');
1166 $rino = intval($rino);
1168 logger("Local rino version: ". $rino, LOGGER_DEBUG);
1170 $ssl_val = intval(Config::get('system', 'ssl_policy'));
1174 case SSL_POLICY_FULL:
1175 $ssl_policy = 'full';
1177 case SSL_POLICY_SELFSIGN:
1178 $ssl_policy = 'self';
1180 case SSL_POLICY_NONE:
1182 $ssl_policy = 'none';
1186 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1188 logger('dfrn_deliver: ' . $url);
1190 $ret = Network::curl($url);
1192 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1193 Contact::markForArchival($contact);
1194 return -2; // timed out
1197 $xml = $ret['body'];
1199 $curl_stat = $a->get_curl_code();
1200 if (empty($curl_stat)) {
1201 Contact::markForArchival($contact);
1202 return -3; // timed out
1205 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1208 Contact::markForArchival($contact);
1212 if (strpos($xml, '<?xml') === false) {
1213 logger('dfrn_deliver: no valid XML returned');
1214 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1215 Contact::markForArchival($contact);
1219 $res = XML::parseString($xml);
1221 if (!is_object($res) || (intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
1222 Contact::markForArchival($contact);
1224 if (empty($res->status)) {
1227 $status = $res->status;
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"] = XML::getFirstNodeValue($xpath, $element."/atom:name/text()", $context);
1547 $author["link"] = XML::getFirstNodeValue($xpath, $element."/atom:uri/text()", $context);
1549 $fields = ['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 $condition = ["`uid` = ? AND `nurl` = ? AND `network` != ?",
1552 $importer["importer_uid"], normalise_link($author["link"]), NETWORK_STATUSNET];
1553 $contact_old = DBA::selectFirst('contact', $fields, $condition);
1555 if (DBM::is_result($contact_old)) {
1556 $author["contact-id"] = $contact_old["id"];
1557 $author["network"] = $contact_old["network"];
1560 logger("Contact ".$author["link"]." wasn't found for user ".$importer["importer_uid"]." XML: ".$xml, LOGGER_DEBUG);
1563 $author["contact-unknown"] = true;
1564 $author["contact-id"] = $importer["id"];
1565 $author["network"] = $importer["network"];
1569 // Until now we aren't serving different sizes - but maybe later
1571 /// @todo check if "avatar" or "photo" would be the best field in the specification
1572 $avatars = $xpath->query($element . "/atom:link[@rel='avatar']", $context);
1573 foreach ($avatars as $avatar) {
1576 foreach ($avatar->attributes as $attributes) {
1577 /// @TODO Rewrite these similar if() to one switch
1578 if ($attributes->name == "href") {
1579 $href = $attributes->textContent;
1581 if ($attributes->name == "width") {
1582 $width = $attributes->textContent;
1584 if ($attributes->name == "updated") {
1585 $author["avatar-date"] = $attributes->textContent;
1588 if (($width > 0) && ($href != "")) {
1589 $avatarlist[$width] = $href;
1593 if (count($avatarlist) > 0) {
1594 krsort($avatarlist);
1595 $author["avatar"] = current($avatarlist);
1598 if (DBM::is_result($contact_old) && !$onlyfetch) {
1599 logger("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", LOGGER_DEBUG);
1601 $poco = ["url" => $contact_old["url"]];
1603 // When was the last change to name or uri?
1604 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1605 foreach ($name_element->attributes as $attributes) {
1606 if ($attributes->name == "updated") {
1607 $poco["name-date"] = $attributes->textContent;
1611 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1612 foreach ($link_element->attributes as $attributes) {
1613 if ($attributes->name == "updated") {
1614 $poco["uri-date"] = $attributes->textContent;
1618 // Update contact data
1619 $value = XML::getFirstNodeValue($xpath, $element . "/dfrn:handle/text()", $context);
1621 $poco["addr"] = $value;
1624 $value = XML::getFirstNodeValue($xpath, $element . "/poco:displayName/text()", $context);
1626 $poco["name"] = $value;
1629 $value = XML::getFirstNodeValue($xpath, $element . "/poco:preferredUsername/text()", $context);
1631 $poco["nick"] = $value;
1634 $value = XML::getFirstNodeValue($xpath, $element . "/poco:note/text()", $context);
1636 $poco["about"] = $value;
1639 $value = XML::getFirstNodeValue($xpath, $element . "/poco:address/poco:formatted/text()", $context);
1641 $poco["location"] = $value;
1644 /// @todo Only search for elements with "poco:type" = "xmpp"
1645 $value = XML::getFirstNodeValue($xpath, $element . "/poco:ims/poco:value/text()", $context);
1647 $poco["xmpp"] = $value;
1650 /// @todo Add support for the following fields that we don't support by now in the contact table:
1651 /// - poco:utcOffset
1657 // If the "hide" element is present then the profile isn't searchable.
1658 $hide = intval(XML::getFirstNodeValue($xpath, $element . "/dfrn:hide/text()", $context) == "true");
1660 logger("Hidden status for contact " . $contact_old["url"] . ": " . $hide, LOGGER_DEBUG);
1662 // If the contact isn't searchable then set the contact to "hidden".
1663 // Problem: This can be manually overridden by the user.
1665 $contact_old["hidden"] = true;
1668 // Save the keywords into the contact table
1670 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1671 foreach ($tagelements as $tag) {
1672 $tags[$tag->nodeValue] = $tag->nodeValue;
1676 $poco["keywords"] = implode(", ", $tags);
1679 // "dfrn:birthday" contains the birthday converted to UTC
1680 $birthday = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1682 if (strtotime($birthday) > time()) {
1683 $bd_timestamp = strtotime($birthday);
1685 $poco["bdyear"] = date("Y", $bd_timestamp);
1688 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1689 $value = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1691 if (!in_array($value, ["", "0000-00-00", "0001-01-01"])) {
1692 $bdyear = date("Y");
1693 $value = str_replace("0000", $bdyear, $value);
1695 if (strtotime($value) < time()) {
1696 $value = str_replace($bdyear, $bdyear + 1, $value);
1697 $bdyear = $bdyear + 1;
1700 $poco["bd"] = $value;
1703 $contact = array_merge($contact_old, $poco);
1705 if ($contact_old["bdyear"] != $contact["bdyear"]) {
1706 self::birthdayEvent($contact, $birthday);
1709 // Get all field names
1711 foreach ($contact_old as $field => $data) {
1712 $fields[$field] = $data;
1715 unset($fields["id"]);
1716 unset($fields["uid"]);
1717 unset($fields["url"]);
1718 unset($fields["avatar-date"]);
1719 unset($fields["avatar"]);
1720 unset($fields["name-date"]);
1721 unset($fields["uri-date"]);
1724 // Update check for this field has to be done differently
1725 $datefields = ["name-date", "uri-date"];
1726 foreach ($datefields as $field) {
1727 if (strtotime($contact[$field]) > strtotime($contact_old[$field])) {
1728 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1733 foreach ($fields as $field => $data) {
1734 if ($contact[$field] != $contact_old[$field]) {
1735 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1741 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1744 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1745 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1746 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1747 WHERE `id` = %d AND `network` = '%s'",
1748 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
1749 dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1750 dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
1751 dbesc(DateTimeFormat::utc($contact["name-date"])), dbesc(DateTimeFormat::utc($contact["uri-date"])),
1752 intval($contact["id"]), dbesc($contact["network"])
1756 Contact::updateAvatar(
1758 $importer['importer_uid'],
1760 (strtotime($contact['avatar-date']) > strtotime($contact_old['avatar-date']) || ($author['avatar'] != $contact_old['avatar']))
1764 * The generation is a sign for the reliability of the provided data.
1765 * It is used in the socgraph.php to prevent that old contact data
1766 * that was relayed over several servers can overwrite contact
1767 * data that we received directly.
1770 $poco["generation"] = 2;
1771 $poco["photo"] = $author["avatar"];
1772 $poco["hide"] = $hide;
1773 $poco["contact-type"] = $contact["contact-type"];
1774 $gcid = GContact::update($poco);
1776 GContact::link($gcid, $importer["importer_uid"], $contact["id"]);
1783 * @brief Transforms activity objects into an XML string
1785 * @param object $xpath XPath object
1786 * @param object $activity Activity object
1787 * @param string $element element name
1789 * @return string XML string
1790 * @todo Find good type-hints for all parameter
1792 private static function transformActivity($xpath, $activity, $element)
1794 if (!is_object($activity)) {
1798 $obj_doc = new DOMDocument("1.0", "utf-8");
1799 $obj_doc->formatOutput = true;
1801 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1803 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1804 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1806 $id = $xpath->query("atom:id", $activity)->item(0);
1807 if (is_object($id)) {
1808 $obj_element->appendChild($obj_doc->importNode($id, true));
1811 $title = $xpath->query("atom:title", $activity)->item(0);
1812 if (is_object($title)) {
1813 $obj_element->appendChild($obj_doc->importNode($title, true));
1816 $links = $xpath->query("atom:link", $activity);
1817 if (is_object($links)) {
1818 foreach ($links as $link) {
1819 $obj_element->appendChild($obj_doc->importNode($link, true));
1823 $content = $xpath->query("atom:content", $activity)->item(0);
1824 if (is_object($content)) {
1825 $obj_element->appendChild($obj_doc->importNode($content, true));
1828 $obj_doc->appendChild($obj_element);
1830 $objxml = $obj_doc->saveXML($obj_element);
1832 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1833 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1838 * @brief Processes the mail elements
1840 * @param object $xpath XPath object
1841 * @param object $mail mail elements
1842 * @param array $importer Record of the importer user mixed with contact of the content
1844 * @todo Find good type-hints for all parameter
1846 private static function processMail($xpath, $mail, $importer)
1848 logger("Processing mails");
1850 /// @TODO Rewrite this to one statement
1852 $msg["uid"] = $importer["importer_uid"];
1853 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1854 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1855 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1856 $msg["contact-id"] = $importer["id"];
1857 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1858 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1859 $msg["created"] = DateTimeFormat::utc($xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue);
1860 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1861 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1863 $msg["replied"] = 0;
1865 DBA::insert('mail', $msg);
1867 // send notifications.
1868 /// @TODO Arange this mess
1870 "type" => NOTIFY_MAIL,
1871 "notify_flags" => $importer["notify-flags"],
1872 "language" => $importer["language"],
1873 "to_name" => $importer["username"],
1874 "to_email" => $importer["email"],
1875 "uid" => $importer["importer_uid"],
1877 "source_name" => $msg["from-name"],
1878 "source_link" => $importer["url"],
1879 "source_photo" => $importer["thumb"],
1880 "verb" => ACTIVITY_POST,
1884 notification($notif_params);
1886 logger("Mail is processed, notification was sent.");
1890 * @brief Processes the suggestion elements
1892 * @param object $xpath XPath object
1893 * @param object $suggestion suggestion elements
1894 * @param array $importer Record of the importer user mixed with contact of the content
1896 * @todo Find good type-hints for all parameter
1898 private static function processSuggestion($xpath, $suggestion, $importer)
1902 logger("Processing suggestions");
1904 /// @TODO Rewrite this to one statement
1906 $suggest["uid"] = $importer["importer_uid"];
1907 $suggest["cid"] = $importer["id"];
1908 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1909 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1910 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1911 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1912 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1914 // Does our member already have a friend matching this description?
1917 "SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1918 dbesc($suggest["name"]),
1919 dbesc(normalise_link($suggest["url"])),
1920 intval($suggest["uid"])
1924 * The valid result means the friend we're about to send a friend
1925 * suggestion already has them in their contact, which means no further
1926 * action is required.
1928 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1930 if (DBM::is_result($r)) {
1934 // Do we already have an fcontact record for this person?
1938 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1939 dbesc($suggest["url"]),
1940 dbesc($suggest["name"]),
1941 dbesc($suggest["request"])
1943 if (DBM::is_result($r)) {
1946 // OK, we do. Do we already have an introduction for this person ?
1948 "SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1949 intval($suggest["uid"]),
1954 * The valid result means the friend we're about to send a friend
1955 * suggestion already has them in their contact, which means no further
1956 * action is required.
1958 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1960 if (DBM::is_result($r)) {
1966 "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1967 dbesc($suggest["name"]),
1968 dbesc($suggest["url"]),
1969 dbesc($suggest["photo"]),
1970 dbesc($suggest["request"])
1974 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1975 dbesc($suggest["url"]),
1976 dbesc($suggest["name"]),
1977 dbesc($suggest["request"])
1981 * If no record in fcontact is found, below INSERT statement will not
1982 * link an introduction to it.
1984 if (!DBM::is_result($r)) {
1985 // Database record did not get created. Quietly give up.
1991 $hash = random_string();
1994 "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1995 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1996 intval($suggest["uid"]),
1998 intval($suggest["cid"]),
1999 dbesc($suggest["body"]),
2001 dbesc(DateTimeFormat::utcNow()),
2007 "type" => NOTIFY_SUGGEST,
2008 "notify_flags" => $importer["notify-flags"],
2009 "language" => $importer["language"],
2010 "to_name" => $importer["username"],
2011 "to_email" => $importer["email"],
2012 "uid" => $importer["importer_uid"],
2014 "link" => System::baseUrl()."/notifications/intros",
2015 "source_name" => $importer["name"],
2016 "source_link" => $importer["url"],
2017 "source_photo" => $importer["photo"],
2018 "verb" => ACTIVITY_REQ_FRIEND,
2026 * @brief Processes the relocation elements
2028 * @param object $xpath XPath object
2029 * @param object $relocation relocation elements
2030 * @param array $importer Record of the importer user mixed with contact of the content
2032 * @todo Find good type-hints for all parameter
2034 private static function processRelocation($xpath, $relocation, $importer)
2036 logger("Processing relocations");
2038 /// @TODO Rewrite this to one statement
2040 $relocate["uid"] = $importer["importer_uid"];
2041 $relocate["cid"] = $importer["id"];
2042 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
2043 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
2044 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
2045 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
2046 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
2047 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
2048 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
2049 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
2050 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
2051 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
2052 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
2053 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
2055 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
2056 $relocate["avatar"] = $relocate["photo"];
2059 if ($relocate["addr"] == "") {
2060 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
2065 "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d",
2066 intval($importer["id"]),
2067 intval($importer["importer_uid"])
2070 if (!DBM::is_result($r)) {
2071 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2077 // Update the gcontact entry
2078 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
2080 $fields = ['name' => $relocate["name"], 'photo' => $relocate["avatar"],
2081 'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2082 'addr' => $relocate["addr"], 'connect' => $relocate["addr"],
2083 'notify' => $relocate["notify"], 'server_url' => $relocate["server_url"]];
2084 DBA::update('gcontact', $fields, ['nurl' => normalise_link($old["url"])]);
2086 // Update the contact table. We try to find every entry.
2087 $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
2088 'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2089 'addr' => $relocate["addr"], 'request' => $relocate["request"],
2090 'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
2091 'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
2092 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], normalise_link($old["url"])];
2094 DBA::update('contact', $fields, $condition);
2096 Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
2098 logger('Contacts are updated.');
2101 /// merge with current record, current contents have priority
2102 /// update record, set url-updated
2103 /// update profile photos
2104 /// schedule a scan?
2109 * @brief Updates an item
2111 * @param array $current the current item record
2112 * @param array $item the new item record
2113 * @param array $importer Record of the importer user mixed with contact of the content
2114 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2116 * @todo set proper type-hints (array?)
2118 private static function updateContent($current, $item, $importer, $entrytype)
2122 if (self::isEditedTimestampNewer($current, $item)) {
2123 // do not accept (ignore) an earlier edit than one we currently have.
2124 if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
2128 $fields = ['title' => defaults($item, 'title', ''), 'body' => defaults($item, 'body', ''),
2129 'tag' => defaults($item, 'tag', ''), 'changed' => DateTimeFormat::utcNow(),
2130 'edited' => DateTimeFormat::utc($item["edited"])];
2132 $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
2133 Item::update($fields, $condition);
2141 * @brief Detects the entry type of the item
2143 * @param array $importer Record of the importer user mixed with contact of the content
2144 * @param array $item the new item record
2146 * @return int Is it a toplevel entry, a comment or a relayed comment?
2147 * @todo set proper type-hints (array?)
2149 private static function getEntryType($importer, $item)
2151 if ($item["parent-uri"] != $item["uri"]) {
2154 if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
2157 logger("possible community action");
2159 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2162 // was the top-level post for this action written by somebody on this site?
2163 // Specifically, the recipient?
2165 $is_a_remote_action = false;
2167 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item["parent-uri"]]);
2168 if (DBM::is_result($parent)) {
2170 "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2171 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2172 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2173 AND `item`.`uid` = %d
2176 dbesc($parent["parent-uri"]),
2177 dbesc($parent["parent-uri"]),
2178 dbesc($parent["parent-uri"]),
2179 intval($importer["importer_uid"])
2181 if (DBM::is_result($r)) {
2182 $is_a_remote_action = true;
2187 * Does this have the characteristics of a community or private group action?
2188 * If it's an action to a wall post on a community/prvgroup page it's a
2189 * valid community action. Also forum_mode makes it valid for sure.
2190 * If neither, it's not.
2192 if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2193 $is_a_remote_action = false;
2194 logger("not a community action");
2197 if ($is_a_remote_action) {
2198 return DFRN::REPLY_RC;
2203 return DFRN::TOP_LEVEL;
2208 * @brief Send a "poke"
2210 * @param array $item the new item record
2211 * @param array $importer Record of the importer user mixed with contact of the content
2212 * @param int $posted_id The record number of item record that was just posted
2214 * @todo set proper type-hints (array?)
2216 private static function doPoke($item, $importer, $posted_id)
2218 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2222 $xo = XML::parseString($item["object"], false);
2224 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2225 // somebody was poked/prodded. Was it me?
2226 foreach ($xo->link as $l) {
2227 $atts = $l->attributes();
2228 switch ($atts["rel"]) {
2230 $Blink = $atts["href"];
2237 if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2238 $author = DBA::selectFirst('contact', ['name', 'thumb', 'url'], ['id' => $item['author-id']]);
2240 // send a notification
2243 "type" => NOTIFY_POKE,
2244 "notify_flags" => $importer["notify-flags"],
2245 "language" => $importer["language"],
2246 "to_name" => $importer["username"],
2247 "to_email" => $importer["email"],
2248 "uid" => $importer["importer_uid"],
2250 "link" => System::baseUrl()."/display/".urlencode(Item::getGuidById($posted_id)),
2251 "source_name" => $author["name"],
2252 "source_link" => $author["url"],
2253 "source_photo" => $author["thumb"],
2254 "verb" => $item["verb"],
2255 "otype" => "person",
2256 "activity" => $verb,
2257 "parent" => $item["parent"]]
2264 * @brief Processes several actions, depending on the verb
2266 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2267 * @param array $importer Record of the importer user mixed with contact of the content
2268 * @param array $item the new item record
2269 * @param bool $is_like Is the verb a "like"?
2271 * @return bool Should the processing of the entries be continued?
2272 * @todo set proper type-hints (array?)
2274 private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2276 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2278 if (($entrytype == DFRN::TOP_LEVEL)) {
2279 // The filling of the the "contact" variable is done for legcy reasons
2280 // The functions below are partly used by ostatus.php as well - where we have this variable
2281 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2283 $nickname = $contact["nick"];
2285 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2286 // This function once was responsible for DFRN and OStatus.
2287 if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2288 logger("New follower");
2289 Contact::addRelationship($importer, $contact, $item, $nickname);
2292 if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2293 logger("Lost follower");
2294 Contact::removeFollower($importer, $contact, $item);
2297 if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2298 logger("New friend request");
2299 Contact::addRelationship($importer, $contact, $item, $nickname, true);
2302 if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2303 logger("Lost sharer");
2304 Contact::removeSharer($importer, $contact, $item);
2308 if (($item["verb"] == ACTIVITY_LIKE)
2309 || ($item["verb"] == ACTIVITY_DISLIKE)
2310 || ($item["verb"] == ACTIVITY_ATTEND)
2311 || ($item["verb"] == ACTIVITY_ATTENDNO)
2312 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
2315 $item["gravity"] = GRAVITY_ACTIVITY;
2316 // only one like or dislike per person
2317 // splitted into two queries for performance issues
2318 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2319 'verb' => $item["verb"], 'parent-uri' => $item["parent-uri"]];
2320 if (Item::exists($condition)) {
2324 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2325 'verb' => $item["verb"], 'thr-parent' => $item["parent-uri"]];
2326 if (Item::exists($condition)) {
2333 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2334 $xo = XML::parseString($item["object"], false);
2335 $xt = XML::parseString($item["target"], false);
2337 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2338 $item_tag = Item::selectFirst(['id', 'tag'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]);
2340 if (!DBM::is_result($item_tag)) {
2341 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2345 // extract tag, if not duplicate, add to parent item
2347 if (!stristr($item_tag["tag"], trim($xo->content))) {
2348 $tag = $item_tag["tag"] . (strlen($item_tag["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2349 Item::update(['tag' => $tag], ['id' => $item_tag["id"]]);
2359 * @brief Processes the link elements
2361 * @param object $links link elements
2362 * @param array $item the item record
2364 * @todo set proper type-hints
2366 private static function parseLinks($links, &$item)
2373 foreach ($links as $link) {
2374 foreach ($link->attributes as $attributes) {
2375 switch ($attributes->name) {
2376 case "href" : $href = $attributes->textContent; break;
2377 case "rel" : $rel = $attributes->textContent; break;
2378 case "type" : $type = $attributes->textContent; break;
2379 case "length": $length = $attributes->textContent; break;
2380 case "title" : $title = $attributes->textContent; break;
2383 if (($rel != "") && ($href != "")) {
2386 $item["plink"] = $href;
2390 if (strlen($item["attach"])) {
2391 $item["attach"] .= ",";
2394 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2402 * @brief Processes the entry elements which contain the items and comments
2404 * @param array $header Array of the header elements that always stay the same
2405 * @param object $xpath XPath object
2406 * @param object $entry entry elements
2407 * @param array $importer Record of the importer user mixed with contact of the content
2408 * @param object $xml xml
2410 * @todo Add type-hints
2412 private static function processEntry($header, $xpath, $entry, $importer, $xml)
2414 logger("Processing entries");
2418 $item["protocol"] = PROTOCOL_DFRN;
2420 $item["source"] = $xml;
2423 $item["uri"] = XML::getFirstNodeValue($xpath, "atom:id/text()", $entry);
2425 $item["edited"] = XML::getFirstNodeValue($xpath, "atom:updated/text()", $entry);
2427 $current = Item::selectFirst(['id', 'uid', 'edited', 'body'],
2428 ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
2430 // Is there an existing item?
2431 if (DBM::is_result($current) && !self::isEditedTimestampNewer($current, $item)) {
2432 logger("Item ".$item["uri"]." (".$item['edited'].") already existed.", LOGGER_DEBUG);
2437 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2439 $owner_unknown = (isset($owner["contact-unknown"]) && $owner["contact-unknown"]);
2441 $item["owner-link"] = $owner["link"];
2442 $item["owner-id"] = Contact::getIdForURL($owner["link"], 0);
2445 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2447 $item["author-link"] = $author["link"];
2448 $item["author-id"] = Contact::getIdForURL($author["link"], 0);
2450 $item["title"] = XML::getFirstNodeValue($xpath, "atom:title/text()", $entry);
2452 $item["created"] = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2454 $item["body"] = XML::getFirstNodeValue($xpath, "dfrn:env/text()", $entry);
2455 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2456 // make sure nobody is trying to sneak some html tags by us
2457 $item["body"] = notags(base64url_decode($item["body"]));
2459 $item["body"] = BBCode::limitBodySize($item["body"]);
2461 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2462 if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
2463 $base_url = get_app()->get_baseurl();
2464 $item['body'] = reltoabs($item['body'], $base_url);
2466 $item['body'] = html2bb_video($item['body']);
2468 $item['body'] = OEmbed::HTML2BBCode($item['body']);
2470 $config = HTMLPurifier_Config::createDefault();
2471 $config->set('Cache.DefinitionImpl', null);
2473 // we shouldn't need a whitelist, because the bbcode converter
2474 // will strip out any unsupported tags.
2476 $purifier = new HTMLPurifier($config);
2477 $item['body'] = $purifier->purify($item['body']);
2479 $item['body'] = @HTML::toBBCode($item['body']);
2482 /// @todo We should check for a repeated post and if we know the repeated author.
2484 // We don't need the content element since "dfrn:env" is always present
2485 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2487 $item["location"] = XML::getFirstNodeValue($xpath, "dfrn:location/text()", $entry);
2489 $item["coord"] = XML::getFirstNodeValue($xpath, "georss:point", $entry);
2491 $item["private"] = XML::getFirstNodeValue($xpath, "dfrn:private/text()", $entry);
2493 $item["extid"] = XML::getFirstNodeValue($xpath, "dfrn:extid/text()", $entry);
2495 if (XML::getFirstNodeValue($xpath, "dfrn:bookmark/text()", $entry) == "true") {
2496 $item["post-type"] = Item::PT_PAGE;
2499 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2500 if ($notice_info && ($notice_info->length > 0)) {
2501 foreach ($notice_info->item(0)->attributes as $attributes) {
2502 if ($attributes->name == "source") {
2503 $item["app"] = strip_tags($attributes->textContent);
2508 $item["guid"] = XML::getFirstNodeValue($xpath, "dfrn:diaspora_guid/text()", $entry);
2510 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
2511 $dsprsig = unxmlify(XML::getFirstNodeValue($xpath, "dfrn:diaspora_signature/text()", $entry));
2512 if ($dsprsig != "") {
2513 $item["dsprsig"] = $dsprsig;
2516 $item["verb"] = XML::getFirstNodeValue($xpath, "activity:verb/text()", $entry);
2518 if (XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry) != "") {
2519 $item["object-type"] = XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry);
2522 $object = $xpath->query("activity:object", $entry)->item(0);
2523 $item["object"] = self::transformActivity($xpath, $object, "object");
2525 if (trim($item["object"]) != "") {
2526 $r = XML::parseString($item["object"], false);
2527 if (isset($r->type)) {
2528 $item["object-type"] = $r->type;
2532 $target = $xpath->query("activity:target", $entry)->item(0);
2533 $item["target"] = self::transformActivity($xpath, $target, "target");
2535 $categories = $xpath->query("atom:category", $entry);
2537 foreach ($categories as $category) {
2540 foreach ($category->attributes as $attributes) {
2541 if ($attributes->name == "term") {
2542 $term = $attributes->textContent;
2545 if ($attributes->name == "scheme") {
2546 $scheme = $attributes->textContent;
2550 if (($term != "") && ($scheme != "")) {
2551 $parts = explode(":", $scheme);
2552 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2553 $termhash = array_shift($parts);
2554 $termurl = implode(":", $parts);
2556 if (!empty($item["tag"])) {
2557 $item["tag"] .= ",";
2562 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2570 $links = $xpath->query("atom:link", $entry);
2572 self::parseLinks($links, $item);
2575 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
2577 $conv = $xpath->query('ostatus:conversation', $entry);
2578 if (is_object($conv->item(0))) {
2579 foreach ($conv->item(0)->attributes as $attributes) {
2580 if ($attributes->name == "ref") {
2581 $item['conversation-uri'] = $attributes->textContent;
2583 if ($attributes->name == "href") {
2584 $item['conversation-href'] = $attributes->textContent;
2589 // Is it a reply or a top level posting?
2590 $item["parent-uri"] = $item["uri"];
2592 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2593 if (is_object($inreplyto->item(0))) {
2594 foreach ($inreplyto->item(0)->attributes as $attributes) {
2595 if ($attributes->name == "ref") {
2596 $item["parent-uri"] = $attributes->textContent;
2601 // Get the type of the item (Top level post, reply or remote reply)
2602 $entrytype = self::getEntryType($importer, $item);
2604 // Now assign the rest of the values that depend on the type of the message
2605 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2606 if (!isset($item["object-type"])) {
2607 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2610 if ($item["contact-id"] != $owner["contact-id"]) {
2611 $item["contact-id"] = $owner["contact-id"];
2614 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2615 $item["network"] = $owner["network"];
2618 if ($item["contact-id"] != $author["contact-id"]) {
2619 $item["contact-id"] = $author["contact-id"];
2622 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2623 $item["network"] = $author["network"];
2627 if ($entrytype == DFRN::REPLY_RC) {
2629 } elseif ($entrytype == DFRN::TOP_LEVEL) {
2630 if (!isset($item["object-type"])) {
2631 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2635 if (($item["object-type"] == ACTIVITY_OBJ_EVENT) && !$owner_unknown) {
2636 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2637 $ev = Event::fromBBCode($item["body"]);
2638 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2639 logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2640 $ev["cid"] = $importer["id"];
2641 $ev["uid"] = $importer["importer_uid"];
2642 $ev["uri"] = $item["uri"];
2643 $ev["edited"] = $item["edited"];
2644 $ev["private"] = $item["private"];
2645 $ev["guid"] = $item["guid"];
2648 "SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2649 dbesc($item["uri"]),
2650 intval($importer["importer_uid"])
2652 if (DBM::is_result($r)) {
2653 $ev["id"] = $r[0]["id"];
2656 $event_id = Event::store($ev);
2657 logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2663 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2664 logger("Exiting because 'processVerbs' told us so", LOGGER_DEBUG);
2668 // This check is done here to be able to receive connection requests in "processVerbs"
2669 if (($entrytype == DFRN::TOP_LEVEL) && $owner_unknown) {
2670 logger("Item won't be stored because user " . $importer["importer_uid"] . " doesn't follow " . $item["owner-link"] . ".", LOGGER_DEBUG);
2675 // Update content if 'updated' changes
2676 if (DBM::is_result($current)) {
2677 if (self::updateContent($current, $item, $importer, $entrytype)) {
2678 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2680 logger("Item " . $item["uri"] . " already existed.", LOGGER_DEBUG);
2685 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2686 $posted_id = Item::insert($item);
2690 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2692 if ($item['uid'] == 0) {
2693 Item::distribute($posted_id);
2698 } else { // $entrytype == DFRN::TOP_LEVEL
2699 if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
2700 logger("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", LOGGER_DEBUG);
2703 if (!link_compare($item["owner-link"], $importer["url"])) {
2705 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2706 * but otherwise there's a possible data mixup on the sender's system.
2707 * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2708 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2710 logger('Correcting item owner.', LOGGER_DEBUG);
2711 $item["owner-link"] = $importer["url"];
2712 $item["owner-id"] = Contact::getIdForURL($importer["url"], 0);
2715 if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2716 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2720 // This is my contact on another system, but it's really me.
2721 // Turn this into a wall post.
2722 $notify = Item::isRemoteSelf($importer, $item);
2724 $posted_id = Item::insert($item, false, $notify);
2727 $posted_id = $notify;
2730 logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2732 if ($item['uid'] == 0) {
2733 Item::distribute($posted_id);
2736 if (stristr($item["verb"], ACTIVITY_POKE)) {
2737 self::doPoke($item, $importer, $posted_id);
2743 * @brief Deletes items
2745 * @param object $xpath XPath object
2746 * @param object $deletion deletion elements
2747 * @param array $importer Record of the importer user mixed with contact of the content
2749 * @todo set proper type-hints
2751 private static function processDeletion($xpath, $deletion, $importer)
2753 logger("Processing deletions");
2756 foreach ($deletion->attributes as $attributes) {
2757 if ($attributes->name == "ref") {
2758 $uri = $attributes->textContent;
2762 if (!$uri || !$importer["id"]) {
2766 $condition = ['uri' => $uri, 'uid' => $importer["importer_uid"]];
2767 $item = Item::selectFirst(['id', 'parent', 'contact-id', 'file', 'deleted'], $condition);
2768 if (!DBM::is_result($item)) {
2769 logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", LOGGER_DEBUG);
2773 if (strstr($item['file'], '[')) {
2774 logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " is filed. So it won't be deleted.", LOGGER_DEBUG);
2778 // When it is a starting post it has to belong to the person that wants to delete it
2779 if (($item['id'] == $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2780 logger("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2784 // Comments can be deleted by the thread owner or comment owner
2785 if (($item['id'] != $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2786 $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2787 if (!Item::exists($condition)) {
2788 logger("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2793 if ($item["deleted"]) {
2797 logger('deleting item '.$item['id'].' uri='.$uri, LOGGER_DEBUG);
2799 Item::delete(['id' => $item['id']]);
2803 * @brief Imports a DFRN message
2805 * @param string $xml The DFRN message
2806 * @param array $importer Record of the importer user mixed with contact of the content
2807 * @param bool $sort_by_date Is used when feeds are polled
2808 * @return integer Import status
2809 * @todo set proper type-hints
2811 public static function import($xml, $importer, $sort_by_date = false)
2817 $doc = new DOMDocument();
2818 @$doc->loadXML($xml);
2820 $xpath = new DOMXPath($doc);
2821 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2822 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2823 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2824 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2825 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2826 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2827 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2828 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2829 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2830 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2833 $header["uid"] = $importer["importer_uid"];
2834 $header["network"] = NETWORK_DFRN;
2835 $header["wall"] = 0;
2836 $header["origin"] = 0;
2837 $header["contact-id"] = $importer["id"];
2839 // Update the contact table if the data has changed
2841 // The "atom:author" is only present in feeds
2842 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2843 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2846 // Only the "dfrn:owner" in the head section contains all data
2847 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2848 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2851 logger("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2853 // is it a public forum? Private forums aren't exposed with this method
2854 $forum = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:community/text()"));
2856 // The account type is new since 3.5.1
2857 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2858 $accounttype = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:account_type/text()"));
2860 if ($accounttype != $importer["contact-type"]) {
2861 DBA::update('contact', ['contact-type' => $accounttype], ['id' => $importer["id"]]);
2863 // A forum contact can either have set "forum" or "prv" - but not both
2864 if (($accounttype == ACCOUNT_TYPE_COMMUNITY) && (($forum != $importer["forum"]) || ($forum == $importer["prv"]))) {
2865 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer["id"]];
2866 DBA::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2868 } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
2869 $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2870 DBA::update('contact', ['forum' => $forum], $condition);
2874 // We are processing relocations even if we are ignoring a contact
2875 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2876 foreach ($relocations as $relocation) {
2877 self::processRelocation($xpath, $relocation, $importer);
2880 if (($importer["uid"] != 0) && !$importer["readonly"]) {
2881 $mails = $xpath->query("/atom:feed/dfrn:mail");
2882 foreach ($mails as $mail) {
2883 self::processMail($xpath, $mail, $importer);
2886 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2887 foreach ($suggestions as $suggestion) {
2888 self::processSuggestion($xpath, $suggestion, $importer);
2892 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2893 foreach ($deletions as $deletion) {
2894 self::processDeletion($xpath, $deletion, $importer);
2897 if (!$sort_by_date) {
2898 $entries = $xpath->query("/atom:feed/atom:entry");
2899 foreach ($entries as $entry) {
2900 self::processEntry($header, $xpath, $entry, $importer, $xml);
2904 $entries = $xpath->query("/atom:feed/atom:entry");
2905 foreach ($entries as $entry) {
2906 $created = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2907 $newentries[strtotime($created)] = $entry;
2910 // Now sort after the publishing date
2913 foreach ($newentries as $entry) {
2914 self::processEntry($header, $xpath, $entry, $importer, $xml);
2917 logger("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2923 * @param string $contact_nick contact nickname
2925 public static function autoRedir(App $a, $contact_nick)
2928 if (x($_REQUEST, 'redir') && intval($_REQUEST['redir'])) {
2932 if ((! $contact_nick) || ($contact_nick === $a->user['nickname'])) {
2937 // We need to find out if $contact_nick is a user on this hub, and if so, if I
2938 // am a contact of that user. However, that user may have other contacts with the
2939 // same nickname as me on other hubs or other networks. Exclude these by requiring
2940 // that the contact have a local URL. I will be the only person with my nickname at
2941 // this URL, so if a result is found, then I am a contact of the $contact_nick user.
2943 // We also have to make sure that I'm a legitimate contact--I'm not blocked or pending.
2945 $baseurl = System::baseUrl();
2946 $domain_st = strpos($baseurl, "://");
2947 if ($domain_st === false) {
2950 $baseurl = substr($baseurl, $domain_st + 3);
2951 $nurl = normalise_link($baseurl);
2953 /// @todo Why is there a query for "url" *and* "nurl"? Especially this normalising is strange.
2954 $r = q("SELECT `id` FROM `contact` WHERE `uid` = (SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1)
2955 AND `nick` = '%s' AND NOT `self` AND (`url` LIKE '%%%s%%' OR `nurl` LIKE '%%%s%%') AND NOT `blocked` AND NOT `pending` LIMIT 1",
2956 dbesc($contact_nick),
2957 dbesc($a->user['nickname']),
2961 if ((! DBM::is_result($r)) || $r[0]['id'] == remote_user()) {
2965 $r = q("SELECT * FROM contact WHERE nick = '%s'
2966 AND network = '%s' AND uid = %d AND url LIKE '%%%s%%' LIMIT 1",
2967 dbesc($contact_nick),
2968 dbesc(NETWORK_DFRN),
2969 intval(local_user()),
2972 if (! DBM::is_result($r)) {
2978 $dfrn_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2980 if ($r[0]['duplex'] && $r[0]['issued-id']) {
2981 $orig_id = $r[0]['issued-id'];
2982 $dfrn_id = '1:' . $orig_id;
2984 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
2985 $orig_id = $r[0]['dfrn-id'];
2986 $dfrn_id = '0:' . $orig_id;
2989 // ensure that we've got a valid ID. There may be some edge cases with forums and non-duplex mode
2990 // that may have triggered some of the "went to {profile/intro} and got an RSS feed" issues
2992 if (strlen($dfrn_id) < 3) {
2996 $sec = random_string();
2998 DBA::insert('profile_check', ['uid' => local_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id, 'sec' => $sec, 'expire' => time() + 45]);
3000 $url = curPageURL();
3002 logger('auto_redir: ' . $r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
3003 $dest = (($url) ? '&destination_url=' . $url : '');
3004 goaway($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
3005 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest);
3012 * @brief Returns the activity verb
3014 * @param array $item Item array
3016 * @return string activity verb
3018 private static function constructVerb(array $item)
3020 if ($item['verb']) {
3021 return $item['verb'];
3023 return ACTIVITY_POST;
3026 private static function tgroupCheck($uid, $item)
3030 // check that the message originated elsewhere and is a top-level post
3032 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['parent-uri'])) {
3036 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
3039 if (!DBM::is_result($u)) {
3043 $community_page = ($u[0]['page-flags'] == PAGE_COMMUNITY);
3044 $prvgroup = ($u[0]['page-flags'] == PAGE_PRVGROUP);
3046 $link = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
3049 * Diaspora uses their own hardwired link URL in @-tags
3050 * instead of the one we supply with webfinger
3052 $dlink = normalise_link(System::baseUrl() . '/u/' . $u[0]['nickname']);
3054 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
3056 foreach ($matches as $mtch) {
3057 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
3059 logger('mention found: ' . $mtch[2]);
3068 return $community_page || $prvgroup;
3072 * This function returns true if $update has an edited timestamp newer
3073 * than $existing, i.e. $update contains new data which should override
3074 * what's already there. If there is no timestamp yet, the update is
3075 * assumed to be newer. If the update has no timestamp, the existing
3076 * item is assumed to be up-to-date. If the timestamps are equal it
3077 * assumes the update has been seen before and should be ignored.
3080 private static function isEditedTimestampNewer($existing, $update)
3082 if (!x($existing, 'edited') || !$existing['edited']) {
3085 if (!x($update, 'edited') || !$update['edited']) {
3089 $existing_edited = DateTimeFormat::utc($existing['edited']);
3090 $update_edited = DateTimeFormat::utc($update['edited']);
3092 return (strcmp($existing_edited, $update_edited) < 0);