3 * @file include/dfrn.php
4 * @brief The implementation of the dfrn protocol
6 * @see https://github.com/friendica/friendica/wiki/Protocol and
7 * https://github.com/friendica/friendica/blob/master/spec/dfrn2.pdf
9 namespace Friendica\Protocol;
12 use Friendica\Content\OEmbed;
13 use Friendica\Content\Text\BBCode;
14 use Friendica\Content\Text\HTML;
15 use Friendica\Core\Addon;
16 use Friendica\Core\Config;
17 use Friendica\Core\L10n;
18 use Friendica\Core\System;
19 use Friendica\Core\Worker;
20 use Friendica\Database\DBM;
21 use Friendica\Model\Contact;
22 use Friendica\Model\Event;
23 use Friendica\Model\GContact;
24 use Friendica\Model\Group;
25 use Friendica\Model\Item;
26 use Friendica\Model\Profile;
27 use Friendica\Model\User;
28 use Friendica\Object\Image;
29 use Friendica\Protocol\OStatus;
30 use Friendica\Util\Crypto;
31 use Friendica\Util\DateTimeFormat;
32 use Friendica\Util\Network;
33 use Friendica\Util\XML;
34 use Friendica\Protocol\Diaspora;
39 use HTMLPurifier_Config;
41 require_once 'boot.php';
42 require_once 'include/dba.php';
43 require_once "include/enotify.php";
44 require_once "include/items.php";
45 require_once "include/text.php";
48 * @brief This class contain functions to create and send DFRN XML files
53 const TOP_LEVEL = 0; // Top level posting
54 const REPLY = 1; // Regular reply that is stored locally
55 const REPLY_RC = 2; // Reply that will be relayed
58 * @brief Generates the atom entries for delivery.php
60 * This function is used whenever content is transmitted via DFRN.
62 * @param array $items Item elements
63 * @param array $owner Owner record
65 * @return string DFRN entries
66 * @todo Find proper type-hints
68 public static function entries($items, $owner)
70 $doc = new DOMDocument('1.0', 'utf-8');
71 $doc->formatOutput = true;
73 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
75 if (! count($items)) {
76 return trim($doc->saveXML());
79 foreach ($items as $item) {
80 // These values aren't sent when sending from the queue.
81 /// @todo Check if we can set these values from the queue or if they are needed at all.
82 $item["entry:comment-allow"] = defaults($item, "entry:comment-allow", true);
83 $item["entry:cid"] = defaults($item, "entry:cid", 0);
85 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
86 $root->appendChild($entry);
89 return trim($doc->saveXML());
93 * @brief Generate an atom feed for the given user
95 * This function is called when another server is pulling data from the user feed.
97 * @param string $dfrn_id DFRN ID from the requesting party
98 * @param string $owner_nick Owner nick name
99 * @param string $last_update Date of the last update
100 * @param int $direction Can be -1, 0 or 1.
101 * @param boolean $onlyheader Output only the header without content? (Default is "no")
103 * @return string DFRN feed entries
105 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false)
109 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
110 $public_feed = (($dfrn_id) ? false : true);
111 $starred = false; // not yet implemented, possible security issues
114 if ($public_feed && $a->argc > 2) {
115 for ($x = 2; $x < $a->argc; $x++) {
116 if ($a->argv[$x] == 'converse') {
119 if ($a->argv[$x] == 'starred') {
122 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
123 $category = $a->argv[$x+1];
128 // default permissions - anonymous user
130 $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = '' ";
133 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
134 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
135 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
139 if (! DBM::is_result($r)) {
140 logger(sprintf('No contact found for nickname=%d', $owner_nick), LOGGER_WARNING);
145 $owner_id = $owner['uid'];
146 $owner_nick = $owner['nickname'];
148 $sql_post_table = "";
150 if (! $public_feed) {
152 switch ($direction) {
154 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
158 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
159 $my_id = '1:' . $dfrn_id;
162 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
163 $my_id = '0:' . $dfrn_id;
171 "SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
175 if (! DBM::is_result($r)) {
176 logger(sprintf('No contact found for uid=%d', $owner_id), LOGGER_WARNING);
181 include_once 'include/security.php';
182 $groups = Group::getIdsByContactId($contact['id']);
184 if (count($groups)) {
185 for ($x = 0; $x < count($groups); $x ++) {
186 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
189 $gs = implode('|', $groups);
191 $gs = '<<>>' ; // Impossible to match
194 $sql_extra = sprintf(
196 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
197 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
198 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
199 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
201 intval($contact['id']),
202 intval($contact['id']),
214 if (! strlen($last_update)) {
215 $last_update = 'now -30 days';
218 if (isset($category)) {
219 $sql_post_table = sprintf(
220 "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` ",
221 dbesc(protect_sprintf($category)),
222 intval(TERM_OBJ_POST),
223 intval(TERM_CATEGORY),
226 //$sql_extra .= file_tag_file_query('item',$category,'category');
229 if ($public_feed && ! $converse) {
230 $sql_extra .= " AND `contact`.`self` = 1 ";
233 $check_date = DateTimeFormat::utc($last_update);
237 FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
238 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
239 WHERE `item`.`uid` = %d AND `item`.`wall` AND `item`.`changed` > '%s'
241 ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
248 foreach ($r as $item) {
249 $ids[] = $item['id'];
253 $ret = Item::select(Item::DELIVER_FIELDLIST, ['id' => $ids]);
254 $items = Item::inArray($ret);
260 * Will check further below if this actually returned results.
261 * We will provide an empty feed if that is the case.
264 $doc = new DOMDocument('1.0', 'utf-8');
265 $doc->formatOutput = true;
267 $alternatelink = $owner['url'];
269 if (isset($category)) {
270 $alternatelink .= "/category/".$category;
274 $author = "dfrn:owner";
279 $root = self::addHeader($doc, $owner, $author, $alternatelink, true);
281 /// @TODO This hook can't work anymore
282 // Addon::callHooks('atom_feed', $atom);
284 if (!DBM::is_result($items) || $onlyheader) {
285 $atom = trim($doc->saveXML());
287 Addon::callHooks('atom_feed_end', $atom);
292 foreach ($items as $item) {
293 // prevent private email from leaking.
294 if ($item['network'] == NETWORK_MAIL) {
298 // public feeds get html, our own nodes use bbcode
302 // catch any email that's in a public conversation and make sure it doesn't leak
303 if ($item['private']) {
310 $entry = self::entry($doc, $type, $item, $owner, true);
311 $root->appendChild($entry);
314 $atom = trim($doc->saveXML());
316 Addon::callHooks('atom_feed_end', $atom);
322 * @brief Generate an atom entry for a given item id
324 * @param int $item_id The item id
325 * @param boolean $conversation Show the conversation. If false show the single post.
327 * @return string DFRN feed entry
329 public static function itemFeed($item_id, $conversation = false)
332 $condition = ['parent' => $item_id];
334 $condition = ['id' => $item_id];
337 $ret = Item::select(Item::DELIVER_FIELDLIST, $condition);
338 $items = Item::inArray($ret);
339 if (!DBM::is_result($items)) {
345 if ($item['uid'] != 0) {
346 $owner = User::getOwnerDataById($item['uid']);
351 $owner = ['uid' => 0, 'nick' => 'feed-item'];
354 $doc = new DOMDocument('1.0', 'utf-8');
355 $doc->formatOutput = true;
359 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
360 $doc->appendChild($root);
362 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
363 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
364 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
365 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
366 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
367 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
368 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
369 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
370 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
372 //$root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
374 foreach ($items as $item) {
375 $entry = self::entry($doc, $type, $item, $owner, true, 0);
376 $root->appendChild($entry);
379 $root = self::entry($doc, $type, $item, $owner, true, 0, true);
382 $atom = trim($doc->saveXML());
387 * @brief Create XML text for DFRN mails
389 * @param array $item message elements
390 * @param array $owner Owner record
392 * @return string DFRN mail
393 * @todo Find proper type-hints
395 public static function mail($item, $owner)
397 $doc = new DOMDocument('1.0', 'utf-8');
398 $doc->formatOutput = true;
400 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
402 $mail = $doc->createElement("dfrn:mail");
403 $sender = $doc->createElement("dfrn:sender");
405 XML::addElement($doc, $sender, "dfrn:name", $owner['name']);
406 XML::addElement($doc, $sender, "dfrn:uri", $owner['url']);
407 XML::addElement($doc, $sender, "dfrn:avatar", $owner['thumb']);
409 $mail->appendChild($sender);
411 XML::addElement($doc, $mail, "dfrn:id", $item['uri']);
412 XML::addElement($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
413 XML::addElement($doc, $mail, "dfrn:sentdate", DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
414 XML::addElement($doc, $mail, "dfrn:subject", $item['title']);
415 XML::addElement($doc, $mail, "dfrn:content", $item['body']);
417 $root->appendChild($mail);
419 return trim($doc->saveXML());
423 * @brief Create XML text for DFRN friend suggestions
425 * @param array $item suggestion elements
426 * @param array $owner Owner record
428 * @return string DFRN suggestions
429 * @todo Find proper type-hints
431 public static function fsuggest($item, $owner)
433 $doc = new DOMDocument('1.0', 'utf-8');
434 $doc->formatOutput = true;
436 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
438 $suggest = $doc->createElement("dfrn:suggest");
440 XML::addElement($doc, $suggest, "dfrn:url", $item['url']);
441 XML::addElement($doc, $suggest, "dfrn:name", $item['name']);
442 XML::addElement($doc, $suggest, "dfrn:photo", $item['photo']);
443 XML::addElement($doc, $suggest, "dfrn:request", $item['request']);
444 XML::addElement($doc, $suggest, "dfrn:note", $item['note']);
446 $root->appendChild($suggest);
448 return trim($doc->saveXML());
452 * @brief Create XML text for DFRN relocations
454 * @param array $owner Owner record
455 * @param int $uid User ID
457 * @return string DFRN relocations
458 * @todo Find proper type-hints
460 public static function relocate($owner, $uid)
463 /* get site pubkey. this could be a new installation with no site keys*/
464 $pubkey = Config::get('system', 'site_pubkey');
466 $res = Crypto::newKeypair(1024);
467 Config::set('system', 'site_prvkey', $res['prvkey']);
468 Config::set('system', 'site_pubkey', $res['pubkey']);
472 "SELECT `resource-id` , `scale`, type FROM `photo`
473 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;",
477 $ext = Image::supportedTypes();
479 foreach ($rp as $p) {
480 $photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
484 $doc = new DOMDocument('1.0', 'utf-8');
485 $doc->formatOutput = true;
487 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
489 $relocate = $doc->createElement("dfrn:relocate");
491 XML::addElement($doc, $relocate, "dfrn:url", $owner['url']);
492 XML::addElement($doc, $relocate, "dfrn:name", $owner['name']);
493 XML::addElement($doc, $relocate, "dfrn:addr", $owner['addr']);
494 XML::addElement($doc, $relocate, "dfrn:avatar", $owner['avatar']);
495 XML::addElement($doc, $relocate, "dfrn:photo", $photos[4]);
496 XML::addElement($doc, $relocate, "dfrn:thumb", $photos[5]);
497 XML::addElement($doc, $relocate, "dfrn:micro", $photos[6]);
498 XML::addElement($doc, $relocate, "dfrn:request", $owner['request']);
499 XML::addElement($doc, $relocate, "dfrn:confirm", $owner['confirm']);
500 XML::addElement($doc, $relocate, "dfrn:notify", $owner['notify']);
501 XML::addElement($doc, $relocate, "dfrn:poll", $owner['poll']);
502 XML::addElement($doc, $relocate, "dfrn:sitepubkey", Config::get('system', 'site_pubkey'));
504 $root->appendChild($relocate);
506 return trim($doc->saveXML());
510 * @brief Adds the header elements for the DFRN protocol
512 * @param object $doc XML document
513 * @param array $owner Owner record
514 * @param string $authorelement Element name for the author
515 * @param string $alternatelink link to profile or category
516 * @param bool $public Is it a header for public posts?
518 * @return object XML root object
519 * @todo Find proper type-hints
521 private static function addHeader($doc, $owner, $authorelement, $alternatelink = "", $public = false)
524 if ($alternatelink == "") {
525 $alternatelink = $owner['url'];
528 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
529 $doc->appendChild($root);
531 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
532 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
533 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
534 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
535 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
536 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
537 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
538 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
539 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
541 XML::addElement($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
542 XML::addElement($doc, $root, "title", $owner["name"]);
544 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION];
545 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
547 $attributes = ["rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/"];
548 XML::addElement($doc, $root, "link", "", $attributes);
550 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $alternatelink];
551 XML::addElement($doc, $root, "link", "", $attributes);
555 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
556 OStatus::hublinks($doc, $root, $owner["nick"]);
558 $attributes = ["rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
559 XML::addElement($doc, $root, "link", "", $attributes);
561 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
562 XML::addElement($doc, $root, "link", "", $attributes);
564 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
565 XML::addElement($doc, $root, "link", "", $attributes);
568 // For backward compatibility we keep this element
569 if ($owner['page-flags'] == PAGE_COMMUNITY) {
570 XML::addElement($doc, $root, "dfrn:community", 1);
573 // The former element is replaced by this one
574 XML::addElement($doc, $root, "dfrn:account_type", $owner["account-type"]);
576 /// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
578 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
580 $author = self::addAuthor($doc, $owner, $authorelement, $public);
581 $root->appendChild($author);
587 * @brief Adds the author element in the header for the DFRN protocol
589 * @param object $doc XML document
590 * @param array $owner Owner record
591 * @param string $authorelement Element name for the author
592 * @param boolean $public boolean
594 * @return object XML author object
595 * @todo Find proper type-hints
597 private static function addAuthor($doc, $owner, $authorelement, $public)
599 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
601 "SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
602 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
603 intval($owner['uid'])
605 if (DBM::is_result($r)) {
611 $author = $doc->createElement($authorelement);
613 $namdate = DateTimeFormat::utc($owner['name-date'].'+00:00', DateTimeFormat::ATOM);
614 $uridate = DateTimeFormat::utc($owner['uri-date'].'+00:00', DateTimeFormat::ATOM);
615 $picdate = DateTimeFormat::utc($owner['avatar-date'].'+00:00', DateTimeFormat::ATOM);
619 if (!$public || !$hidewall) {
620 $attributes = ["dfrn:updated" => $namdate];
623 XML::addElement($doc, $author, "name", $owner["name"], $attributes);
624 XML::addElement($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
625 XML::addElement($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
627 $attributes = ["rel" => "photo", "type" => "image/jpeg",
628 "media:width" => 175, "media:height" => 175, "href" => $owner['photo']];
630 if (!$public || !$hidewall) {
631 $attributes["dfrn:updated"] = $picdate;
634 XML::addElement($doc, $author, "link", "", $attributes);
636 $attributes["rel"] = "avatar";
637 XML::addElement($doc, $author, "link", "", $attributes);
640 XML::addElement($doc, $author, "dfrn:hide", "true");
643 // The following fields will only be generated if the data isn't meant for a public feed
648 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
651 XML::addElement($doc, $author, "dfrn:birthday", $birthday);
654 // Only show contact details when we are allowed to
656 "SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
657 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
658 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
660 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
661 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
662 intval($owner['uid'])
664 if (DBM::is_result($r)) {
667 XML::addElement($doc, $author, "poco:displayName", $profile["name"]);
668 XML::addElement($doc, $author, "poco:updated", $namdate);
670 if (trim($profile["dob"]) > '0001-01-01') {
671 XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
674 XML::addElement($doc, $author, "poco:note", $profile["about"]);
675 XML::addElement($doc, $author, "poco:preferredUsername", $profile["nickname"]);
677 $savetz = date_default_timezone_get();
678 date_default_timezone_set($profile["timezone"]);
679 XML::addElement($doc, $author, "poco:utcOffset", date("P"));
680 date_default_timezone_set($savetz);
682 if (trim($profile["homepage"]) != "") {
683 $urls = $doc->createElement("poco:urls");
684 XML::addElement($doc, $urls, "poco:type", "homepage");
685 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
686 XML::addElement($doc, $urls, "poco:primary", "true");
687 $author->appendChild($urls);
690 if (trim($profile["pub_keywords"]) != "") {
691 $keywords = explode(",", $profile["pub_keywords"]);
693 foreach ($keywords as $keyword) {
694 XML::addElement($doc, $author, "poco:tags", trim($keyword));
698 if (trim($profile["xmpp"]) != "") {
699 $ims = $doc->createElement("poco:ims");
700 XML::addElement($doc, $ims, "poco:type", "xmpp");
701 XML::addElement($doc, $ims, "poco:value", $profile["xmpp"]);
702 XML::addElement($doc, $ims, "poco:primary", "true");
703 $author->appendChild($ims);
706 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
707 $element = $doc->createElement("poco:address");
709 XML::addElement($doc, $element, "poco:formatted", Profile::formatLocation($profile));
711 if (trim($profile["locality"]) != "") {
712 XML::addElement($doc, $element, "poco:locality", $profile["locality"]);
715 if (trim($profile["region"]) != "") {
716 XML::addElement($doc, $element, "poco:region", $profile["region"]);
719 if (trim($profile["country-name"]) != "") {
720 XML::addElement($doc, $element, "poco:country", $profile["country-name"]);
723 $author->appendChild($element);
731 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
733 * @param object $doc XML document
734 * @param string $element Element name for the author
735 * @param string $contact_url Link of the contact
736 * @param array $item Item elements
738 * @return object XML author object
739 * @todo Find proper type-hints
741 private static function addEntryAuthor($doc, $element, $contact_url, $item)
743 $contact = Contact::getDetailsByURL($contact_url, $item["uid"]);
745 $author = $doc->createElement($element);
746 XML::addElement($doc, $author, "name", $contact["name"]);
747 XML::addElement($doc, $author, "uri", $contact["url"]);
748 XML::addElement($doc, $author, "dfrn:handle", $contact["addr"]);
751 /// - Check real image type and image size
752 /// - Check which of these boths elements we should use
755 "type" => "image/jpeg",
757 "media:height" => 80,
758 "href" => $contact["photo"]];
759 XML::addElement($doc, $author, "link", "", $attributes);
763 "type" => "image/jpeg",
765 "media:height" => 80,
766 "href" => $contact["photo"]];
767 XML::addElement($doc, $author, "link", "", $attributes);
773 * @brief Adds the activity elements
775 * @param object $doc XML document
776 * @param string $element Element name for the activity
777 * @param string $activity activity value
779 * @return object XML activity object
780 * @todo Find proper type-hints
782 private static function createActivity($doc, $element, $activity)
785 $entry = $doc->createElement($element);
787 $r = XML::parseString($activity, false);
793 XML::addElement($doc, $entry, "activity:object-type", $r->type);
797 XML::addElement($doc, $entry, "id", $r->id);
801 XML::addElement($doc, $entry, "title", $r->title);
805 if (substr($r->link, 0, 1) == '<') {
806 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
807 $r->link = str_replace('&', '&', $r->link);
810 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
812 // XML does need a single element as root element so we add a dummy element here
813 $data = XML::parseString("<dummy>" . $r->link . "</dummy>", false);
814 if (is_object($data)) {
815 foreach ($data->link as $link) {
817 foreach ($link->attributes() as $parameter => $value) {
818 $attributes[$parameter] = $value;
820 XML::addElement($doc, $entry, "link", "", $attributes);
824 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
825 XML::addElement($doc, $entry, "link", "", $attributes);
829 XML::addElement($doc, $entry, "content", BBCode::convert($r->content), ["type" => "html"]);
839 * @brief Adds the elements for attachments
841 * @param object $doc XML document
842 * @param object $root XML root
843 * @param array $item Item element
845 * @return object XML attachment object
846 * @todo Find proper type-hints
848 private static function getAttachment($doc, $root, $item)
850 $arr = explode('[/attach],', $item['attach']);
852 foreach ($arr as $r) {
854 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
856 $attributes = ["rel" => "enclosure",
857 "href" => $matches[1],
858 "type" => $matches[3]];
860 if (intval($matches[2])) {
861 $attributes["length"] = intval($matches[2]);
864 if (trim($matches[4]) != "") {
865 $attributes["title"] = trim($matches[4]);
868 XML::addElement($doc, $root, "link", "", $attributes);
875 * @brief Adds the "entry" elements for the DFRN protocol
877 * @param object $doc XML document
878 * @param string $type "text" or "html"
879 * @param array $item Item element
880 * @param array $owner Owner record
881 * @param bool $comment Trigger the sending of the "comment" element
882 * @param int $cid Contact ID of the recipient
883 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
885 * @return object XML entry object
886 * @todo Find proper type-hints
888 private static function entry($doc, $type, array $item, array $owner, $comment = false, $cid = 0, $single = false)
892 if (!$item['parent']) {
896 if ($item['deleted']) {
897 $attributes = ["ref" => $item['uri'], "when" => DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM)];
898 return XML::createElement($doc, "at:deleted-entry", "", $attributes);
902 $entry = $doc->createElement("entry");
904 $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry');
905 $doc->appendChild($entry);
907 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
908 $entry->setAttribute("xmlns:at", NAMESPACE_TOMB);
909 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
910 $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
911 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
912 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
913 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
914 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
915 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
918 if ($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid']) {
919 $body = Item::fixPrivatePhotos($item['body'], $owner['uid'], $item, $cid);
921 $body = $item['body'];
924 // Remove the abstract element. It is only locally important.
925 $body = BBCode::stripAbstract($body);
928 if ($type == 'html') {
931 if ($item['title'] != "") {
932 $htmlbody = "[b]" . $item['title'] . "[/b]\n\n" . $htmlbody;
935 $htmlbody = BBCode::convert($htmlbody, false, 7);
938 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
939 $entry->appendChild($author);
941 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
942 $entry->appendChild($dfrnowner);
944 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
945 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
946 $parent = Item::selectFirst(['guid', 'plink'], ['uri' => $parent_item, 'uid' => $item['uid']]);
947 $attributes = ["ref" => $parent_item, "type" => "text/html",
948 "href" => $parent['plink'],
949 "dfrn:diaspora_guid" => $parent['guid']];
950 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
953 // Add conversation data. This is used for OStatus
954 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
955 $conversation_uri = $conversation_href;
957 if (isset($parent_item)) {
958 $conversation = dba::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $item['parent-uri']]);
959 if (DBM::is_result($conversation)) {
960 if ($conversation['conversation-uri'] != '') {
961 $conversation_uri = $conversation['conversation-uri'];
963 if ($conversation['conversation-href'] != '') {
964 $conversation_href = $conversation['conversation-href'];
970 "href" => $conversation_href,
971 "ref" => $conversation_uri];
973 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
975 XML::addElement($doc, $entry, "id", $item["uri"]);
976 XML::addElement($doc, $entry, "title", $item["title"]);
978 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"] . "+00:00", DateTimeFormat::ATOM));
979 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"] . "+00:00", DateTimeFormat::ATOM));
981 // "dfrn:env" is used to read the content
982 XML::addElement($doc, $entry, "dfrn:env", base64url_encode($body, true));
984 // The "content" field is not read by the receiver. We could remove it when the type is "text"
985 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
986 XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
988 // We save this value in "plink". Maybe we should read it from there as well?
994 ["rel" => "alternate", "type" => "text/html",
995 "href" => System::baseUrl() . "/display/" . $item["guid"]]
998 // "comment-allow" is some old fashioned stuff for old Friendica versions.
999 // It is included in the rewritten code for completeness
1001 XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
1004 if ($item['location']) {
1005 XML::addElement($doc, $entry, "dfrn:location", $item['location']);
1008 if ($item['coord']) {
1009 XML::addElement($doc, $entry, "georss:point", $item['coord']);
1012 if (($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])) {
1013 XML::addElement($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
1016 if ($item['extid']) {
1017 XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
1020 if ($item['bookmark']) {
1021 XML::addElement($doc, $entry, "dfrn:bookmark", "true");
1025 XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
1028 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
1030 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
1031 // It is needed for relayed comments to Diaspora.
1032 if ($item['signed_text']) {
1033 $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer']]));
1034 XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
1037 XML::addElement($doc, $entry, "activity:verb", self::constructVerb($item));
1039 if ($item['object-type'] != "") {
1040 XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
1041 } elseif ($item['id'] == $item['parent']) {
1042 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1044 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
1047 $actobj = self::createActivity($doc, "activity:object", $item['object']);
1049 $entry->appendChild($actobj);
1052 $actarg = self::createActivity($doc, "activity:target", $item['target']);
1054 $entry->appendChild($actarg);
1057 $tags = Item::getFeedTags($item);
1059 /// @TODO Combine this with similar below if() block?
1061 foreach ($tags as $t) {
1062 if (($type != 'html') || ($t[0] != "@")) {
1063 XML::addElement($doc, $entry, "category", "", ["scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]]);
1069 foreach ($tags as $t) {
1071 $mentioned[$t[1]] = $t[1];
1076 foreach ($mentioned as $mention) {
1078 "SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1079 intval($owner["uid"]),
1080 dbesc(normalise_link($mention))
1083 if (DBM::is_result($r) && ($r[0]["forum"] || $r[0]["prv"])) {
1089 ["rel" => "mentioned",
1090 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1099 ["rel" => "mentioned",
1100 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1106 self::getAttachment($doc, $entry, $item);
1112 * @brief encrypts data via AES
1114 * @param string $data The data that is to be encrypted
1115 * @param string $key The AES key
1117 * @return string encrypted data
1119 private static function aesEncrypt($data, $key)
1121 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1125 * @brief decrypts data via AES
1127 * @param string $encrypted The encrypted data
1128 * @param string $key The AES key
1130 * @return string decrypted data
1132 public static function aesDecrypt($encrypted, $key)
1134 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1138 * @brief Delivers the atom content to the contacts
1140 * @param array $owner Owner record
1141 * @param array $contact Contact record of the receiver
1142 * @param string $atom Content that will be transmitted
1143 * @param bool $dissolve (to be documented)
1145 * @return int Deliver status. Negative values mean an error.
1146 * @todo Add array type-hint for $owner, $contact
1148 public static function deliver($owner, $contact, $atom, $dissolve = false)
1152 // At first try the Diaspora transport layer
1153 $ret = self::transmit($owner, $contact, $atom);
1155 logger('Delivery via Diaspora transport layer was successful with status ' . $ret);
1159 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1161 if ($contact['duplex'] && $contact['dfrn-id']) {
1162 $idtosend = '0:' . $orig_id;
1164 if ($contact['duplex'] && $contact['issued-id']) {
1165 $idtosend = '1:' . $orig_id;
1168 $rino = Config::get('system', 'rino_encrypt');
1169 $rino = intval($rino);
1171 logger("Local rino version: ". $rino, LOGGER_DEBUG);
1173 $ssl_val = intval(Config::get('system', 'ssl_policy'));
1177 case SSL_POLICY_FULL:
1178 $ssl_policy = 'full';
1180 case SSL_POLICY_SELFSIGN:
1181 $ssl_policy = 'self';
1183 case SSL_POLICY_NONE:
1185 $ssl_policy = 'none';
1189 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1191 logger('dfrn_deliver: ' . $url);
1193 $ret = Network::curl($url);
1195 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1196 Contact::markForArchival($contact);
1197 return -2; // timed out
1200 $xml = $ret['body'];
1202 $curl_stat = $a->get_curl_code();
1203 if (empty($curl_stat)) {
1204 Contact::markForArchival($contact);
1205 return -3; // timed out
1208 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1211 Contact::markForArchival($contact);
1215 if (strpos($xml, '<?xml') === false) {
1216 logger('dfrn_deliver: no valid XML returned');
1217 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1218 Contact::markForArchival($contact);
1222 $res = XML::parseString($xml);
1224 if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
1225 Contact::markForArchival($contact);
1226 return ($res->status ? $res->status : 3);
1230 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1231 $challenge = hex2bin((string) $res->challenge);
1232 $perm = (($res->perm) ? $res->perm : null);
1233 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1234 $rino_remote_version = intval($res->rino);
1235 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1237 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
1239 if ($owner['page-flags'] == PAGE_PRVGROUP) {
1243 $final_dfrn_id = '';
1246 if ((($perm == 'rw') && (! intval($contact['writable'])))
1247 || (($perm == 'r') && (intval($contact['writable'])))
1250 "update contact set writable = %d where id = %d",
1251 intval(($perm == 'rw') ? 1 : 0),
1252 intval($contact['id'])
1254 $contact['writable'] = (string) 1 - intval($contact['writable']);
1258 if (($contact['duplex'] && strlen($contact['pubkey']))
1259 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1260 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
1262 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
1263 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
1265 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
1266 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
1269 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1271 if (strpos($final_dfrn_id, ':') == 1) {
1272 $final_dfrn_id = substr($final_dfrn_id, 2);
1275 if ($final_dfrn_id != $orig_id) {
1276 logger('dfrn_deliver: wrong dfrn_id.');
1277 // did not decode properly - cannot trust this site
1278 Contact::markForArchival($contact);
1282 $postvars['dfrn_id'] = $idtosend;
1283 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1285 $postvars['dissolve'] = '1';
1288 if ((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1289 $postvars['data'] = $atom;
1290 $postvars['perm'] = 'rw';
1292 $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
1293 $postvars['perm'] = 'r';
1296 $postvars['ssl_policy'] = $ssl_policy;
1299 $postvars['page'] = $page;
1303 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1304 logger('rino version: '. $rino_remote_version);
1306 switch ($rino_remote_version) {
1308 $key = openssl_random_pseudo_bytes(16);
1309 $data = self::aesEncrypt($postvars['data'], $key);
1312 logger("rino: invalid requested version '$rino_remote_version'");
1313 Contact::markForArchival($contact);
1317 $postvars['rino'] = $rino_remote_version;
1318 $postvars['data'] = bin2hex($data);
1320 if ($dfrn_version >= 2.1) {
1321 if (($contact['duplex'] && strlen($contact['pubkey']))
1322 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1323 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
1325 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1327 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1330 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1331 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1333 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1337 logger('md5 rawkey ' . md5($postvars['key']));
1339 $postvars['key'] = bin2hex($postvars['key']);
1343 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), LOGGER_DATA);
1345 $xml = Network::post($contact['notify'], $postvars);
1347 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1349 $curl_stat = $a->get_curl_code();
1350 if (empty($curl_stat) || empty($xml)) {
1351 Contact::markForArchival($contact);
1352 return -9; // timed out
1355 if (($curl_stat == 503) && stristr($a->get_curl_headers(), 'retry-after')) {
1356 Contact::markForArchival($contact);
1360 if (strpos($xml, '<?xml') === false) {
1361 logger('dfrn_deliver: phase 2: no valid XML returned');
1362 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1363 Contact::markForArchival($contact);
1367 $res = XML::parseString($xml);
1369 if (!isset($res->status)) {
1370 Contact::markForArchival($contact);
1374 // Possibly old servers had returned an empty value when everything was okay
1375 if (empty($res->status)) {
1379 if (!empty($res->message)) {
1380 logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1383 if (($res->status >= 200) && ($res->status <= 299)) {
1384 Contact::unmarkForArchival($contact);
1387 return intval($res->status);
1391 * @brief Transmits atom content to the contacts via the Diaspora transport layer
1393 * @param array $owner Owner record
1394 * @param array $contact Contact record of the receiver
1395 * @param string $atom Content that will be transmitted
1397 * @return int Deliver status. Negative values mean an error.
1399 public static function transmit($owner, $contact, $atom, $public_batch = false)
1403 if (!$public_batch) {
1404 if (empty($contact['addr'])) {
1405 logger('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.');
1406 if (Contact::updateFromProbe($contact['id'])) {
1407 $new_contact = dba::selectFirst('contact', ['addr'], ['id' => $contact['id']]);
1408 $contact['addr'] = $new_contact['addr'];
1411 if (empty($contact['addr'])) {
1412 logger('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
1413 Contact::markForArchival($contact);
1418 $fcontact = Diaspora::personByHandle($contact['addr']);
1419 if (empty($fcontact)) {
1420 logger('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
1421 Contact::markForArchival($contact);
1424 $pubkey = $fcontact['pubkey'];
1429 $envelope = Diaspora::buildMessage($atom, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
1431 // Create the endpoint for public posts. This is some WIP and should later be added to the probing
1432 if ($public_batch && empty($contact["batch"])) {
1433 $parts = parse_url($contact["notify"]);
1434 $path_parts = explode('/', $parts['path']);
1435 array_pop($path_parts);
1436 $parts['path'] = implode('/', $path_parts);
1437 $contact["batch"] = Network::unparseURL($parts);
1440 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
1442 $content_type = ($public_batch ? "application/magic-envelope+xml" : "application/json");
1444 $xml = Network::post($dest_url, $envelope, ["Content-Type: ".$content_type]);
1446 $curl_stat = $a->get_curl_code();
1447 if (empty($curl_stat) || empty($xml)) {
1448 logger('Empty answer from ' . $contact['id'] . ' - ' . $dest_url);
1449 Contact::markForArchival($contact);
1450 return -9; // timed out
1453 if (($curl_stat == 503) && (stristr($a->get_curl_headers(), 'retry-after'))) {
1454 Contact::markForArchival($contact);
1458 if (strpos($xml, '<?xml') === false) {
1459 logger('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url);
1460 logger('Returned XML: ' . $xml, LOGGER_DATA);
1461 Contact::markForArchival($contact);
1465 $res = XML::parseString($xml);
1467 if (empty($res->status)) {
1468 Contact::markForArchival($contact);
1472 if (!empty($res->message)) {
1473 logger('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1476 if (($res->status >= 200) && ($res->status <= 299)) {
1477 Contact::unmarkForArchival($contact);
1480 return intval($res->status);
1484 * @brief Add new birthday event for this person
1486 * @param array $contact Contact record
1487 * @param string $birthday Birthday of the contact
1489 * @todo Add array type-hint for $contact
1491 private static function birthdayEvent($contact, $birthday)
1493 // Check for duplicates
1495 "SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1496 intval($contact['uid']),
1497 intval($contact['id']),
1498 dbesc(DateTimeFormat::utc($birthday)),
1502 if (DBM::is_result($r)) {
1506 logger('updating birthday: ' . $birthday . ' for contact ' . $contact['id']);
1508 $bdtext = L10n::t('%s\'s birthday', $contact['name']);
1509 $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]');
1512 "INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1513 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1514 intval($contact['uid']),
1515 intval($contact['id']),
1516 dbesc(DateTimeFormat::utcNow()),
1517 dbesc(DateTimeFormat::utcNow()),
1518 dbesc(DateTimeFormat::utc($birthday)),
1519 dbesc(DateTimeFormat::utc($birthday . ' + 1 day ')),
1527 * @brief Fetch the author data from head or entry items
1529 * @param object $xpath XPath object
1530 * @param object $context In which context should the data be searched
1531 * @param array $importer Record of the importer user mixed with contact of the content
1532 * @param string $element Element name from which the data is fetched
1533 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1534 * @param string $xml optional, default empty
1536 * @return array Relevant data of the author
1537 * @todo Find good type-hints for all parameter
1539 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
1542 $author["name"] = XML::getFirstNodeValue($xpath, $element."/atom:name/text()", $context);
1543 $author["link"] = XML::getFirstNodeValue($xpath, $element."/atom:uri/text()", $context);
1545 $fields = ['id', 'uid', 'url', 'network', 'avatar-date', 'avatar', 'name-date', 'uri-date', 'addr',
1546 'name', 'nick', 'about', 'location', 'keywords', 'xmpp', 'bdyear', 'bd', 'hidden', 'contact-type'];
1547 $condition = ["`uid` = ? AND `nurl` = ? AND `network` != ?",
1548 $importer["importer_uid"], normalise_link($author["link"]), NETWORK_STATUSNET];
1549 $contact_old = dba::selectFirst('contact', $fields, $condition);
1551 if (DBM::is_result($contact_old)) {
1552 $author["contact-id"] = $contact_old["id"];
1553 $author["network"] = $contact_old["network"];
1556 logger("Contact ".$author["link"]." wasn't found for user ".$importer["importer_uid"]." XML: ".$xml, LOGGER_DEBUG);
1559 $author["contact-unknown"] = true;
1560 $author["contact-id"] = $importer["id"];
1561 $author["network"] = $importer["network"];
1565 // Until now we aren't serving different sizes - but maybe later
1567 /// @todo check if "avatar" or "photo" would be the best field in the specification
1568 $avatars = $xpath->query($element . "/atom:link[@rel='avatar']", $context);
1569 foreach ($avatars as $avatar) {
1572 foreach ($avatar->attributes as $attributes) {
1573 /// @TODO Rewrite these similar if() to one switch
1574 if ($attributes->name == "href") {
1575 $href = $attributes->textContent;
1577 if ($attributes->name == "width") {
1578 $width = $attributes->textContent;
1580 if ($attributes->name == "updated") {
1581 $author["avatar-date"] = $attributes->textContent;
1584 if (($width > 0) && ($href != "")) {
1585 $avatarlist[$width] = $href;
1589 if (count($avatarlist) > 0) {
1590 krsort($avatarlist);
1591 $author["avatar"] = current($avatarlist);
1594 if (DBM::is_result($contact_old) && !$onlyfetch) {
1595 logger("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", LOGGER_DEBUG);
1597 $poco = ["url" => $contact_old["url"]];
1599 // When was the last change to name or uri?
1600 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1601 foreach ($name_element->attributes as $attributes) {
1602 if ($attributes->name == "updated") {
1603 $poco["name-date"] = $attributes->textContent;
1607 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1608 foreach ($link_element->attributes as $attributes) {
1609 if ($attributes->name == "updated") {
1610 $poco["uri-date"] = $attributes->textContent;
1614 // Update contact data
1615 $value = XML::getFirstNodeValue($xpath, $element . "/dfrn:handle/text()", $context);
1617 $poco["addr"] = $value;
1620 $value = XML::getFirstNodeValue($xpath, $element . "/poco:displayName/text()", $context);
1622 $poco["name"] = $value;
1625 $value = XML::getFirstNodeValue($xpath, $element . "/poco:preferredUsername/text()", $context);
1627 $poco["nick"] = $value;
1630 $value = XML::getFirstNodeValue($xpath, $element . "/poco:note/text()", $context);
1632 $poco["about"] = $value;
1635 $value = XML::getFirstNodeValue($xpath, $element . "/poco:address/poco:formatted/text()", $context);
1637 $poco["location"] = $value;
1640 /// @todo Only search for elements with "poco:type" = "xmpp"
1641 $value = XML::getFirstNodeValue($xpath, $element . "/poco:ims/poco:value/text()", $context);
1643 $poco["xmpp"] = $value;
1646 /// @todo Add support for the following fields that we don't support by now in the contact table:
1647 /// - poco:utcOffset
1653 // If the "hide" element is present then the profile isn't searchable.
1654 $hide = intval(XML::getFirstNodeValue($xpath, $element . "/dfrn:hide/text()", $context) == "true");
1656 logger("Hidden status for contact " . $contact_old["url"] . ": " . $hide, LOGGER_DEBUG);
1658 // If the contact isn't searchable then set the contact to "hidden".
1659 // Problem: This can be manually overridden by the user.
1661 $contact_old["hidden"] = true;
1664 // Save the keywords into the contact table
1666 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1667 foreach ($tagelements as $tag) {
1668 $tags[$tag->nodeValue] = $tag->nodeValue;
1672 $poco["keywords"] = implode(", ", $tags);
1675 // "dfrn:birthday" contains the birthday converted to UTC
1676 $birthday = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1678 if (strtotime($birthday) > time()) {
1679 $bd_timestamp = strtotime($birthday);
1681 $poco["bdyear"] = date("Y", $bd_timestamp);
1684 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1685 $value = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1687 if (!in_array($value, ["", "0000-00-00", "0001-01-01"])) {
1688 $bdyear = date("Y");
1689 $value = str_replace("0000", $bdyear, $value);
1691 if (strtotime($value) < time()) {
1692 $value = str_replace($bdyear, $bdyear + 1, $value);
1693 $bdyear = $bdyear + 1;
1696 $poco["bd"] = $value;
1699 $contact = array_merge($contact_old, $poco);
1701 if ($contact_old["bdyear"] != $contact["bdyear"]) {
1702 self::birthdayEvent($contact, $birthday);
1705 // Get all field names
1707 foreach ($contact_old as $field => $data) {
1708 $fields[$field] = $data;
1711 unset($fields["id"]);
1712 unset($fields["uid"]);
1713 unset($fields["url"]);
1714 unset($fields["avatar-date"]);
1715 unset($fields["avatar"]);
1716 unset($fields["name-date"]);
1717 unset($fields["uri-date"]);
1720 // Update check for this field has to be done differently
1721 $datefields = ["name-date", "uri-date"];
1722 foreach ($datefields as $field) {
1723 if (strtotime($contact[$field]) > strtotime($contact_old[$field])) {
1724 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1729 foreach ($fields as $field => $data) {
1730 if ($contact[$field] != $contact_old[$field]) {
1731 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1737 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1740 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1741 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1742 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1743 WHERE `id` = %d AND `network` = '%s'",
1744 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
1745 dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1746 dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
1747 dbesc(DBM::date($contact["name-date"])), dbesc(DBM::date($contact["uri-date"])),
1748 intval($contact["id"]), dbesc($contact["network"])
1752 Contact::updateAvatar(
1754 $importer['importer_uid'],
1756 (strtotime($contact['avatar-date']) > strtotime($contact_old['avatar-date']) || ($author['avatar'] != $contact_old['avatar']))
1760 * The generation is a sign for the reliability of the provided data.
1761 * It is used in the socgraph.php to prevent that old contact data
1762 * that was relayed over several servers can overwrite contact
1763 * data that we received directly.
1766 $poco["generation"] = 2;
1767 $poco["photo"] = $author["avatar"];
1768 $poco["hide"] = $hide;
1769 $poco["contact-type"] = $contact["contact-type"];
1770 $gcid = GContact::update($poco);
1772 GContact::link($gcid, $importer["importer_uid"], $contact["id"]);
1779 * @brief Transforms activity objects into an XML string
1781 * @param object $xpath XPath object
1782 * @param object $activity Activity object
1783 * @param string $element element name
1785 * @return string XML string
1786 * @todo Find good type-hints for all parameter
1788 private static function transformActivity($xpath, $activity, $element)
1790 if (!is_object($activity)) {
1794 $obj_doc = new DOMDocument("1.0", "utf-8");
1795 $obj_doc->formatOutput = true;
1797 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1799 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1800 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1802 $id = $xpath->query("atom:id", $activity)->item(0);
1803 if (is_object($id)) {
1804 $obj_element->appendChild($obj_doc->importNode($id, true));
1807 $title = $xpath->query("atom:title", $activity)->item(0);
1808 if (is_object($title)) {
1809 $obj_element->appendChild($obj_doc->importNode($title, true));
1812 $links = $xpath->query("atom:link", $activity);
1813 if (is_object($links)) {
1814 foreach ($links as $link) {
1815 $obj_element->appendChild($obj_doc->importNode($link, true));
1819 $content = $xpath->query("atom:content", $activity)->item(0);
1820 if (is_object($content)) {
1821 $obj_element->appendChild($obj_doc->importNode($content, true));
1824 $obj_doc->appendChild($obj_element);
1826 $objxml = $obj_doc->saveXML($obj_element);
1828 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1829 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1834 * @brief Processes the mail elements
1836 * @param object $xpath XPath object
1837 * @param object $mail mail elements
1838 * @param array $importer Record of the importer user mixed with contact of the content
1840 * @todo Find good type-hints for all parameter
1842 private static function processMail($xpath, $mail, $importer)
1844 logger("Processing mails");
1846 /// @TODO Rewrite this to one statement
1848 $msg["uid"] = $importer["importer_uid"];
1849 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1850 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1851 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1852 $msg["contact-id"] = $importer["id"];
1853 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1854 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1855 $msg["created"] = DateTimeFormat::utc($xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue);
1856 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1857 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1859 $msg["replied"] = 0;
1861 dba::insert('mail', $msg);
1863 // send notifications.
1864 /// @TODO Arange this mess
1866 "type" => NOTIFY_MAIL,
1867 "notify_flags" => $importer["notify-flags"],
1868 "language" => $importer["language"],
1869 "to_name" => $importer["username"],
1870 "to_email" => $importer["email"],
1871 "uid" => $importer["importer_uid"],
1873 "source_name" => $msg["from-name"],
1874 "source_link" => $importer["url"],
1875 "source_photo" => $importer["thumb"],
1876 "verb" => ACTIVITY_POST,
1880 notification($notif_params);
1882 logger("Mail is processed, notification was sent.");
1886 * @brief Processes the suggestion elements
1888 * @param object $xpath XPath object
1889 * @param object $suggestion suggestion elements
1890 * @param array $importer Record of the importer user mixed with contact of the content
1892 * @todo Find good type-hints for all parameter
1894 private static function processSuggestion($xpath, $suggestion, $importer)
1898 logger("Processing suggestions");
1900 /// @TODO Rewrite this to one statement
1902 $suggest["uid"] = $importer["importer_uid"];
1903 $suggest["cid"] = $importer["id"];
1904 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1905 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1906 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1907 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1908 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1910 // Does our member already have a friend matching this description?
1913 "SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1914 dbesc($suggest["name"]),
1915 dbesc(normalise_link($suggest["url"])),
1916 intval($suggest["uid"])
1920 * The valid result means the friend we're about to send a friend
1921 * suggestion already has them in their contact, which means no further
1922 * action is required.
1924 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1926 if (DBM::is_result($r)) {
1930 // Do we already have an fcontact record for this person?
1934 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1935 dbesc($suggest["url"]),
1936 dbesc($suggest["name"]),
1937 dbesc($suggest["request"])
1939 if (DBM::is_result($r)) {
1942 // OK, we do. Do we already have an introduction for this person ?
1944 "SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1945 intval($suggest["uid"]),
1950 * The valid result means the friend we're about to send a friend
1951 * suggestion already has them in their contact, which means no further
1952 * action is required.
1954 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1956 if (DBM::is_result($r)) {
1962 "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1963 dbesc($suggest["name"]),
1964 dbesc($suggest["url"]),
1965 dbesc($suggest["photo"]),
1966 dbesc($suggest["request"])
1970 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1971 dbesc($suggest["url"]),
1972 dbesc($suggest["name"]),
1973 dbesc($suggest["request"])
1977 * If no record in fcontact is found, below INSERT statement will not
1978 * link an introduction to it.
1980 if (!DBM::is_result($r)) {
1981 // database record did not get created. Quietly give up.
1987 $hash = random_string();
1990 "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1991 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1992 intval($suggest["uid"]),
1994 intval($suggest["cid"]),
1995 dbesc($suggest["body"]),
1997 dbesc(DateTimeFormat::utcNow()),
2003 "type" => NOTIFY_SUGGEST,
2004 "notify_flags" => $importer["notify-flags"],
2005 "language" => $importer["language"],
2006 "to_name" => $importer["username"],
2007 "to_email" => $importer["email"],
2008 "uid" => $importer["importer_uid"],
2010 "link" => System::baseUrl()."/notifications/intros",
2011 "source_name" => $importer["name"],
2012 "source_link" => $importer["url"],
2013 "source_photo" => $importer["photo"],
2014 "verb" => ACTIVITY_REQ_FRIEND,
2022 * @brief Processes the relocation elements
2024 * @param object $xpath XPath object
2025 * @param object $relocation relocation elements
2026 * @param array $importer Record of the importer user mixed with contact of the content
2028 * @todo Find good type-hints for all parameter
2030 private static function processRelocation($xpath, $relocation, $importer)
2032 logger("Processing relocations");
2034 /// @TODO Rewrite this to one statement
2036 $relocate["uid"] = $importer["importer_uid"];
2037 $relocate["cid"] = $importer["id"];
2038 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
2039 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
2040 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
2041 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
2042 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
2043 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
2044 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
2045 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
2046 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
2047 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
2048 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
2049 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
2051 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
2052 $relocate["avatar"] = $relocate["photo"];
2055 if ($relocate["addr"] == "") {
2056 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
2061 "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
2062 intval($importer["id"]),
2063 intval($importer["importer_uid"])
2066 if (!DBM::is_result($r)) {
2067 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2073 // Update the gcontact entry
2074 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
2076 $fields = ['name' => $relocate["name"], 'photo' => $relocate["avatar"],
2077 'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2078 'addr' => $relocate["addr"], 'connect' => $relocate["addr"],
2079 'notify' => $relocate["notify"], 'server_url' => $relocate["server_url"]];
2080 dba::update('gcontact', $fields, ['nurl' => normalise_link($old["url"])]);
2082 // Update the contact table. We try to find every entry.
2083 $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
2084 'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2085 'addr' => $relocate["addr"], 'request' => $relocate["request"],
2086 'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
2087 'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
2088 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], normalise_link($old["url"])];
2090 dba::update('contact', $fields, $condition);
2092 Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
2094 logger('Contacts are updated.');
2097 /// merge with current record, current contents have priority
2098 /// update record, set url-updated
2099 /// update profile photos
2100 /// schedule a scan?
2105 * @brief Updates an item
2107 * @param array $current the current item record
2108 * @param array $item the new item record
2109 * @param array $importer Record of the importer user mixed with contact of the content
2110 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2112 * @todo set proper type-hints (array?)
2114 private static function updateContent($current, $item, $importer, $entrytype)
2118 if (self::isEditedTimestampNewer($current, $item)) {
2119 // do not accept (ignore) an earlier edit than one we currently have.
2120 if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
2124 $fields = ['title' => defaults($item, 'title', ''), 'body' => defaults($item, 'body', ''),
2125 'tag' => defaults($item, 'tag', ''), 'changed' => DateTimeFormat::utcNow(),
2126 'edited' => DateTimeFormat::utc($item["edited"])];
2128 $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
2129 Item::update($fields, $condition);
2137 * @brief Detects the entry type of the item
2139 * @param array $importer Record of the importer user mixed with contact of the content
2140 * @param array $item the new item record
2142 * @return int Is it a toplevel entry, a comment or a relayed comment?
2143 * @todo set proper type-hints (array?)
2145 private static function getEntryType($importer, $item)
2147 if ($item["parent-uri"] != $item["uri"]) {
2150 if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
2153 logger("possible community action");
2155 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2158 // was the top-level post for this action written by somebody on this site?
2159 // Specifically, the recipient?
2161 $is_a_remote_action = false;
2163 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item["parent-uri"]]);
2164 if (DBM::is_result($parent)) {
2166 "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2167 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2168 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2169 AND `item`.`uid` = %d
2172 dbesc($parent["parent-uri"]),
2173 dbesc($parent["parent-uri"]),
2174 dbesc($parent["parent-uri"]),
2175 intval($importer["importer_uid"])
2177 if (DBM::is_result($r)) {
2178 $is_a_remote_action = true;
2183 * Does this have the characteristics of a community or private group action?
2184 * If it's an action to a wall post on a community/prvgroup page it's a
2185 * valid community action. Also forum_mode makes it valid for sure.
2186 * If neither, it's not.
2188 if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2189 $is_a_remote_action = false;
2190 logger("not a community action");
2193 if ($is_a_remote_action) {
2194 return DFRN::REPLY_RC;
2199 return DFRN::TOP_LEVEL;
2204 * @brief Send a "poke"
2206 * @param array $item the new item record
2207 * @param array $importer Record of the importer user mixed with contact of the content
2208 * @param int $posted_id The record number of item record that was just posted
2210 * @todo set proper type-hints (array?)
2212 private static function doPoke($item, $importer, $posted_id)
2214 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2218 $xo = XML::parseString($item["object"], false);
2220 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2221 // somebody was poked/prodded. Was it me?
2222 foreach ($xo->link as $l) {
2223 $atts = $l->attributes();
2224 switch ($atts["rel"]) {
2226 $Blink = $atts["href"];
2233 if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2234 $author = dba::selectFirst('contact', ['name', 'thumb', 'url'], ['id' => $item['author-id']]);
2236 // send a notification
2239 "type" => NOTIFY_POKE,
2240 "notify_flags" => $importer["notify-flags"],
2241 "language" => $importer["language"],
2242 "to_name" => $importer["username"],
2243 "to_email" => $importer["email"],
2244 "uid" => $importer["importer_uid"],
2246 "link" => System::baseUrl()."/display/".urlencode(Item::getGuidById($posted_id)),
2247 "source_name" => $author["name"],
2248 "source_link" => $author["url"],
2249 "source_photo" => $author["thumb"],
2250 "verb" => $item["verb"],
2251 "otype" => "person",
2252 "activity" => $verb,
2253 "parent" => $item["parent"]]
2260 * @brief Processes several actions, depending on the verb
2262 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2263 * @param array $importer Record of the importer user mixed with contact of the content
2264 * @param array $item the new item record
2265 * @param bool $is_like Is the verb a "like"?
2267 * @return bool Should the processing of the entries be continued?
2268 * @todo set proper type-hints (array?)
2270 private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2272 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2274 if (($entrytype == DFRN::TOP_LEVEL)) {
2275 // The filling of the the "contact" variable is done for legcy reasons
2276 // The functions below are partly used by ostatus.php as well - where we have this variable
2277 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2279 $nickname = $contact["nick"];
2281 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2282 // This function once was responsible for DFRN and OStatus.
2283 if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2284 logger("New follower");
2285 Contact::addRelationship($importer, $contact, $item, $nickname);
2288 if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2289 logger("Lost follower");
2290 Contact::removeFollower($importer, $contact, $item);
2293 if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2294 logger("New friend request");
2295 Contact::addRelationship($importer, $contact, $item, $nickname, true);
2298 if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2299 logger("Lost sharer");
2300 Contact::removeSharer($importer, $contact, $item);
2304 if (($item["verb"] == ACTIVITY_LIKE)
2305 || ($item["verb"] == ACTIVITY_DISLIKE)
2306 || ($item["verb"] == ACTIVITY_ATTEND)
2307 || ($item["verb"] == ACTIVITY_ATTENDNO)
2308 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
2311 $item["type"] = "activity";
2312 $item["gravity"] = GRAVITY_ACTIVITY;
2313 // only one like or dislike per person
2314 // splitted into two queries for performance issues
2315 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2316 'verb' => $item["verb"], 'parent-uri' => $item["parent-uri"]];
2317 if (Item::exists($condition)) {
2321 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2322 'verb' => $item["verb"], 'thr-parent' => $item["parent-uri"]];
2323 if (Item::exists($condition)) {
2330 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2331 $xo = XML::parseString($item["object"], false);
2332 $xt = XML::parseString($item["target"], false);
2334 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2335 $item_tag = Item::selectFirst(['id', 'tag'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]);
2336 if (!DBM::is_result($item_tag)) {
2337 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2341 // extract tag, if not duplicate, add to parent item
2343 if (!stristr($item_tag["tag"], trim($xo->content))) {
2344 $tag = $item_tag["tag"] . (strlen($item_tag["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2345 Item::update(['tag' => $tag], ['id' => $item_tag["id"]]);
2355 * @brief Processes the link elements
2357 * @param object $links link elements
2358 * @param array $item the item record
2360 * @todo set proper type-hints
2362 private static function parseLinks($links, &$item)
2369 foreach ($links as $link) {
2370 foreach ($link->attributes as $attributes) {
2371 switch ($attributes->name) {
2372 case "href" : $href = $attributes->textContent; break;
2373 case "rel" : $rel = $attributes->textContent; break;
2374 case "type" : $type = $attributes->textContent; break;
2375 case "length": $length = $attributes->textContent; break;
2376 case "title" : $title = $attributes->textContent; break;
2379 if (($rel != "") && ($href != "")) {
2382 $item["plink"] = $href;
2386 if (strlen($item["attach"])) {
2387 $item["attach"] .= ",";
2390 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2398 * @brief Processes the entry elements which contain the items and comments
2400 * @param array $header Array of the header elements that always stay the same
2401 * @param object $xpath XPath object
2402 * @param object $entry entry elements
2403 * @param array $importer Record of the importer user mixed with contact of the content
2404 * @param object $xml xml
2406 * @todo Add type-hints
2408 private static function processEntry($header, $xpath, $entry, $importer, $xml)
2410 logger("Processing entries");
2414 $item["protocol"] = PROTOCOL_DFRN;
2416 $item["source"] = $xml;
2419 $item["uri"] = XML::getFirstNodeValue($xpath, "atom:id/text()", $entry);
2421 $item["edited"] = XML::getFirstNodeValue($xpath, "atom:updated/text()", $entry);
2423 $current = Item::selectFirst(['id', 'uid', 'edited', 'body'],
2424 ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
2426 // Is there an existing item?
2427 if (DBM::is_result($current) && !self::isEditedTimestampNewer($current, $item)) {
2428 logger("Item ".$item["uri"]." (".$item['edited'].") already existed.", LOGGER_DEBUG);
2433 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2435 $owner_unknown = (isset($owner["contact-unknown"]) && $owner["contact-unknown"]);
2437 $item["owner-link"] = $owner["link"];
2438 $item["owner-id"] = Contact::getIdForURL($owner["link"], 0);
2441 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2443 $item["author-link"] = $author["link"];
2444 $item["author-id"] = Contact::getIdForURL($author["link"], 0);
2446 $item["title"] = XML::getFirstNodeValue($xpath, "atom:title/text()", $entry);
2448 $item["created"] = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2450 $item["body"] = XML::getFirstNodeValue($xpath, "dfrn:env/text()", $entry);
2451 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2452 // make sure nobody is trying to sneak some html tags by us
2453 $item["body"] = notags(base64url_decode($item["body"]));
2455 $item["body"] = BBCode::limitBodySize($item["body"]);
2457 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2458 if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
2459 $base_url = get_app()->get_baseurl();
2460 $item['body'] = reltoabs($item['body'], $base_url);
2462 $item['body'] = html2bb_video($item['body']);
2464 $item['body'] = OEmbed::HTML2BBCode($item['body']);
2466 $config = HTMLPurifier_Config::createDefault();
2467 $config->set('Cache.DefinitionImpl', null);
2469 // we shouldn't need a whitelist, because the bbcode converter
2470 // will strip out any unsupported tags.
2472 $purifier = new HTMLPurifier($config);
2473 $item['body'] = $purifier->purify($item['body']);
2475 $item['body'] = @HTML::toBBCode($item['body']);
2478 /// @todo We should check for a repeated post and if we know the repeated author.
2480 // We don't need the content element since "dfrn:env" is always present
2481 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2483 $item["location"] = XML::getFirstNodeValue($xpath, "dfrn:location/text()", $entry);
2485 $item["coord"] = XML::getFirstNodeValue($xpath, "georss:point", $entry);
2487 $item["private"] = XML::getFirstNodeValue($xpath, "dfrn:private/text()", $entry);
2489 $item["extid"] = XML::getFirstNodeValue($xpath, "dfrn:extid/text()", $entry);
2491 if (XML::getFirstNodeValue($xpath, "dfrn:bookmark/text()", $entry) == "true") {
2492 $item["bookmark"] = true;
2495 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2496 if ($notice_info && ($notice_info->length > 0)) {
2497 foreach ($notice_info->item(0)->attributes as $attributes) {
2498 if ($attributes->name == "source") {
2499 $item["app"] = strip_tags($attributes->textContent);
2504 $item["guid"] = XML::getFirstNodeValue($xpath, "dfrn:diaspora_guid/text()", $entry);
2506 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
2507 $dsprsig = unxmlify(XML::getFirstNodeValue($xpath, "dfrn:diaspora_signature/text()", $entry));
2508 if ($dsprsig != "") {
2509 $item["dsprsig"] = $dsprsig;
2512 $item["verb"] = XML::getFirstNodeValue($xpath, "activity:verb/text()", $entry);
2514 if (XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry) != "") {
2515 $item["object-type"] = XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry);
2518 $object = $xpath->query("activity:object", $entry)->item(0);
2519 $item["object"] = self::transformActivity($xpath, $object, "object");
2521 if (trim($item["object"]) != "") {
2522 $r = XML::parseString($item["object"], false);
2523 if (isset($r->type)) {
2524 $item["object-type"] = $r->type;
2528 $target = $xpath->query("activity:target", $entry)->item(0);
2529 $item["target"] = self::transformActivity($xpath, $target, "target");
2531 $categories = $xpath->query("atom:category", $entry);
2533 foreach ($categories as $category) {
2536 foreach ($category->attributes as $attributes) {
2537 if ($attributes->name == "term") {
2538 $term = $attributes->textContent;
2541 if ($attributes->name == "scheme") {
2542 $scheme = $attributes->textContent;
2546 if (($term != "") && ($scheme != "")) {
2547 $parts = explode(":", $scheme);
2548 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2549 $termhash = array_shift($parts);
2550 $termurl = implode(":", $parts);
2552 if (!empty($item["tag"])) {
2553 $item["tag"] .= ",";
2558 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2566 $links = $xpath->query("atom:link", $entry);
2568 self::parseLinks($links, $item);
2571 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
2573 $conv = $xpath->query('ostatus:conversation', $entry);
2574 if (is_object($conv->item(0))) {
2575 foreach ($conv->item(0)->attributes as $attributes) {
2576 if ($attributes->name == "ref") {
2577 $item['conversation-uri'] = $attributes->textContent;
2579 if ($attributes->name == "href") {
2580 $item['conversation-href'] = $attributes->textContent;
2585 // Is it a reply or a top level posting?
2586 $item["parent-uri"] = $item["uri"];
2588 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2589 if (is_object($inreplyto->item(0))) {
2590 foreach ($inreplyto->item(0)->attributes as $attributes) {
2591 if ($attributes->name == "ref") {
2592 $item["parent-uri"] = $attributes->textContent;
2597 // Get the type of the item (Top level post, reply or remote reply)
2598 $entrytype = self::getEntryType($importer, $item);
2600 // Now assign the rest of the values that depend on the type of the message
2601 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2602 if (!isset($item["object-type"])) {
2603 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2606 if ($item["contact-id"] != $owner["contact-id"]) {
2607 $item["contact-id"] = $owner["contact-id"];
2610 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2611 $item["network"] = $owner["network"];
2614 if ($item["contact-id"] != $author["contact-id"]) {
2615 $item["contact-id"] = $author["contact-id"];
2618 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2619 $item["network"] = $author["network"];
2623 if ($entrytype == DFRN::REPLY_RC) {
2624 $item["type"] = "remote-comment";
2626 } elseif ($entrytype == DFRN::TOP_LEVEL) {
2627 if ($owner_unknown) {
2628 logger("Item won't be stored because user " . $importer["importer_uid"] . " doesn't follow " . $item["owner-link"] . ".", LOGGER_DEBUG);
2632 if (!isset($item["object-type"])) {
2633 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2637 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2638 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2639 $ev = Event::fromBBCode($item["body"]);
2640 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2641 logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2642 $ev["cid"] = $importer["id"];
2643 $ev["uid"] = $importer["importer_uid"];
2644 $ev["uri"] = $item["uri"];
2645 $ev["edited"] = $item["edited"];
2646 $ev["private"] = $item["private"];
2647 $ev["guid"] = $item["guid"];
2650 "SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2651 dbesc($item["uri"]),
2652 intval($importer["importer_uid"])
2654 if (DBM::is_result($r)) {
2655 $ev["id"] = $r[0]["id"];
2658 $event_id = Event::store($ev);
2659 logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2665 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2666 logger("Exiting because 'processVerbs' told us so", LOGGER_DEBUG);
2670 // Update content if 'updated' changes
2671 if (DBM::is_result($current)) {
2672 if (self::updateContent($current, $item, $importer, $entrytype)) {
2673 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2675 logger("Item " . $item["uri"] . " already existed.", LOGGER_DEBUG);
2680 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2681 $posted_id = Item::insert($item);
2685 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2687 if ($item['uid'] == 0) {
2688 Item::distribute($posted_id);
2693 } else { // $entrytype == DFRN::TOP_LEVEL
2694 if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
2695 logger("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", LOGGER_DEBUG);
2698 if (!link_compare($item["owner-link"], $importer["url"])) {
2700 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2701 * but otherwise there's a possible data mixup on the sender's system.
2702 * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2703 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2705 logger('Correcting item owner.', LOGGER_DEBUG);
2706 $item["owner-link"] = $importer["url"];
2707 $item["owner-id"] = Contact::getIdForURL($importer["url"], 0);
2710 if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2711 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2715 // This is my contact on another system, but it's really me.
2716 // Turn this into a wall post.
2717 $notify = Item::isRemoteSelf($importer, $item);
2719 $posted_id = Item::insert($item, false, $notify);
2722 $posted_id = $notify;
2725 logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2727 if ($item['uid'] == 0) {
2728 Item::distribute($posted_id);
2731 if (stristr($item["verb"], ACTIVITY_POKE)) {
2732 self::doPoke($item, $importer, $posted_id);
2738 * @brief Deletes items
2740 * @param object $xpath XPath object
2741 * @param object $deletion deletion elements
2742 * @param array $importer Record of the importer user mixed with contact of the content
2744 * @todo set proper type-hints
2746 private static function processDeletion($xpath, $deletion, $importer)
2748 logger("Processing deletions");
2751 foreach ($deletion->attributes as $attributes) {
2752 if ($attributes->name == "ref") {
2753 $uri = $attributes->textContent;
2757 if (!$uri || !$importer["id"]) {
2761 $condition = ['uri' => $uri, 'uid' => $importer["importer_uid"]];
2762 $item = Item::selectFirst(['id', 'parent', 'contact-id', 'file', 'deleted'], $condition);
2763 if (!DBM::is_result($item)) {
2764 logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", LOGGER_DEBUG);
2768 if (strstr($item['file'], '[')) {
2769 logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " is filed. So it won't be deleted.", LOGGER_DEBUG);
2773 // When it is a starting post it has to belong to the person that wants to delete it
2774 if (($item['id'] == $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2775 logger("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2779 // Comments can be deleted by the thread owner or comment owner
2780 if (($item['id'] != $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2781 $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2782 if (!Item::exists($condition)) {
2783 logger("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2788 if ($item["deleted"]) {
2792 logger('deleting item '.$item['id'].' uri='.$uri, LOGGER_DEBUG);
2794 Item::delete(['id' => $item['id']]);
2798 * @brief Imports a DFRN message
2800 * @param string $xml The DFRN message
2801 * @param array $importer Record of the importer user mixed with contact of the content
2802 * @param bool $sort_by_date Is used when feeds are polled
2803 * @return integer Import status
2804 * @todo set proper type-hints
2806 public static function import($xml, $importer, $sort_by_date = false)
2812 $doc = new DOMDocument();
2813 @$doc->loadXML($xml);
2815 $xpath = new DOMXPath($doc);
2816 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2817 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2818 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2819 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2820 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2821 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2822 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2823 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2824 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2825 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2828 $header["uid"] = $importer["importer_uid"];
2829 $header["network"] = NETWORK_DFRN;
2830 $header["type"] = "remote";
2831 $header["wall"] = 0;
2832 $header["origin"] = 0;
2833 $header["contact-id"] = $importer["id"];
2835 // Update the contact table if the data has changed
2837 // The "atom:author" is only present in feeds
2838 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2839 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2842 // Only the "dfrn:owner" in the head section contains all data
2843 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2844 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2847 logger("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2849 // is it a public forum? Private forums aren't exposed with this method
2850 $forum = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:community/text()"));
2852 // The account type is new since 3.5.1
2853 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2854 $accounttype = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:account_type/text()"));
2856 if ($accounttype != $importer["contact-type"]) {
2857 dba::update('contact', ['contact-type' => $accounttype], ['id' => $importer["id"]]);
2859 // A forum contact can either have set "forum" or "prv" - but not both
2860 if (($accounttype == ACCOUNT_TYPE_COMMUNITY) && (($forum != $importer["forum"]) || ($forum == $importer["prv"]))) {
2861 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer["id"]];
2862 dba::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2864 } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
2865 $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2866 dba::update('contact', ['forum' => $forum], $condition);
2870 // We are processing relocations even if we are ignoring a contact
2871 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2872 foreach ($relocations as $relocation) {
2873 self::processRelocation($xpath, $relocation, $importer);
2876 if (($importer["uid"] != 0) && !$importer["readonly"]) {
2877 $mails = $xpath->query("/atom:feed/dfrn:mail");
2878 foreach ($mails as $mail) {
2879 self::processMail($xpath, $mail, $importer);
2882 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2883 foreach ($suggestions as $suggestion) {
2884 self::processSuggestion($xpath, $suggestion, $importer);
2888 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2889 foreach ($deletions as $deletion) {
2890 self::processDeletion($xpath, $deletion, $importer);
2893 if (!$sort_by_date) {
2894 $entries = $xpath->query("/atom:feed/atom:entry");
2895 foreach ($entries as $entry) {
2896 self::processEntry($header, $xpath, $entry, $importer, $xml);
2900 $entries = $xpath->query("/atom:feed/atom:entry");
2901 foreach ($entries as $entry) {
2902 $created = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2903 $newentries[strtotime($created)] = $entry;
2906 // Now sort after the publishing date
2909 foreach ($newentries as $entry) {
2910 self::processEntry($header, $xpath, $entry, $importer, $xml);
2913 logger("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2919 * @param string $contact_nick contact nickname
2921 public static function autoRedir(App $a, $contact_nick)
2924 if (x($_REQUEST, 'redir') && intval($_REQUEST['redir'])) {
2928 if ((! $contact_nick) || ($contact_nick === $a->user['nickname'])) {
2933 // We need to find out if $contact_nick is a user on this hub, and if so, if I
2934 // am a contact of that user. However, that user may have other contacts with the
2935 // same nickname as me on other hubs or other networks. Exclude these by requiring
2936 // that the contact have a local URL. I will be the only person with my nickname at
2937 // this URL, so if a result is found, then I am a contact of the $contact_nick user.
2939 // We also have to make sure that I'm a legitimate contact--I'm not blocked or pending.
2941 $baseurl = System::baseUrl();
2942 $domain_st = strpos($baseurl, "://");
2943 if ($domain_st === false) {
2946 $baseurl = substr($baseurl, $domain_st + 3);
2947 $nurl = normalise_link($baseurl);
2949 /// @todo Why is there a query for "url" *and* "nurl"? Especially this normalising is strange.
2950 $r = q("SELECT `id` FROM `contact` WHERE `uid` = (SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1)
2951 AND `nick` = '%s' AND NOT `self` AND (`url` LIKE '%%%s%%' OR `nurl` LIKE '%%%s%%') AND NOT `blocked` AND NOT `pending` LIMIT 1",
2952 dbesc($contact_nick),
2953 dbesc($a->user['nickname']),
2957 if ((! DBM::is_result($r)) || $r[0]['id'] == remote_user()) {
2961 $r = q("SELECT * FROM contact WHERE nick = '%s'
2962 AND network = '%s' AND uid = %d AND url LIKE '%%%s%%' LIMIT 1",
2963 dbesc($contact_nick),
2964 dbesc(NETWORK_DFRN),
2965 intval(local_user()),
2968 if (! DBM::is_result($r)) {
2974 $dfrn_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2976 if ($r[0]['duplex'] && $r[0]['issued-id']) {
2977 $orig_id = $r[0]['issued-id'];
2978 $dfrn_id = '1:' . $orig_id;
2980 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
2981 $orig_id = $r[0]['dfrn-id'];
2982 $dfrn_id = '0:' . $orig_id;
2985 // ensure that we've got a valid ID. There may be some edge cases with forums and non-duplex mode
2986 // that may have triggered some of the "went to {profile/intro} and got an RSS feed" issues
2988 if (strlen($dfrn_id) < 3) {
2992 $sec = random_string();
2994 dba::insert('profile_check', ['uid' => local_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id, 'sec' => $sec, 'expire' => time() + 45]);
2996 $url = curPageURL();
2998 logger('auto_redir: ' . $r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
2999 $dest = (($url) ? '&destination_url=' . $url : '');
3000 goaway($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
3001 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest);
3008 * @brief Returns the activity verb
3010 * @param array $item Item array
3012 * @return string activity verb
3014 private static function constructVerb(array $item)
3016 if ($item['verb']) {
3017 return $item['verb'];
3019 return ACTIVITY_POST;
3022 private static function tgroupCheck($uid, $item)
3026 // check that the message originated elsewhere and is a top-level post
3028 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['parent-uri'])) {
3032 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
3035 if (!DBM::is_result($u)) {
3039 $community_page = ($u[0]['page-flags'] == PAGE_COMMUNITY);
3040 $prvgroup = ($u[0]['page-flags'] == PAGE_PRVGROUP);
3042 $link = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
3045 * Diaspora uses their own hardwired link URL in @-tags
3046 * instead of the one we supply with webfinger
3048 $dlink = normalise_link(System::baseUrl() . '/u/' . $u[0]['nickname']);
3050 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
3052 foreach ($matches as $mtch) {
3053 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
3055 logger('mention found: ' . $mtch[2]);
3064 return $community_page || $prvgroup;
3068 * This function returns true if $update has an edited timestamp newer
3069 * than $existing, i.e. $update contains new data which should override
3070 * what's already there. If there is no timestamp yet, the update is
3071 * assumed to be newer. If the update has no timestamp, the existing
3072 * item is assumed to be up-to-date. If the timestamps are equal it
3073 * assumes the update has been seen before and should be ignored.
3076 private static function isEditedTimestampNewer($existing, $update)
3078 if (!x($existing, 'edited') || !$existing['edited']) {
3081 if (!x($update, 'edited') || !$update['edited']) {
3085 $existing_edited = DateTimeFormat::utc($existing['edited']);
3086 $update_edited = DateTimeFormat::utc($update['edited']);
3088 return (strcmp($existing_edited, $update_edited) < 0);