3 * @file include/dfrn.php
4 * @brief The implementation of the dfrn protocol
6 * @see https://github.com/friendica/friendica/wiki/Protocol and
7 * https://github.com/friendica/friendica/blob/master/spec/dfrn2.pdf
9 namespace Friendica\Protocol;
12 use Friendica\Content\OEmbed;
13 use Friendica\Content\Text\BBCode;
14 use Friendica\Content\Text\HTML;
15 use Friendica\Core\Addon;
16 use Friendica\Core\Config;
17 use Friendica\Core\L10n;
18 use Friendica\Core\System;
19 use Friendica\Core\Worker;
20 use Friendica\Database\DBM;
21 use Friendica\Model\Contact;
22 use Friendica\Model\Event;
23 use Friendica\Model\GContact;
24 use Friendica\Model\Group;
25 use Friendica\Model\Item;
26 use Friendica\Model\Profile;
27 use Friendica\Model\User;
28 use Friendica\Object\Image;
29 use Friendica\Protocol\OStatus;
30 use Friendica\Util\Crypto;
31 use Friendica\Util\DateTimeFormat;
32 use Friendica\Util\Network;
33 use Friendica\Util\XML;
34 use Friendica\Protocol\Diaspora;
39 use HTMLPurifier_Config;
41 require_once 'boot.php';
42 require_once 'include/dba.php';
43 require_once "include/enotify.php";
44 require_once "include/items.php";
45 require_once "include/text.php";
48 * @brief This class contain functions to create and send DFRN XML files
53 const TOP_LEVEL = 0; // Top level posting
54 const REPLY = 1; // Regular reply that is stored locally
55 const REPLY_RC = 2; // Reply that will be relayed
58 * @brief Generates the atom entries for delivery.php
60 * This function is used whenever content is transmitted via DFRN.
62 * @param array $items Item elements
63 * @param array $owner Owner record
65 * @return string DFRN entries
66 * @todo Find proper type-hints
68 public static function entries($items, $owner)
70 $doc = new DOMDocument('1.0', 'utf-8');
71 $doc->formatOutput = true;
73 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
75 if (! count($items)) {
76 return trim($doc->saveXML());
79 foreach ($items as $item) {
80 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
81 $root->appendChild($entry);
84 return trim($doc->saveXML());
88 * @brief Generate an atom feed for the given user
90 * This function is called when another server is pulling data from the user feed.
92 * @param string $dfrn_id DFRN ID from the requesting party
93 * @param string $owner_nick Owner nick name
94 * @param string $last_update Date of the last update
95 * @param int $direction Can be -1, 0 or 1.
96 * @param boolean $onlyheader Output only the header without content? (Default is "no")
98 * @return string DFRN feed entries
100 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false)
104 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
105 $public_feed = (($dfrn_id) ? false : true);
106 $starred = false; // not yet implemented, possible security issues
109 if ($public_feed && $a->argc > 2) {
110 for ($x = 2; $x < $a->argc; $x++) {
111 if ($a->argv[$x] == 'converse') {
114 if ($a->argv[$x] == 'starred') {
117 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
118 $category = $a->argv[$x+1];
123 // default permissions - anonymous user
125 $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = '' ";
128 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
129 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
130 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
134 if (! DBM::is_result($r)) {
135 logger(sprintf('No contact found for nickname=%d', $owner_nick), LOGGER_WARNING);
140 $owner_id = $owner['uid'];
141 $owner_nick = $owner['nickname'];
143 $sql_post_table = "";
145 if (! $public_feed) {
147 switch ($direction) {
149 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
153 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
154 $my_id = '1:' . $dfrn_id;
157 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
158 $my_id = '0:' . $dfrn_id;
166 "SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
170 if (! DBM::is_result($r)) {
171 logger(sprintf('No contact found for uid=%d', $owner_id), LOGGER_WARNING);
176 include_once 'include/security.php';
177 $groups = Group::getIdsByContactId($contact['id']);
179 if (count($groups)) {
180 for ($x = 0; $x < count($groups); $x ++) {
181 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
184 $gs = implode('|', $groups);
186 $gs = '<<>>' ; // Impossible to match
189 $sql_extra = sprintf(
191 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
192 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
193 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
194 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
196 intval($contact['id']),
197 intval($contact['id']),
209 if (! strlen($last_update)) {
210 $last_update = 'now -30 days';
213 if (isset($category)) {
214 $sql_post_table = sprintf(
215 "INNER JOIN (SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d ORDER BY `tid` DESC) AS `term` ON `item`.`id` = `term`.`oid` ",
216 dbesc(protect_sprintf($category)),
217 intval(TERM_OBJ_POST),
218 intval(TERM_CATEGORY),
221 //$sql_extra .= file_tag_file_query('item',$category,'category');
224 if ($public_feed && ! $converse) {
225 $sql_extra .= " AND `contact`.`self` = 1 ";
228 $check_date = DateTimeFormat::utc($last_update);
232 FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
233 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
234 WHERE `item`.`uid` = %d AND `item`.`wall` AND `item`.`changed` > '%s'
236 ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
243 foreach ($r as $item) {
244 $ids[] = $item['id'];
248 $ret = Item::select(Item::DELIVER_FIELDLIST, ['id' => $ids]);
249 $items = Item::inArray($ret);
255 * Will check further below if this actually returned results.
256 * We will provide an empty feed if that is the case.
259 $doc = new DOMDocument('1.0', 'utf-8');
260 $doc->formatOutput = true;
262 $alternatelink = $owner['url'];
264 if (isset($category)) {
265 $alternatelink .= "/category/".$category;
269 $author = "dfrn:owner";
274 $root = self::addHeader($doc, $owner, $author, $alternatelink, true);
276 /// @TODO This hook can't work anymore
277 // Addon::callHooks('atom_feed', $atom);
279 if (!DBM::is_result($items) || $onlyheader) {
280 $atom = trim($doc->saveXML());
282 Addon::callHooks('atom_feed_end', $atom);
287 foreach ($items as $item) {
288 // prevent private email from leaking.
289 if ($item['network'] == NETWORK_MAIL) {
293 // public feeds get html, our own nodes use bbcode
297 // catch any email that's in a public conversation and make sure it doesn't leak
298 if ($item['private']) {
305 $entry = self::entry($doc, $type, $item, $owner, true);
306 $root->appendChild($entry);
309 $atom = trim($doc->saveXML());
311 Addon::callHooks('atom_feed_end', $atom);
317 * @brief Generate an atom entry for a given item id
319 * @param int $item_id The item id
320 * @param boolean $conversation Show the conversation. If false show the single post.
322 * @return string DFRN feed entry
324 public static function itemFeed($item_id, $conversation = false)
327 $condition = ['parent' => $item_id];
329 $condition = ['id' => $item_id];
332 $ret = Item::select(Item::DELIVER_FIELDLIST, $condition);
333 $items = Item::inArray($ret);
334 if (!DBM::is_result($items)) {
340 if ($item['uid'] != 0) {
341 $owner = User::getOwnerDataById($item['uid']);
346 $owner = ['uid' => 0, 'nick' => 'feed-item'];
349 $doc = new DOMDocument('1.0', 'utf-8');
350 $doc->formatOutput = true;
354 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
355 $doc->appendChild($root);
357 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
358 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
359 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
360 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
361 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
362 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
363 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
364 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
365 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
367 //$root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
369 foreach ($items as $item) {
370 $entry = self::entry($doc, $type, $item, $owner, true, 0);
371 $root->appendChild($entry);
374 $root = self::entry($doc, $type, $item, $owner, true, 0, true);
377 $atom = trim($doc->saveXML());
382 * @brief Create XML text for DFRN mails
384 * @param array $item message elements
385 * @param array $owner Owner record
387 * @return string DFRN mail
388 * @todo Find proper type-hints
390 public static function mail($item, $owner)
392 $doc = new DOMDocument('1.0', 'utf-8');
393 $doc->formatOutput = true;
395 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
397 $mail = $doc->createElement("dfrn:mail");
398 $sender = $doc->createElement("dfrn:sender");
400 XML::addElement($doc, $sender, "dfrn:name", $owner['name']);
401 XML::addElement($doc, $sender, "dfrn:uri", $owner['url']);
402 XML::addElement($doc, $sender, "dfrn:avatar", $owner['thumb']);
404 $mail->appendChild($sender);
406 XML::addElement($doc, $mail, "dfrn:id", $item['uri']);
407 XML::addElement($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
408 XML::addElement($doc, $mail, "dfrn:sentdate", DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
409 XML::addElement($doc, $mail, "dfrn:subject", $item['title']);
410 XML::addElement($doc, $mail, "dfrn:content", $item['body']);
412 $root->appendChild($mail);
414 return trim($doc->saveXML());
418 * @brief Create XML text for DFRN friend suggestions
420 * @param array $item suggestion elements
421 * @param array $owner Owner record
423 * @return string DFRN suggestions
424 * @todo Find proper type-hints
426 public static function fsuggest($item, $owner)
428 $doc = new DOMDocument('1.0', 'utf-8');
429 $doc->formatOutput = true;
431 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
433 $suggest = $doc->createElement("dfrn:suggest");
435 XML::addElement($doc, $suggest, "dfrn:url", $item['url']);
436 XML::addElement($doc, $suggest, "dfrn:name", $item['name']);
437 XML::addElement($doc, $suggest, "dfrn:photo", $item['photo']);
438 XML::addElement($doc, $suggest, "dfrn:request", $item['request']);
439 XML::addElement($doc, $suggest, "dfrn:note", $item['note']);
441 $root->appendChild($suggest);
443 return trim($doc->saveXML());
447 * @brief Create XML text for DFRN relocations
449 * @param array $owner Owner record
450 * @param int $uid User ID
452 * @return string DFRN relocations
453 * @todo Find proper type-hints
455 public static function relocate($owner, $uid)
458 /* get site pubkey. this could be a new installation with no site keys*/
459 $pubkey = Config::get('system', 'site_pubkey');
461 $res = Crypto::newKeypair(1024);
462 Config::set('system', 'site_prvkey', $res['prvkey']);
463 Config::set('system', 'site_pubkey', $res['pubkey']);
467 "SELECT `resource-id` , `scale`, type FROM `photo`
468 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;",
472 $ext = Image::supportedTypes();
474 foreach ($rp as $p) {
475 $photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
479 $doc = new DOMDocument('1.0', 'utf-8');
480 $doc->formatOutput = true;
482 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
484 $relocate = $doc->createElement("dfrn:relocate");
486 XML::addElement($doc, $relocate, "dfrn:url", $owner['url']);
487 XML::addElement($doc, $relocate, "dfrn:name", $owner['name']);
488 XML::addElement($doc, $relocate, "dfrn:addr", $owner['addr']);
489 XML::addElement($doc, $relocate, "dfrn:avatar", $owner['avatar']);
490 XML::addElement($doc, $relocate, "dfrn:photo", $photos[4]);
491 XML::addElement($doc, $relocate, "dfrn:thumb", $photos[5]);
492 XML::addElement($doc, $relocate, "dfrn:micro", $photos[6]);
493 XML::addElement($doc, $relocate, "dfrn:request", $owner['request']);
494 XML::addElement($doc, $relocate, "dfrn:confirm", $owner['confirm']);
495 XML::addElement($doc, $relocate, "dfrn:notify", $owner['notify']);
496 XML::addElement($doc, $relocate, "dfrn:poll", $owner['poll']);
497 XML::addElement($doc, $relocate, "dfrn:sitepubkey", Config::get('system', 'site_pubkey'));
499 $root->appendChild($relocate);
501 return trim($doc->saveXML());
505 * @brief Adds the header elements for the DFRN protocol
507 * @param object $doc XML document
508 * @param array $owner Owner record
509 * @param string $authorelement Element name for the author
510 * @param string $alternatelink link to profile or category
511 * @param bool $public Is it a header for public posts?
513 * @return object XML root object
514 * @todo Find proper type-hints
516 private static function addHeader($doc, $owner, $authorelement, $alternatelink = "", $public = false)
519 if ($alternatelink == "") {
520 $alternatelink = $owner['url'];
523 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
524 $doc->appendChild($root);
526 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
527 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
528 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
529 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
530 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
531 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
532 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
533 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
534 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
536 XML::addElement($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
537 XML::addElement($doc, $root, "title", $owner["name"]);
539 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION];
540 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
542 $attributes = ["rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/"];
543 XML::addElement($doc, $root, "link", "", $attributes);
545 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $alternatelink];
546 XML::addElement($doc, $root, "link", "", $attributes);
550 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
551 OStatus::hublinks($doc, $root, $owner["nick"]);
553 $attributes = ["rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
554 XML::addElement($doc, $root, "link", "", $attributes);
556 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
557 XML::addElement($doc, $root, "link", "", $attributes);
559 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
560 XML::addElement($doc, $root, "link", "", $attributes);
563 // For backward compatibility we keep this element
564 if ($owner['page-flags'] == PAGE_COMMUNITY) {
565 XML::addElement($doc, $root, "dfrn:community", 1);
568 // The former element is replaced by this one
569 XML::addElement($doc, $root, "dfrn:account_type", $owner["account-type"]);
571 /// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
573 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
575 $author = self::addAuthor($doc, $owner, $authorelement, $public);
576 $root->appendChild($author);
582 * @brief Adds the author element in the header for the DFRN protocol
584 * @param object $doc XML document
585 * @param array $owner Owner record
586 * @param string $authorelement Element name for the author
587 * @param boolean $public boolean
589 * @return object XML author object
590 * @todo Find proper type-hints
592 private static function addAuthor($doc, $owner, $authorelement, $public)
594 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
596 "SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
597 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
598 intval($owner['uid'])
600 if (DBM::is_result($r)) {
606 $author = $doc->createElement($authorelement);
608 $namdate = DateTimeFormat::utc($owner['name-date'].'+00:00', DateTimeFormat::ATOM);
609 $uridate = DateTimeFormat::utc($owner['uri-date'].'+00:00', DateTimeFormat::ATOM);
610 $picdate = DateTimeFormat::utc($owner['avatar-date'].'+00:00', DateTimeFormat::ATOM);
614 if (!$public || !$hidewall) {
615 $attributes = ["dfrn:updated" => $namdate];
618 XML::addElement($doc, $author, "name", $owner["name"], $attributes);
619 XML::addElement($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
620 XML::addElement($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
622 $attributes = ["rel" => "photo", "type" => "image/jpeg",
623 "media:width" => 175, "media:height" => 175, "href" => $owner['photo']];
625 if (!$public || !$hidewall) {
626 $attributes["dfrn:updated"] = $picdate;
629 XML::addElement($doc, $author, "link", "", $attributes);
631 $attributes["rel"] = "avatar";
632 XML::addElement($doc, $author, "link", "", $attributes);
635 XML::addElement($doc, $author, "dfrn:hide", "true");
638 // The following fields will only be generated if the data isn't meant for a public feed
643 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
646 XML::addElement($doc, $author, "dfrn:birthday", $birthday);
649 // Only show contact details when we are allowed to
651 "SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
652 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
653 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
655 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
656 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
657 intval($owner['uid'])
659 if (DBM::is_result($r)) {
662 XML::addElement($doc, $author, "poco:displayName", $profile["name"]);
663 XML::addElement($doc, $author, "poco:updated", $namdate);
665 if (trim($profile["dob"]) > '0001-01-01') {
666 XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
669 XML::addElement($doc, $author, "poco:note", $profile["about"]);
670 XML::addElement($doc, $author, "poco:preferredUsername", $profile["nickname"]);
672 $savetz = date_default_timezone_get();
673 date_default_timezone_set($profile["timezone"]);
674 XML::addElement($doc, $author, "poco:utcOffset", date("P"));
675 date_default_timezone_set($savetz);
677 if (trim($profile["homepage"]) != "") {
678 $urls = $doc->createElement("poco:urls");
679 XML::addElement($doc, $urls, "poco:type", "homepage");
680 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
681 XML::addElement($doc, $urls, "poco:primary", "true");
682 $author->appendChild($urls);
685 if (trim($profile["pub_keywords"]) != "") {
686 $keywords = explode(",", $profile["pub_keywords"]);
688 foreach ($keywords as $keyword) {
689 XML::addElement($doc, $author, "poco:tags", trim($keyword));
693 if (trim($profile["xmpp"]) != "") {
694 $ims = $doc->createElement("poco:ims");
695 XML::addElement($doc, $ims, "poco:type", "xmpp");
696 XML::addElement($doc, $ims, "poco:value", $profile["xmpp"]);
697 XML::addElement($doc, $ims, "poco:primary", "true");
698 $author->appendChild($ims);
701 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
702 $element = $doc->createElement("poco:address");
704 XML::addElement($doc, $element, "poco:formatted", Profile::formatLocation($profile));
706 if (trim($profile["locality"]) != "") {
707 XML::addElement($doc, $element, "poco:locality", $profile["locality"]);
710 if (trim($profile["region"]) != "") {
711 XML::addElement($doc, $element, "poco:region", $profile["region"]);
714 if (trim($profile["country-name"]) != "") {
715 XML::addElement($doc, $element, "poco:country", $profile["country-name"]);
718 $author->appendChild($element);
726 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
728 * @param object $doc XML document
729 * @param string $element Element name for the author
730 * @param string $contact_url Link of the contact
731 * @param array $item Item elements
733 * @return object XML author object
734 * @todo Find proper type-hints
736 private static function addEntryAuthor($doc, $element, $contact_url, $item)
738 $contact = Contact::getDetailsByURL($contact_url, $item["uid"]);
740 $author = $doc->createElement($element);
741 XML::addElement($doc, $author, "name", $contact["name"]);
742 XML::addElement($doc, $author, "uri", $contact["url"]);
743 XML::addElement($doc, $author, "dfrn:handle", $contact["addr"]);
746 /// - Check real image type and image size
747 /// - Check which of these boths elements we should use
750 "type" => "image/jpeg",
752 "media:height" => 80,
753 "href" => $contact["photo"]];
754 XML::addElement($doc, $author, "link", "", $attributes);
758 "type" => "image/jpeg",
760 "media:height" => 80,
761 "href" => $contact["photo"]];
762 XML::addElement($doc, $author, "link", "", $attributes);
768 * @brief Adds the activity elements
770 * @param object $doc XML document
771 * @param string $element Element name for the activity
772 * @param string $activity activity value
774 * @return object XML activity object
775 * @todo Find proper type-hints
777 private static function createActivity($doc, $element, $activity)
780 $entry = $doc->createElement($element);
782 $r = XML::parseString($activity, false);
788 XML::addElement($doc, $entry, "activity:object-type", $r->type);
792 XML::addElement($doc, $entry, "id", $r->id);
796 XML::addElement($doc, $entry, "title", $r->title);
800 if (substr($r->link, 0, 1) == '<') {
801 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
802 $r->link = str_replace('&', '&', $r->link);
805 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
807 // XML does need a single element as root element so we add a dummy element here
808 $data = XML::parseString("<dummy>" . $r->link . "</dummy>", false);
809 if (is_object($data)) {
810 foreach ($data->link as $link) {
812 foreach ($link->attributes() as $parameter => $value) {
813 $attributes[$parameter] = $value;
815 XML::addElement($doc, $entry, "link", "", $attributes);
819 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
820 XML::addElement($doc, $entry, "link", "", $attributes);
824 XML::addElement($doc, $entry, "content", BBCode::convert($r->content), ["type" => "html"]);
834 * @brief Adds the elements for attachments
836 * @param object $doc XML document
837 * @param object $root XML root
838 * @param array $item Item element
840 * @return object XML attachment object
841 * @todo Find proper type-hints
843 private static function getAttachment($doc, $root, $item)
845 $arr = explode('[/attach],', $item['attach']);
847 foreach ($arr as $r) {
849 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
851 $attributes = ["rel" => "enclosure",
852 "href" => $matches[1],
853 "type" => $matches[3]];
855 if (intval($matches[2])) {
856 $attributes["length"] = intval($matches[2]);
859 if (trim($matches[4]) != "") {
860 $attributes["title"] = trim($matches[4]);
863 XML::addElement($doc, $root, "link", "", $attributes);
870 * @brief Adds the "entry" elements for the DFRN protocol
872 * @param object $doc XML document
873 * @param string $type "text" or "html"
874 * @param array $item Item element
875 * @param array $owner Owner record
876 * @param bool $comment Trigger the sending of the "comment" element
877 * @param int $cid Contact ID of the recipient
878 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
880 * @return object XML entry object
881 * @todo Find proper type-hints
883 private static function entry($doc, $type, array $item, array $owner, $comment = false, $cid = 0, $single = false)
887 if (!$item['parent']) {
891 if ($item['deleted']) {
892 $attributes = ["ref" => $item['uri'], "when" => DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM)];
893 return XML::createElement($doc, "at:deleted-entry", "", $attributes);
897 $entry = $doc->createElement("entry");
899 $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry');
900 $doc->appendChild($entry);
902 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
903 $entry->setAttribute("xmlns:at", NAMESPACE_TOMB);
904 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
905 $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
906 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
907 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
908 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
909 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
910 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
913 if ($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid']) {
914 $body = Item::fixPrivatePhotos($item['body'], $owner['uid'], $item, $cid);
916 $body = $item['body'];
919 // Remove the abstract element. It is only locally important.
920 $body = BBCode::stripAbstract($body);
923 if ($type == 'html') {
926 if ($item['title'] != "") {
927 $htmlbody = "[b]" . $item['title'] . "[/b]\n\n" . $htmlbody;
930 $htmlbody = BBCode::convert($htmlbody, false, 7);
933 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
934 $entry->appendChild($author);
936 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
937 $entry->appendChild($dfrnowner);
939 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
940 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
941 $parent = Item::selectFirst(['guid', 'plink'], ['uri' => $parent_item, 'uid' => $item['uid']]);
942 $attributes = ["ref" => $parent_item, "type" => "text/html",
943 "href" => $parent['plink'],
944 "dfrn:diaspora_guid" => $parent['guid']];
945 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
948 // Add conversation data. This is used for OStatus
949 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
950 $conversation_uri = $conversation_href;
952 if (isset($parent_item)) {
953 $conversation = dba::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $item['parent-uri']]);
954 if (DBM::is_result($conversation)) {
955 if ($r['conversation-uri'] != '') {
956 $conversation_uri = $conversation['conversation-uri'];
958 if ($r['conversation-href'] != '') {
959 $conversation_href = $conversation['conversation-href'];
965 "href" => $conversation_href,
966 "ref" => $conversation_uri];
968 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
970 XML::addElement($doc, $entry, "id", $item["uri"]);
971 XML::addElement($doc, $entry, "title", $item["title"]);
973 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"] . "+00:00", DateTimeFormat::ATOM));
974 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"] . "+00:00", DateTimeFormat::ATOM));
976 // "dfrn:env" is used to read the content
977 XML::addElement($doc, $entry, "dfrn:env", base64url_encode($body, true));
979 // The "content" field is not read by the receiver. We could remove it when the type is "text"
980 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
981 XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
983 // We save this value in "plink". Maybe we should read it from there as well?
989 ["rel" => "alternate", "type" => "text/html",
990 "href" => System::baseUrl() . "/display/" . $item["guid"]]
993 // "comment-allow" is some old fashioned stuff for old Friendica versions.
994 // It is included in the rewritten code for completeness
996 XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
999 if ($item['location']) {
1000 XML::addElement($doc, $entry, "dfrn:location", $item['location']);
1003 if ($item['coord']) {
1004 XML::addElement($doc, $entry, "georss:point", $item['coord']);
1007 if (($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])) {
1008 XML::addElement($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
1011 if ($item['extid']) {
1012 XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
1015 if ($item['bookmark']) {
1016 XML::addElement($doc, $entry, "dfrn:bookmark", "true");
1020 XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
1023 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
1025 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
1026 // It is needed for relayed comments to Diaspora.
1027 if ($item['signed_text']) {
1028 $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer']]));
1029 XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
1032 XML::addElement($doc, $entry, "activity:verb", self::constructVerb($item));
1034 if ($item['object-type'] != "") {
1035 XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
1036 } elseif ($item['id'] == $item['parent']) {
1037 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1039 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
1042 $actobj = self::createActivity($doc, "activity:object", $item['object']);
1044 $entry->appendChild($actobj);
1047 $actarg = self::createActivity($doc, "activity:target", $item['target']);
1049 $entry->appendChild($actarg);
1052 $tags = Item::getFeedTags($item);
1054 /// @TODO Combine this with similar below if() block?
1056 foreach ($tags as $t) {
1057 if (($type != 'html') || ($t[0] != "@")) {
1058 XML::addElement($doc, $entry, "category", "", ["scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]]);
1064 foreach ($tags as $t) {
1066 $mentioned[$t[1]] = $t[1];
1071 foreach ($mentioned as $mention) {
1073 "SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1074 intval($owner["uid"]),
1075 dbesc(normalise_link($mention))
1078 if (DBM::is_result($r) && ($r[0]["forum"] || $r[0]["prv"])) {
1084 ["rel" => "mentioned",
1085 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1094 ["rel" => "mentioned",
1095 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1101 self::getAttachment($doc, $entry, $item);
1107 * @brief encrypts data via AES
1109 * @param string $data The data that is to be encrypted
1110 * @param string $key The AES key
1112 * @return string encrypted data
1114 private static function aesEncrypt($data, $key)
1116 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1120 * @brief decrypts data via AES
1122 * @param string $encrypted The encrypted data
1123 * @param string $key The AES key
1125 * @return string decrypted data
1127 public static function aesDecrypt($encrypted, $key)
1129 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1133 * @brief Delivers the atom content to the contacts
1135 * @param array $owner Owner record
1136 * @param array $contact Contact record of the receiver
1137 * @param string $atom Content that will be transmitted
1138 * @param bool $dissolve (to be documented)
1140 * @return int Deliver status. Negative values mean an error.
1141 * @todo Add array type-hint for $owner, $contact
1143 public static function deliver($owner, $contact, $atom, $dissolve = false)
1147 // At first try the Diaspora transport layer
1148 $ret = self::transmit($owner, $contact, $atom);
1150 logger('Delivery via Diaspora transport layer was successful with status ' . $ret);
1154 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1156 if ($contact['duplex'] && $contact['dfrn-id']) {
1157 $idtosend = '0:' . $orig_id;
1159 if ($contact['duplex'] && $contact['issued-id']) {
1160 $idtosend = '1:' . $orig_id;
1163 $rino = Config::get('system', 'rino_encrypt');
1164 $rino = intval($rino);
1166 logger("Local rino version: ". $rino, LOGGER_DEBUG);
1168 $ssl_val = intval(Config::get('system', 'ssl_policy'));
1172 case SSL_POLICY_FULL:
1173 $ssl_policy = 'full';
1175 case SSL_POLICY_SELFSIGN:
1176 $ssl_policy = 'self';
1178 case SSL_POLICY_NONE:
1180 $ssl_policy = 'none';
1184 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1186 logger('dfrn_deliver: ' . $url);
1188 $ret = Network::curl($url);
1190 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1191 Contact::markForArchival($contact);
1192 return -2; // timed out
1195 $xml = $ret['body'];
1197 $curl_stat = $a->get_curl_code();
1198 if (empty($curl_stat)) {
1199 Contact::markForArchival($contact);
1200 return -3; // timed out
1203 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1206 Contact::markForArchival($contact);
1210 if (strpos($xml, '<?xml') === false) {
1211 logger('dfrn_deliver: no valid XML returned');
1212 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1213 Contact::markForArchival($contact);
1217 $res = XML::parseString($xml);
1219 if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
1220 Contact::markForArchival($contact);
1221 return ($res->status ? $res->status : 3);
1225 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1226 $challenge = hex2bin((string) $res->challenge);
1227 $perm = (($res->perm) ? $res->perm : null);
1228 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1229 $rino_remote_version = intval($res->rino);
1230 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1232 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
1234 if ($owner['page-flags'] == PAGE_PRVGROUP) {
1238 $final_dfrn_id = '';
1241 if ((($perm == 'rw') && (! intval($contact['writable'])))
1242 || (($perm == 'r') && (intval($contact['writable'])))
1245 "update contact set writable = %d where id = %d",
1246 intval(($perm == 'rw') ? 1 : 0),
1247 intval($contact['id'])
1249 $contact['writable'] = (string) 1 - intval($contact['writable']);
1253 if (($contact['duplex'] && strlen($contact['pubkey']))
1254 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1255 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
1257 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
1258 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
1260 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
1261 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
1264 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1266 if (strpos($final_dfrn_id, ':') == 1) {
1267 $final_dfrn_id = substr($final_dfrn_id, 2);
1270 if ($final_dfrn_id != $orig_id) {
1271 logger('dfrn_deliver: wrong dfrn_id.');
1272 // did not decode properly - cannot trust this site
1273 Contact::markForArchival($contact);
1277 $postvars['dfrn_id'] = $idtosend;
1278 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1280 $postvars['dissolve'] = '1';
1283 if ((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1284 $postvars['data'] = $atom;
1285 $postvars['perm'] = 'rw';
1287 $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
1288 $postvars['perm'] = 'r';
1291 $postvars['ssl_policy'] = $ssl_policy;
1294 $postvars['page'] = $page;
1298 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1299 logger('rino version: '. $rino_remote_version);
1301 switch ($rino_remote_version) {
1303 $key = openssl_random_pseudo_bytes(16);
1304 $data = self::aesEncrypt($postvars['data'], $key);
1307 logger("rino: invalid requested version '$rino_remote_version'");
1308 Contact::markForArchival($contact);
1312 $postvars['rino'] = $rino_remote_version;
1313 $postvars['data'] = bin2hex($data);
1315 if ($dfrn_version >= 2.1) {
1316 if (($contact['duplex'] && strlen($contact['pubkey']))
1317 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1318 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
1320 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1322 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1325 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1326 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1328 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1332 logger('md5 rawkey ' . md5($postvars['key']));
1334 $postvars['key'] = bin2hex($postvars['key']);
1338 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), LOGGER_DATA);
1340 $xml = Network::post($contact['notify'], $postvars);
1342 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1344 $curl_stat = $a->get_curl_code();
1345 if (empty($curl_stat) || empty($xml)) {
1346 Contact::markForArchival($contact);
1347 return -9; // timed out
1350 if (($curl_stat == 503) && stristr($a->get_curl_headers(), 'retry-after')) {
1351 Contact::markForArchival($contact);
1355 if (strpos($xml, '<?xml') === false) {
1356 logger('dfrn_deliver: phase 2: no valid XML returned');
1357 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1358 Contact::markForArchival($contact);
1362 $res = XML::parseString($xml);
1364 if (!isset($res->status)) {
1365 Contact::markForArchival($contact);
1369 // Possibly old servers had returned an empty value when everything was okay
1370 if (empty($res->status)) {
1374 if (!empty($res->message)) {
1375 logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1378 if (($res->status >= 200) && ($res->status <= 299)) {
1379 Contact::unmarkForArchival($contact);
1382 return intval($res->status);
1386 * @brief Transmits atom content to the contacts via the Diaspora transport layer
1388 * @param array $owner Owner record
1389 * @param array $contact Contact record of the receiver
1390 * @param string $atom Content that will be transmitted
1392 * @return int Deliver status. Negative values mean an error.
1394 public static function transmit($owner, $contact, $atom, $public_batch = false)
1398 if (!$public_batch) {
1399 if (empty($contact['addr'])) {
1400 logger('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.');
1401 if (Contact::updateFromProbe($contact['id'])) {
1402 $new_contact = dba::selectFirst('contact', ['addr'], ['id' => $contact['id']]);
1403 $contact['addr'] = $new_contact['addr'];
1406 if (empty($contact['addr'])) {
1407 logger('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
1408 Contact::markForArchival($contact);
1413 $fcontact = Diaspora::personByHandle($contact['addr']);
1414 if (empty($fcontact)) {
1415 logger('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
1416 Contact::markForArchival($contact);
1419 $pubkey = $fcontact['pubkey'];
1424 $envelope = Diaspora::buildMessage($atom, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
1426 // Create the endpoint for public posts. This is some WIP and should later be added to the probing
1427 if ($public_batch && empty($contact["batch"])) {
1428 $parts = parse_url($contact["notify"]);
1429 $path_parts = explode('/', $parts['path']);
1430 array_pop($path_parts);
1431 $parts['path'] = implode('/', $path_parts);
1432 $contact["batch"] = Network::unparseURL($parts);
1435 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
1437 $content_type = ($public_batch ? "application/magic-envelope+xml" : "application/json");
1439 $xml = Network::post($dest_url, $envelope, ["Content-Type: ".$content_type]);
1441 $curl_stat = $a->get_curl_code();
1442 if (empty($curl_stat) || empty($xml)) {
1443 logger('Empty answer from ' . $contact['id'] . ' - ' . $dest_url);
1444 Contact::markForArchival($contact);
1445 return -9; // timed out
1448 if (($curl_stat == 503) && (stristr($a->get_curl_headers(), 'retry-after'))) {
1449 Contact::markForArchival($contact);
1453 if (strpos($xml, '<?xml') === false) {
1454 logger('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url);
1455 logger('Returned XML: ' . $xml, LOGGER_DATA);
1456 Contact::markForArchival($contact);
1460 $res = XML::parseString($xml);
1462 if (empty($res->status)) {
1463 Contact::markForArchival($contact);
1467 if (!empty($res->message)) {
1468 logger('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1471 if (($res->status >= 200) && ($res->status <= 299)) {
1472 Contact::unmarkForArchival($contact);
1475 return intval($res->status);
1479 * @brief Add new birthday event for this person
1481 * @param array $contact Contact record
1482 * @param string $birthday Birthday of the contact
1484 * @todo Add array type-hint for $contact
1486 private static function birthdayEvent($contact, $birthday)
1488 // Check for duplicates
1490 "SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1491 intval($contact['uid']),
1492 intval($contact['id']),
1493 dbesc(DateTimeFormat::utc($birthday)),
1497 if (DBM::is_result($r)) {
1501 logger('updating birthday: ' . $birthday . ' for contact ' . $contact['id']);
1503 $bdtext = L10n::t('%s\'s birthday', $contact['name']);
1504 $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]');
1507 "INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1508 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1509 intval($contact['uid']),
1510 intval($contact['id']),
1511 dbesc(DateTimeFormat::utcNow()),
1512 dbesc(DateTimeFormat::utcNow()),
1513 dbesc(DateTimeFormat::utc($birthday)),
1514 dbesc(DateTimeFormat::utc($birthday . ' + 1 day ')),
1522 * @brief Fetch the author data from head or entry items
1524 * @param object $xpath XPath object
1525 * @param object $context In which context should the data be searched
1526 * @param array $importer Record of the importer user mixed with contact of the content
1527 * @param string $element Element name from which the data is fetched
1528 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1529 * @param string $xml optional, default empty
1531 * @return array Relevant data of the author
1532 * @todo Find good type-hints for all parameter
1534 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
1537 $author["name"] = $xpath->evaluate($element."/atom:name/text()", $context)->item(0)->nodeValue;
1538 $author["link"] = $xpath->evaluate($element."/atom:uri/text()", $context)->item(0)->nodeValue;
1540 $fields = ['id', 'uid', 'url', 'network', 'avatar-date', 'avatar', 'name-date', 'uri-date', 'addr',
1541 'name', 'nick', 'about', 'location', 'keywords', 'xmpp', 'bdyear', 'bd', 'hidden', 'contact-type'];
1542 $condition = ["`uid` = ? AND `nurl` = ? AND `network` != ?",
1543 $importer["importer_uid"], normalise_link($author["link"]), NETWORK_STATUSNET];
1544 $contact_old = dba::selectFirst('contact', $fields, $condition);
1546 if (DBM::is_result($contact_old)) {
1547 $author["contact-id"] = $contact_old["id"];
1548 $author["network"] = $contact_old["network"];
1551 logger("Contact ".$author["link"]." wasn't found for user ".$importer["importer_uid"]." XML: ".$xml, LOGGER_DEBUG);
1554 $author["contact-id"] = $importer["id"];
1555 $author["network"] = $importer["network"];
1559 // Until now we aren't serving different sizes - but maybe later
1561 /// @todo check if "avatar" or "photo" would be the best field in the specification
1562 $avatars = $xpath->query($element . "/atom:link[@rel='avatar']", $context);
1563 foreach ($avatars as $avatar) {
1566 foreach ($avatar->attributes as $attributes) {
1567 /// @TODO Rewrite these similar if() to one switch
1568 if ($attributes->name == "href") {
1569 $href = $attributes->textContent;
1571 if ($attributes->name == "width") {
1572 $width = $attributes->textContent;
1574 if ($attributes->name == "updated") {
1575 $author["avatar-date"] = $attributes->textContent;
1578 if (($width > 0) && ($href != "")) {
1579 $avatarlist[$width] = $href;
1583 if (count($avatarlist) > 0) {
1584 krsort($avatarlist);
1585 $author["avatar"] = current($avatarlist);
1588 if (DBM::is_result($contact_old) && !$onlyfetch) {
1589 logger("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", LOGGER_DEBUG);
1591 $poco = ["url" => $contact_old["url"]];
1593 // When was the last change to name or uri?
1594 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1595 foreach ($name_element->attributes as $attributes) {
1596 if ($attributes->name == "updated") {
1597 $poco["name-date"] = $attributes->textContent;
1601 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1602 foreach ($link_element->attributes as $attributes) {
1603 if ($attributes->name == "updated") {
1604 $poco["uri-date"] = $attributes->textContent;
1608 // Update contact data
1609 $value = $xpath->evaluate($element . "/dfrn:handle/text()", $context)->item(0)->nodeValue;
1611 $poco["addr"] = $value;
1614 $value = $xpath->evaluate($element . "/poco:displayName/text()", $context)->item(0)->nodeValue;
1616 $poco["name"] = $value;
1619 $value = $xpath->evaluate($element . "/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
1621 $poco["nick"] = $value;
1624 $value = $xpath->evaluate($element . "/poco:note/text()", $context)->item(0)->nodeValue;
1626 $poco["about"] = $value;
1629 $value = $xpath->evaluate($element . "/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
1631 $poco["location"] = $value;
1634 /// @todo Only search for elements with "poco:type" = "xmpp"
1635 $value = $xpath->evaluate($element . "/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
1637 $poco["xmpp"] = $value;
1640 /// @todo Add support for the following fields that we don't support by now in the contact table:
1641 /// - poco:utcOffset
1647 // If the "hide" element is present then the profile isn't searchable.
1648 $hide = intval($xpath->evaluate($element . "/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
1650 logger("Hidden status for contact " . $contact_old["url"] . ": " . $hide, LOGGER_DEBUG);
1652 // If the contact isn't searchable then set the contact to "hidden".
1653 // Problem: This can be manually overridden by the user.
1655 $contact_old["hidden"] = true;
1658 // Save the keywords into the contact table
1660 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1661 foreach ($tagelements as $tag) {
1662 $tags[$tag->nodeValue] = $tag->nodeValue;
1666 $poco["keywords"] = implode(", ", $tags);
1669 // "dfrn:birthday" contains the birthday converted to UTC
1670 $birthday = $xpath->evaluate($element . "/dfrn:birthday/text()", $context)->item(0)->nodeValue;
1672 if (strtotime($birthday) > time()) {
1673 $bd_timestamp = strtotime($birthday);
1675 $poco["bdyear"] = date("Y", $bd_timestamp);
1678 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1679 $value = $xpath->evaluate($element . "/poco:birthday/text()", $context)->item(0)->nodeValue;
1681 if (!in_array($value, ["", "0000-00-00", "0001-01-01"])) {
1682 $bdyear = date("Y");
1683 $value = str_replace("0000", $bdyear, $value);
1685 if (strtotime($value) < time()) {
1686 $value = str_replace($bdyear, $bdyear + 1, $value);
1687 $bdyear = $bdyear + 1;
1690 $poco["bd"] = $value;
1693 $contact = array_merge($contact_old, $poco);
1695 if ($contact_old["bdyear"] != $contact["bdyear"]) {
1696 self::birthdayEvent($contact, $birthday);
1699 // Get all field names
1701 foreach ($contact_old as $field => $data) {
1702 $fields[$field] = $data;
1705 unset($fields["id"]);
1706 unset($fields["uid"]);
1707 unset($fields["url"]);
1708 unset($fields["avatar-date"]);
1709 unset($fields["avatar"]);
1710 unset($fields["name-date"]);
1711 unset($fields["uri-date"]);
1714 // Update check for this field has to be done differently
1715 $datefields = ["name-date", "uri-date"];
1716 foreach ($datefields as $field) {
1717 if (strtotime($contact[$field]) > strtotime($contact_old[$field])) {
1718 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1723 foreach ($fields as $field => $data) {
1724 if ($contact[$field] != $contact_old[$field]) {
1725 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1731 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1734 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1735 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1736 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1737 WHERE `id` = %d AND `network` = '%s'",
1738 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
1739 dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1740 dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
1741 dbesc(DBM::date($contact["name-date"])), dbesc(DBM::date($contact["uri-date"])),
1742 intval($contact["id"]), dbesc($contact["network"])
1746 Contact::updateAvatar(
1748 $importer['importer_uid'],
1750 (strtotime($contact['avatar-date']) > strtotime($contact_old['avatar-date']) || ($author['avatar'] != $contact_old['avatar']))
1754 * The generation is a sign for the reliability of the provided data.
1755 * It is used in the socgraph.php to prevent that old contact data
1756 * that was relayed over several servers can overwrite contact
1757 * data that we received directly.
1760 $poco["generation"] = 2;
1761 $poco["photo"] = $author["avatar"];
1762 $poco["hide"] = $hide;
1763 $poco["contact-type"] = $contact["contact-type"];
1764 $gcid = GContact::update($poco);
1766 GContact::link($gcid, $importer["importer_uid"], $contact["id"]);
1773 * @brief Transforms activity objects into an XML string
1775 * @param object $xpath XPath object
1776 * @param object $activity Activity object
1777 * @param string $element element name
1779 * @return string XML string
1780 * @todo Find good type-hints for all parameter
1782 private static function transformActivity($xpath, $activity, $element)
1784 if (!is_object($activity)) {
1788 $obj_doc = new DOMDocument("1.0", "utf-8");
1789 $obj_doc->formatOutput = true;
1791 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1793 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1794 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1796 $id = $xpath->query("atom:id", $activity)->item(0);
1797 if (is_object($id)) {
1798 $obj_element->appendChild($obj_doc->importNode($id, true));
1801 $title = $xpath->query("atom:title", $activity)->item(0);
1802 if (is_object($title)) {
1803 $obj_element->appendChild($obj_doc->importNode($title, true));
1806 $links = $xpath->query("atom:link", $activity);
1807 if (is_object($links)) {
1808 foreach ($links as $link) {
1809 $obj_element->appendChild($obj_doc->importNode($link, true));
1813 $content = $xpath->query("atom:content", $activity)->item(0);
1814 if (is_object($content)) {
1815 $obj_element->appendChild($obj_doc->importNode($content, true));
1818 $obj_doc->appendChild($obj_element);
1820 $objxml = $obj_doc->saveXML($obj_element);
1822 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1823 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1828 * @brief Processes the mail elements
1830 * @param object $xpath XPath object
1831 * @param object $mail mail elements
1832 * @param array $importer Record of the importer user mixed with contact of the content
1834 * @todo Find good type-hints for all parameter
1836 private static function processMail($xpath, $mail, $importer)
1838 logger("Processing mails");
1840 /// @TODO Rewrite this to one statement
1842 $msg["uid"] = $importer["importer_uid"];
1843 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1844 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1845 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1846 $msg["contact-id"] = $importer["id"];
1847 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1848 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1849 $msg["created"] = DateTimeFormat::utc($xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue);
1850 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1851 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1853 $msg["replied"] = 0;
1855 dba::insert('mail', $msg);
1857 // send notifications.
1858 /// @TODO Arange this mess
1860 "type" => NOTIFY_MAIL,
1861 "notify_flags" => $importer["notify-flags"],
1862 "language" => $importer["language"],
1863 "to_name" => $importer["username"],
1864 "to_email" => $importer["email"],
1865 "uid" => $importer["importer_uid"],
1867 "source_name" => $msg["from-name"],
1868 "source_link" => $importer["url"],
1869 "source_photo" => $importer["thumb"],
1870 "verb" => ACTIVITY_POST,
1874 notification($notif_params);
1876 logger("Mail is processed, notification was sent.");
1880 * @brief Processes the suggestion elements
1882 * @param object $xpath XPath object
1883 * @param object $suggestion suggestion elements
1884 * @param array $importer Record of the importer user mixed with contact of the content
1886 * @todo Find good type-hints for all parameter
1888 private static function processSuggestion($xpath, $suggestion, $importer)
1892 logger("Processing suggestions");
1894 /// @TODO Rewrite this to one statement
1896 $suggest["uid"] = $importer["importer_uid"];
1897 $suggest["cid"] = $importer["id"];
1898 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1899 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1900 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1901 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1902 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1904 // Does our member already have a friend matching this description?
1907 "SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1908 dbesc($suggest["name"]),
1909 dbesc(normalise_link($suggest["url"])),
1910 intval($suggest["uid"])
1914 * The valid result means the friend we're about to send a friend
1915 * suggestion already has them in their contact, which means no further
1916 * action is required.
1918 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1920 if (DBM::is_result($r)) {
1924 // Do we already have an fcontact record for this person?
1928 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1929 dbesc($suggest["url"]),
1930 dbesc($suggest["name"]),
1931 dbesc($suggest["request"])
1933 if (DBM::is_result($r)) {
1936 // OK, we do. Do we already have an introduction for this person ?
1938 "SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1939 intval($suggest["uid"]),
1944 * The valid result means the friend we're about to send a friend
1945 * suggestion already has them in their contact, which means no further
1946 * action is required.
1948 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1950 if (DBM::is_result($r)) {
1956 "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1957 dbesc($suggest["name"]),
1958 dbesc($suggest["url"]),
1959 dbesc($suggest["photo"]),
1960 dbesc($suggest["request"])
1964 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1965 dbesc($suggest["url"]),
1966 dbesc($suggest["name"]),
1967 dbesc($suggest["request"])
1971 * If no record in fcontact is found, below INSERT statement will not
1972 * link an introduction to it.
1974 if (!DBM::is_result($r)) {
1975 // database record did not get created. Quietly give up.
1981 $hash = random_string();
1984 "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1985 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1986 intval($suggest["uid"]),
1988 intval($suggest["cid"]),
1989 dbesc($suggest["body"]),
1991 dbesc(DateTimeFormat::utcNow()),
1997 "type" => NOTIFY_SUGGEST,
1998 "notify_flags" => $importer["notify-flags"],
1999 "language" => $importer["language"],
2000 "to_name" => $importer["username"],
2001 "to_email" => $importer["email"],
2002 "uid" => $importer["importer_uid"],
2004 "link" => System::baseUrl()."/notifications/intros",
2005 "source_name" => $importer["name"],
2006 "source_link" => $importer["url"],
2007 "source_photo" => $importer["photo"],
2008 "verb" => ACTIVITY_REQ_FRIEND,
2016 * @brief Processes the relocation elements
2018 * @param object $xpath XPath object
2019 * @param object $relocation relocation elements
2020 * @param array $importer Record of the importer user mixed with contact of the content
2022 * @todo Find good type-hints for all parameter
2024 private static function processRelocation($xpath, $relocation, $importer)
2026 logger("Processing relocations");
2028 /// @TODO Rewrite this to one statement
2030 $relocate["uid"] = $importer["importer_uid"];
2031 $relocate["cid"] = $importer["id"];
2032 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
2033 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
2034 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
2035 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
2036 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
2037 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
2038 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
2039 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
2040 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
2041 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
2042 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
2043 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
2045 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
2046 $relocate["avatar"] = $relocate["photo"];
2049 if ($relocate["addr"] == "") {
2050 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
2055 "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
2056 intval($importer["id"]),
2057 intval($importer["importer_uid"])
2060 if (!DBM::is_result($r)) {
2061 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2067 // Update the gcontact entry
2068 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
2070 $fields = ['name' => $relocate["name"], 'photo' => $relocate["avatar"],
2071 'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2072 'addr' => $relocate["addr"], 'connect' => $relocate["addr"],
2073 'notify' => $relocate["notify"], 'server_url' => $relocate["server_url"]];
2074 dba::update('gcontact', $fields, ['nurl' => normalise_link($old["url"])]);
2076 // Update the contact table. We try to find every entry.
2077 $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
2078 'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2079 'addr' => $relocate["addr"], 'request' => $relocate["request"],
2080 'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
2081 'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
2082 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], normalise_link($old["url"])];
2084 dba::update('contact', $fields, $condition);
2086 Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
2088 logger('Contacts are updated.');
2091 // This is an extreme performance killer
2092 Item::update(['owner-link' => $relocate["url"]], ['owner-link' => $old["url"], 'uid' => $importer["importer_uid"]]);
2093 Item::update(['author-link' => $relocate["url"]], ['author-link' => $old["url"], 'uid' => $importer["importer_uid"]]);
2095 logger('Items are updated.');
2098 /// merge with current record, current contents have priority
2099 /// update record, set url-updated
2100 /// update profile photos
2101 /// schedule a scan?
2106 * @brief Updates an item
2108 * @param array $current the current item record
2109 * @param array $item the new item record
2110 * @param array $importer Record of the importer user mixed with contact of the content
2111 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2113 * @todo set proper type-hints (array?)
2115 private static function updateContent($current, $item, $importer, $entrytype)
2119 if (self::isEditedTimestampNewer($current, $item)) {
2120 // do not accept (ignore) an earlier edit than one we currently have.
2121 if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
2125 $fields = ['title' => defaults($item, 'title', ''), 'body' => defaults($item, 'body', ''),
2126 'tag' => defaults($item, 'tag', ''), 'changed' => DateTimeFormat::utcNow(),
2127 'edited' => DateTimeFormat::utc($item["edited"])];
2129 $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
2130 Item::update($fields, $condition);
2138 * @brief Detects the entry type of the item
2140 * @param array $importer Record of the importer user mixed with contact of the content
2141 * @param array $item the new item record
2143 * @return int Is it a toplevel entry, a comment or a relayed comment?
2144 * @todo set proper type-hints (array?)
2146 private static function getEntryType($importer, $item)
2148 if ($item["parent-uri"] != $item["uri"]) {
2151 if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
2154 logger("possible community action");
2156 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2159 // was the top-level post for this action written by somebody on this site?
2160 // Specifically, the recipient?
2162 $is_a_remote_action = false;
2164 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item["parent-uri"]]);
2165 if (DBM::is_result($parent)) {
2167 "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2168 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2169 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2170 AND `item`.`uid` = %d
2173 dbesc($parent["parent-uri"]),
2174 dbesc($parent["parent-uri"]),
2175 dbesc($parent["parent-uri"]),
2176 intval($importer["importer_uid"])
2178 if (DBM::is_result($r)) {
2179 $is_a_remote_action = true;
2184 * Does this have the characteristics of a community or private group action?
2185 * If it's an action to a wall post on a community/prvgroup page it's a
2186 * valid community action. Also forum_mode makes it valid for sure.
2187 * If neither, it's not.
2189 if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2190 $is_a_remote_action = false;
2191 logger("not a community action");
2194 if ($is_a_remote_action) {
2195 return DFRN::REPLY_RC;
2200 return DFRN::TOP_LEVEL;
2205 * @brief Send a "poke"
2207 * @param array $item the new item record
2208 * @param array $importer Record of the importer user mixed with contact of the content
2209 * @param int $posted_id The record number of item record that was just posted
2211 * @todo set proper type-hints (array?)
2213 private static function doPoke($item, $importer, $posted_id)
2215 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2219 $xo = XML::parseString($item["object"], false);
2221 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2222 // somebody was poked/prodded. Was it me?
2223 foreach ($xo->link as $l) {
2224 $atts = $l->attributes();
2225 switch ($atts["rel"]) {
2227 $Blink = $atts["href"];
2234 if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2235 $author = dba::selectFirst('contact', ['name', 'thumb', 'url'], ['id' => $item['author-id']]);
2237 // send a notification
2240 "type" => NOTIFY_POKE,
2241 "notify_flags" => $importer["notify-flags"],
2242 "language" => $importer["language"],
2243 "to_name" => $importer["username"],
2244 "to_email" => $importer["email"],
2245 "uid" => $importer["importer_uid"],
2247 "link" => System::baseUrl()."/display/".urlencode(Item::getGuidById($posted_id)),
2248 "source_name" => $author["name"],
2249 "source_link" => $author["url"],
2250 "source_photo" => $author["thumb"],
2251 "verb" => $item["verb"],
2252 "otype" => "person",
2253 "activity" => $verb,
2254 "parent" => $item["parent"]]
2261 * @brief Processes several actions, depending on the verb
2263 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2264 * @param array $importer Record of the importer user mixed with contact of the content
2265 * @param array $item the new item record
2266 * @param bool $is_like Is the verb a "like"?
2268 * @return bool Should the processing of the entries be continued?
2269 * @todo set proper type-hints (array?)
2271 private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2273 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2275 if (($entrytype == DFRN::TOP_LEVEL)) {
2276 // The filling of the the "contact" variable is done for legcy reasons
2277 // The functions below are partly used by ostatus.php as well - where we have this variable
2278 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2280 $nickname = $contact["nick"];
2282 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2283 // This function once was responsible for DFRN and OStatus.
2284 if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2285 logger("New follower");
2286 Contact::addRelationship($importer, $contact, $item, $nickname);
2289 if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2290 logger("Lost follower");
2291 Contact::removeFollower($importer, $contact, $item);
2294 if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2295 logger("New friend request");
2296 Contact::addRelationship($importer, $contact, $item, $nickname, true);
2299 if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2300 logger("Lost sharer");
2301 Contact::removeSharer($importer, $contact, $item);
2305 if (($item["verb"] == ACTIVITY_LIKE)
2306 || ($item["verb"] == ACTIVITY_DISLIKE)
2307 || ($item["verb"] == ACTIVITY_ATTEND)
2308 || ($item["verb"] == ACTIVITY_ATTENDNO)
2309 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
2312 $item["type"] = "activity";
2313 $item["gravity"] = GRAVITY_ACTIVITY;
2314 // only one like or dislike per person
2315 // splitted into two queries for performance issues
2316 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"],
2317 'verb' => $item["verb"], 'parent-uri' => $item["parent-uri"]];
2318 if (dba::exists('item', $condition)) {
2322 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"],
2323 'verb' => $item["verb"], 'thr-parent' => $item["parent-uri"]];
2324 if (dba::exists('item', $condition)) {
2331 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2332 $xo = XML::parseString($item["object"], false);
2333 $xt = XML::parseString($item["target"], false);
2335 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2336 $item_tag = Item::selectFirst(['id', 'tag'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]);
2337 if (!DBM::is_result($item_tag)) {
2338 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2342 // extract tag, if not duplicate, add to parent item
2344 if (!stristr($item_tag["tag"], trim($xo->content))) {
2345 $tag = $item_tag["tag"] . (strlen($item_tag["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2346 Item::update(['tag' => $tag], ['id' => $item_tag["id"]]);
2356 * @brief Processes the link elements
2358 * @param object $links link elements
2359 * @param array $item the item record
2361 * @todo set proper type-hints
2363 private static function parseLinks($links, &$item)
2370 foreach ($links as $link) {
2371 foreach ($link->attributes as $attributes) {
2372 switch ($attributes->name) {
2373 case "href" : $href = $attributes->textContent; break;
2374 case "rel" : $rel = $attributes->textContent; break;
2375 case "type" : $type = $attributes->textContent; break;
2376 case "length": $length = $attributes->textContent; break;
2377 case "title" : $title = $attributes->textContent; break;
2380 if (($rel != "") && ($href != "")) {
2383 $item["plink"] = $href;
2387 if (strlen($item["attach"])) {
2388 $item["attach"] .= ",";
2391 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2399 * @brief Processes the entry elements which contain the items and comments
2401 * @param array $header Array of the header elements that always stay the same
2402 * @param object $xpath XPath object
2403 * @param object $entry entry elements
2404 * @param array $importer Record of the importer user mixed with contact of the content
2405 * @param object $xml xml
2407 * @todo Add type-hints
2409 private static function processEntry($header, $xpath, $entry, $importer, $xml)
2411 logger("Processing entries");
2415 $item["protocol"] = PROTOCOL_DFRN;
2417 $item["source"] = $xml;
2420 $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
2422 $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
2424 $current = dba::selectFirst('item',
2425 ['id', 'uid', 'edited', 'body'],
2426 ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
2428 // Is there an existing item?
2429 if (DBM::is_result($current) && !self::isEditedTimestampNewer($current, $item)) {
2430 logger("Item ".$item["uri"]." (".$item['edited'].") already existed.", LOGGER_DEBUG);
2435 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
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"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
2448 $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2450 $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
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"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
2485 $georsspoint = $xpath->query("georss:point", $entry);
2487 $item["coord"] = $georsspoint->item(0)->nodeValue;
2490 $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
2492 $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
2494 if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true") {
2495 $item["bookmark"] = true;
2498 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2499 if ($notice_info && ($notice_info->length > 0)) {
2500 foreach ($notice_info->item(0)->attributes as $attributes) {
2501 if ($attributes->name == "source") {
2502 $item["app"] = strip_tags($attributes->textContent);
2507 $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
2509 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
2510 $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
2511 if ($dsprsig != "") {
2512 $item["dsprsig"] = $dsprsig;
2515 $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
2517 if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "") {
2518 $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
2521 $object = $xpath->query("activity:object", $entry)->item(0);
2522 $item["object"] = self::transformActivity($xpath, $object, "object");
2524 if (trim($item["object"]) != "") {
2525 $r = XML::parseString($item["object"], false);
2526 if (isset($r->type)) {
2527 $item["object-type"] = $r->type;
2531 $target = $xpath->query("activity:target", $entry)->item(0);
2532 $item["target"] = self::transformActivity($xpath, $target, "target");
2534 $categories = $xpath->query("atom:category", $entry);
2536 foreach ($categories as $category) {
2539 foreach ($category->attributes as $attributes) {
2540 if ($attributes->name == "term") {
2541 $term = $attributes->textContent;
2544 if ($attributes->name == "scheme") {
2545 $scheme = $attributes->textContent;
2549 if (($term != "") && ($scheme != "")) {
2550 $parts = explode(":", $scheme);
2551 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2552 $termhash = array_shift($parts);
2553 $termurl = implode(":", $parts);
2555 if (strlen($item["tag"])) {
2556 $item["tag"] .= ",";
2559 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2567 $links = $xpath->query("atom:link", $entry);
2569 self::parseLinks($links, $item);
2572 $item['conversation-uri'] = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
2574 $conv = $xpath->query('ostatus:conversation', $entry);
2575 if (is_object($conv->item(0))) {
2576 foreach ($conv->item(0)->attributes as $attributes) {
2577 if ($attributes->name == "ref") {
2578 $item['conversation-uri'] = $attributes->textContent;
2580 if ($attributes->name == "href") {
2581 $item['conversation-href'] = $attributes->textContent;
2586 // Is it a reply or a top level posting?
2587 $item["parent-uri"] = $item["uri"];
2589 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2590 if (is_object($inreplyto->item(0))) {
2591 foreach ($inreplyto->item(0)->attributes as $attributes) {
2592 if ($attributes->name == "ref") {
2593 $item["parent-uri"] = $attributes->textContent;
2598 // Get the type of the item (Top level post, reply or remote reply)
2599 $entrytype = self::getEntryType($importer, $item);
2601 // Now assign the rest of the values that depend on the type of the message
2602 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2603 if (!isset($item["object-type"])) {
2604 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2607 if ($item["contact-id"] != $owner["contact-id"]) {
2608 $item["contact-id"] = $owner["contact-id"];
2611 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2612 $item["network"] = $owner["network"];
2615 if ($item["contact-id"] != $author["contact-id"]) {
2616 $item["contact-id"] = $author["contact-id"];
2619 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2620 $item["network"] = $author["network"];
2624 if ($entrytype == DFRN::REPLY_RC) {
2625 $item["type"] = "remote-comment";
2627 } elseif ($entrytype == DFRN::TOP_LEVEL) {
2628 if (!isset($item["object-type"])) {
2629 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2633 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2634 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2635 $ev = Event::fromBBCode($item["body"]);
2636 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2637 logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2638 $ev["cid"] = $importer["id"];
2639 $ev["uid"] = $importer["importer_uid"];
2640 $ev["uri"] = $item["uri"];
2641 $ev["edited"] = $item["edited"];
2642 $ev["private"] = $item["private"];
2643 $ev["guid"] = $item["guid"];
2646 "SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2647 dbesc($item["uri"]),
2648 intval($importer["importer_uid"])
2650 if (DBM::is_result($r)) {
2651 $ev["id"] = $r[0]["id"];
2654 $event_id = Event::store($ev);
2655 logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2661 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2662 logger("Exiting because 'processVerbs' told us so", LOGGER_DEBUG);
2666 // Update content if 'updated' changes
2667 if (DBM::is_result($current)) {
2668 if (self::updateContent($current, $item, $importer, $entrytype)) {
2669 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2671 logger("Item " . $item["uri"] . " already existed.", LOGGER_DEBUG);
2676 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2677 $posted_id = Item::insert($item);
2681 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2683 if ($item['uid'] == 0) {
2684 Item::distribute($posted_id);
2689 } else { // $entrytype == DFRN::TOP_LEVEL
2690 if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
2691 logger("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", LOGGER_DEBUG);
2694 if (!link_compare($item["owner-link"], $importer["url"])) {
2696 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2697 * but otherwise there's a possible data mixup on the sender's system.
2698 * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2699 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2701 logger('Correcting item owner.', LOGGER_DEBUG);
2702 $item["owner-link"] = $importer["url"];
2703 $item["owner-id"] = Contact::getIdForURL($importer["url"], 0);
2706 if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2707 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2711 // This is my contact on another system, but it's really me.
2712 // Turn this into a wall post.
2713 $notify = Item::isRemoteSelf($importer, $item);
2715 $posted_id = Item::insert($item, false, $notify);
2718 $posted_id = $notify;
2721 logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2723 if ($item['uid'] == 0) {
2724 Item::distribute($posted_id);
2727 if (stristr($item["verb"], ACTIVITY_POKE)) {
2728 self::doPoke($item, $importer, $posted_id);
2734 * @brief Deletes items
2736 * @param object $xpath XPath object
2737 * @param object $deletion deletion elements
2738 * @param array $importer Record of the importer user mixed with contact of the content
2740 * @todo set proper type-hints
2742 private static function processDeletion($xpath, $deletion, $importer)
2744 logger("Processing deletions");
2747 foreach ($deletion->attributes as $attributes) {
2748 if ($attributes->name == "ref") {
2749 $uri = $attributes->textContent;
2753 if (!$uri || !$importer["id"]) {
2757 $condition = ["`uri` = ? AND `uid` = ? AND NOT `file` LIKE '%[%'", $uri, $importer["importer_uid"]];
2758 $item = dba::selectFirst('item', ['id', 'parent', 'contact-id'], $condition);
2759 if (!DBM::is_result($item)) {
2760 logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", LOGGER_DEBUG);
2764 // When it is a starting post it has to belong to the person that wants to delete it
2765 if (($item['id'] == $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2766 logger("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2770 // Comments can be deleted by the thread owner or comment owner
2771 if (($item['id'] != $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2772 $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2773 if (!dba::exists('item', $condition)) {
2774 logger("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2779 if ($item["deleted"]) {
2783 logger('deleting item '.$item['id'].' uri='.$uri, LOGGER_DEBUG);
2785 Item::delete(['id' => $item['id']]);
2789 * @brief Imports a DFRN message
2791 * @param string $xml The DFRN message
2792 * @param array $importer Record of the importer user mixed with contact of the content
2793 * @param bool $sort_by_date Is used when feeds are polled
2794 * @return integer Import status
2795 * @todo set proper type-hints
2797 public static function import($xml, $importer, $sort_by_date = false)
2803 $doc = new DOMDocument();
2804 @$doc->loadXML($xml);
2806 $xpath = new DOMXPath($doc);
2807 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2808 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2809 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2810 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2811 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2812 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2813 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2814 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2815 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2816 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2819 $header["uid"] = $importer["importer_uid"];
2820 $header["network"] = NETWORK_DFRN;
2821 $header["type"] = "remote";
2822 $header["wall"] = 0;
2823 $header["origin"] = 0;
2824 $header["contact-id"] = $importer["id"];
2826 // Update the contact table if the data has changed
2828 // The "atom:author" is only present in feeds
2829 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2830 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2833 // Only the "dfrn:owner" in the head section contains all data
2834 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2835 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2838 logger("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2840 // is it a public forum? Private forums aren't exposed with this method
2841 $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()")->item(0)->nodeValue);
2843 // The account type is new since 3.5.1
2844 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2845 $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()")->item(0)->nodeValue);
2847 if ($accounttype != $importer["contact-type"]) {
2848 dba::update('contact', ['contact-type' => $accounttype], ['id' => $importer["id"]]);
2850 // A forum contact can either have set "forum" or "prv" - but not both
2851 if (($accounttype == ACCOUNT_TYPE_COMMUNITY) && (($forum != $importer["forum"]) || ($forum == $importer["prv"]))) {
2852 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer["id"]];
2853 dba::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2855 } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
2856 $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2857 dba::update('contact', ['forum' => $forum], $condition);
2861 // We are processing relocations even if we are ignoring a contact
2862 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2863 foreach ($relocations as $relocation) {
2864 self::processRelocation($xpath, $relocation, $importer);
2867 if (($importer["uid"] != 0) && !$importer["readonly"]) {
2868 $mails = $xpath->query("/atom:feed/dfrn:mail");
2869 foreach ($mails as $mail) {
2870 self::processMail($xpath, $mail, $importer);
2873 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2874 foreach ($suggestions as $suggestion) {
2875 self::processSuggestion($xpath, $suggestion, $importer);
2879 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2880 foreach ($deletions as $deletion) {
2881 self::processDeletion($xpath, $deletion, $importer);
2884 if (!$sort_by_date) {
2885 $entries = $xpath->query("/atom:feed/atom:entry");
2886 foreach ($entries as $entry) {
2887 self::processEntry($header, $xpath, $entry, $importer, $xml);
2891 $entries = $xpath->query("/atom:feed/atom:entry");
2892 foreach ($entries as $entry) {
2893 $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2894 $newentries[strtotime($created)] = $entry;
2897 // Now sort after the publishing date
2900 foreach ($newentries as $entry) {
2901 self::processEntry($header, $xpath, $entry, $importer, $xml);
2904 logger("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2910 * @param string $contact_nick contact nickname
2912 public static function autoRedir(App $a, $contact_nick)
2915 if (x($_REQUEST, 'redir') && intval($_REQUEST['redir'])) {
2919 if ((! $contact_nick) || ($contact_nick === $a->user['nickname'])) {
2924 // We need to find out if $contact_nick is a user on this hub, and if so, if I
2925 // am a contact of that user. However, that user may have other contacts with the
2926 // same nickname as me on other hubs or other networks. Exclude these by requiring
2927 // that the contact have a local URL. I will be the only person with my nickname at
2928 // this URL, so if a result is found, then I am a contact of the $contact_nick user.
2930 // We also have to make sure that I'm a legitimate contact--I'm not blocked or pending.
2932 $baseurl = System::baseUrl();
2933 $domain_st = strpos($baseurl, "://");
2934 if ($domain_st === false) {
2937 $baseurl = substr($baseurl, $domain_st + 3);
2938 $nurl = normalise_link($baseurl);
2940 /// @todo Why is there a query for "url" *and* "nurl"? Especially this normalising is strange.
2941 $r = q("SELECT `id` FROM `contact` WHERE `uid` = (SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1)
2942 AND `nick` = '%s' AND NOT `self` AND (`url` LIKE '%%%s%%' OR `nurl` LIKE '%%%s%%') AND NOT `blocked` AND NOT `pending` LIMIT 1",
2943 dbesc($contact_nick),
2944 dbesc($a->user['nickname']),
2948 if ((! DBM::is_result($r)) || $r[0]['id'] == remote_user()) {
2952 $r = q("SELECT * FROM contact WHERE nick = '%s'
2953 AND network = '%s' AND uid = %d AND url LIKE '%%%s%%' LIMIT 1",
2954 dbesc($contact_nick),
2955 dbesc(NETWORK_DFRN),
2956 intval(local_user()),
2959 if (! DBM::is_result($r)) {
2965 $dfrn_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2967 if ($r[0]['duplex'] && $r[0]['issued-id']) {
2968 $orig_id = $r[0]['issued-id'];
2969 $dfrn_id = '1:' . $orig_id;
2971 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
2972 $orig_id = $r[0]['dfrn-id'];
2973 $dfrn_id = '0:' . $orig_id;
2976 // ensure that we've got a valid ID. There may be some edge cases with forums and non-duplex mode
2977 // that may have triggered some of the "went to {profile/intro} and got an RSS feed" issues
2979 if (strlen($dfrn_id) < 3) {
2983 $sec = random_string();
2985 dba::insert('profile_check', ['uid' => local_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id, 'sec' => $sec, 'expire' => time() + 45]);
2987 $url = curPageURL();
2989 logger('auto_redir: ' . $r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
2990 $dest = (($url) ? '&destination_url=' . $url : '');
2991 goaway($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
2992 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest);
2999 * @brief Returns the activity verb
3001 * @param array $item Item array
3003 * @return string activity verb
3005 private static function constructVerb(array $item)
3007 if ($item['verb']) {
3008 return $item['verb'];
3010 return ACTIVITY_POST;
3013 private static function tgroupCheck($uid, $item)
3017 // check that the message originated elsewhere and is a top-level post
3019 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['parent-uri'])) {
3023 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
3026 if (!DBM::is_result($u)) {
3030 $community_page = ($u[0]['page-flags'] == PAGE_COMMUNITY);
3031 $prvgroup = ($u[0]['page-flags'] == PAGE_PRVGROUP);
3033 $link = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
3036 * Diaspora uses their own hardwired link URL in @-tags
3037 * instead of the one we supply with webfinger
3039 $dlink = normalise_link(System::baseUrl() . '/u/' . $u[0]['nickname']);
3041 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
3043 foreach ($matches as $mtch) {
3044 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
3046 logger('mention found: ' . $mtch[2]);
3055 return $community_page || $prvgroup;
3059 * This function returns true if $update has an edited timestamp newer
3060 * than $existing, i.e. $update contains new data which should override
3061 * what's already there. If there is no timestamp yet, the update is
3062 * assumed to be newer. If the update has no timestamp, the existing
3063 * item is assumed to be up-to-date. If the timestamps are equal it
3064 * assumes the update has been seen before and should be ignored.
3067 private static function isEditedTimestampNewer($existing, $update)
3069 if (!x($existing, 'edited') || !$existing['edited']) {
3072 if (!x($update, 'edited') || !$update['edited']) {
3076 $existing_edited = DateTimeFormat::utc($existing['edited']);
3077 $update_edited = DateTimeFormat::utc($update['edited']);
3079 return (strcmp($existing_edited, $update_edited) < 0);