3 * @file include/dfrn.php
4 * @brief The implementation of the dfrn protocol
6 * @see https://github.com/friendica/friendica/wiki/Protocol and
7 * https://github.com/friendica/friendica/blob/master/spec/dfrn2.pdf
9 namespace Friendica\Protocol;
12 use Friendica\Content\OEmbed;
13 use Friendica\Content\Text\BBCode;
14 use Friendica\Content\Text\HTML;
15 use Friendica\Core\Addon;
16 use Friendica\Core\Config;
17 use Friendica\Core\L10n;
18 use Friendica\Core\System;
19 use Friendica\Core\Worker;
20 use Friendica\Database\DBM;
21 use Friendica\Model\Contact;
22 use Friendica\Model\Event;
23 use Friendica\Model\GContact;
24 use Friendica\Model\Group;
25 use Friendica\Model\Item;
26 use Friendica\Model\Profile;
27 use Friendica\Model\User;
28 use Friendica\Object\Image;
29 use Friendica\Protocol\OStatus;
30 use Friendica\Util\Crypto;
31 use Friendica\Util\DateTimeFormat;
32 use Friendica\Util\Network;
33 use Friendica\Util\XML;
34 use Friendica\Protocol\Diaspora;
39 use HTMLPurifier_Config;
41 require_once 'boot.php';
42 require_once 'include/dba.php';
43 require_once "include/enotify.php";
44 require_once "include/items.php";
45 require_once "include/text.php";
48 * @brief This class contain functions to create and send DFRN XML files
53 const TOP_LEVEL = 0; // Top level posting
54 const REPLY = 1; // Regular reply that is stored locally
55 const REPLY_RC = 2; // Reply that will be relayed
58 * @brief Generates the atom entries for delivery.php
60 * This function is used whenever content is transmitted via DFRN.
62 * @param array $items Item elements
63 * @param array $owner Owner record
65 * @return string DFRN entries
66 * @todo Find proper type-hints
68 public static function entries($items, $owner)
70 $doc = new DOMDocument('1.0', 'utf-8');
71 $doc->formatOutput = true;
73 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
75 if (! count($items)) {
76 return trim($doc->saveXML());
79 foreach ($items as $item) {
80 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
81 $root->appendChild($entry);
84 return trim($doc->saveXML());
88 * @brief Generate an atom feed for the given user
90 * This function is called when another server is pulling data from the user feed.
92 * @param string $dfrn_id DFRN ID from the requesting party
93 * @param string $owner_nick Owner nick name
94 * @param string $last_update Date of the last update
95 * @param int $direction Can be -1, 0 or 1.
96 * @param boolean $onlyheader Output only the header without content? (Default is "no")
98 * @return string DFRN feed entries
99 * @todo Find proper type-hints
101 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false)
105 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
106 $public_feed = (($dfrn_id) ? false : true);
107 $starred = false; // not yet implemented, possible security issues
110 if ($public_feed && $a->argc > 2) {
111 for ($x = 2; $x < $a->argc; $x++) {
112 if ($a->argv[$x] == 'converse') {
115 if ($a->argv[$x] == 'starred') {
118 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
119 $category = $a->argv[$x+1];
124 // default permissions - anonymous user
126 $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = '' ";
129 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
130 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
131 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
135 if (! DBM::is_result($r)) {
136 logger(sprintf('No contact found for nickname=%d', $owner_nick), LOGGER_WARNING);
141 $owner_id = $owner['uid'];
142 $owner_nick = $owner['nickname'];
144 $sql_post_table = "";
146 if (! $public_feed) {
148 switch ($direction) {
150 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
154 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
155 $my_id = '1:' . $dfrn_id;
158 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
159 $my_id = '0:' . $dfrn_id;
167 "SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
171 if (! DBM::is_result($r)) {
172 logger(sprintf('No contact found for uid=%d', $owner_id), LOGGER_WARNING);
177 include_once 'include/security.php';
178 $groups = Group::getIdsByContactId($contact['id']);
180 if (count($groups)) {
181 for ($x = 0; $x < count($groups); $x ++) {
182 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
185 $gs = implode('|', $groups);
187 $gs = '<<>>' ; // Impossible to match
190 $sql_extra = sprintf(
192 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
193 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
194 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
195 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
197 intval($contact['id']),
198 intval($contact['id']),
210 if (! strlen($last_update)) {
211 $last_update = 'now -30 days';
214 if (isset($category)) {
215 $sql_post_table = sprintf(
216 "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` ",
217 dbesc(protect_sprintf($category)),
218 intval(TERM_OBJ_POST),
219 intval(TERM_CATEGORY),
222 //$sql_extra .= file_tag_file_query('item',$category,'category');
225 if ($public_feed && ! $converse) {
226 $sql_extra .= " AND `contact`.`self` = 1 ";
229 $check_date = DateTimeFormat::utc($last_update);
233 FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
234 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
235 WHERE `item`.`uid` = %d AND `item`.`wall` AND `item`.`changed` > '%s'
237 ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
244 foreach ($r as $item) {
245 $ids[] = $item['id'];
249 $ret = Item::select(Item::DELIVER_FIELDLIST, ['id' => $ids]);
250 $items = dba::inArray($ret);
256 * Will check further below if this actually returned results.
257 * We will provide an empty feed if that is the case.
260 $doc = new DOMDocument('1.0', 'utf-8');
261 $doc->formatOutput = true;
263 $alternatelink = $owner['url'];
265 if (isset($category)) {
266 $alternatelink .= "/category/".$category;
270 $author = "dfrn:owner";
275 $root = self::addHeader($doc, $owner, $author, $alternatelink, true);
277 /// @TODO This hook can't work anymore
278 // Addon::callHooks('atom_feed', $atom);
280 if (!DBM::is_result($items) || $onlyheader) {
281 $atom = trim($doc->saveXML());
283 Addon::callHooks('atom_feed_end', $atom);
288 foreach ($items as $item) {
289 // prevent private email from leaking.
290 if ($item['network'] == NETWORK_MAIL) {
294 // public feeds get html, our own nodes use bbcode
298 // catch any email that's in a public conversation and make sure it doesn't leak
299 if ($item['private']) {
306 $entry = self::entry($doc, $type, $item, $owner, true);
307 $root->appendChild($entry);
310 $atom = trim($doc->saveXML());
312 Addon::callHooks('atom_feed_end', $atom);
318 * @brief Generate an atom entry for a given item id
320 * @param int $item_id The item id
321 * @param boolean $conversation Show the conversation. If false show the single post.
323 * @return string DFRN feed entry
325 public static function itemFeed($item_id, $conversation = false)
328 $condition = ['parent' => $item_id];
330 $condition = ['id' => $item_id];
333 $ret = Item::select(Item::DELIVER_FIELDLIST, $condition);
334 $items = dba::inArray($ret);
335 if (!DBM::is_result($items)) {
341 if ($item['uid'] != 0) {
342 $owner = User::getOwnerDataById($item['uid']);
347 $owner = ['uid' => 0, 'nick' => 'feed-item'];
350 $doc = new DOMDocument('1.0', 'utf-8');
351 $doc->formatOutput = true;
355 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
356 $doc->appendChild($root);
358 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
359 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
360 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
361 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
362 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
363 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
364 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
365 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
366 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
368 //$root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
370 foreach ($items as $item) {
371 $entry = self::entry($doc, $type, $item, $owner, true, 0);
372 $root->appendChild($entry);
375 $root = self::entry($doc, $type, $item, $owner, true, 0, true);
378 $atom = trim($doc->saveXML());
383 * @brief Create XML text for DFRN mails
385 * @param array $item message elements
386 * @param array $owner Owner record
388 * @return string DFRN mail
389 * @todo Find proper type-hints
391 public static function mail($item, $owner)
393 $doc = new DOMDocument('1.0', 'utf-8');
394 $doc->formatOutput = true;
396 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
398 $mail = $doc->createElement("dfrn:mail");
399 $sender = $doc->createElement("dfrn:sender");
401 XML::addElement($doc, $sender, "dfrn:name", $owner['name']);
402 XML::addElement($doc, $sender, "dfrn:uri", $owner['url']);
403 XML::addElement($doc, $sender, "dfrn:avatar", $owner['thumb']);
405 $mail->appendChild($sender);
407 XML::addElement($doc, $mail, "dfrn:id", $item['uri']);
408 XML::addElement($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
409 XML::addElement($doc, $mail, "dfrn:sentdate", DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
410 XML::addElement($doc, $mail, "dfrn:subject", $item['title']);
411 XML::addElement($doc, $mail, "dfrn:content", $item['body']);
413 $root->appendChild($mail);
415 return trim($doc->saveXML());
419 * @brief Create XML text for DFRN friend suggestions
421 * @param array $item suggestion elements
422 * @param array $owner Owner record
424 * @return string DFRN suggestions
425 * @todo Find proper type-hints
427 public static function fsuggest($item, $owner)
429 $doc = new DOMDocument('1.0', 'utf-8');
430 $doc->formatOutput = true;
432 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
434 $suggest = $doc->createElement("dfrn:suggest");
436 XML::addElement($doc, $suggest, "dfrn:url", $item['url']);
437 XML::addElement($doc, $suggest, "dfrn:name", $item['name']);
438 XML::addElement($doc, $suggest, "dfrn:photo", $item['photo']);
439 XML::addElement($doc, $suggest, "dfrn:request", $item['request']);
440 XML::addElement($doc, $suggest, "dfrn:note", $item['note']);
442 $root->appendChild($suggest);
444 return trim($doc->saveXML());
448 * @brief Create XML text for DFRN relocations
450 * @param array $owner Owner record
451 * @param int $uid User ID
453 * @return string DFRN relocations
454 * @todo Find proper type-hints
456 public static function relocate($owner, $uid)
459 /* get site pubkey. this could be a new installation with no site keys*/
460 $pubkey = Config::get('system', 'site_pubkey');
462 $res = Crypto::newKeypair(1024);
463 Config::set('system', 'site_prvkey', $res['prvkey']);
464 Config::set('system', 'site_pubkey', $res['pubkey']);
468 "SELECT `resource-id` , `scale`, type FROM `photo`
469 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;",
473 $ext = Image::supportedTypes();
475 foreach ($rp as $p) {
476 $photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
480 $doc = new DOMDocument('1.0', 'utf-8');
481 $doc->formatOutput = true;
483 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
485 $relocate = $doc->createElement("dfrn:relocate");
487 XML::addElement($doc, $relocate, "dfrn:url", $owner['url']);
488 XML::addElement($doc, $relocate, "dfrn:name", $owner['name']);
489 XML::addElement($doc, $relocate, "dfrn:addr", $owner['addr']);
490 XML::addElement($doc, $relocate, "dfrn:avatar", $owner['avatar']);
491 XML::addElement($doc, $relocate, "dfrn:photo", $photos[4]);
492 XML::addElement($doc, $relocate, "dfrn:thumb", $photos[5]);
493 XML::addElement($doc, $relocate, "dfrn:micro", $photos[6]);
494 XML::addElement($doc, $relocate, "dfrn:request", $owner['request']);
495 XML::addElement($doc, $relocate, "dfrn:confirm", $owner['confirm']);
496 XML::addElement($doc, $relocate, "dfrn:notify", $owner['notify']);
497 XML::addElement($doc, $relocate, "dfrn:poll", $owner['poll']);
498 XML::addElement($doc, $relocate, "dfrn:sitepubkey", Config::get('system', 'site_pubkey'));
500 $root->appendChild($relocate);
502 return trim($doc->saveXML());
506 * @brief Adds the header elements for the DFRN protocol
508 * @param object $doc XML document
509 * @param array $owner Owner record
510 * @param string $authorelement Element name for the author
511 * @param string $alternatelink link to profile or category
512 * @param bool $public Is it a header for public posts?
514 * @return object XML root object
515 * @todo Find proper type-hints
517 private static function addHeader($doc, $owner, $authorelement, $alternatelink = "", $public = false)
520 if ($alternatelink == "") {
521 $alternatelink = $owner['url'];
524 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
525 $doc->appendChild($root);
527 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
528 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
529 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
530 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
531 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
532 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
533 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
534 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
535 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
537 XML::addElement($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
538 XML::addElement($doc, $root, "title", $owner["name"]);
540 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION];
541 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
543 $attributes = ["rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/"];
544 XML::addElement($doc, $root, "link", "", $attributes);
546 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $alternatelink];
547 XML::addElement($doc, $root, "link", "", $attributes);
551 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
552 OStatus::hublinks($doc, $root, $owner["nick"]);
554 $attributes = ["rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
555 XML::addElement($doc, $root, "link", "", $attributes);
557 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
558 XML::addElement($doc, $root, "link", "", $attributes);
560 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
561 XML::addElement($doc, $root, "link", "", $attributes);
564 // For backward compatibility we keep this element
565 if ($owner['page-flags'] == PAGE_COMMUNITY) {
566 XML::addElement($doc, $root, "dfrn:community", 1);
569 // The former element is replaced by this one
570 XML::addElement($doc, $root, "dfrn:account_type", $owner["account-type"]);
572 /// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
574 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
576 $author = self::addAuthor($doc, $owner, $authorelement, $public);
577 $root->appendChild($author);
583 * @brief Adds the author element in the header for the DFRN protocol
585 * @param object $doc XML document
586 * @param array $owner Owner record
587 * @param string $authorelement Element name for the author
588 * @param boolean $public boolean
590 * @return object XML author object
591 * @todo Find proper type-hints
593 private static function addAuthor($doc, $owner, $authorelement, $public)
595 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
597 "SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
598 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
599 intval($owner['uid'])
601 if (DBM::is_result($r)) {
607 $author = $doc->createElement($authorelement);
609 $namdate = DateTimeFormat::utc($owner['name-date'].'+00:00', DateTimeFormat::ATOM);
610 $uridate = DateTimeFormat::utc($owner['uri-date'].'+00:00', DateTimeFormat::ATOM);
611 $picdate = DateTimeFormat::utc($owner['avatar-date'].'+00:00', DateTimeFormat::ATOM);
615 if (!$public || !$hidewall) {
616 $attributes = ["dfrn:updated" => $namdate];
619 XML::addElement($doc, $author, "name", $owner["name"], $attributes);
620 XML::addElement($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
621 XML::addElement($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
623 $attributes = ["rel" => "photo", "type" => "image/jpeg",
624 "media:width" => 175, "media:height" => 175, "href" => $owner['photo']];
626 if (!$public || !$hidewall) {
627 $attributes["dfrn:updated"] = $picdate;
630 XML::addElement($doc, $author, "link", "", $attributes);
632 $attributes["rel"] = "avatar";
633 XML::addElement($doc, $author, "link", "", $attributes);
636 XML::addElement($doc, $author, "dfrn:hide", "true");
639 // The following fields will only be generated if the data isn't meant for a public feed
644 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
647 XML::addElement($doc, $author, "dfrn:birthday", $birthday);
650 // Only show contact details when we are allowed to
652 "SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
653 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
654 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
656 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
657 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
658 intval($owner['uid'])
660 if (DBM::is_result($r)) {
663 XML::addElement($doc, $author, "poco:displayName", $profile["name"]);
664 XML::addElement($doc, $author, "poco:updated", $namdate);
666 if (trim($profile["dob"]) > '0001-01-01') {
667 XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
670 XML::addElement($doc, $author, "poco:note", $profile["about"]);
671 XML::addElement($doc, $author, "poco:preferredUsername", $profile["nickname"]);
673 $savetz = date_default_timezone_get();
674 date_default_timezone_set($profile["timezone"]);
675 XML::addElement($doc, $author, "poco:utcOffset", date("P"));
676 date_default_timezone_set($savetz);
678 if (trim($profile["homepage"]) != "") {
679 $urls = $doc->createElement("poco:urls");
680 XML::addElement($doc, $urls, "poco:type", "homepage");
681 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
682 XML::addElement($doc, $urls, "poco:primary", "true");
683 $author->appendChild($urls);
686 if (trim($profile["pub_keywords"]) != "") {
687 $keywords = explode(",", $profile["pub_keywords"]);
689 foreach ($keywords as $keyword) {
690 XML::addElement($doc, $author, "poco:tags", trim($keyword));
694 if (trim($profile["xmpp"]) != "") {
695 $ims = $doc->createElement("poco:ims");
696 XML::addElement($doc, $ims, "poco:type", "xmpp");
697 XML::addElement($doc, $ims, "poco:value", $profile["xmpp"]);
698 XML::addElement($doc, $ims, "poco:primary", "true");
699 $author->appendChild($ims);
702 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
703 $element = $doc->createElement("poco:address");
705 XML::addElement($doc, $element, "poco:formatted", Profile::formatLocation($profile));
707 if (trim($profile["locality"]) != "") {
708 XML::addElement($doc, $element, "poco:locality", $profile["locality"]);
711 if (trim($profile["region"]) != "") {
712 XML::addElement($doc, $element, "poco:region", $profile["region"]);
715 if (trim($profile["country-name"]) != "") {
716 XML::addElement($doc, $element, "poco:country", $profile["country-name"]);
719 $author->appendChild($element);
727 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
729 * @param object $doc XML document
730 * @param string $element Element name for the author
731 * @param string $contact_url Link of the contact
732 * @param array $item Item elements
734 * @return object XML author object
735 * @todo Find proper type-hints
737 private static function addEntryAuthor($doc, $element, $contact_url, $item)
739 $contact = Contact::getDetailsByURL($contact_url, $item["uid"]);
741 $author = $doc->createElement($element);
742 XML::addElement($doc, $author, "name", $contact["name"]);
743 XML::addElement($doc, $author, "uri", $contact["url"]);
744 XML::addElement($doc, $author, "dfrn:handle", $contact["addr"]);
747 /// - Check real image type and image size
748 /// - Check which of these boths elements we should use
751 "type" => "image/jpeg",
753 "media:height" => 80,
754 "href" => $contact["photo"]];
755 XML::addElement($doc, $author, "link", "", $attributes);
759 "type" => "image/jpeg",
761 "media:height" => 80,
762 "href" => $contact["photo"]];
763 XML::addElement($doc, $author, "link", "", $attributes);
769 * @brief Adds the activity elements
771 * @param object $doc XML document
772 * @param string $element Element name for the activity
773 * @param string $activity activity value
775 * @return object XML activity object
776 * @todo Find proper type-hints
778 private static function createActivity($doc, $element, $activity)
781 $entry = $doc->createElement($element);
783 $r = XML::parseString($activity, false);
789 XML::addElement($doc, $entry, "activity:object-type", $r->type);
793 XML::addElement($doc, $entry, "id", $r->id);
797 XML::addElement($doc, $entry, "title", $r->title);
801 if (substr($r->link, 0, 1) == '<') {
802 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
803 $r->link = str_replace('&', '&', $r->link);
806 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
808 // XML does need a single element as root element so we add a dummy element here
809 $data = XML::parseString("<dummy>" . $r->link . "</dummy>", false);
810 if (is_object($data)) {
811 foreach ($data->link as $link) {
813 foreach ($link->attributes() as $parameter => $value) {
814 $attributes[$parameter] = $value;
816 XML::addElement($doc, $entry, "link", "", $attributes);
820 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
821 XML::addElement($doc, $entry, "link", "", $attributes);
825 XML::addElement($doc, $entry, "content", BBCode::convert($r->content), ["type" => "html"]);
835 * @brief Adds the elements for attachments
837 * @param object $doc XML document
838 * @param object $root XML root
839 * @param array $item Item element
841 * @return object XML attachment object
842 * @todo Find proper type-hints
844 private static function getAttachment($doc, $root, $item)
846 $arr = explode('[/attach],', $item['attach']);
848 foreach ($arr as $r) {
850 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
852 $attributes = ["rel" => "enclosure",
853 "href" => $matches[1],
854 "type" => $matches[3]];
856 if (intval($matches[2])) {
857 $attributes["length"] = intval($matches[2]);
860 if (trim($matches[4]) != "") {
861 $attributes["title"] = trim($matches[4]);
864 XML::addElement($doc, $root, "link", "", $attributes);
871 * @brief Adds the "entry" elements for the DFRN protocol
873 * @param object $doc XML document
874 * @param string $type "text" or "html"
875 * @param array $item Item element
876 * @param array $owner Owner record
877 * @param bool $comment Trigger the sending of the "comment" element
878 * @param int $cid Contact ID of the recipient
879 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
881 * @return object XML entry object
882 * @todo Find proper type-hints
884 private static function entry($doc, $type, array $item, array $owner, $comment = false, $cid = 0, $single = false)
888 if (!$item['parent']) {
892 if ($item['deleted']) {
893 $attributes = ["ref" => $item['uri'], "when" => DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM)];
894 return XML::createElement($doc, "at:deleted-entry", "", $attributes);
898 $entry = $doc->createElement("entry");
900 $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry');
901 $doc->appendChild($entry);
903 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
904 $entry->setAttribute("xmlns:at", NAMESPACE_TOMB);
905 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
906 $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
907 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
908 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
909 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
910 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
911 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
914 if ($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid']) {
915 $body = Item::fixPrivatePhotos($item['body'], $owner['uid'], $item, $cid);
917 $body = $item['body'];
920 // Remove the abstract element. It is only locally important.
921 $body = BBCode::stripAbstract($body);
924 if ($type == 'html') {
927 if ($item['title'] != "") {
928 $htmlbody = "[b]" . $item['title'] . "[/b]\n\n" . $htmlbody;
931 $htmlbody = BBCode::convert($htmlbody, false, 7);
934 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
935 $entry->appendChild($author);
937 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
938 $entry->appendChild($dfrnowner);
940 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
941 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
942 $parent = q("SELECT `guid`,`plink` FROM `item` WHERE `uri` = '%s' AND `uid` = %d", dbesc($parent_item), intval($item['uid']));
943 $attributes = ["ref" => $parent_item, "type" => "text/html",
944 "href" => $parent[0]['plink'],
945 "dfrn:diaspora_guid" => $parent[0]['guid']];
946 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
949 // Add conversation data. This is used for OStatus
950 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
951 $conversation_uri = $conversation_href;
953 if (isset($parent_item)) {
954 $conversation = dba::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $item['parent-uri']]);
955 if (DBM::is_result($conversation)) {
956 if ($r['conversation-uri'] != '') {
957 $conversation_uri = $conversation['conversation-uri'];
959 if ($r['conversation-href'] != '') {
960 $conversation_href = $conversation['conversation-href'];
966 "href" => $conversation_href,
967 "ref" => $conversation_uri];
969 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
971 XML::addElement($doc, $entry, "id", $item["uri"]);
972 XML::addElement($doc, $entry, "title", $item["title"]);
974 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"] . "+00:00", DateTimeFormat::ATOM));
975 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"] . "+00:00", DateTimeFormat::ATOM));
977 // "dfrn:env" is used to read the content
978 XML::addElement($doc, $entry, "dfrn:env", base64url_encode($body, true));
980 // The "content" field is not read by the receiver. We could remove it when the type is "text"
981 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
982 XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
984 // We save this value in "plink". Maybe we should read it from there as well?
990 ["rel" => "alternate", "type" => "text/html",
991 "href" => System::baseUrl() . "/display/" . $item["guid"]]
994 // "comment-allow" is some old fashioned stuff for old Friendica versions.
995 // It is included in the rewritten code for completeness
997 XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
1000 if ($item['location']) {
1001 XML::addElement($doc, $entry, "dfrn:location", $item['location']);
1004 if ($item['coord']) {
1005 XML::addElement($doc, $entry, "georss:point", $item['coord']);
1008 if (($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])) {
1009 XML::addElement($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
1012 if ($item['extid']) {
1013 XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
1016 if ($item['bookmark']) {
1017 XML::addElement($doc, $entry, "dfrn:bookmark", "true");
1021 XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
1024 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
1026 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
1027 // It is needed for relayed comments to Diaspora.
1028 if ($item['signed_text']) {
1029 $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer']]));
1030 XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
1033 XML::addElement($doc, $entry, "activity:verb", self::constructVerb($item));
1035 if ($item['object-type'] != "") {
1036 XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
1037 } elseif ($item['id'] == $item['parent']) {
1038 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1040 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
1043 $actobj = self::createActivity($doc, "activity:object", $item['object']);
1045 $entry->appendChild($actobj);
1048 $actarg = self::createActivity($doc, "activity:target", $item['target']);
1050 $entry->appendChild($actarg);
1053 $tags = Item::getFeedTags($item);
1055 /// @TODO Combine this with similar below if() block?
1057 foreach ($tags as $t) {
1058 if (($type != 'html') || ($t[0] != "@")) {
1059 XML::addElement($doc, $entry, "category", "", ["scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]]);
1065 foreach ($tags as $t) {
1067 $mentioned[$t[1]] = $t[1];
1072 foreach ($mentioned as $mention) {
1074 "SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1075 intval($owner["uid"]),
1076 dbesc(normalise_link($mention))
1079 if (DBM::is_result($r) && ($r[0]["forum"] || $r[0]["prv"])) {
1085 ["rel" => "mentioned",
1086 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1095 ["rel" => "mentioned",
1096 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1102 self::getAttachment($doc, $entry, $item);
1108 * @brief encrypts data via AES
1110 * @param string $data The data that is to be encrypted
1111 * @param string $key The AES key
1113 * @return string encrypted data
1115 private static function aesEncrypt($data, $key)
1117 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1121 * @brief decrypts data via AES
1123 * @param string $encrypted The encrypted data
1124 * @param string $key The AES key
1126 * @return string decrypted data
1128 public static function aesDecrypt($encrypted, $key)
1130 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1134 * @brief Delivers the atom content to the contacts
1136 * @param array $owner Owner record
1137 * @param array $contact Contact record of the receiver
1138 * @param string $atom Content that will be transmitted
1139 * @param bool $dissolve (to be documented)
1141 * @return int Deliver status. Negative values mean an error.
1142 * @todo Add array type-hint for $owner, $contact
1144 public static function deliver($owner, $contact, $atom, $dissolve = false)
1148 // At first try the Diaspora transport layer
1149 $ret = self::transmit($owner, $contact, $atom);
1151 logger('Delivery via Diaspora transport layer was successful with status ' . $ret);
1155 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1157 if ($contact['duplex'] && $contact['dfrn-id']) {
1158 $idtosend = '0:' . $orig_id;
1160 if ($contact['duplex'] && $contact['issued-id']) {
1161 $idtosend = '1:' . $orig_id;
1164 $rino = Config::get('system', 'rino_encrypt');
1165 $rino = intval($rino);
1167 logger("Local rino version: ". $rino, LOGGER_DEBUG);
1169 $ssl_val = intval(Config::get('system', 'ssl_policy'));
1173 case SSL_POLICY_FULL:
1174 $ssl_policy = 'full';
1176 case SSL_POLICY_SELFSIGN:
1177 $ssl_policy = 'self';
1179 case SSL_POLICY_NONE:
1181 $ssl_policy = 'none';
1185 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1187 logger('dfrn_deliver: ' . $url);
1189 $ret = Network::curl($url);
1191 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1192 Contact::markForArchival($contact);
1193 return -2; // timed out
1196 $xml = $ret['body'];
1198 $curl_stat = $a->get_curl_code();
1199 if (empty($curl_stat)) {
1200 Contact::markForArchival($contact);
1201 return -3; // timed out
1204 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1207 Contact::markForArchival($contact);
1211 if (strpos($xml, '<?xml') === false) {
1212 logger('dfrn_deliver: no valid XML returned');
1213 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1214 Contact::markForArchival($contact);
1218 $res = XML::parseString($xml);
1220 if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
1221 Contact::markForArchival($contact);
1222 return ($res->status ? $res->status : 3);
1226 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1227 $challenge = hex2bin((string) $res->challenge);
1228 $perm = (($res->perm) ? $res->perm : null);
1229 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1230 $rino_remote_version = intval($res->rino);
1231 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1233 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
1235 if ($owner['page-flags'] == PAGE_PRVGROUP) {
1239 $final_dfrn_id = '';
1242 if ((($perm == 'rw') && (! intval($contact['writable'])))
1243 || (($perm == 'r') && (intval($contact['writable'])))
1246 "update contact set writable = %d where id = %d",
1247 intval(($perm == 'rw') ? 1 : 0),
1248 intval($contact['id'])
1250 $contact['writable'] = (string) 1 - intval($contact['writable']);
1254 if (($contact['duplex'] && strlen($contact['pubkey']))
1255 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1256 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
1258 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
1259 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
1261 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
1262 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
1265 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1267 if (strpos($final_dfrn_id, ':') == 1) {
1268 $final_dfrn_id = substr($final_dfrn_id, 2);
1271 if ($final_dfrn_id != $orig_id) {
1272 logger('dfrn_deliver: wrong dfrn_id.');
1273 // did not decode properly - cannot trust this site
1274 Contact::markForArchival($contact);
1278 $postvars['dfrn_id'] = $idtosend;
1279 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1281 $postvars['dissolve'] = '1';
1284 if ((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1285 $postvars['data'] = $atom;
1286 $postvars['perm'] = 'rw';
1288 $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
1289 $postvars['perm'] = 'r';
1292 $postvars['ssl_policy'] = $ssl_policy;
1295 $postvars['page'] = $page;
1299 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1300 logger('rino version: '. $rino_remote_version);
1302 switch ($rino_remote_version) {
1304 $key = openssl_random_pseudo_bytes(16);
1305 $data = self::aesEncrypt($postvars['data'], $key);
1308 logger("rino: invalid requested version '$rino_remote_version'");
1309 Contact::markForArchival($contact);
1313 $postvars['rino'] = $rino_remote_version;
1314 $postvars['data'] = bin2hex($data);
1316 if ($dfrn_version >= 2.1) {
1317 if (($contact['duplex'] && strlen($contact['pubkey']))
1318 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1319 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
1321 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1323 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1326 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1327 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1329 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1333 logger('md5 rawkey ' . md5($postvars['key']));
1335 $postvars['key'] = bin2hex($postvars['key']);
1339 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), LOGGER_DATA);
1341 $xml = Network::post($contact['notify'], $postvars);
1343 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1345 $curl_stat = $a->get_curl_code();
1346 if (empty($curl_stat) || empty($xml)) {
1347 Contact::markForArchival($contact);
1348 return -9; // timed out
1351 if (($curl_stat == 503) && stristr($a->get_curl_headers(), 'retry-after')) {
1352 Contact::markForArchival($contact);
1356 if (strpos($xml, '<?xml') === false) {
1357 logger('dfrn_deliver: phase 2: no valid XML returned');
1358 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1359 Contact::markForArchival($contact);
1363 $res = XML::parseString($xml);
1365 if (!isset($res->status)) {
1366 Contact::markForArchival($contact);
1370 // Possibly old servers had returned an empty value when everything was okay
1371 if (empty($res->status)) {
1375 if (!empty($res->message)) {
1376 logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1379 if (($res->status >= 200) && ($res->status <= 299)) {
1380 Contact::unmarkForArchival($contact);
1383 return intval($res->status);
1387 * @brief Transmits atom content to the contacts via the Diaspora transport layer
1389 * @param array $owner Owner record
1390 * @param array $contact Contact record of the receiver
1391 * @param string $atom Content that will be transmitted
1393 * @return int Deliver status. Negative values mean an error.
1395 public static function transmit($owner, $contact, $atom, $public_batch = false)
1399 if (!$public_batch) {
1400 if (empty($contact['addr'])) {
1401 logger('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.');
1402 if (Contact::updateFromProbe($contact['id'])) {
1403 $new_contact = dba::selectFirst('contact', ['addr'], ['id' => $contact['id']]);
1404 $contact['addr'] = $new_contact['addr'];
1407 if (empty($contact['addr'])) {
1408 logger('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
1409 Contact::markForArchival($contact);
1414 $fcontact = Diaspora::personByHandle($contact['addr']);
1415 if (empty($fcontact)) {
1416 logger('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
1417 Contact::markForArchival($contact);
1420 $pubkey = $fcontact['pubkey'];
1425 $envelope = Diaspora::buildMessage($atom, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
1427 // Create the endpoint for public posts. This is some WIP and should later be added to the probing
1428 if ($public_batch && empty($contact["batch"])) {
1429 $parts = parse_url($contact["notify"]);
1430 $path_parts = explode('/', $parts['path']);
1431 array_pop($path_parts);
1432 $parts['path'] = implode('/', $path_parts);
1433 $contact["batch"] = Network::unparseURL($parts);
1436 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
1438 $content_type = ($public_batch ? "application/magic-envelope+xml" : "application/json");
1440 $xml = Network::post($dest_url, $envelope, ["Content-Type: ".$content_type]);
1442 $curl_stat = $a->get_curl_code();
1443 if (empty($curl_stat) || empty($xml)) {
1444 logger('Empty answer from ' . $contact['id'] . ' - ' . $dest_url);
1445 Contact::markForArchival($contact);
1446 return -9; // timed out
1449 if (($curl_stat == 503) && (stristr($a->get_curl_headers(), 'retry-after'))) {
1450 Contact::markForArchival($contact);
1454 if (strpos($xml, '<?xml') === false) {
1455 logger('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url);
1456 logger('Returned XML: ' . $xml, LOGGER_DATA);
1457 Contact::markForArchival($contact);
1461 $res = XML::parseString($xml);
1463 if (empty($res->status)) {
1464 Contact::markForArchival($contact);
1468 if (!empty($res->message)) {
1469 logger('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1472 if (($res->status >= 200) && ($res->status <= 299)) {
1473 Contact::unmarkForArchival($contact);
1476 return intval($res->status);
1480 * @brief Add new birthday event for this person
1482 * @param array $contact Contact record
1483 * @param string $birthday Birthday of the contact
1485 * @todo Add array type-hint for $contact
1487 private static function birthdayEvent($contact, $birthday)
1489 // Check for duplicates
1491 "SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1492 intval($contact['uid']),
1493 intval($contact['id']),
1494 dbesc(DateTimeFormat::utc($birthday)),
1498 if (DBM::is_result($r)) {
1502 logger('updating birthday: ' . $birthday . ' for contact ' . $contact['id']);
1504 $bdtext = L10n::t('%s\'s birthday', $contact['name']);
1505 $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]');
1508 "INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1509 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1510 intval($contact['uid']),
1511 intval($contact['id']),
1512 dbesc(DateTimeFormat::utcNow()),
1513 dbesc(DateTimeFormat::utcNow()),
1514 dbesc(DateTimeFormat::utc($birthday)),
1515 dbesc(DateTimeFormat::utc($birthday . ' + 1 day ')),
1523 * @brief Fetch the author data from head or entry items
1525 * @param object $xpath XPath object
1526 * @param object $context In which context should the data be searched
1527 * @param array $importer Record of the importer user mixed with contact of the content
1528 * @param string $element Element name from which the data is fetched
1529 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1530 * @param string $xml optional, default empty
1532 * @return array Relevant data of the author
1533 * @todo Find good type-hints for all parameter
1535 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
1538 $author["name"] = $xpath->evaluate($element."/atom:name/text()", $context)->item(0)->nodeValue;
1539 $author["link"] = $xpath->evaluate($element."/atom:uri/text()", $context)->item(0)->nodeValue;
1541 $fields = ['id', 'uid', 'url', 'network', 'avatar-date', 'avatar', 'name-date', 'uri-date', 'addr',
1542 'name', 'nick', 'about', 'location', 'keywords', 'xmpp', 'bdyear', 'bd', 'hidden', 'contact-type'];
1543 $condition = ["`uid` = ? AND `nurl` = ? AND `network` != ?",
1544 $importer["importer_uid"], normalise_link($author["link"]), NETWORK_STATUSNET];
1545 $contact_old = dba::selectFirst('contact', $fields, $condition);
1547 if (DBM::is_result($contact_old)) {
1548 $author["contact-id"] = $contact_old["id"];
1549 $author["network"] = $contact_old["network"];
1552 logger("Contact ".$author["link"]." wasn't found for user ".$importer["importer_uid"]." XML: ".$xml, LOGGER_DEBUG);
1555 $author["contact-id"] = $importer["id"];
1556 $author["network"] = $importer["network"];
1560 // Until now we aren't serving different sizes - but maybe later
1562 /// @todo check if "avatar" or "photo" would be the best field in the specification
1563 $avatars = $xpath->query($element . "/atom:link[@rel='avatar']", $context);
1564 foreach ($avatars as $avatar) {
1567 foreach ($avatar->attributes as $attributes) {
1568 /// @TODO Rewrite these similar if() to one switch
1569 if ($attributes->name == "href") {
1570 $href = $attributes->textContent;
1572 if ($attributes->name == "width") {
1573 $width = $attributes->textContent;
1575 if ($attributes->name == "updated") {
1576 $author["avatar-date"] = $attributes->textContent;
1579 if (($width > 0) && ($href != "")) {
1580 $avatarlist[$width] = $href;
1584 if (count($avatarlist) > 0) {
1585 krsort($avatarlist);
1586 $author["avatar"] = current($avatarlist);
1589 if (DBM::is_result($contact_old) && !$onlyfetch) {
1590 logger("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", LOGGER_DEBUG);
1592 $poco = ["url" => $contact_old["url"]];
1594 // When was the last change to name or uri?
1595 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1596 foreach ($name_element->attributes as $attributes) {
1597 if ($attributes->name == "updated") {
1598 $poco["name-date"] = $attributes->textContent;
1602 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1603 foreach ($link_element->attributes as $attributes) {
1604 if ($attributes->name == "updated") {
1605 $poco["uri-date"] = $attributes->textContent;
1609 // Update contact data
1610 $value = $xpath->evaluate($element . "/dfrn:handle/text()", $context)->item(0)->nodeValue;
1612 $poco["addr"] = $value;
1615 $value = $xpath->evaluate($element . "/poco:displayName/text()", $context)->item(0)->nodeValue;
1617 $poco["name"] = $value;
1620 $value = $xpath->evaluate($element . "/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
1622 $poco["nick"] = $value;
1625 $value = $xpath->evaluate($element . "/poco:note/text()", $context)->item(0)->nodeValue;
1627 $poco["about"] = $value;
1630 $value = $xpath->evaluate($element . "/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
1632 $poco["location"] = $value;
1635 /// @todo Only search for elements with "poco:type" = "xmpp"
1636 $value = $xpath->evaluate($element . "/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
1638 $poco["xmpp"] = $value;
1641 /// @todo Add support for the following fields that we don't support by now in the contact table:
1642 /// - poco:utcOffset
1648 // If the "hide" element is present then the profile isn't searchable.
1649 $hide = intval($xpath->evaluate($element . "/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
1651 logger("Hidden status for contact " . $contact_old["url"] . ": " . $hide, LOGGER_DEBUG);
1653 // If the contact isn't searchable then set the contact to "hidden".
1654 // Problem: This can be manually overridden by the user.
1656 $contact_old["hidden"] = true;
1659 // Save the keywords into the contact table
1661 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1662 foreach ($tagelements as $tag) {
1663 $tags[$tag->nodeValue] = $tag->nodeValue;
1667 $poco["keywords"] = implode(", ", $tags);
1670 // "dfrn:birthday" contains the birthday converted to UTC
1671 $birthday = $xpath->evaluate($element . "/dfrn:birthday/text()", $context)->item(0)->nodeValue;
1673 if (strtotime($birthday) > time()) {
1674 $bd_timestamp = strtotime($birthday);
1676 $poco["bdyear"] = date("Y", $bd_timestamp);
1679 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1680 $value = $xpath->evaluate($element . "/poco:birthday/text()", $context)->item(0)->nodeValue;
1682 if (!in_array($value, ["", "0000-00-00", "0001-01-01"])) {
1683 $bdyear = date("Y");
1684 $value = str_replace("0000", $bdyear, $value);
1686 if (strtotime($value) < time()) {
1687 $value = str_replace($bdyear, $bdyear + 1, $value);
1688 $bdyear = $bdyear + 1;
1691 $poco["bd"] = $value;
1694 $contact = array_merge($contact_old, $poco);
1696 if ($contact_old["bdyear"] != $contact["bdyear"]) {
1697 self::birthdayEvent($contact, $birthday);
1700 // Get all field names
1702 foreach ($contact_old as $field => $data) {
1703 $fields[$field] = $data;
1706 unset($fields["id"]);
1707 unset($fields["uid"]);
1708 unset($fields["url"]);
1709 unset($fields["avatar-date"]);
1710 unset($fields["avatar"]);
1711 unset($fields["name-date"]);
1712 unset($fields["uri-date"]);
1715 // Update check for this field has to be done differently
1716 $datefields = ["name-date", "uri-date"];
1717 foreach ($datefields as $field) {
1718 if (strtotime($contact[$field]) > strtotime($contact_old[$field])) {
1719 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1724 foreach ($fields as $field => $data) {
1725 if ($contact[$field] != $contact_old[$field]) {
1726 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1732 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1735 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1736 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1737 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1738 WHERE `id` = %d AND `network` = '%s'",
1739 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
1740 dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1741 dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
1742 dbesc(DBM::date($contact["name-date"])), dbesc(DBM::date($contact["uri-date"])),
1743 intval($contact["id"]), dbesc($contact["network"])
1747 Contact::updateAvatar(
1749 $importer['importer_uid'],
1751 (strtotime($contact['avatar-date']) > strtotime($contact_old['avatar-date']) || ($author['avatar'] != $contact_old['avatar']))
1755 * The generation is a sign for the reliability of the provided data.
1756 * It is used in the socgraph.php to prevent that old contact data
1757 * that was relayed over several servers can overwrite contact
1758 * data that we received directly.
1761 $poco["generation"] = 2;
1762 $poco["photo"] = $author["avatar"];
1763 $poco["hide"] = $hide;
1764 $poco["contact-type"] = $contact["contact-type"];
1765 $gcid = GContact::update($poco);
1767 GContact::link($gcid, $importer["importer_uid"], $contact["id"]);
1774 * @brief Transforms activity objects into an XML string
1776 * @param object $xpath XPath object
1777 * @param object $activity Activity object
1778 * @param string $element element name
1780 * @return string XML string
1781 * @todo Find good type-hints for all parameter
1783 private static function transformActivity($xpath, $activity, $element)
1785 if (!is_object($activity)) {
1789 $obj_doc = new DOMDocument("1.0", "utf-8");
1790 $obj_doc->formatOutput = true;
1792 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1794 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1795 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1797 $id = $xpath->query("atom:id", $activity)->item(0);
1798 if (is_object($id)) {
1799 $obj_element->appendChild($obj_doc->importNode($id, true));
1802 $title = $xpath->query("atom:title", $activity)->item(0);
1803 if (is_object($title)) {
1804 $obj_element->appendChild($obj_doc->importNode($title, true));
1807 $links = $xpath->query("atom:link", $activity);
1808 if (is_object($links)) {
1809 foreach ($links as $link) {
1810 $obj_element->appendChild($obj_doc->importNode($link, true));
1814 $content = $xpath->query("atom:content", $activity)->item(0);
1815 if (is_object($content)) {
1816 $obj_element->appendChild($obj_doc->importNode($content, true));
1819 $obj_doc->appendChild($obj_element);
1821 $objxml = $obj_doc->saveXML($obj_element);
1823 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1824 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1829 * @brief Processes the mail elements
1831 * @param object $xpath XPath object
1832 * @param object $mail mail elements
1833 * @param array $importer Record of the importer user mixed with contact of the content
1835 * @todo Find good type-hints for all parameter
1837 private static function processMail($xpath, $mail, $importer)
1839 logger("Processing mails");
1841 /// @TODO Rewrite this to one statement
1843 $msg["uid"] = $importer["importer_uid"];
1844 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1845 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1846 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1847 $msg["contact-id"] = $importer["id"];
1848 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1849 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1850 $msg["created"] = DateTimeFormat::utc($xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue);
1851 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1852 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1854 $msg["replied"] = 0;
1856 dba::insert('mail', $msg);
1858 // send notifications.
1859 /// @TODO Arange this mess
1861 "type" => NOTIFY_MAIL,
1862 "notify_flags" => $importer["notify-flags"],
1863 "language" => $importer["language"],
1864 "to_name" => $importer["username"],
1865 "to_email" => $importer["email"],
1866 "uid" => $importer["importer_uid"],
1868 "source_name" => $msg["from-name"],
1869 "source_link" => $importer["url"],
1870 "source_photo" => $importer["thumb"],
1871 "verb" => ACTIVITY_POST,
1875 notification($notif_params);
1877 logger("Mail is processed, notification was sent.");
1881 * @brief Processes the suggestion elements
1883 * @param object $xpath XPath object
1884 * @param object $suggestion suggestion elements
1885 * @param array $importer Record of the importer user mixed with contact of the content
1887 * @todo Find good type-hints for all parameter
1889 private static function processSuggestion($xpath, $suggestion, $importer)
1893 logger("Processing suggestions");
1895 /// @TODO Rewrite this to one statement
1897 $suggest["uid"] = $importer["importer_uid"];
1898 $suggest["cid"] = $importer["id"];
1899 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1900 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1901 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1902 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1903 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1905 // Does our member already have a friend matching this description?
1908 "SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1909 dbesc($suggest["name"]),
1910 dbesc(normalise_link($suggest["url"])),
1911 intval($suggest["uid"])
1915 * The valid result means the friend we're about to send a friend
1916 * suggestion already has them in their contact, which means no further
1917 * action is required.
1919 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1921 if (DBM::is_result($r)) {
1925 // Do we already have an fcontact record for this person?
1929 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1930 dbesc($suggest["url"]),
1931 dbesc($suggest["name"]),
1932 dbesc($suggest["request"])
1934 if (DBM::is_result($r)) {
1937 // OK, we do. Do we already have an introduction for this person ?
1939 "SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1940 intval($suggest["uid"]),
1945 * The valid result means the friend we're about to send a friend
1946 * suggestion already has them in their contact, which means no further
1947 * action is required.
1949 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1951 if (DBM::is_result($r)) {
1957 "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1958 dbesc($suggest["name"]),
1959 dbesc($suggest["url"]),
1960 dbesc($suggest["photo"]),
1961 dbesc($suggest["request"])
1965 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1966 dbesc($suggest["url"]),
1967 dbesc($suggest["name"]),
1968 dbesc($suggest["request"])
1972 * If no record in fcontact is found, below INSERT statement will not
1973 * link an introduction to it.
1975 if (!DBM::is_result($r)) {
1976 // database record did not get created. Quietly give up.
1982 $hash = random_string();
1985 "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1986 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1987 intval($suggest["uid"]),
1989 intval($suggest["cid"]),
1990 dbesc($suggest["body"]),
1992 dbesc(DateTimeFormat::utcNow()),
1998 "type" => NOTIFY_SUGGEST,
1999 "notify_flags" => $importer["notify-flags"],
2000 "language" => $importer["language"],
2001 "to_name" => $importer["username"],
2002 "to_email" => $importer["email"],
2003 "uid" => $importer["importer_uid"],
2005 "link" => System::baseUrl()."/notifications/intros",
2006 "source_name" => $importer["name"],
2007 "source_link" => $importer["url"],
2008 "source_photo" => $importer["photo"],
2009 "verb" => ACTIVITY_REQ_FRIEND,
2017 * @brief Processes the relocation elements
2019 * @param object $xpath XPath object
2020 * @param object $relocation relocation elements
2021 * @param array $importer Record of the importer user mixed with contact of the content
2023 * @todo Find good type-hints for all parameter
2025 private static function processRelocation($xpath, $relocation, $importer)
2027 logger("Processing relocations");
2029 /// @TODO Rewrite this to one statement
2031 $relocate["uid"] = $importer["importer_uid"];
2032 $relocate["cid"] = $importer["id"];
2033 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
2034 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
2035 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
2036 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
2037 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
2038 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
2039 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
2040 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
2041 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
2042 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
2043 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
2044 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
2046 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
2047 $relocate["avatar"] = $relocate["photo"];
2050 if ($relocate["addr"] == "") {
2051 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
2056 "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
2057 intval($importer["id"]),
2058 intval($importer["importer_uid"])
2061 if (!DBM::is_result($r)) {
2062 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2068 // Update the gcontact entry
2069 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
2071 $fields = ['name' => $relocate["name"], 'photo' => $relocate["avatar"],
2072 'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2073 'addr' => $relocate["addr"], 'connect' => $relocate["addr"],
2074 'notify' => $relocate["notify"], 'server_url' => $relocate["server_url"]];
2075 dba::update('gcontact', $fields, ['nurl' => normalise_link($old["url"])]);
2077 // Update the contact table. We try to find every entry.
2078 $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
2079 'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2080 'addr' => $relocate["addr"], 'request' => $relocate["request"],
2081 'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
2082 'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
2083 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], normalise_link($old["url"])];
2084 dba::update('contact', $fields, $condition);
2086 // @TODO No dba:update here?
2087 dba::update('contact', $fields, $condition);
2089 Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
2091 logger('Contacts are updated.');
2094 // This is an extreme performance killer
2095 Item::update(['owner-link' => $relocate["url"]], ['owner-link' => $old["url"], 'uid' => $importer["importer_uid"]]);
2096 Item::update(['author-link' => $relocate["url"]], ['author-link' => $old["url"], 'uid' => $importer["importer_uid"]]);
2098 logger('Items 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;
2168 "SELECT `item`.`parent-uri` FROM `item`
2169 WHERE `item`.`uri` = '%s'
2171 dbesc($item["parent-uri"])
2173 if (DBM::is_result($r)) {
2175 "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2176 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2177 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2178 AND `item`.`uid` = %d
2181 dbesc($r[0]["parent-uri"]),
2182 dbesc($r[0]["parent-uri"]),
2183 dbesc($r[0]["parent-uri"]),
2184 intval($importer["importer_uid"])
2186 if (DBM::is_result($r)) {
2187 $is_a_remote_action = true;
2192 * Does this have the characteristics of a community or private group action?
2193 * If it's an action to a wall post on a community/prvgroup page it's a
2194 * valid community action. Also forum_mode makes it valid for sure.
2195 * If neither, it's not.
2197 if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2198 $is_a_remote_action = false;
2199 logger("not a community action");
2202 if ($is_a_remote_action) {
2203 return DFRN::REPLY_RC;
2208 return DFRN::TOP_LEVEL;
2213 * @brief Send a "poke"
2215 * @param array $item the new item record
2216 * @param array $importer Record of the importer user mixed with contact of the content
2217 * @param int $posted_id The record number of item record that was just posted
2219 * @todo set proper type-hints (array?)
2221 private static function doPoke($item, $importer, $posted_id)
2223 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2227 $xo = XML::parseString($item["object"], false);
2229 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2230 // somebody was poked/prodded. Was it me?
2231 foreach ($xo->link as $l) {
2232 $atts = $l->attributes();
2233 switch ($atts["rel"]) {
2235 $Blink = $atts["href"];
2242 if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2243 $author = dba::selectFirst('contact', ['name', 'thumb', 'url'], ['id' => $item['author-id']]);
2245 // send a notification
2248 "type" => NOTIFY_POKE,
2249 "notify_flags" => $importer["notify-flags"],
2250 "language" => $importer["language"],
2251 "to_name" => $importer["username"],
2252 "to_email" => $importer["email"],
2253 "uid" => $importer["importer_uid"],
2255 "link" => System::baseUrl()."/display/".urlencode(Item::getGuidById($posted_id)),
2256 "source_name" => $author["name"],
2257 "source_link" => $author["url"],
2258 "source_photo" => $author["thumb"],
2259 "verb" => $item["verb"],
2260 "otype" => "person",
2261 "activity" => $verb,
2262 "parent" => $item["parent"]]
2269 * @brief Processes several actions, depending on the verb
2271 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2272 * @param array $importer Record of the importer user mixed with contact of the content
2273 * @param array $item the new item record
2274 * @param bool $is_like Is the verb a "like"?
2276 * @return bool Should the processing of the entries be continued?
2277 * @todo set proper type-hints (array?)
2279 private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2281 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2283 if (($entrytype == DFRN::TOP_LEVEL)) {
2284 // The filling of the the "contact" variable is done for legcy reasons
2285 // The functions below are partly used by ostatus.php as well - where we have this variable
2286 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2288 $nickname = $contact["nick"];
2290 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2291 // This function once was responsible for DFRN and OStatus.
2292 if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2293 logger("New follower");
2294 Contact::addRelationship($importer, $contact, $item, $nickname);
2297 if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2298 logger("Lost follower");
2299 Contact::removeFollower($importer, $contact, $item);
2302 if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2303 logger("New friend request");
2304 Contact::addRelationship($importer, $contact, $item, $nickname, true);
2307 if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2308 logger("Lost sharer");
2309 Contact::removeSharer($importer, $contact, $item);
2313 if (($item["verb"] == ACTIVITY_LIKE)
2314 || ($item["verb"] == ACTIVITY_DISLIKE)
2315 || ($item["verb"] == ACTIVITY_ATTEND)
2316 || ($item["verb"] == ACTIVITY_ATTENDNO)
2317 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
2320 $item["type"] = "activity";
2321 $item["gravity"] = GRAVITY_LIKE;
2322 // only one like or dislike per person
2323 // splitted into two queries for performance issues
2325 "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-id` = %d AND `verb` = '%s' AND `parent-uri` = '%s' AND NOT `deleted` LIMIT 1",
2326 intval($item["uid"]),
2327 intval($item["author-id"]),
2328 dbesc($item["verb"]),
2329 dbesc($item["parent-uri"])
2331 if (DBM::is_result($r)) {
2336 "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-id` = %d AND `verb` = '%s' AND `thr-parent` = '%s' AND NOT `deleted` LIMIT 1",
2337 intval($item["uid"]),
2338 intval($item["author-id"]),
2339 dbesc($item["verb"]),
2340 dbesc($item["parent-uri"])
2342 if (DBM::is_result($r)) {
2349 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2350 $xo = XML::parseString($item["object"], false);
2351 $xt = XML::parseString($item["target"], false);
2353 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2355 "SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2357 intval($importer["importer_uid"])
2360 if (!DBM::is_result($r)) {
2361 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2365 // extract tag, if not duplicate, add to parent item
2367 if (!stristr($r[0]["tag"], trim($xo->content))) {
2368 $tag = $r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2369 Item::update(['tag' => $tag], ['id' => $r[0]["id"]]);
2379 * @brief Processes the link elements
2381 * @param object $links link elements
2382 * @param array $item the item record
2384 * @todo set proper type-hints
2386 private static function parseLinks($links, &$item)
2393 foreach ($links as $link) {
2394 foreach ($link->attributes as $attributes) {
2395 switch ($attributes->name) {
2396 case "href" : $href = $attributes->textContent; break;
2397 case "rel" : $rel = $attributes->textContent; break;
2398 case "type" : $type = $attributes->textContent; break;
2399 case "length": $length = $attributes->textContent; break;
2400 case "title" : $title = $attributes->textContent; break;
2403 if (($rel != "") && ($href != "")) {
2406 $item["plink"] = $href;
2410 if (strlen($item["attach"])) {
2411 $item["attach"] .= ",";
2414 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2422 * @brief Processes the entry elements which contain the items and comments
2424 * @param array $header Array of the header elements that always stay the same
2425 * @param object $xpath XPath object
2426 * @param object $entry entry elements
2427 * @param array $importer Record of the importer user mixed with contact of the content
2428 * @param object $xml xml
2430 * @todo Add type-hints
2432 private static function processEntry($header, $xpath, $entry, $importer, $xml)
2434 logger("Processing entries");
2438 $item["protocol"] = PROTOCOL_DFRN;
2440 $item["source"] = $xml;
2443 $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
2445 $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
2447 $current = dba::selectFirst('item',
2448 ['id', 'uid', 'edited', 'body'],
2449 ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
2451 // Is there an existing item?
2452 if (DBM::is_result($current) && !self::isEditedTimestampNewer($current, $item)) {
2453 logger("Item ".$item["uri"]." (".$item['edited'].") already existed.", LOGGER_DEBUG);
2458 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2460 $item["owner-link"] = $owner["link"];
2461 $item["owner-id"] = Contact::getIdForURL($owner["link"], 0);
2464 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2466 $item["author-link"] = $author["link"];
2467 $item["author-id"] = Contact::getIdForURL($author["link"], 0);
2469 $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
2471 $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2473 $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
2474 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2475 // make sure nobody is trying to sneak some html tags by us
2476 $item["body"] = notags(base64url_decode($item["body"]));
2478 $item["body"] = BBCode::limitBodySize($item["body"]);
2480 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2481 if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
2482 $base_url = get_app()->get_baseurl();
2483 $item['body'] = reltoabs($item['body'], $base_url);
2485 $item['body'] = html2bb_video($item['body']);
2487 $item['body'] = OEmbed::HTML2BBCode($item['body']);
2489 $config = HTMLPurifier_Config::createDefault();
2490 $config->set('Cache.DefinitionImpl', null);
2492 // we shouldn't need a whitelist, because the bbcode converter
2493 // will strip out any unsupported tags.
2495 $purifier = new HTMLPurifier($config);
2496 $item['body'] = $purifier->purify($item['body']);
2498 $item['body'] = @HTML::toBBCode($item['body']);
2501 /// @todo We should check for a repeated post and if we know the repeated author.
2503 // We don't need the content element since "dfrn:env" is always present
2504 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2506 $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
2508 $georsspoint = $xpath->query("georss:point", $entry);
2510 $item["coord"] = $georsspoint->item(0)->nodeValue;
2513 $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
2515 $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
2517 if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true") {
2518 $item["bookmark"] = true;
2521 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2522 if ($notice_info && ($notice_info->length > 0)) {
2523 foreach ($notice_info->item(0)->attributes as $attributes) {
2524 if ($attributes->name == "source") {
2525 $item["app"] = strip_tags($attributes->textContent);
2530 $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
2532 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
2533 $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
2534 if ($dsprsig != "") {
2535 $item["dsprsig"] = $dsprsig;
2538 $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
2540 if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "") {
2541 $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
2544 $object = $xpath->query("activity:object", $entry)->item(0);
2545 $item["object"] = self::transformActivity($xpath, $object, "object");
2547 if (trim($item["object"]) != "") {
2548 $r = XML::parseString($item["object"], false);
2549 if (isset($r->type)) {
2550 $item["object-type"] = $r->type;
2554 $target = $xpath->query("activity:target", $entry)->item(0);
2555 $item["target"] = self::transformActivity($xpath, $target, "target");
2557 $categories = $xpath->query("atom:category", $entry);
2559 foreach ($categories as $category) {
2562 foreach ($category->attributes as $attributes) {
2563 if ($attributes->name == "term") {
2564 $term = $attributes->textContent;
2567 if ($attributes->name == "scheme") {
2568 $scheme = $attributes->textContent;
2572 if (($term != "") && ($scheme != "")) {
2573 $parts = explode(":", $scheme);
2574 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2575 $termhash = array_shift($parts);
2576 $termurl = implode(":", $parts);
2578 if (strlen($item["tag"])) {
2579 $item["tag"] .= ",";
2582 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2590 $links = $xpath->query("atom:link", $entry);
2592 self::parseLinks($links, $item);
2595 $item['conversation-uri'] = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
2597 $conv = $xpath->query('ostatus:conversation', $entry);
2598 if (is_object($conv->item(0))) {
2599 foreach ($conv->item(0)->attributes as $attributes) {
2600 if ($attributes->name == "ref") {
2601 $item['conversation-uri'] = $attributes->textContent;
2603 if ($attributes->name == "href") {
2604 $item['conversation-href'] = $attributes->textContent;
2609 // Is it a reply or a top level posting?
2610 $item["parent-uri"] = $item["uri"];
2612 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2613 if (is_object($inreplyto->item(0))) {
2614 foreach ($inreplyto->item(0)->attributes as $attributes) {
2615 if ($attributes->name == "ref") {
2616 $item["parent-uri"] = $attributes->textContent;
2621 // Get the type of the item (Top level post, reply or remote reply)
2622 $entrytype = self::getEntryType($importer, $item);
2624 // Now assign the rest of the values that depend on the type of the message
2625 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2626 if (!isset($item["object-type"])) {
2627 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2630 if ($item["contact-id"] != $owner["contact-id"]) {
2631 $item["contact-id"] = $owner["contact-id"];
2634 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2635 $item["network"] = $owner["network"];
2638 if ($item["contact-id"] != $author["contact-id"]) {
2639 $item["contact-id"] = $author["contact-id"];
2642 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2643 $item["network"] = $author["network"];
2647 if ($entrytype == DFRN::REPLY_RC) {
2648 $item["type"] = "remote-comment";
2650 } elseif ($entrytype == DFRN::TOP_LEVEL) {
2651 if (!isset($item["object-type"])) {
2652 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2656 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2657 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2658 $ev = Event::fromBBCode($item["body"]);
2659 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2660 logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2661 $ev["cid"] = $importer["id"];
2662 $ev["uid"] = $importer["importer_uid"];
2663 $ev["uri"] = $item["uri"];
2664 $ev["edited"] = $item["edited"];
2665 $ev["private"] = $item["private"];
2666 $ev["guid"] = $item["guid"];
2669 "SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2670 dbesc($item["uri"]),
2671 intval($importer["importer_uid"])
2673 if (DBM::is_result($r)) {
2674 $ev["id"] = $r[0]["id"];
2677 $event_id = Event::store($ev);
2678 logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2684 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2685 logger("Exiting because 'processVerbs' told us so", LOGGER_DEBUG);
2689 // Update content if 'updated' changes
2690 if (DBM::is_result($current)) {
2691 if (self::updateContent($current, $item, $importer, $entrytype)) {
2692 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2694 logger("Item " . $item["uri"] . " already existed.", LOGGER_DEBUG);
2699 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2700 $posted_id = Item::insert($item);
2704 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2706 if ($item['uid'] == 0) {
2707 Item::distribute($posted_id);
2712 } else { // $entrytype == DFRN::TOP_LEVEL
2713 if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
2714 logger("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", LOGGER_DEBUG);
2717 if (!link_compare($item["owner-link"], $importer["url"])) {
2719 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2720 * but otherwise there's a possible data mixup on the sender's system.
2721 * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2722 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2724 logger('Correcting item owner.', LOGGER_DEBUG);
2725 $item["owner-link"] = $importer["url"];
2726 $item["owner-id"] = Contact::getIdForURL($importer["url"], 0);
2729 if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2730 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2734 // This is my contact on another system, but it's really me.
2735 // Turn this into a wall post.
2736 $notify = Item::isRemoteSelf($importer, $item);
2738 $posted_id = Item::insert($item, false, $notify);
2741 $posted_id = $notify;
2744 logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2746 if ($item['uid'] == 0) {
2747 Item::distribute($posted_id);
2750 if (stristr($item["verb"], ACTIVITY_POKE)) {
2751 self::doPoke($item, $importer, $posted_id);
2757 * @brief Deletes items
2759 * @param object $xpath XPath object
2760 * @param object $deletion deletion elements
2761 * @param array $importer Record of the importer user mixed with contact of the content
2763 * @todo set proper type-hints
2765 private static function processDeletion($xpath, $deletion, $importer)
2767 logger("Processing deletions");
2770 foreach ($deletion->attributes as $attributes) {
2771 if ($attributes->name == "ref") {
2772 $uri = $attributes->textContent;
2776 if (!$uri || !$importer["id"]) {
2780 $condition = ["`uri` = ? AND `uid` = ? AND NOT `file` LIKE '%[%'", $uri, $importer["importer_uid"]];
2781 $item = dba::selectFirst('item', ['id', 'parent', 'contact-id'], $condition);
2782 if (!DBM::is_result($item)) {
2783 logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", LOGGER_DEBUG);
2787 // When it is a starting post it has to belong to the person that wants to delete it
2788 if (($item['id'] == $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2789 logger("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2793 // Comments can be deleted by the thread owner or comment owner
2794 if (($item['id'] != $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2795 $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2796 if (!dba::exists('item', $condition)) {
2797 logger("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2802 if ($item["deleted"]) {
2806 logger('deleting item '.$item['id'].' uri='.$uri, LOGGER_DEBUG);
2808 Item::delete(['id' => $item['id']]);
2812 * @brief Imports a DFRN message
2814 * @param string $xml The DFRN message
2815 * @param array $importer Record of the importer user mixed with contact of the content
2816 * @param bool $sort_by_date Is used when feeds are polled
2817 * @return integer Import status
2818 * @todo set proper type-hints
2820 public static function import($xml, $importer, $sort_by_date = false)
2826 $doc = new DOMDocument();
2827 @$doc->loadXML($xml);
2829 $xpath = new DOMXPath($doc);
2830 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2831 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2832 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2833 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2834 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2835 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2836 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2837 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2838 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2839 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2842 $header["uid"] = $importer["importer_uid"];
2843 $header["network"] = NETWORK_DFRN;
2844 $header["type"] = "remote";
2845 $header["wall"] = 0;
2846 $header["origin"] = 0;
2847 $header["contact-id"] = $importer["id"];
2849 // Update the contact table if the data has changed
2851 // The "atom:author" is only present in feeds
2852 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2853 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2856 // Only the "dfrn:owner" in the head section contains all data
2857 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2858 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2861 logger("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2863 // is it a public forum? Private forums aren't exposed with this method
2864 $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()")->item(0)->nodeValue);
2866 // The account type is new since 3.5.1
2867 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2868 $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()")->item(0)->nodeValue);
2870 if ($accounttype != $importer["contact-type"]) {
2871 dba::update('contact', ['contact-type' => $accounttype], ['id' => $importer["id"]]);
2873 // A forum contact can either have set "forum" or "prv" - but not both
2874 if (($accounttype == ACCOUNT_TYPE_COMMUNITY) && (($forum != $importer["forum"]) || ($forum == $importer["prv"]))) {
2875 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer["id"]];
2876 dba::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2878 } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
2879 $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2880 dba::update('contact', ['forum' => $forum], $condition);
2884 // We are processing relocations even if we are ignoring a contact
2885 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2886 foreach ($relocations as $relocation) {
2887 self::processRelocation($xpath, $relocation, $importer);
2890 if (($importer["uid"] != 0) && !$importer["readonly"]) {
2891 $mails = $xpath->query("/atom:feed/dfrn:mail");
2892 foreach ($mails as $mail) {
2893 self::processMail($xpath, $mail, $importer);
2896 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2897 foreach ($suggestions as $suggestion) {
2898 self::processSuggestion($xpath, $suggestion, $importer);
2902 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2903 foreach ($deletions as $deletion) {
2904 self::processDeletion($xpath, $deletion, $importer);
2907 if (!$sort_by_date) {
2908 $entries = $xpath->query("/atom:feed/atom:entry");
2909 foreach ($entries as $entry) {
2910 self::processEntry($header, $xpath, $entry, $importer, $xml);
2914 $entries = $xpath->query("/atom:feed/atom:entry");
2915 foreach ($entries as $entry) {
2916 $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2917 $newentries[strtotime($created)] = $entry;
2920 // Now sort after the publishing date
2923 foreach ($newentries as $entry) {
2924 self::processEntry($header, $xpath, $entry, $importer, $xml);
2927 logger("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2933 * @param string $contact_nick contact nickname
2935 public static function autoRedir(App $a, $contact_nick)
2938 if (x($_REQUEST, 'redir') && intval($_REQUEST['redir'])) {
2942 if ((! $contact_nick) || ($contact_nick === $a->user['nickname'])) {
2947 // We need to find out if $contact_nick is a user on this hub, and if so, if I
2948 // am a contact of that user. However, that user may have other contacts with the
2949 // same nickname as me on other hubs or other networks. Exclude these by requiring
2950 // that the contact have a local URL. I will be the only person with my nickname at
2951 // this URL, so if a result is found, then I am a contact of the $contact_nick user.
2953 // We also have to make sure that I'm a legitimate contact--I'm not blocked or pending.
2955 $baseurl = System::baseUrl();
2956 $domain_st = strpos($baseurl, "://");
2957 if ($domain_st === false) {
2960 $baseurl = substr($baseurl, $domain_st + 3);
2961 $nurl = normalise_link($baseurl);
2963 /// @todo Why is there a query for "url" *and* "nurl"? Especially this normalising is strange.
2964 $r = q("SELECT `id` FROM `contact` WHERE `uid` = (SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1)
2965 AND `nick` = '%s' AND NOT `self` AND (`url` LIKE '%%%s%%' OR `nurl` LIKE '%%%s%%') AND NOT `blocked` AND NOT `pending` LIMIT 1",
2966 dbesc($contact_nick),
2967 dbesc($a->user['nickname']),
2971 if ((! DBM::is_result($r)) || $r[0]['id'] == remote_user()) {
2975 $r = q("SELECT * FROM contact WHERE nick = '%s'
2976 AND network = '%s' AND uid = %d AND url LIKE '%%%s%%' LIMIT 1",
2977 dbesc($contact_nick),
2978 dbesc(NETWORK_DFRN),
2979 intval(local_user()),
2982 if (! DBM::is_result($r)) {
2988 $dfrn_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2990 if ($r[0]['duplex'] && $r[0]['issued-id']) {
2991 $orig_id = $r[0]['issued-id'];
2992 $dfrn_id = '1:' . $orig_id;
2994 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
2995 $orig_id = $r[0]['dfrn-id'];
2996 $dfrn_id = '0:' . $orig_id;
2999 // ensure that we've got a valid ID. There may be some edge cases with forums and non-duplex mode
3000 // that may have triggered some of the "went to {profile/intro} and got an RSS feed" issues
3002 if (strlen($dfrn_id) < 3) {
3006 $sec = random_string();
3008 dba::insert('profile_check', ['uid' => local_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id, 'sec' => $sec, 'expire' => time() + 45]);
3010 $url = curPageURL();
3012 logger('auto_redir: ' . $r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
3013 $dest = (($url) ? '&destination_url=' . $url : '');
3014 goaway($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
3015 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest);
3022 * @brief Returns the activity verb
3024 * @param array $item Item array
3026 * @return string activity verb
3028 private static function constructVerb(array $item)
3030 if ($item['verb']) {
3031 return $item['verb'];
3033 return ACTIVITY_POST;
3036 private static function tgroupCheck($uid, $item)
3040 // check that the message originated elsewhere and is a top-level post
3042 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['parent-uri'])) {
3046 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
3049 if (!DBM::is_result($u)) {
3053 $community_page = ($u[0]['page-flags'] == PAGE_COMMUNITY);
3054 $prvgroup = ($u[0]['page-flags'] == PAGE_PRVGROUP);
3056 $link = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
3059 * Diaspora uses their own hardwired link URL in @-tags
3060 * instead of the one we supply with webfinger
3062 $dlink = normalise_link(System::baseUrl() . '/u/' . $u[0]['nickname']);
3064 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
3066 foreach ($matches as $mtch) {
3067 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
3069 logger('mention found: ' . $mtch[2]);
3078 return $community_page || $prvgroup;
3082 * This function returns true if $update has an edited timestamp newer
3083 * than $existing, i.e. $update contains new data which should override
3084 * what's already there. If there is no timestamp yet, the update is
3085 * assumed to be newer. If the update has no timestamp, the existing
3086 * item is assumed to be up-to-date. If the timestamps are equal it
3087 * assumes the update has been seen before and should be ignored.
3090 private static function isEditedTimestampNewer($existing, $update)
3092 if (!x($existing, 'edited') || !$existing['edited']) {
3095 if (!x($update, 'edited') || !$update['edited']) {
3099 $existing_edited = DateTimeFormat::utc($existing['edited']);
3100 $update_edited = DateTimeFormat::utc($update['edited']);
3102 return (strcmp($existing_edited, $update_edited) < 0);