3 * @file include/dfrn.php
4 * @brief The implementation of the dfrn protocol
6 * @see https://github.com/friendica/friendica/wiki/Protocol and
7 * https://github.com/friendica/friendica/blob/master/spec/dfrn2.pdf
9 namespace Friendica\Protocol;
14 use Friendica\Content\OEmbed;
15 use Friendica\Content\Text\BBCode;
16 use Friendica\Content\Text\HTML;
17 use Friendica\Core\Addon;
18 use Friendica\Core\Config;
19 use Friendica\Core\L10n;
20 use Friendica\Core\System;
21 use Friendica\Database\DBA;
22 use Friendica\Database\DBM;
23 use Friendica\Model\Contact;
24 use Friendica\Model\Event;
25 use Friendica\Model\GContact;
26 use Friendica\Model\Group;
27 use Friendica\Model\Item;
28 use Friendica\Model\Profile;
29 use Friendica\Model\User;
30 use Friendica\Object\Image;
31 use Friendica\Util\Crypto;
32 use Friendica\Util\DateTimeFormat;
33 use Friendica\Util\Network;
34 use Friendica\Util\XML;
36 use HTMLPurifier_Config;
38 require_once 'boot.php';
39 require_once 'include/dba.php';
40 require_once "include/enotify.php";
41 require_once "include/items.php";
42 require_once "include/text.php";
45 * @brief This class contain functions to create and send DFRN XML files
50 const TOP_LEVEL = 0; // Top level posting
51 const REPLY = 1; // Regular reply that is stored locally
52 const REPLY_RC = 2; // Reply that will be relayed
55 * @brief Generates the atom entries for delivery.php
57 * This function is used whenever content is transmitted via DFRN.
59 * @param array $items Item elements
60 * @param array $owner Owner record
62 * @return string DFRN entries
63 * @todo Find proper type-hints
65 public static function entries($items, $owner)
67 $doc = new DOMDocument('1.0', 'utf-8');
68 $doc->formatOutput = true;
70 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
72 if (! count($items)) {
73 return trim($doc->saveXML());
76 foreach ($items as $item) {
77 // These values aren't sent when sending from the queue.
78 /// @todo Check if we can set these values from the queue or if they are needed at all.
79 $item["entry:comment-allow"] = defaults($item, "entry:comment-allow", true);
80 $item["entry:cid"] = defaults($item, "entry:cid", 0);
82 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
83 $root->appendChild($entry);
86 return trim($doc->saveXML());
90 * @brief Generate an atom feed for the given user
92 * This function is called when another server is pulling data from the user feed.
94 * @param string $dfrn_id DFRN ID from the requesting party
95 * @param string $owner_nick Owner nick name
96 * @param string $last_update Date of the last update
97 * @param int $direction Can be -1, 0 or 1.
98 * @param boolean $onlyheader Output only the header without content? (Default is "no")
100 * @return string DFRN feed entries
102 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false)
106 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
107 $public_feed = (($dfrn_id) ? false : true);
108 $starred = false; // not yet implemented, possible security issues
111 if ($public_feed && $a->argc > 2) {
112 for ($x = 2; $x < $a->argc; $x++) {
113 if ($a->argv[$x] == 'converse') {
116 if ($a->argv[$x] == 'starred') {
119 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
120 $category = $a->argv[$x+1];
125 // default permissions - anonymous user
127 $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = '' ";
130 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
131 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
132 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
136 if (! DBM::is_result($r)) {
137 logger(sprintf('No contact found for nickname=%d', $owner_nick), LOGGER_WARNING);
142 $owner_id = $owner['uid'];
143 $owner_nick = $owner['nickname'];
145 $sql_post_table = "";
147 if (! $public_feed) {
149 switch ($direction) {
151 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
155 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
156 $my_id = '1:' . $dfrn_id;
159 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
160 $my_id = '0:' . $dfrn_id;
168 "SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
172 if (! DBM::is_result($r)) {
173 logger(sprintf('No contact found for uid=%d', $owner_id), LOGGER_WARNING);
178 include_once 'include/security.php';
179 $groups = Group::getIdsByContactId($contact['id']);
181 if (count($groups)) {
182 for ($x = 0; $x < count($groups); $x ++) {
183 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
186 $gs = implode('|', $groups);
188 $gs = '<<>>' ; // Impossible to match
191 $sql_extra = sprintf(
193 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
194 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
195 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
196 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
198 intval($contact['id']),
199 intval($contact['id']),
211 if (! strlen($last_update)) {
212 $last_update = 'now -30 days';
215 if (isset($category)) {
216 $sql_post_table = sprintf(
217 "INNER JOIN (SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d ORDER BY `tid` DESC) AS `term` ON `item`.`id` = `term`.`oid` ",
218 dbesc(protect_sprintf($category)),
219 intval(TERM_OBJ_POST),
220 intval(TERM_CATEGORY),
223 //$sql_extra .= file_tag_file_query('item',$category,'category');
226 if ($public_feed && ! $converse) {
227 $sql_extra .= " AND `contact`.`self` = 1 ";
230 $check_date = DateTimeFormat::utc($last_update);
234 FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
235 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
236 WHERE `item`.`uid` = %d AND `item`.`wall` AND `item`.`changed` > '%s'
238 ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
245 foreach ($r as $item) {
246 $ids[] = $item['id'];
250 $ret = Item::select(Item::DELIVER_FIELDLIST, ['id' => $ids]);
251 $items = Item::inArray($ret);
257 * Will check further below if this actually returned results.
258 * We will provide an empty feed if that is the case.
261 $doc = new DOMDocument('1.0', 'utf-8');
262 $doc->formatOutput = true;
264 $alternatelink = $owner['url'];
266 if (isset($category)) {
267 $alternatelink .= "/category/".$category;
271 $author = "dfrn:owner";
276 $root = self::addHeader($doc, $owner, $author, $alternatelink, true);
278 /// @TODO This hook can't work anymore
279 // Addon::callHooks('atom_feed', $atom);
281 if (!DBM::is_result($items) || $onlyheader) {
282 $atom = trim($doc->saveXML());
284 Addon::callHooks('atom_feed_end', $atom);
289 foreach ($items as $item) {
290 // prevent private email from leaking.
291 if ($item['network'] == NETWORK_MAIL) {
295 // public feeds get html, our own nodes use bbcode
299 // catch any email that's in a public conversation and make sure it doesn't leak
300 if ($item['private']) {
307 $entry = self::entry($doc, $type, $item, $owner, true);
308 $root->appendChild($entry);
311 $atom = trim($doc->saveXML());
313 Addon::callHooks('atom_feed_end', $atom);
319 * @brief Generate an atom entry for a given item id
321 * @param int $item_id The item id
322 * @param boolean $conversation Show the conversation. If false show the single post.
324 * @return string DFRN feed entry
326 public static function itemFeed($item_id, $conversation = false)
329 $condition = ['parent' => $item_id];
331 $condition = ['id' => $item_id];
334 $ret = Item::select(Item::DELIVER_FIELDLIST, $condition);
335 $items = Item::inArray($ret);
336 if (!DBM::is_result($items)) {
342 if ($item['uid'] != 0) {
343 $owner = User::getOwnerDataById($item['uid']);
348 $owner = ['uid' => 0, 'nick' => 'feed-item'];
351 $doc = new DOMDocument('1.0', 'utf-8');
352 $doc->formatOutput = true;
356 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
357 $doc->appendChild($root);
359 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
360 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
361 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
362 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
363 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
364 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
365 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
366 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
367 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
369 //$root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
371 foreach ($items as $item) {
372 $entry = self::entry($doc, $type, $item, $owner, true, 0);
373 $root->appendChild($entry);
376 $root = self::entry($doc, $type, $item, $owner, true, 0, true);
379 $atom = trim($doc->saveXML());
384 * @brief Create XML text for DFRN mails
386 * @param array $item message elements
387 * @param array $owner Owner record
389 * @return string DFRN mail
390 * @todo Find proper type-hints
392 public static function mail($item, $owner)
394 $doc = new DOMDocument('1.0', 'utf-8');
395 $doc->formatOutput = true;
397 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
399 $mail = $doc->createElement("dfrn:mail");
400 $sender = $doc->createElement("dfrn:sender");
402 XML::addElement($doc, $sender, "dfrn:name", $owner['name']);
403 XML::addElement($doc, $sender, "dfrn:uri", $owner['url']);
404 XML::addElement($doc, $sender, "dfrn:avatar", $owner['thumb']);
406 $mail->appendChild($sender);
408 XML::addElement($doc, $mail, "dfrn:id", $item['uri']);
409 XML::addElement($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
410 XML::addElement($doc, $mail, "dfrn:sentdate", DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
411 XML::addElement($doc, $mail, "dfrn:subject", $item['title']);
412 XML::addElement($doc, $mail, "dfrn:content", $item['body']);
414 $root->appendChild($mail);
416 return trim($doc->saveXML());
420 * @brief Create XML text for DFRN friend suggestions
422 * @param array $item suggestion elements
423 * @param array $owner Owner record
425 * @return string DFRN suggestions
426 * @todo Find proper type-hints
428 public static function fsuggest($item, $owner)
430 $doc = new DOMDocument('1.0', 'utf-8');
431 $doc->formatOutput = true;
433 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
435 $suggest = $doc->createElement("dfrn:suggest");
437 XML::addElement($doc, $suggest, "dfrn:url", $item['url']);
438 XML::addElement($doc, $suggest, "dfrn:name", $item['name']);
439 XML::addElement($doc, $suggest, "dfrn:photo", $item['photo']);
440 XML::addElement($doc, $suggest, "dfrn:request", $item['request']);
441 XML::addElement($doc, $suggest, "dfrn:note", $item['note']);
443 $root->appendChild($suggest);
445 return trim($doc->saveXML());
449 * @brief Create XML text for DFRN relocations
451 * @param array $owner Owner record
452 * @param int $uid User ID
454 * @return string DFRN relocations
455 * @todo Find proper type-hints
457 public static function relocate($owner, $uid)
460 /* get site pubkey. this could be a new installation with no site keys*/
461 $pubkey = Config::get('system', 'site_pubkey');
463 $res = Crypto::newKeypair(1024);
464 Config::set('system', 'site_prvkey', $res['prvkey']);
465 Config::set('system', 'site_pubkey', $res['pubkey']);
469 "SELECT `resource-id` , `scale`, type FROM `photo`
470 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;",
474 $ext = Image::supportedTypes();
476 foreach ($rp as $p) {
477 $photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
481 $doc = new DOMDocument('1.0', 'utf-8');
482 $doc->formatOutput = true;
484 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
486 $relocate = $doc->createElement("dfrn:relocate");
488 XML::addElement($doc, $relocate, "dfrn:url", $owner['url']);
489 XML::addElement($doc, $relocate, "dfrn:name", $owner['name']);
490 XML::addElement($doc, $relocate, "dfrn:addr", $owner['addr']);
491 XML::addElement($doc, $relocate, "dfrn:avatar", $owner['avatar']);
492 XML::addElement($doc, $relocate, "dfrn:photo", $photos[4]);
493 XML::addElement($doc, $relocate, "dfrn:thumb", $photos[5]);
494 XML::addElement($doc, $relocate, "dfrn:micro", $photos[6]);
495 XML::addElement($doc, $relocate, "dfrn:request", $owner['request']);
496 XML::addElement($doc, $relocate, "dfrn:confirm", $owner['confirm']);
497 XML::addElement($doc, $relocate, "dfrn:notify", $owner['notify']);
498 XML::addElement($doc, $relocate, "dfrn:poll", $owner['poll']);
499 XML::addElement($doc, $relocate, "dfrn:sitepubkey", Config::get('system', 'site_pubkey'));
501 $root->appendChild($relocate);
503 return trim($doc->saveXML());
507 * @brief Adds the header elements for the DFRN protocol
509 * @param object $doc XML document
510 * @param array $owner Owner record
511 * @param string $authorelement Element name for the author
512 * @param string $alternatelink link to profile or category
513 * @param bool $public Is it a header for public posts?
515 * @return object XML root object
516 * @todo Find proper type-hints
518 private static function addHeader($doc, $owner, $authorelement, $alternatelink = "", $public = false)
521 if ($alternatelink == "") {
522 $alternatelink = $owner['url'];
525 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
526 $doc->appendChild($root);
528 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
529 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
530 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
531 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
532 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
533 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
534 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
535 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
536 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
538 XML::addElement($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
539 XML::addElement($doc, $root, "title", $owner["name"]);
541 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION];
542 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
544 $attributes = ["rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/"];
545 XML::addElement($doc, $root, "link", "", $attributes);
547 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $alternatelink];
548 XML::addElement($doc, $root, "link", "", $attributes);
552 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
553 OStatus::hublinks($doc, $root, $owner["nick"]);
555 $attributes = ["rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
556 XML::addElement($doc, $root, "link", "", $attributes);
558 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
559 XML::addElement($doc, $root, "link", "", $attributes);
561 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
562 XML::addElement($doc, $root, "link", "", $attributes);
565 // For backward compatibility we keep this element
566 if ($owner['page-flags'] == PAGE_COMMUNITY) {
567 XML::addElement($doc, $root, "dfrn:community", 1);
570 // The former element is replaced by this one
571 XML::addElement($doc, $root, "dfrn:account_type", $owner["account-type"]);
573 /// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
575 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
577 $author = self::addAuthor($doc, $owner, $authorelement, $public);
578 $root->appendChild($author);
584 * @brief Adds the author element in the header for the DFRN protocol
586 * @param object $doc XML document
587 * @param array $owner Owner record
588 * @param string $authorelement Element name for the author
589 * @param boolean $public boolean
591 * @return object XML author object
592 * @todo Find proper type-hints
594 private static function addAuthor($doc, $owner, $authorelement, $public)
596 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
598 "SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
599 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
600 intval($owner['uid'])
602 if (DBM::is_result($r)) {
608 $author = $doc->createElement($authorelement);
610 $namdate = DateTimeFormat::utc($owner['name-date'].'+00:00', DateTimeFormat::ATOM);
611 $uridate = DateTimeFormat::utc($owner['uri-date'].'+00:00', DateTimeFormat::ATOM);
612 $picdate = DateTimeFormat::utc($owner['avatar-date'].'+00:00', DateTimeFormat::ATOM);
616 if (!$public || !$hidewall) {
617 $attributes = ["dfrn:updated" => $namdate];
620 XML::addElement($doc, $author, "name", $owner["name"], $attributes);
621 XML::addElement($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
622 XML::addElement($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
624 $attributes = ["rel" => "photo", "type" => "image/jpeg",
625 "media:width" => 175, "media:height" => 175, "href" => $owner['photo']];
627 if (!$public || !$hidewall) {
628 $attributes["dfrn:updated"] = $picdate;
631 XML::addElement($doc, $author, "link", "", $attributes);
633 $attributes["rel"] = "avatar";
634 XML::addElement($doc, $author, "link", "", $attributes);
637 XML::addElement($doc, $author, "dfrn:hide", "true");
640 // The following fields will only be generated if the data isn't meant for a public feed
645 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
648 XML::addElement($doc, $author, "dfrn:birthday", $birthday);
651 // Only show contact details when we are allowed to
653 "SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
654 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
655 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
657 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
658 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
659 intval($owner['uid'])
661 if (DBM::is_result($r)) {
664 XML::addElement($doc, $author, "poco:displayName", $profile["name"]);
665 XML::addElement($doc, $author, "poco:updated", $namdate);
667 if (trim($profile["dob"]) > '0001-01-01') {
668 XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
671 XML::addElement($doc, $author, "poco:note", $profile["about"]);
672 XML::addElement($doc, $author, "poco:preferredUsername", $profile["nickname"]);
674 $savetz = date_default_timezone_get();
675 date_default_timezone_set($profile["timezone"]);
676 XML::addElement($doc, $author, "poco:utcOffset", date("P"));
677 date_default_timezone_set($savetz);
679 if (trim($profile["homepage"]) != "") {
680 $urls = $doc->createElement("poco:urls");
681 XML::addElement($doc, $urls, "poco:type", "homepage");
682 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
683 XML::addElement($doc, $urls, "poco:primary", "true");
684 $author->appendChild($urls);
687 if (trim($profile["pub_keywords"]) != "") {
688 $keywords = explode(",", $profile["pub_keywords"]);
690 foreach ($keywords as $keyword) {
691 XML::addElement($doc, $author, "poco:tags", trim($keyword));
695 if (trim($profile["xmpp"]) != "") {
696 $ims = $doc->createElement("poco:ims");
697 XML::addElement($doc, $ims, "poco:type", "xmpp");
698 XML::addElement($doc, $ims, "poco:value", $profile["xmpp"]);
699 XML::addElement($doc, $ims, "poco:primary", "true");
700 $author->appendChild($ims);
703 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
704 $element = $doc->createElement("poco:address");
706 XML::addElement($doc, $element, "poco:formatted", Profile::formatLocation($profile));
708 if (trim($profile["locality"]) != "") {
709 XML::addElement($doc, $element, "poco:locality", $profile["locality"]);
712 if (trim($profile["region"]) != "") {
713 XML::addElement($doc, $element, "poco:region", $profile["region"]);
716 if (trim($profile["country-name"]) != "") {
717 XML::addElement($doc, $element, "poco:country", $profile["country-name"]);
720 $author->appendChild($element);
728 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
730 * @param object $doc XML document
731 * @param string $element Element name for the author
732 * @param string $contact_url Link of the contact
733 * @param array $item Item elements
735 * @return object XML author object
736 * @todo Find proper type-hints
738 private static function addEntryAuthor($doc, $element, $contact_url, $item)
740 $contact = Contact::getDetailsByURL($contact_url, $item["uid"]);
742 $author = $doc->createElement($element);
743 XML::addElement($doc, $author, "name", $contact["name"]);
744 XML::addElement($doc, $author, "uri", $contact["url"]);
745 XML::addElement($doc, $author, "dfrn:handle", $contact["addr"]);
748 /// - Check real image type and image size
749 /// - Check which of these boths elements we should use
752 "type" => "image/jpeg",
754 "media:height" => 80,
755 "href" => $contact["photo"]];
756 XML::addElement($doc, $author, "link", "", $attributes);
760 "type" => "image/jpeg",
762 "media:height" => 80,
763 "href" => $contact["photo"]];
764 XML::addElement($doc, $author, "link", "", $attributes);
770 * @brief Adds the activity elements
772 * @param object $doc XML document
773 * @param string $element Element name for the activity
774 * @param string $activity activity value
776 * @return object XML activity object
777 * @todo Find proper type-hints
779 private static function createActivity($doc, $element, $activity)
782 $entry = $doc->createElement($element);
784 $r = XML::parseString($activity, false);
790 XML::addElement($doc, $entry, "activity:object-type", $r->type);
794 XML::addElement($doc, $entry, "id", $r->id);
798 XML::addElement($doc, $entry, "title", $r->title);
802 if (substr($r->link, 0, 1) == '<') {
803 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
804 $r->link = str_replace('&', '&', $r->link);
807 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
809 // XML does need a single element as root element so we add a dummy element here
810 $data = XML::parseString("<dummy>" . $r->link . "</dummy>", false);
811 if (is_object($data)) {
812 foreach ($data->link as $link) {
814 foreach ($link->attributes() as $parameter => $value) {
815 $attributes[$parameter] = $value;
817 XML::addElement($doc, $entry, "link", "", $attributes);
821 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
822 XML::addElement($doc, $entry, "link", "", $attributes);
826 XML::addElement($doc, $entry, "content", BBCode::convert($r->content), ["type" => "html"]);
836 * @brief Adds the elements for attachments
838 * @param object $doc XML document
839 * @param object $root XML root
840 * @param array $item Item element
842 * @return object XML attachment object
843 * @todo Find proper type-hints
845 private static function getAttachment($doc, $root, $item)
847 $arr = explode('[/attach],', $item['attach']);
849 foreach ($arr as $r) {
851 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
853 $attributes = ["rel" => "enclosure",
854 "href" => $matches[1],
855 "type" => $matches[3]];
857 if (intval($matches[2])) {
858 $attributes["length"] = intval($matches[2]);
861 if (trim($matches[4]) != "") {
862 $attributes["title"] = trim($matches[4]);
865 XML::addElement($doc, $root, "link", "", $attributes);
872 * @brief Adds the "entry" elements for the DFRN protocol
874 * @param object $doc XML document
875 * @param string $type "text" or "html"
876 * @param array $item Item element
877 * @param array $owner Owner record
878 * @param bool $comment Trigger the sending of the "comment" element
879 * @param int $cid Contact ID of the recipient
880 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
882 * @return object XML entry object
883 * @todo Find proper type-hints
885 private static function entry($doc, $type, array $item, array $owner, $comment = false, $cid = 0, $single = false)
889 if (!$item['parent']) {
893 if ($item['deleted']) {
894 $attributes = ["ref" => $item['uri'], "when" => DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM)];
895 return XML::createElement($doc, "at:deleted-entry", "", $attributes);
899 $entry = $doc->createElement("entry");
901 $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry');
902 $doc->appendChild($entry);
904 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
905 $entry->setAttribute("xmlns:at", NAMESPACE_TOMB);
906 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
907 $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
908 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
909 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
910 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
911 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
912 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
915 if ($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid']) {
916 $body = Item::fixPrivatePhotos($item['body'], $owner['uid'], $item, $cid);
918 $body = $item['body'];
921 // Remove the abstract element. It is only locally important.
922 $body = BBCode::stripAbstract($body);
925 if ($type == 'html') {
928 if ($item['title'] != "") {
929 $htmlbody = "[b]" . $item['title'] . "[/b]\n\n" . $htmlbody;
932 $htmlbody = BBCode::convert($htmlbody, false, 7);
935 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
936 $entry->appendChild($author);
938 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
939 $entry->appendChild($dfrnowner);
941 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
942 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
943 $parent = Item::selectFirst(['guid', 'plink'], ['uri' => $parent_item, 'uid' => $item['uid']]);
944 $attributes = ["ref" => $parent_item, "type" => "text/html",
945 "href" => $parent['plink'],
946 "dfrn:diaspora_guid" => $parent['guid']];
947 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
950 // Add conversation data. This is used for OStatus
951 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
952 $conversation_uri = $conversation_href;
954 if (isset($parent_item)) {
955 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $item['parent-uri']]);
956 if (DBM::is_result($conversation)) {
957 if ($conversation['conversation-uri'] != '') {
958 $conversation_uri = $conversation['conversation-uri'];
960 if ($conversation['conversation-href'] != '') {
961 $conversation_href = $conversation['conversation-href'];
967 "href" => $conversation_href,
968 "ref" => $conversation_uri];
970 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
972 XML::addElement($doc, $entry, "id", $item["uri"]);
973 XML::addElement($doc, $entry, "title", $item["title"]);
975 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"] . "+00:00", DateTimeFormat::ATOM));
976 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"] . "+00:00", DateTimeFormat::ATOM));
978 // "dfrn:env" is used to read the content
979 XML::addElement($doc, $entry, "dfrn:env", base64url_encode($body, true));
981 // The "content" field is not read by the receiver. We could remove it when the type is "text"
982 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
983 XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
985 // We save this value in "plink". Maybe we should read it from there as well?
991 ["rel" => "alternate", "type" => "text/html",
992 "href" => System::baseUrl() . "/display/" . $item["guid"]]
995 // "comment-allow" is some old fashioned stuff for old Friendica versions.
996 // It is included in the rewritten code for completeness
998 XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
1001 if ($item['location']) {
1002 XML::addElement($doc, $entry, "dfrn:location", $item['location']);
1005 if ($item['coord']) {
1006 XML::addElement($doc, $entry, "georss:point", $item['coord']);
1009 if (($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])) {
1010 XML::addElement($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
1013 if ($item['extid']) {
1014 XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
1017 if ($item['post-type'] == Item::PT_PAGE) {
1018 XML::addElement($doc, $entry, "dfrn:bookmark", "true");
1022 XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
1025 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
1027 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
1028 // It is needed for relayed comments to Diaspora.
1029 if ($item['signed_text']) {
1030 $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer']]));
1031 XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
1034 XML::addElement($doc, $entry, "activity:verb", self::constructVerb($item));
1036 if ($item['object-type'] != "") {
1037 XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
1038 } elseif ($item['id'] == $item['parent']) {
1039 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1041 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
1044 $actobj = self::createActivity($doc, "activity:object", $item['object']);
1046 $entry->appendChild($actobj);
1049 $actarg = self::createActivity($doc, "activity:target", $item['target']);
1051 $entry->appendChild($actarg);
1054 $tags = Item::getFeedTags($item);
1056 /// @TODO Combine this with similar below if() block?
1058 foreach ($tags as $t) {
1059 if (($type != 'html') || ($t[0] != "@")) {
1060 XML::addElement($doc, $entry, "category", "", ["scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]]);
1066 foreach ($tags as $t) {
1068 $mentioned[$t[1]] = $t[1];
1073 foreach ($mentioned as $mention) {
1075 "SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1076 intval($owner["uid"]),
1077 dbesc(normalise_link($mention))
1080 if (DBM::is_result($r) && ($r[0]["forum"] || $r[0]["prv"])) {
1086 ["rel" => "mentioned",
1087 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1096 ["rel" => "mentioned",
1097 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1103 self::getAttachment($doc, $entry, $item);
1109 * @brief encrypts data via AES
1111 * @param string $data The data that is to be encrypted
1112 * @param string $key The AES key
1114 * @return string encrypted data
1116 private static function aesEncrypt($data, $key)
1118 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1122 * @brief decrypts data via AES
1124 * @param string $encrypted The encrypted data
1125 * @param string $key The AES key
1127 * @return string decrypted data
1129 public static function aesDecrypt($encrypted, $key)
1131 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1135 * @brief Delivers the atom content to the contacts
1137 * @param array $owner Owner record
1138 * @param array $contact Contact record of the receiver
1139 * @param string $atom Content that will be transmitted
1140 * @param bool $dissolve (to be documented)
1142 * @return int Deliver status. Negative values mean an error.
1143 * @todo Add array type-hint for $owner, $contact
1145 public static function deliver($owner, $contact, $atom, $dissolve = false)
1149 // At first try the Diaspora transport layer
1150 $ret = self::transmit($owner, $contact, $atom);
1152 logger('Delivery via Diaspora transport layer was successful with status ' . $ret);
1156 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1158 if ($contact['duplex'] && $contact['dfrn-id']) {
1159 $idtosend = '0:' . $orig_id;
1161 if ($contact['duplex'] && $contact['issued-id']) {
1162 $idtosend = '1:' . $orig_id;
1165 $rino = Config::get('system', 'rino_encrypt');
1166 $rino = intval($rino);
1168 logger("Local rino version: ". $rino, LOGGER_DEBUG);
1170 $ssl_val = intval(Config::get('system', 'ssl_policy'));
1174 case SSL_POLICY_FULL:
1175 $ssl_policy = 'full';
1177 case SSL_POLICY_SELFSIGN:
1178 $ssl_policy = 'self';
1180 case SSL_POLICY_NONE:
1182 $ssl_policy = 'none';
1186 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1188 logger('dfrn_deliver: ' . $url);
1190 $ret = Network::curl($url);
1192 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1193 Contact::markForArchival($contact);
1194 return -2; // timed out
1197 $xml = $ret['body'];
1199 $curl_stat = $a->get_curl_code();
1200 if (empty($curl_stat)) {
1201 Contact::markForArchival($contact);
1202 return -3; // timed out
1205 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1208 Contact::markForArchival($contact);
1212 if (strpos($xml, '<?xml') === false) {
1213 logger('dfrn_deliver: no valid XML returned');
1214 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1215 Contact::markForArchival($contact);
1219 $res = XML::parseString($xml);
1221 if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
1222 Contact::markForArchival($contact);
1223 return ($res->status ? $res->status : 3);
1227 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1228 $challenge = hex2bin((string) $res->challenge);
1229 $perm = (($res->perm) ? $res->perm : null);
1230 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1231 $rino_remote_version = intval($res->rino);
1232 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1234 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
1236 if ($owner['page-flags'] == PAGE_PRVGROUP) {
1240 $final_dfrn_id = '';
1243 if ((($perm == 'rw') && (! intval($contact['writable'])))
1244 || (($perm == 'r') && (intval($contact['writable'])))
1247 "update contact set writable = %d where id = %d",
1248 intval(($perm == 'rw') ? 1 : 0),
1249 intval($contact['id'])
1251 $contact['writable'] = (string) 1 - intval($contact['writable']);
1255 if (($contact['duplex'] && strlen($contact['pubkey']))
1256 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1257 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
1259 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
1260 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
1262 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
1263 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
1266 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1268 if (strpos($final_dfrn_id, ':') == 1) {
1269 $final_dfrn_id = substr($final_dfrn_id, 2);
1272 if ($final_dfrn_id != $orig_id) {
1273 logger('dfrn_deliver: wrong dfrn_id.');
1274 // did not decode properly - cannot trust this site
1275 Contact::markForArchival($contact);
1279 $postvars['dfrn_id'] = $idtosend;
1280 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1282 $postvars['dissolve'] = '1';
1285 if ((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1286 $postvars['data'] = $atom;
1287 $postvars['perm'] = 'rw';
1289 $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
1290 $postvars['perm'] = 'r';
1293 $postvars['ssl_policy'] = $ssl_policy;
1296 $postvars['page'] = $page;
1300 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1301 logger('rino version: '. $rino_remote_version);
1303 switch ($rino_remote_version) {
1305 $key = openssl_random_pseudo_bytes(16);
1306 $data = self::aesEncrypt($postvars['data'], $key);
1309 logger("rino: invalid requested version '$rino_remote_version'");
1310 Contact::markForArchival($contact);
1314 $postvars['rino'] = $rino_remote_version;
1315 $postvars['data'] = bin2hex($data);
1317 if ($dfrn_version >= 2.1) {
1318 if (($contact['duplex'] && strlen($contact['pubkey']))
1319 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1320 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
1322 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1324 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1327 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1328 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1330 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1334 logger('md5 rawkey ' . md5($postvars['key']));
1336 $postvars['key'] = bin2hex($postvars['key']);
1340 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), LOGGER_DATA);
1342 $xml = Network::post($contact['notify'], $postvars);
1344 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1346 $curl_stat = $a->get_curl_code();
1347 if (empty($curl_stat) || empty($xml)) {
1348 Contact::markForArchival($contact);
1349 return -9; // timed out
1352 if (($curl_stat == 503) && stristr($a->get_curl_headers(), 'retry-after')) {
1353 Contact::markForArchival($contact);
1357 if (strpos($xml, '<?xml') === false) {
1358 logger('dfrn_deliver: phase 2: no valid XML returned');
1359 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1360 Contact::markForArchival($contact);
1364 $res = XML::parseString($xml);
1366 if (!isset($res->status)) {
1367 Contact::markForArchival($contact);
1371 // Possibly old servers had returned an empty value when everything was okay
1372 if (empty($res->status)) {
1376 if (!empty($res->message)) {
1377 logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1380 if (($res->status >= 200) && ($res->status <= 299)) {
1381 Contact::unmarkForArchival($contact);
1384 return intval($res->status);
1388 * @brief Transmits atom content to the contacts via the Diaspora transport layer
1390 * @param array $owner Owner record
1391 * @param array $contact Contact record of the receiver
1392 * @param string $atom Content that will be transmitted
1394 * @return int Deliver status. Negative values mean an error.
1396 public static function transmit($owner, $contact, $atom, $public_batch = false)
1400 if (!$public_batch) {
1401 if (empty($contact['addr'])) {
1402 logger('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.');
1403 if (Contact::updateFromProbe($contact['id'])) {
1404 $new_contact = DBA::selectFirst('contact', ['addr'], ['id' => $contact['id']]);
1405 $contact['addr'] = $new_contact['addr'];
1408 if (empty($contact['addr'])) {
1409 logger('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
1410 Contact::markForArchival($contact);
1415 $fcontact = Diaspora::personByHandle($contact['addr']);
1416 if (empty($fcontact)) {
1417 logger('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
1418 Contact::markForArchival($contact);
1421 $pubkey = $fcontact['pubkey'];
1426 $envelope = Diaspora::buildMessage($atom, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
1428 // Create the endpoint for public posts. This is some WIP and should later be added to the probing
1429 if ($public_batch && empty($contact["batch"])) {
1430 $parts = parse_url($contact["notify"]);
1431 $path_parts = explode('/', $parts['path']);
1432 array_pop($path_parts);
1433 $parts['path'] = implode('/', $path_parts);
1434 $contact["batch"] = Network::unparseURL($parts);
1437 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
1439 $content_type = ($public_batch ? "application/magic-envelope+xml" : "application/json");
1441 $xml = Network::post($dest_url, $envelope, ["Content-Type: ".$content_type]);
1443 $curl_stat = $a->get_curl_code();
1444 if (empty($curl_stat) || empty($xml)) {
1445 logger('Empty answer from ' . $contact['id'] . ' - ' . $dest_url);
1446 Contact::markForArchival($contact);
1447 return -9; // timed out
1450 if (($curl_stat == 503) && (stristr($a->get_curl_headers(), 'retry-after'))) {
1451 Contact::markForArchival($contact);
1455 if (strpos($xml, '<?xml') === false) {
1456 logger('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url);
1457 logger('Returned XML: ' . $xml, LOGGER_DATA);
1458 Contact::markForArchival($contact);
1462 $res = XML::parseString($xml);
1464 if (empty($res->status)) {
1465 Contact::markForArchival($contact);
1469 if (!empty($res->message)) {
1470 logger('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1473 if (($res->status >= 200) && ($res->status <= 299)) {
1474 Contact::unmarkForArchival($contact);
1477 return intval($res->status);
1481 * @brief Add new birthday event for this person
1483 * @param array $contact Contact record
1484 * @param string $birthday Birthday of the contact
1486 * @todo Add array type-hint for $contact
1488 private static function birthdayEvent($contact, $birthday)
1490 // Check for duplicates
1492 "SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1493 intval($contact['uid']),
1494 intval($contact['id']),
1495 dbesc(DateTimeFormat::utc($birthday)),
1499 if (DBM::is_result($r)) {
1503 logger('updating birthday: ' . $birthday . ' for contact ' . $contact['id']);
1505 $bdtext = L10n::t('%s\'s birthday', $contact['name']);
1506 $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]');
1509 "INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1510 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1511 intval($contact['uid']),
1512 intval($contact['id']),
1513 dbesc(DateTimeFormat::utcNow()),
1514 dbesc(DateTimeFormat::utcNow()),
1515 dbesc(DateTimeFormat::utc($birthday)),
1516 dbesc(DateTimeFormat::utc($birthday . ' + 1 day ')),
1524 * @brief Fetch the author data from head or entry items
1526 * @param object $xpath XPath object
1527 * @param object $context In which context should the data be searched
1528 * @param array $importer Record of the importer user mixed with contact of the content
1529 * @param string $element Element name from which the data is fetched
1530 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1531 * @param string $xml optional, default empty
1533 * @return array Relevant data of the author
1534 * @todo Find good type-hints for all parameter
1536 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
1539 $author["name"] = XML::getFirstNodeValue($xpath, $element."/atom:name/text()", $context);
1540 $author["link"] = XML::getFirstNodeValue($xpath, $element."/atom:uri/text()", $context);
1542 $fields = ['id', 'uid', 'url', 'network', 'avatar-date', 'avatar', 'name-date', 'uri-date', 'addr',
1543 'name', 'nick', 'about', 'location', 'keywords', 'xmpp', 'bdyear', 'bd', 'hidden', 'contact-type'];
1544 $condition = ["`uid` = ? AND `nurl` = ? AND `network` != ?",
1545 $importer["importer_uid"], normalise_link($author["link"]), NETWORK_STATUSNET];
1546 $contact_old = DBA::selectFirst('contact', $fields, $condition);
1548 if (DBM::is_result($contact_old)) {
1549 $author["contact-id"] = $contact_old["id"];
1550 $author["network"] = $contact_old["network"];
1553 logger("Contact ".$author["link"]." wasn't found for user ".$importer["importer_uid"]." XML: ".$xml, LOGGER_DEBUG);
1556 $author["contact-unknown"] = true;
1557 $author["contact-id"] = $importer["id"];
1558 $author["network"] = $importer["network"];
1562 // Until now we aren't serving different sizes - but maybe later
1564 /// @todo check if "avatar" or "photo" would be the best field in the specification
1565 $avatars = $xpath->query($element . "/atom:link[@rel='avatar']", $context);
1566 foreach ($avatars as $avatar) {
1569 foreach ($avatar->attributes as $attributes) {
1570 /// @TODO Rewrite these similar if() to one switch
1571 if ($attributes->name == "href") {
1572 $href = $attributes->textContent;
1574 if ($attributes->name == "width") {
1575 $width = $attributes->textContent;
1577 if ($attributes->name == "updated") {
1578 $author["avatar-date"] = $attributes->textContent;
1581 if (($width > 0) && ($href != "")) {
1582 $avatarlist[$width] = $href;
1586 if (count($avatarlist) > 0) {
1587 krsort($avatarlist);
1588 $author["avatar"] = current($avatarlist);
1591 if (DBM::is_result($contact_old) && !$onlyfetch) {
1592 logger("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", LOGGER_DEBUG);
1594 $poco = ["url" => $contact_old["url"]];
1596 // When was the last change to name or uri?
1597 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1598 foreach ($name_element->attributes as $attributes) {
1599 if ($attributes->name == "updated") {
1600 $poco["name-date"] = $attributes->textContent;
1604 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1605 foreach ($link_element->attributes as $attributes) {
1606 if ($attributes->name == "updated") {
1607 $poco["uri-date"] = $attributes->textContent;
1611 // Update contact data
1612 $value = XML::getFirstNodeValue($xpath, $element . "/dfrn:handle/text()", $context);
1614 $poco["addr"] = $value;
1617 $value = XML::getFirstNodeValue($xpath, $element . "/poco:displayName/text()", $context);
1619 $poco["name"] = $value;
1622 $value = XML::getFirstNodeValue($xpath, $element . "/poco:preferredUsername/text()", $context);
1624 $poco["nick"] = $value;
1627 $value = XML::getFirstNodeValue($xpath, $element . "/poco:note/text()", $context);
1629 $poco["about"] = $value;
1632 $value = XML::getFirstNodeValue($xpath, $element . "/poco:address/poco:formatted/text()", $context);
1634 $poco["location"] = $value;
1637 /// @todo Only search for elements with "poco:type" = "xmpp"
1638 $value = XML::getFirstNodeValue($xpath, $element . "/poco:ims/poco:value/text()", $context);
1640 $poco["xmpp"] = $value;
1643 /// @todo Add support for the following fields that we don't support by now in the contact table:
1644 /// - poco:utcOffset
1650 // If the "hide" element is present then the profile isn't searchable.
1651 $hide = intval(XML::getFirstNodeValue($xpath, $element . "/dfrn:hide/text()", $context) == "true");
1653 logger("Hidden status for contact " . $contact_old["url"] . ": " . $hide, LOGGER_DEBUG);
1655 // If the contact isn't searchable then set the contact to "hidden".
1656 // Problem: This can be manually overridden by the user.
1658 $contact_old["hidden"] = true;
1661 // Save the keywords into the contact table
1663 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1664 foreach ($tagelements as $tag) {
1665 $tags[$tag->nodeValue] = $tag->nodeValue;
1669 $poco["keywords"] = implode(", ", $tags);
1672 // "dfrn:birthday" contains the birthday converted to UTC
1673 $birthday = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1675 if (strtotime($birthday) > time()) {
1676 $bd_timestamp = strtotime($birthday);
1678 $poco["bdyear"] = date("Y", $bd_timestamp);
1681 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1682 $value = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1684 if (!in_array($value, ["", "0000-00-00", "0001-01-01"])) {
1685 $bdyear = date("Y");
1686 $value = str_replace("0000", $bdyear, $value);
1688 if (strtotime($value) < time()) {
1689 $value = str_replace($bdyear, $bdyear + 1, $value);
1690 $bdyear = $bdyear + 1;
1693 $poco["bd"] = $value;
1696 $contact = array_merge($contact_old, $poco);
1698 if ($contact_old["bdyear"] != $contact["bdyear"]) {
1699 self::birthdayEvent($contact, $birthday);
1702 // Get all field names
1704 foreach ($contact_old as $field => $data) {
1705 $fields[$field] = $data;
1708 unset($fields["id"]);
1709 unset($fields["uid"]);
1710 unset($fields["url"]);
1711 unset($fields["avatar-date"]);
1712 unset($fields["avatar"]);
1713 unset($fields["name-date"]);
1714 unset($fields["uri-date"]);
1717 // Update check for this field has to be done differently
1718 $datefields = ["name-date", "uri-date"];
1719 foreach ($datefields as $field) {
1720 if (strtotime($contact[$field]) > strtotime($contact_old[$field])) {
1721 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1726 foreach ($fields as $field => $data) {
1727 if ($contact[$field] != $contact_old[$field]) {
1728 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1734 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1737 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1738 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1739 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1740 WHERE `id` = %d AND `network` = '%s'",
1741 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
1742 dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1743 dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
1744 dbesc(DBM::date($contact["name-date"])), dbesc(DBM::date($contact["uri-date"])),
1745 intval($contact["id"]), dbesc($contact["network"])
1749 Contact::updateAvatar(
1751 $importer['importer_uid'],
1753 (strtotime($contact['avatar-date']) > strtotime($contact_old['avatar-date']) || ($author['avatar'] != $contact_old['avatar']))
1757 * The generation is a sign for the reliability of the provided data.
1758 * It is used in the socgraph.php to prevent that old contact data
1759 * that was relayed over several servers can overwrite contact
1760 * data that we received directly.
1763 $poco["generation"] = 2;
1764 $poco["photo"] = $author["avatar"];
1765 $poco["hide"] = $hide;
1766 $poco["contact-type"] = $contact["contact-type"];
1767 $gcid = GContact::update($poco);
1769 GContact::link($gcid, $importer["importer_uid"], $contact["id"]);
1776 * @brief Transforms activity objects into an XML string
1778 * @param object $xpath XPath object
1779 * @param object $activity Activity object
1780 * @param string $element element name
1782 * @return string XML string
1783 * @todo Find good type-hints for all parameter
1785 private static function transformActivity($xpath, $activity, $element)
1787 if (!is_object($activity)) {
1791 $obj_doc = new DOMDocument("1.0", "utf-8");
1792 $obj_doc->formatOutput = true;
1794 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1796 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1797 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1799 $id = $xpath->query("atom:id", $activity)->item(0);
1800 if (is_object($id)) {
1801 $obj_element->appendChild($obj_doc->importNode($id, true));
1804 $title = $xpath->query("atom:title", $activity)->item(0);
1805 if (is_object($title)) {
1806 $obj_element->appendChild($obj_doc->importNode($title, true));
1809 $links = $xpath->query("atom:link", $activity);
1810 if (is_object($links)) {
1811 foreach ($links as $link) {
1812 $obj_element->appendChild($obj_doc->importNode($link, true));
1816 $content = $xpath->query("atom:content", $activity)->item(0);
1817 if (is_object($content)) {
1818 $obj_element->appendChild($obj_doc->importNode($content, true));
1821 $obj_doc->appendChild($obj_element);
1823 $objxml = $obj_doc->saveXML($obj_element);
1825 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1826 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1831 * @brief Processes the mail elements
1833 * @param object $xpath XPath object
1834 * @param object $mail mail elements
1835 * @param array $importer Record of the importer user mixed with contact of the content
1837 * @todo Find good type-hints for all parameter
1839 private static function processMail($xpath, $mail, $importer)
1841 logger("Processing mails");
1843 /// @TODO Rewrite this to one statement
1845 $msg["uid"] = $importer["importer_uid"];
1846 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1847 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1848 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1849 $msg["contact-id"] = $importer["id"];
1850 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1851 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1852 $msg["created"] = DateTimeFormat::utc($xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue);
1853 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1854 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1856 $msg["replied"] = 0;
1858 DBA::insert('mail', $msg);
1860 // send notifications.
1861 /// @TODO Arange this mess
1863 "type" => NOTIFY_MAIL,
1864 "notify_flags" => $importer["notify-flags"],
1865 "language" => $importer["language"],
1866 "to_name" => $importer["username"],
1867 "to_email" => $importer["email"],
1868 "uid" => $importer["importer_uid"],
1870 "source_name" => $msg["from-name"],
1871 "source_link" => $importer["url"],
1872 "source_photo" => $importer["thumb"],
1873 "verb" => ACTIVITY_POST,
1877 notification($notif_params);
1879 logger("Mail is processed, notification was sent.");
1883 * @brief Processes the suggestion elements
1885 * @param object $xpath XPath object
1886 * @param object $suggestion suggestion elements
1887 * @param array $importer Record of the importer user mixed with contact of the content
1889 * @todo Find good type-hints for all parameter
1891 private static function processSuggestion($xpath, $suggestion, $importer)
1895 logger("Processing suggestions");
1897 /// @TODO Rewrite this to one statement
1899 $suggest["uid"] = $importer["importer_uid"];
1900 $suggest["cid"] = $importer["id"];
1901 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1902 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1903 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1904 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1905 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1907 // Does our member already have a friend matching this description?
1910 "SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1911 dbesc($suggest["name"]),
1912 dbesc(normalise_link($suggest["url"])),
1913 intval($suggest["uid"])
1917 * The valid result means the friend we're about to send a friend
1918 * suggestion already has them in their contact, which means no further
1919 * action is required.
1921 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1923 if (DBM::is_result($r)) {
1927 // Do we already have an fcontact record for this person?
1931 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1932 dbesc($suggest["url"]),
1933 dbesc($suggest["name"]),
1934 dbesc($suggest["request"])
1936 if (DBM::is_result($r)) {
1939 // OK, we do. Do we already have an introduction for this person ?
1941 "SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1942 intval($suggest["uid"]),
1947 * The valid result means the friend we're about to send a friend
1948 * suggestion already has them in their contact, which means no further
1949 * action is required.
1951 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1953 if (DBM::is_result($r)) {
1959 "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1960 dbesc($suggest["name"]),
1961 dbesc($suggest["url"]),
1962 dbesc($suggest["photo"]),
1963 dbesc($suggest["request"])
1967 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1968 dbesc($suggest["url"]),
1969 dbesc($suggest["name"]),
1970 dbesc($suggest["request"])
1974 * If no record in fcontact is found, below INSERT statement will not
1975 * link an introduction to it.
1977 if (!DBM::is_result($r)) {
1978 // Database record did not get created. Quietly give up.
1984 $hash = random_string();
1987 "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1988 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1989 intval($suggest["uid"]),
1991 intval($suggest["cid"]),
1992 dbesc($suggest["body"]),
1994 dbesc(DateTimeFormat::utcNow()),
2000 "type" => NOTIFY_SUGGEST,
2001 "notify_flags" => $importer["notify-flags"],
2002 "language" => $importer["language"],
2003 "to_name" => $importer["username"],
2004 "to_email" => $importer["email"],
2005 "uid" => $importer["importer_uid"],
2007 "link" => System::baseUrl()."/notifications/intros",
2008 "source_name" => $importer["name"],
2009 "source_link" => $importer["url"],
2010 "source_photo" => $importer["photo"],
2011 "verb" => ACTIVITY_REQ_FRIEND,
2019 * @brief Processes the relocation elements
2021 * @param object $xpath XPath object
2022 * @param object $relocation relocation elements
2023 * @param array $importer Record of the importer user mixed with contact of the content
2025 * @todo Find good type-hints for all parameter
2027 private static function processRelocation($xpath, $relocation, $importer)
2029 logger("Processing relocations");
2031 /// @TODO Rewrite this to one statement
2033 $relocate["uid"] = $importer["importer_uid"];
2034 $relocate["cid"] = $importer["id"];
2035 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
2036 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
2037 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
2038 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
2039 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
2040 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
2041 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
2042 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
2043 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
2044 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
2045 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
2046 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
2048 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
2049 $relocate["avatar"] = $relocate["photo"];
2052 if ($relocate["addr"] == "") {
2053 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
2058 "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d",
2059 intval($importer["id"]),
2060 intval($importer["importer_uid"])
2063 if (!DBM::is_result($r)) {
2064 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2070 // Update the gcontact entry
2071 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
2073 $fields = ['name' => $relocate["name"], 'photo' => $relocate["avatar"],
2074 'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2075 'addr' => $relocate["addr"], 'connect' => $relocate["addr"],
2076 'notify' => $relocate["notify"], 'server_url' => $relocate["server_url"]];
2077 DBA::update('gcontact', $fields, ['nurl' => normalise_link($old["url"])]);
2079 // Update the contact table. We try to find every entry.
2080 $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
2081 'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2082 'addr' => $relocate["addr"], 'request' => $relocate["request"],
2083 'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
2084 'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
2085 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], normalise_link($old["url"])];
2087 DBA::update('contact', $fields, $condition);
2089 Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
2091 logger('Contacts are updated.');
2094 /// merge with current record, current contents have priority
2095 /// update record, set url-updated
2096 /// update profile photos
2097 /// schedule a scan?
2102 * @brief Updates an item
2104 * @param array $current the current item record
2105 * @param array $item the new item record
2106 * @param array $importer Record of the importer user mixed with contact of the content
2107 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2109 * @todo set proper type-hints (array?)
2111 private static function updateContent($current, $item, $importer, $entrytype)
2115 if (self::isEditedTimestampNewer($current, $item)) {
2116 // do not accept (ignore) an earlier edit than one we currently have.
2117 if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
2121 $fields = ['title' => defaults($item, 'title', ''), 'body' => defaults($item, 'body', ''),
2122 'tag' => defaults($item, 'tag', ''), 'changed' => DateTimeFormat::utcNow(),
2123 'edited' => DateTimeFormat::utc($item["edited"])];
2125 $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
2126 Item::update($fields, $condition);
2134 * @brief Detects the entry type of the item
2136 * @param array $importer Record of the importer user mixed with contact of the content
2137 * @param array $item the new item record
2139 * @return int Is it a toplevel entry, a comment or a relayed comment?
2140 * @todo set proper type-hints (array?)
2142 private static function getEntryType($importer, $item)
2144 if ($item["parent-uri"] != $item["uri"]) {
2147 if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
2150 logger("possible community action");
2152 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2155 // was the top-level post for this action written by somebody on this site?
2156 // Specifically, the recipient?
2158 $is_a_remote_action = false;
2160 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item["parent-uri"]]);
2161 if (DBM::is_result($parent)) {
2163 "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2164 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2165 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2166 AND `item`.`uid` = %d
2169 dbesc($parent["parent-uri"]),
2170 dbesc($parent["parent-uri"]),
2171 dbesc($parent["parent-uri"]),
2172 intval($importer["importer_uid"])
2174 if (DBM::is_result($r)) {
2175 $is_a_remote_action = true;
2180 * Does this have the characteristics of a community or private group action?
2181 * If it's an action to a wall post on a community/prvgroup page it's a
2182 * valid community action. Also forum_mode makes it valid for sure.
2183 * If neither, it's not.
2185 if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2186 $is_a_remote_action = false;
2187 logger("not a community action");
2190 if ($is_a_remote_action) {
2191 return DFRN::REPLY_RC;
2196 return DFRN::TOP_LEVEL;
2201 * @brief Send a "poke"
2203 * @param array $item the new item record
2204 * @param array $importer Record of the importer user mixed with contact of the content
2205 * @param int $posted_id The record number of item record that was just posted
2207 * @todo set proper type-hints (array?)
2209 private static function doPoke($item, $importer, $posted_id)
2211 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2215 $xo = XML::parseString($item["object"], false);
2217 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2218 // somebody was poked/prodded. Was it me?
2219 foreach ($xo->link as $l) {
2220 $atts = $l->attributes();
2221 switch ($atts["rel"]) {
2223 $Blink = $atts["href"];
2230 if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2231 $author = DBA::selectFirst('contact', ['name', 'thumb', 'url'], ['id' => $item['author-id']]);
2233 // send a notification
2236 "type" => NOTIFY_POKE,
2237 "notify_flags" => $importer["notify-flags"],
2238 "language" => $importer["language"],
2239 "to_name" => $importer["username"],
2240 "to_email" => $importer["email"],
2241 "uid" => $importer["importer_uid"],
2243 "link" => System::baseUrl()."/display/".urlencode(Item::getGuidById($posted_id)),
2244 "source_name" => $author["name"],
2245 "source_link" => $author["url"],
2246 "source_photo" => $author["thumb"],
2247 "verb" => $item["verb"],
2248 "otype" => "person",
2249 "activity" => $verb,
2250 "parent" => $item["parent"]]
2257 * @brief Processes several actions, depending on the verb
2259 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2260 * @param array $importer Record of the importer user mixed with contact of the content
2261 * @param array $item the new item record
2262 * @param bool $is_like Is the verb a "like"?
2264 * @return bool Should the processing of the entries be continued?
2265 * @todo set proper type-hints (array?)
2267 private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2269 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2271 if (($entrytype == DFRN::TOP_LEVEL)) {
2272 // The filling of the the "contact" variable is done for legcy reasons
2273 // The functions below are partly used by ostatus.php as well - where we have this variable
2274 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2276 $nickname = $contact["nick"];
2278 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2279 // This function once was responsible for DFRN and OStatus.
2280 if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2281 logger("New follower");
2282 Contact::addRelationship($importer, $contact, $item, $nickname);
2285 if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2286 logger("Lost follower");
2287 Contact::removeFollower($importer, $contact, $item);
2290 if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2291 logger("New friend request");
2292 Contact::addRelationship($importer, $contact, $item, $nickname, true);
2295 if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2296 logger("Lost sharer");
2297 Contact::removeSharer($importer, $contact, $item);
2301 if (($item["verb"] == ACTIVITY_LIKE)
2302 || ($item["verb"] == ACTIVITY_DISLIKE)
2303 || ($item["verb"] == ACTIVITY_ATTEND)
2304 || ($item["verb"] == ACTIVITY_ATTENDNO)
2305 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
2308 $item["gravity"] = GRAVITY_ACTIVITY;
2309 // only one like or dislike per person
2310 // splitted into two queries for performance issues
2311 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2312 'verb' => $item["verb"], 'parent-uri' => $item["parent-uri"]];
2313 if (Item::exists($condition)) {
2317 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2318 'verb' => $item["verb"], 'thr-parent' => $item["parent-uri"]];
2319 if (Item::exists($condition)) {
2326 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2327 $xo = XML::parseString($item["object"], false);
2328 $xt = XML::parseString($item["target"], false);
2330 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2331 $item_tag = Item::selectFirst(['id', 'tag'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]);
2333 if (!DBM::is_result($item_tag)) {
2334 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2338 // extract tag, if not duplicate, add to parent item
2340 if (!stristr($item_tag["tag"], trim($xo->content))) {
2341 $tag = $item_tag["tag"] . (strlen($item_tag["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2342 Item::update(['tag' => $tag], ['id' => $item_tag["id"]]);
2352 * @brief Processes the link elements
2354 * @param object $links link elements
2355 * @param array $item the item record
2357 * @todo set proper type-hints
2359 private static function parseLinks($links, &$item)
2366 foreach ($links as $link) {
2367 foreach ($link->attributes as $attributes) {
2368 switch ($attributes->name) {
2369 case "href" : $href = $attributes->textContent; break;
2370 case "rel" : $rel = $attributes->textContent; break;
2371 case "type" : $type = $attributes->textContent; break;
2372 case "length": $length = $attributes->textContent; break;
2373 case "title" : $title = $attributes->textContent; break;
2376 if (($rel != "") && ($href != "")) {
2379 $item["plink"] = $href;
2383 if (strlen($item["attach"])) {
2384 $item["attach"] .= ",";
2387 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2395 * @brief Processes the entry elements which contain the items and comments
2397 * @param array $header Array of the header elements that always stay the same
2398 * @param object $xpath XPath object
2399 * @param object $entry entry elements
2400 * @param array $importer Record of the importer user mixed with contact of the content
2401 * @param object $xml xml
2403 * @todo Add type-hints
2405 private static function processEntry($header, $xpath, $entry, $importer, $xml)
2407 logger("Processing entries");
2411 $item["protocol"] = PROTOCOL_DFRN;
2413 $item["source"] = $xml;
2416 $item["uri"] = XML::getFirstNodeValue($xpath, "atom:id/text()", $entry);
2418 $item["edited"] = XML::getFirstNodeValue($xpath, "atom:updated/text()", $entry);
2420 $current = Item::selectFirst(['id', 'uid', 'edited', 'body'],
2421 ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
2423 // Is there an existing item?
2424 if (DBM::is_result($current) && !self::isEditedTimestampNewer($current, $item)) {
2425 logger("Item ".$item["uri"]." (".$item['edited'].") already existed.", LOGGER_DEBUG);
2430 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2432 $owner_unknown = (isset($owner["contact-unknown"]) && $owner["contact-unknown"]);
2434 $item["owner-link"] = $owner["link"];
2435 $item["owner-id"] = Contact::getIdForURL($owner["link"], 0);
2438 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2440 $item["author-link"] = $author["link"];
2441 $item["author-id"] = Contact::getIdForURL($author["link"], 0);
2443 $item["title"] = XML::getFirstNodeValue($xpath, "atom:title/text()", $entry);
2445 $item["created"] = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2447 $item["body"] = XML::getFirstNodeValue($xpath, "dfrn:env/text()", $entry);
2448 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2449 // make sure nobody is trying to sneak some html tags by us
2450 $item["body"] = notags(base64url_decode($item["body"]));
2452 $item["body"] = BBCode::limitBodySize($item["body"]);
2454 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2455 if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
2456 $base_url = get_app()->get_baseurl();
2457 $item['body'] = reltoabs($item['body'], $base_url);
2459 $item['body'] = html2bb_video($item['body']);
2461 $item['body'] = OEmbed::HTML2BBCode($item['body']);
2463 $config = HTMLPurifier_Config::createDefault();
2464 $config->set('Cache.DefinitionImpl', null);
2466 // we shouldn't need a whitelist, because the bbcode converter
2467 // will strip out any unsupported tags.
2469 $purifier = new HTMLPurifier($config);
2470 $item['body'] = $purifier->purify($item['body']);
2472 $item['body'] = @HTML::toBBCode($item['body']);
2475 /// @todo We should check for a repeated post and if we know the repeated author.
2477 // We don't need the content element since "dfrn:env" is always present
2478 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2480 $item["location"] = XML::getFirstNodeValue($xpath, "dfrn:location/text()", $entry);
2482 $item["coord"] = XML::getFirstNodeValue($xpath, "georss:point", $entry);
2484 $item["private"] = XML::getFirstNodeValue($xpath, "dfrn:private/text()", $entry);
2486 $item["extid"] = XML::getFirstNodeValue($xpath, "dfrn:extid/text()", $entry);
2488 if (XML::getFirstNodeValue($xpath, "dfrn:bookmark/text()", $entry) == "true") {
2489 $item["post-type"] = Item::PT_PAGE;
2492 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2493 if ($notice_info && ($notice_info->length > 0)) {
2494 foreach ($notice_info->item(0)->attributes as $attributes) {
2495 if ($attributes->name == "source") {
2496 $item["app"] = strip_tags($attributes->textContent);
2501 $item["guid"] = XML::getFirstNodeValue($xpath, "dfrn:diaspora_guid/text()", $entry);
2503 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
2504 $dsprsig = unxmlify(XML::getFirstNodeValue($xpath, "dfrn:diaspora_signature/text()", $entry));
2505 if ($dsprsig != "") {
2506 $item["dsprsig"] = $dsprsig;
2509 $item["verb"] = XML::getFirstNodeValue($xpath, "activity:verb/text()", $entry);
2511 if (XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry) != "") {
2512 $item["object-type"] = XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry);
2515 $object = $xpath->query("activity:object", $entry)->item(0);
2516 $item["object"] = self::transformActivity($xpath, $object, "object");
2518 if (trim($item["object"]) != "") {
2519 $r = XML::parseString($item["object"], false);
2520 if (isset($r->type)) {
2521 $item["object-type"] = $r->type;
2525 $target = $xpath->query("activity:target", $entry)->item(0);
2526 $item["target"] = self::transformActivity($xpath, $target, "target");
2528 $categories = $xpath->query("atom:category", $entry);
2530 foreach ($categories as $category) {
2533 foreach ($category->attributes as $attributes) {
2534 if ($attributes->name == "term") {
2535 $term = $attributes->textContent;
2538 if ($attributes->name == "scheme") {
2539 $scheme = $attributes->textContent;
2543 if (($term != "") && ($scheme != "")) {
2544 $parts = explode(":", $scheme);
2545 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2546 $termhash = array_shift($parts);
2547 $termurl = implode(":", $parts);
2549 if (!empty($item["tag"])) {
2550 $item["tag"] .= ",";
2555 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2563 $links = $xpath->query("atom:link", $entry);
2565 self::parseLinks($links, $item);
2568 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
2570 $conv = $xpath->query('ostatus:conversation', $entry);
2571 if (is_object($conv->item(0))) {
2572 foreach ($conv->item(0)->attributes as $attributes) {
2573 if ($attributes->name == "ref") {
2574 $item['conversation-uri'] = $attributes->textContent;
2576 if ($attributes->name == "href") {
2577 $item['conversation-href'] = $attributes->textContent;
2582 // Is it a reply or a top level posting?
2583 $item["parent-uri"] = $item["uri"];
2585 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2586 if (is_object($inreplyto->item(0))) {
2587 foreach ($inreplyto->item(0)->attributes as $attributes) {
2588 if ($attributes->name == "ref") {
2589 $item["parent-uri"] = $attributes->textContent;
2594 // Get the type of the item (Top level post, reply or remote reply)
2595 $entrytype = self::getEntryType($importer, $item);
2597 // Now assign the rest of the values that depend on the type of the message
2598 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2599 if (!isset($item["object-type"])) {
2600 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2603 if ($item["contact-id"] != $owner["contact-id"]) {
2604 $item["contact-id"] = $owner["contact-id"];
2607 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2608 $item["network"] = $owner["network"];
2611 if ($item["contact-id"] != $author["contact-id"]) {
2612 $item["contact-id"] = $author["contact-id"];
2615 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2616 $item["network"] = $author["network"];
2620 if ($entrytype == DFRN::REPLY_RC) {
2622 } elseif ($entrytype == DFRN::TOP_LEVEL) {
2623 if (!isset($item["object-type"])) {
2624 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2628 if (($item["object-type"] == ACTIVITY_OBJ_EVENT) && !$owner_unknown) {
2629 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2630 $ev = Event::fromBBCode($item["body"]);
2631 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2632 logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2633 $ev["cid"] = $importer["id"];
2634 $ev["uid"] = $importer["importer_uid"];
2635 $ev["uri"] = $item["uri"];
2636 $ev["edited"] = $item["edited"];
2637 $ev["private"] = $item["private"];
2638 $ev["guid"] = $item["guid"];
2641 "SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2642 dbesc($item["uri"]),
2643 intval($importer["importer_uid"])
2645 if (DBM::is_result($r)) {
2646 $ev["id"] = $r[0]["id"];
2649 $event_id = Event::store($ev);
2650 logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2656 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2657 logger("Exiting because 'processVerbs' told us so", LOGGER_DEBUG);
2661 // This check is done here to be able to receive connection requests in "processVerbs"
2662 if (($entrytype == DFRN::TOP_LEVEL) && $owner_unknown) {
2663 logger("Item won't be stored because user " . $importer["importer_uid"] . " doesn't follow " . $item["owner-link"] . ".", LOGGER_DEBUG);
2668 // Update content if 'updated' changes
2669 if (DBM::is_result($current)) {
2670 if (self::updateContent($current, $item, $importer, $entrytype)) {
2671 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2673 logger("Item " . $item["uri"] . " already existed.", LOGGER_DEBUG);
2678 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2679 $posted_id = Item::insert($item);
2683 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2685 if ($item['uid'] == 0) {
2686 Item::distribute($posted_id);
2691 } else { // $entrytype == DFRN::TOP_LEVEL
2692 if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
2693 logger("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", LOGGER_DEBUG);
2696 if (!link_compare($item["owner-link"], $importer["url"])) {
2698 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2699 * but otherwise there's a possible data mixup on the sender's system.
2700 * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2701 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2703 logger('Correcting item owner.', LOGGER_DEBUG);
2704 $item["owner-link"] = $importer["url"];
2705 $item["owner-id"] = Contact::getIdForURL($importer["url"], 0);
2708 if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2709 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2713 // This is my contact on another system, but it's really me.
2714 // Turn this into a wall post.
2715 $notify = Item::isRemoteSelf($importer, $item);
2717 $posted_id = Item::insert($item, false, $notify);
2720 $posted_id = $notify;
2723 logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2725 if ($item['uid'] == 0) {
2726 Item::distribute($posted_id);
2729 if (stristr($item["verb"], ACTIVITY_POKE)) {
2730 self::doPoke($item, $importer, $posted_id);
2736 * @brief Deletes items
2738 * @param object $xpath XPath object
2739 * @param object $deletion deletion elements
2740 * @param array $importer Record of the importer user mixed with contact of the content
2742 * @todo set proper type-hints
2744 private static function processDeletion($xpath, $deletion, $importer)
2746 logger("Processing deletions");
2749 foreach ($deletion->attributes as $attributes) {
2750 if ($attributes->name == "ref") {
2751 $uri = $attributes->textContent;
2755 if (!$uri || !$importer["id"]) {
2759 $condition = ['uri' => $uri, 'uid' => $importer["importer_uid"]];
2760 $item = Item::selectFirst(['id', 'parent', 'contact-id', 'file', 'deleted'], $condition);
2761 if (!DBM::is_result($item)) {
2762 logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", LOGGER_DEBUG);
2766 if (strstr($item['file'], '[')) {
2767 logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " is filed. So it won't be deleted.", LOGGER_DEBUG);
2771 // When it is a starting post it has to belong to the person that wants to delete it
2772 if (($item['id'] == $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2773 logger("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2777 // Comments can be deleted by the thread owner or comment owner
2778 if (($item['id'] != $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2779 $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2780 if (!Item::exists($condition)) {
2781 logger("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2786 if ($item["deleted"]) {
2790 logger('deleting item '.$item['id'].' uri='.$uri, LOGGER_DEBUG);
2792 Item::delete(['id' => $item['id']]);
2796 * @brief Imports a DFRN message
2798 * @param string $xml The DFRN message
2799 * @param array $importer Record of the importer user mixed with contact of the content
2800 * @param bool $sort_by_date Is used when feeds are polled
2801 * @return integer Import status
2802 * @todo set proper type-hints
2804 public static function import($xml, $importer, $sort_by_date = false)
2810 $doc = new DOMDocument();
2811 @$doc->loadXML($xml);
2813 $xpath = new DOMXPath($doc);
2814 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2815 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2816 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2817 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2818 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2819 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2820 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2821 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2822 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2823 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2826 $header["uid"] = $importer["importer_uid"];
2827 $header["network"] = NETWORK_DFRN;
2828 $header["wall"] = 0;
2829 $header["origin"] = 0;
2830 $header["contact-id"] = $importer["id"];
2832 // Update the contact table if the data has changed
2834 // The "atom:author" is only present in feeds
2835 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2836 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2839 // Only the "dfrn:owner" in the head section contains all data
2840 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2841 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2844 logger("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2846 // is it a public forum? Private forums aren't exposed with this method
2847 $forum = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:community/text()"));
2849 // The account type is new since 3.5.1
2850 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2851 $accounttype = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:account_type/text()"));
2853 if ($accounttype != $importer["contact-type"]) {
2854 DBA::update('contact', ['contact-type' => $accounttype], ['id' => $importer["id"]]);
2856 // A forum contact can either have set "forum" or "prv" - but not both
2857 if (($accounttype == ACCOUNT_TYPE_COMMUNITY) && (($forum != $importer["forum"]) || ($forum == $importer["prv"]))) {
2858 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer["id"]];
2859 DBA::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2861 } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
2862 $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2863 DBA::update('contact', ['forum' => $forum], $condition);
2867 // We are processing relocations even if we are ignoring a contact
2868 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2869 foreach ($relocations as $relocation) {
2870 self::processRelocation($xpath, $relocation, $importer);
2873 if (($importer["uid"] != 0) && !$importer["readonly"]) {
2874 $mails = $xpath->query("/atom:feed/dfrn:mail");
2875 foreach ($mails as $mail) {
2876 self::processMail($xpath, $mail, $importer);
2879 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2880 foreach ($suggestions as $suggestion) {
2881 self::processSuggestion($xpath, $suggestion, $importer);
2885 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2886 foreach ($deletions as $deletion) {
2887 self::processDeletion($xpath, $deletion, $importer);
2890 if (!$sort_by_date) {
2891 $entries = $xpath->query("/atom:feed/atom:entry");
2892 foreach ($entries as $entry) {
2893 self::processEntry($header, $xpath, $entry, $importer, $xml);
2897 $entries = $xpath->query("/atom:feed/atom:entry");
2898 foreach ($entries as $entry) {
2899 $created = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2900 $newentries[strtotime($created)] = $entry;
2903 // Now sort after the publishing date
2906 foreach ($newentries as $entry) {
2907 self::processEntry($header, $xpath, $entry, $importer, $xml);
2910 logger("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2916 * @param string $contact_nick contact nickname
2918 public static function autoRedir(App $a, $contact_nick)
2921 if (x($_REQUEST, 'redir') && intval($_REQUEST['redir'])) {
2925 if ((! $contact_nick) || ($contact_nick === $a->user['nickname'])) {
2930 // We need to find out if $contact_nick is a user on this hub, and if so, if I
2931 // am a contact of that user. However, that user may have other contacts with the
2932 // same nickname as me on other hubs or other networks. Exclude these by requiring
2933 // that the contact have a local URL. I will be the only person with my nickname at
2934 // this URL, so if a result is found, then I am a contact of the $contact_nick user.
2936 // We also have to make sure that I'm a legitimate contact--I'm not blocked or pending.
2938 $baseurl = System::baseUrl();
2939 $domain_st = strpos($baseurl, "://");
2940 if ($domain_st === false) {
2943 $baseurl = substr($baseurl, $domain_st + 3);
2944 $nurl = normalise_link($baseurl);
2946 /// @todo Why is there a query for "url" *and* "nurl"? Especially this normalising is strange.
2947 $r = q("SELECT `id` FROM `contact` WHERE `uid` = (SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1)
2948 AND `nick` = '%s' AND NOT `self` AND (`url` LIKE '%%%s%%' OR `nurl` LIKE '%%%s%%') AND NOT `blocked` AND NOT `pending` LIMIT 1",
2949 dbesc($contact_nick),
2950 dbesc($a->user['nickname']),
2954 if ((! DBM::is_result($r)) || $r[0]['id'] == remote_user()) {
2958 $r = q("SELECT * FROM contact WHERE nick = '%s'
2959 AND network = '%s' AND uid = %d AND url LIKE '%%%s%%' LIMIT 1",
2960 dbesc($contact_nick),
2961 dbesc(NETWORK_DFRN),
2962 intval(local_user()),
2965 if (! DBM::is_result($r)) {
2971 $dfrn_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2973 if ($r[0]['duplex'] && $r[0]['issued-id']) {
2974 $orig_id = $r[0]['issued-id'];
2975 $dfrn_id = '1:' . $orig_id;
2977 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
2978 $orig_id = $r[0]['dfrn-id'];
2979 $dfrn_id = '0:' . $orig_id;
2982 // ensure that we've got a valid ID. There may be some edge cases with forums and non-duplex mode
2983 // that may have triggered some of the "went to {profile/intro} and got an RSS feed" issues
2985 if (strlen($dfrn_id) < 3) {
2989 $sec = random_string();
2991 DBA::insert('profile_check', ['uid' => local_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id, 'sec' => $sec, 'expire' => time() + 45]);
2993 $url = curPageURL();
2995 logger('auto_redir: ' . $r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
2996 $dest = (($url) ? '&destination_url=' . $url : '');
2997 goaway($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
2998 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest);
3005 * @brief Returns the activity verb
3007 * @param array $item Item array
3009 * @return string activity verb
3011 private static function constructVerb(array $item)
3013 if ($item['verb']) {
3014 return $item['verb'];
3016 return ACTIVITY_POST;
3019 private static function tgroupCheck($uid, $item)
3023 // check that the message originated elsewhere and is a top-level post
3025 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['parent-uri'])) {
3029 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
3032 if (!DBM::is_result($u)) {
3036 $community_page = ($u[0]['page-flags'] == PAGE_COMMUNITY);
3037 $prvgroup = ($u[0]['page-flags'] == PAGE_PRVGROUP);
3039 $link = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
3042 * Diaspora uses their own hardwired link URL in @-tags
3043 * instead of the one we supply with webfinger
3045 $dlink = normalise_link(System::baseUrl() . '/u/' . $u[0]['nickname']);
3047 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
3049 foreach ($matches as $mtch) {
3050 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
3052 logger('mention found: ' . $mtch[2]);
3061 return $community_page || $prvgroup;
3065 * This function returns true if $update has an edited timestamp newer
3066 * than $existing, i.e. $update contains new data which should override
3067 * what's already there. If there is no timestamp yet, the update is
3068 * assumed to be newer. If the update has no timestamp, the existing
3069 * item is assumed to be up-to-date. If the timestamps are equal it
3070 * assumes the update has been seen before and should be ignored.
3073 private static function isEditedTimestampNewer($existing, $update)
3075 if (!x($existing, 'edited') || !$existing['edited']) {
3078 if (!x($update, 'edited') || !$update['edited']) {
3082 $existing_edited = DateTimeFormat::utc($existing['edited']);
3083 $update_edited = DateTimeFormat::utc($update['edited']);
3085 return (strcmp($existing_edited, $update_edited) < 0);