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 = dba::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 = dba::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 = q("SELECT `guid`,`plink` FROM `item` WHERE `uri` = '%s' AND `uid` = %d", dbesc($parent_item), intval($item['uid']));
942 $attributes = ["ref" => $parent_item, "type" => "text/html",
943 "href" => $parent[0]['plink'],
944 "dfrn:diaspora_guid" => $parent[0]['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 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $item['parent-uri']);
954 if (DBM::is_result($r)) {
955 if ($r['conversation-uri'] != '') {
956 $conversation_uri = $r['conversation-uri'];
958 if ($r['conversation-href'] != '') {
959 $conversation_href = $r['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 $contact_old = dba::fetch_first("SELECT `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 FROM `contact` WHERE `uid` = ? AND `nurl` = ? AND `network` != ?",
1543 $importer["importer_uid"],
1544 normalise_link($author["link"]),
1548 if (DBM::is_result($contact_old)) {
1549 $author["contact-id"] = $contact_old["id"];
1550 $author["network"] = $contact_old["network"];
1553 logger("Contact ".$author["link"]." wasn't found for user ".$importer["importer_uid"]." XML: ".$xml, LOGGER_DEBUG);
1556 $author["contact-id"] = $importer["id"];
1557 $author["network"] = $importer["network"];
1561 // Until now we aren't serving different sizes - but maybe later
1563 /// @todo check if "avatar" or "photo" would be the best field in the specification
1564 $avatars = $xpath->query($element . "/atom:link[@rel='avatar']", $context);
1565 foreach ($avatars as $avatar) {
1568 foreach ($avatar->attributes as $attributes) {
1569 /// @TODO Rewrite these similar if() to one switch
1570 if ($attributes->name == "href") {
1571 $href = $attributes->textContent;
1573 if ($attributes->name == "width") {
1574 $width = $attributes->textContent;
1576 if ($attributes->name == "updated") {
1577 $author["avatar-date"] = $attributes->textContent;
1580 if (($width > 0) && ($href != "")) {
1581 $avatarlist[$width] = $href;
1585 if (count($avatarlist) > 0) {
1586 krsort($avatarlist);
1587 $author["avatar"] = current($avatarlist);
1590 if (DBM::is_result($contact_old) && !$onlyfetch) {
1591 logger("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", LOGGER_DEBUG);
1593 $poco = ["url" => $contact_old["url"]];
1595 // When was the last change to name or uri?
1596 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1597 foreach ($name_element->attributes as $attributes) {
1598 if ($attributes->name == "updated") {
1599 $poco["name-date"] = $attributes->textContent;
1603 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1604 foreach ($link_element->attributes as $attributes) {
1605 if ($attributes->name == "updated") {
1606 $poco["uri-date"] = $attributes->textContent;
1610 // Update contact data
1611 $value = $xpath->evaluate($element . "/dfrn:handle/text()", $context)->item(0)->nodeValue;
1613 $poco["addr"] = $value;
1616 $value = $xpath->evaluate($element . "/poco:displayName/text()", $context)->item(0)->nodeValue;
1618 $poco["name"] = $value;
1621 $value = $xpath->evaluate($element . "/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
1623 $poco["nick"] = $value;
1626 $value = $xpath->evaluate($element . "/poco:note/text()", $context)->item(0)->nodeValue;
1628 $poco["about"] = $value;
1631 $value = $xpath->evaluate($element . "/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
1633 $poco["location"] = $value;
1636 /// @todo Only search for elements with "poco:type" = "xmpp"
1637 $value = $xpath->evaluate($element . "/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
1639 $poco["xmpp"] = $value;
1642 /// @todo Add support for the following fields that we don't support by now in the contact table:
1643 /// - poco:utcOffset
1649 // If the "hide" element is present then the profile isn't searchable.
1650 $hide = intval($xpath->evaluate($element . "/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
1652 logger("Hidden status for contact " . $contact_old["url"] . ": " . $hide, LOGGER_DEBUG);
1654 // If the contact isn't searchable then set the contact to "hidden".
1655 // Problem: This can be manually overridden by the user.
1657 $contact_old["hidden"] = true;
1660 // Save the keywords into the contact table
1662 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1663 foreach ($tagelements as $tag) {
1664 $tags[$tag->nodeValue] = $tag->nodeValue;
1668 $poco["keywords"] = implode(", ", $tags);
1671 // "dfrn:birthday" contains the birthday converted to UTC
1672 $birthday = $xpath->evaluate($element . "/dfrn:birthday/text()", $context)->item(0)->nodeValue;
1674 if (strtotime($birthday) > time()) {
1675 $bd_timestamp = strtotime($birthday);
1677 $poco["bdyear"] = date("Y", $bd_timestamp);
1680 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1681 $value = $xpath->evaluate($element . "/poco:birthday/text()", $context)->item(0)->nodeValue;
1683 if (!in_array($value, ["", "0000-00-00", "0001-01-01"])) {
1684 $bdyear = date("Y");
1685 $value = str_replace("0000", $bdyear, $value);
1687 if (strtotime($value) < time()) {
1688 $value = str_replace($bdyear, $bdyear + 1, $value);
1689 $bdyear = $bdyear + 1;
1692 $poco["bd"] = $value;
1695 $contact = array_merge($contact_old, $poco);
1697 if ($contact_old["bdyear"] != $contact["bdyear"]) {
1698 self::birthdayEvent($contact, $birthday);
1701 // Get all field names
1703 foreach ($contact_old as $field => $data) {
1704 $fields[$field] = $data;
1707 unset($fields["id"]);
1708 unset($fields["uid"]);
1709 unset($fields["url"]);
1710 unset($fields["avatar-date"]);
1711 unset($fields["avatar"]);
1712 unset($fields["name-date"]);
1713 unset($fields["uri-date"]);
1716 // Update check for this field has to be done differently
1717 $datefields = ["name-date", "uri-date"];
1718 foreach ($datefields as $field) {
1719 if (strtotime($contact[$field]) > strtotime($contact_old[$field])) {
1720 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1725 foreach ($fields as $field => $data) {
1726 if ($contact[$field] != $contact_old[$field]) {
1727 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1733 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1736 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1737 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1738 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1739 WHERE `id` = %d AND `network` = '%s'",
1740 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
1741 dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1742 dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
1743 dbesc(DBM::date($contact["name-date"])), dbesc(DBM::date($contact["uri-date"])),
1744 intval($contact["id"]), dbesc($contact["network"])
1748 Contact::updateAvatar(
1750 $importer['importer_uid'],
1752 (strtotime($contact['avatar-date']) > strtotime($contact_old['avatar-date']) || ($author['avatar'] != $contact_old['avatar']))
1756 * The generation is a sign for the reliability of the provided data.
1757 * It is used in the socgraph.php to prevent that old contact data
1758 * that was relayed over several servers can overwrite contact
1759 * data that we received directly.
1762 $poco["generation"] = 2;
1763 $poco["photo"] = $author["avatar"];
1764 $poco["hide"] = $hide;
1765 $poco["contact-type"] = $contact["contact-type"];
1766 $gcid = GContact::update($poco);
1768 GContact::link($gcid, $importer["importer_uid"], $contact["id"]);
1775 * @brief Transforms activity objects into an XML string
1777 * @param object $xpath XPath object
1778 * @param object $activity Activity object
1779 * @param string $element element name
1781 * @return string XML string
1782 * @todo Find good type-hints for all parameter
1784 private static function transformActivity($xpath, $activity, $element)
1786 if (!is_object($activity)) {
1790 $obj_doc = new DOMDocument("1.0", "utf-8");
1791 $obj_doc->formatOutput = true;
1793 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1795 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1796 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1798 $id = $xpath->query("atom:id", $activity)->item(0);
1799 if (is_object($id)) {
1800 $obj_element->appendChild($obj_doc->importNode($id, true));
1803 $title = $xpath->query("atom:title", $activity)->item(0);
1804 if (is_object($title)) {
1805 $obj_element->appendChild($obj_doc->importNode($title, true));
1808 $links = $xpath->query("atom:link", $activity);
1809 if (is_object($links)) {
1810 foreach ($links as $link) {
1811 $obj_element->appendChild($obj_doc->importNode($link, true));
1815 $content = $xpath->query("atom:content", $activity)->item(0);
1816 if (is_object($content)) {
1817 $obj_element->appendChild($obj_doc->importNode($content, true));
1820 $obj_doc->appendChild($obj_element);
1822 $objxml = $obj_doc->saveXML($obj_element);
1824 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1825 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1830 * @brief Processes the mail elements
1832 * @param object $xpath XPath object
1833 * @param object $mail mail elements
1834 * @param array $importer Record of the importer user mixed with contact of the content
1836 * @todo Find good type-hints for all parameter
1838 private static function processMail($xpath, $mail, $importer)
1840 logger("Processing mails");
1842 /// @TODO Rewrite this to one statement
1844 $msg["uid"] = $importer["importer_uid"];
1845 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1846 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1847 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1848 $msg["contact-id"] = $importer["id"];
1849 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1850 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1851 $msg["created"] = DateTimeFormat::utc($xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue);
1852 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1853 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1855 $msg["replied"] = 0;
1857 dba::insert('mail', $msg);
1859 // send notifications.
1860 /// @TODO Arange this mess
1862 "type" => NOTIFY_MAIL,
1863 "notify_flags" => $importer["notify-flags"],
1864 "language" => $importer["language"],
1865 "to_name" => $importer["username"],
1866 "to_email" => $importer["email"],
1867 "uid" => $importer["importer_uid"],
1869 "source_name" => $msg["from-name"],
1870 "source_link" => $importer["url"],
1871 "source_photo" => $importer["thumb"],
1872 "verb" => ACTIVITY_POST,
1876 notification($notif_params);
1878 logger("Mail is processed, notification was sent.");
1882 * @brief Processes the suggestion elements
1884 * @param object $xpath XPath object
1885 * @param object $suggestion suggestion elements
1886 * @param array $importer Record of the importer user mixed with contact of the content
1888 * @todo Find good type-hints for all parameter
1890 private static function processSuggestion($xpath, $suggestion, $importer)
1894 logger("Processing suggestions");
1896 /// @TODO Rewrite this to one statement
1898 $suggest["uid"] = $importer["importer_uid"];
1899 $suggest["cid"] = $importer["id"];
1900 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1901 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1902 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1903 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1904 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1906 // Does our member already have a friend matching this description?
1909 "SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1910 dbesc($suggest["name"]),
1911 dbesc(normalise_link($suggest["url"])),
1912 intval($suggest["uid"])
1916 * The valid result means the friend we're about to send a friend
1917 * suggestion already has them in their contact, which means no further
1918 * action is required.
1920 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1922 if (DBM::is_result($r)) {
1926 // Do we already have an fcontact record for this person?
1930 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1931 dbesc($suggest["url"]),
1932 dbesc($suggest["name"]),
1933 dbesc($suggest["request"])
1935 if (DBM::is_result($r)) {
1938 // OK, we do. Do we already have an introduction for this person ?
1940 "SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1941 intval($suggest["uid"]),
1946 * The valid result means the friend we're about to send a friend
1947 * suggestion already has them in their contact, which means no further
1948 * action is required.
1950 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1952 if (DBM::is_result($r)) {
1958 "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1959 dbesc($suggest["name"]),
1960 dbesc($suggest["url"]),
1961 dbesc($suggest["photo"]),
1962 dbesc($suggest["request"])
1966 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1967 dbesc($suggest["url"]),
1968 dbesc($suggest["name"]),
1969 dbesc($suggest["request"])
1973 * If no record in fcontact is found, below INSERT statement will not
1974 * link an introduction to it.
1976 if (!DBM::is_result($r)) {
1977 // database record did not get created. Quietly give up.
1983 $hash = random_string();
1986 "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1987 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1988 intval($suggest["uid"]),
1990 intval($suggest["cid"]),
1991 dbesc($suggest["body"]),
1993 dbesc(DateTimeFormat::utcNow()),
1999 "type" => NOTIFY_SUGGEST,
2000 "notify_flags" => $importer["notify-flags"],
2001 "language" => $importer["language"],
2002 "to_name" => $importer["username"],
2003 "to_email" => $importer["email"],
2004 "uid" => $importer["importer_uid"],
2006 "link" => System::baseUrl()."/notifications/intros",
2007 "source_name" => $importer["name"],
2008 "source_link" => $importer["url"],
2009 "source_photo" => $importer["photo"],
2010 "verb" => ACTIVITY_REQ_FRIEND,
2018 * @brief Processes the relocation elements
2020 * @param object $xpath XPath object
2021 * @param object $relocation relocation elements
2022 * @param array $importer Record of the importer user mixed with contact of the content
2024 * @todo Find good type-hints for all parameter
2026 private static function processRelocation($xpath, $relocation, $importer)
2028 logger("Processing relocations");
2030 /// @TODO Rewrite this to one statement
2032 $relocate["uid"] = $importer["importer_uid"];
2033 $relocate["cid"] = $importer["id"];
2034 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
2035 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
2036 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
2037 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
2038 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
2039 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
2040 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
2041 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
2042 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
2043 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
2044 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
2045 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
2047 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
2048 $relocate["avatar"] = $relocate["photo"];
2051 if ($relocate["addr"] == "") {
2052 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
2057 "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
2058 intval($importer["id"]),
2059 intval($importer["importer_uid"])
2062 if (!DBM::is_result($r)) {
2063 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2069 // Update the gcontact entry
2070 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
2072 $fields = ['name' => $relocate["name"], 'photo' => $relocate["avatar"],
2073 'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2074 'addr' => $relocate["addr"], 'connect' => $relocate["addr"],
2075 'notify' => $relocate["notify"], 'server_url' => $relocate["server_url"]];
2076 dba::update('gcontact', $fields, ['nurl' => normalise_link($old["url"])]);
2078 // Update the contact table. We try to find every entry.
2079 $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
2080 'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2081 'addr' => $relocate["addr"], 'request' => $relocate["request"],
2082 'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
2083 'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
2084 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], normalise_link($old["url"])];
2085 dba::update('contact', $fields, $condition);
2087 // @TODO No dba:update here?
2088 dba::update('contact', $fields, $condition);
2090 Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
2092 logger('Contacts are updated.');
2095 // This is an extreme performance killer
2096 Item::update(['owner-link' => $relocate["url"]], ['owner-link' => $old["url"], 'uid' => $importer["importer_uid"]]);
2097 Item::update(['author-link' => $relocate["url"]], ['author-link' => $old["url"], 'uid' => $importer["importer_uid"]]);
2099 logger('Items are updated.');
2102 /// merge with current record, current contents have priority
2103 /// update record, set url-updated
2104 /// update profile photos
2105 /// schedule a scan?
2110 * @brief Updates an item
2112 * @param array $current the current item record
2113 * @param array $item the new item record
2114 * @param array $importer Record of the importer user mixed with contact of the content
2115 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2117 * @todo set proper type-hints (array?)
2119 private static function updateContent($current, $item, $importer, $entrytype)
2123 if (self::isEditedTimestampNewer($current, $item)) {
2124 // do not accept (ignore) an earlier edit than one we currently have.
2125 if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
2129 $fields = ['title' => defaults($item, 'title', ''), 'body' => defaults($item, 'body', ''),
2130 'tag' => defaults($item, 'tag', ''), 'changed' => DateTimeFormat::utcNow(),
2131 'edited' => DateTimeFormat::utc($item["edited"])];
2133 $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
2134 Item::update($fields, $condition);
2142 * @brief Detects the entry type of the item
2144 * @param array $importer Record of the importer user mixed with contact of the content
2145 * @param array $item the new item record
2147 * @return int Is it a toplevel entry, a comment or a relayed comment?
2148 * @todo set proper type-hints (array?)
2150 private static function getEntryType($importer, $item)
2152 if ($item["parent-uri"] != $item["uri"]) {
2155 if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
2158 logger("possible community action");
2160 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2163 // was the top-level post for this action written by somebody on this site?
2164 // Specifically, the recipient?
2166 $is_a_remote_action = false;
2169 "SELECT `item`.`parent-uri` FROM `item`
2170 WHERE `item`.`uri` = '%s'
2172 dbesc($item["parent-uri"])
2174 if (DBM::is_result($r)) {
2176 "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2177 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2178 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2179 AND `item`.`uid` = %d
2182 dbesc($r[0]["parent-uri"]),
2183 dbesc($r[0]["parent-uri"]),
2184 dbesc($r[0]["parent-uri"]),
2185 intval($importer["importer_uid"])
2187 if (DBM::is_result($r)) {
2188 $is_a_remote_action = true;
2193 * Does this have the characteristics of a community or private group action?
2194 * If it's an action to a wall post on a community/prvgroup page it's a
2195 * valid community action. Also forum_mode makes it valid for sure.
2196 * If neither, it's not.
2198 if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2199 $is_a_remote_action = false;
2200 logger("not a community action");
2203 if ($is_a_remote_action) {
2204 return DFRN::REPLY_RC;
2209 return DFRN::TOP_LEVEL;
2214 * @brief Send a "poke"
2216 * @param array $item the new item record
2217 * @param array $importer Record of the importer user mixed with contact of the content
2218 * @param int $posted_id The record number of item record that was just posted
2220 * @todo set proper type-hints (array?)
2222 private static function doPoke($item, $importer, $posted_id)
2224 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2228 $xo = XML::parseString($item["object"], false);
2230 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2231 // somebody was poked/prodded. Was it me?
2232 foreach ($xo->link as $l) {
2233 $atts = $l->attributes();
2234 switch ($atts["rel"]) {
2236 $Blink = $atts["href"];
2243 if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2244 $author = dba::selectFirst('contact', ['name', 'thumb', 'url'], ['id' => $item['author-id']]);
2246 // send a notification
2249 "type" => NOTIFY_POKE,
2250 "notify_flags" => $importer["notify-flags"],
2251 "language" => $importer["language"],
2252 "to_name" => $importer["username"],
2253 "to_email" => $importer["email"],
2254 "uid" => $importer["importer_uid"],
2256 "link" => System::baseUrl()."/display/".urlencode(Item::getGuidById($posted_id)),
2257 "source_name" => $author["name"],
2258 "source_link" => $author["url"],
2259 "source_photo" => $author["thumb"],
2260 "verb" => $item["verb"],
2261 "otype" => "person",
2262 "activity" => $verb,
2263 "parent" => $item["parent"]]
2270 * @brief Processes several actions, depending on the verb
2272 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2273 * @param array $importer Record of the importer user mixed with contact of the content
2274 * @param array $item the new item record
2275 * @param bool $is_like Is the verb a "like"?
2277 * @return bool Should the processing of the entries be continued?
2278 * @todo set proper type-hints (array?)
2280 private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2282 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2284 if (($entrytype == DFRN::TOP_LEVEL)) {
2285 // The filling of the the "contact" variable is done for legcy reasons
2286 // The functions below are partly used by ostatus.php as well - where we have this variable
2287 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2289 $nickname = $contact["nick"];
2291 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2292 // This function once was responsible for DFRN and OStatus.
2293 if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2294 logger("New follower");
2295 Contact::addRelationship($importer, $contact, $item, $nickname);
2298 if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2299 logger("Lost follower");
2300 Contact::removeFollower($importer, $contact, $item);
2303 if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2304 logger("New friend request");
2305 Contact::addRelationship($importer, $contact, $item, $nickname, true);
2308 if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2309 logger("Lost sharer");
2310 Contact::removeSharer($importer, $contact, $item);
2314 if (($item["verb"] == ACTIVITY_LIKE)
2315 || ($item["verb"] == ACTIVITY_DISLIKE)
2316 || ($item["verb"] == ACTIVITY_ATTEND)
2317 || ($item["verb"] == ACTIVITY_ATTENDNO)
2318 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
2321 $item["type"] = "activity";
2322 $item["gravity"] = GRAVITY_LIKE;
2323 // only one like or dislike per person
2324 // splitted into two queries for performance issues
2326 "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-id` = %d AND `verb` = '%s' AND `parent-uri` = '%s' AND NOT `deleted` LIMIT 1",
2327 intval($item["uid"]),
2328 intval($item["author-id"]),
2329 dbesc($item["verb"]),
2330 dbesc($item["parent-uri"])
2332 if (DBM::is_result($r)) {
2337 "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-id` = %d AND `verb` = '%s' AND `thr-parent` = '%s' AND NOT `deleted` LIMIT 1",
2338 intval($item["uid"]),
2339 intval($item["author-id"]),
2340 dbesc($item["verb"]),
2341 dbesc($item["parent-uri"])
2343 if (DBM::is_result($r)) {
2350 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2351 $xo = XML::parseString($item["object"], false);
2352 $xt = XML::parseString($item["target"], false);
2354 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2356 "SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2358 intval($importer["importer_uid"])
2361 if (!DBM::is_result($r)) {
2362 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2366 // extract tag, if not duplicate, add to parent item
2368 if (!stristr($r[0]["tag"], trim($xo->content))) {
2369 $tag = $r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2370 Item::update(['tag' => $tag], ['id' => $r[0]["id"]]);
2380 * @brief Processes the link elements
2382 * @param object $links link elements
2383 * @param array $item the item record
2385 * @todo set proper type-hints
2387 private static function parseLinks($links, &$item)
2394 foreach ($links as $link) {
2395 foreach ($link->attributes as $attributes) {
2396 switch ($attributes->name) {
2397 case "href" : $href = $attributes->textContent; break;
2398 case "rel" : $rel = $attributes->textContent; break;
2399 case "type" : $type = $attributes->textContent; break;
2400 case "length": $length = $attributes->textContent; break;
2401 case "title" : $title = $attributes->textContent; break;
2404 if (($rel != "") && ($href != "")) {
2407 $item["plink"] = $href;
2411 if (strlen($item["attach"])) {
2412 $item["attach"] .= ",";
2415 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2423 * @brief Processes the entry elements which contain the items and comments
2425 * @param array $header Array of the header elements that always stay the same
2426 * @param object $xpath XPath object
2427 * @param object $entry entry elements
2428 * @param array $importer Record of the importer user mixed with contact of the content
2429 * @param object $xml xml
2431 * @todo Add type-hints
2433 private static function processEntry($header, $xpath, $entry, $importer, $xml)
2435 logger("Processing entries");
2439 $item["protocol"] = PROTOCOL_DFRN;
2441 $item["source"] = $xml;
2444 $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
2446 $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
2448 $current = dba::selectFirst('item',
2449 ['id', 'uid', 'edited', 'body'],
2450 ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
2452 // Is there an existing item?
2453 if (DBM::is_result($current) && !self::isEditedTimestampNewer($current, $item)) {
2454 logger("Item ".$item["uri"]." (".$item['edited'].") already existed.", LOGGER_DEBUG);
2459 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2461 $item["owner-link"] = $owner["link"];
2462 $item["owner-id"] = Contact::getIdForURL($owner["link"], 0);
2465 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2467 $item["author-link"] = $author["link"];
2468 $item["author-id"] = Contact::getIdForURL($author["link"], 0);
2470 $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
2472 $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2474 $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
2475 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2476 // make sure nobody is trying to sneak some html tags by us
2477 $item["body"] = notags(base64url_decode($item["body"]));
2479 $item["body"] = BBCode::limitBodySize($item["body"]);
2481 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2482 if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
2483 $base_url = get_app()->get_baseurl();
2484 $item['body'] = reltoabs($item['body'], $base_url);
2486 $item['body'] = html2bb_video($item['body']);
2488 $item['body'] = OEmbed::HTML2BBCode($item['body']);
2490 $config = HTMLPurifier_Config::createDefault();
2491 $config->set('Cache.DefinitionImpl', null);
2493 // we shouldn't need a whitelist, because the bbcode converter
2494 // will strip out any unsupported tags.
2496 $purifier = new HTMLPurifier($config);
2497 $item['body'] = $purifier->purify($item['body']);
2499 $item['body'] = @HTML::toBBCode($item['body']);
2502 /// @todo We should check for a repeated post and if we know the repeated author.
2504 // We don't need the content element since "dfrn:env" is always present
2505 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2507 $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
2509 $georsspoint = $xpath->query("georss:point", $entry);
2511 $item["coord"] = $georsspoint->item(0)->nodeValue;
2514 $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
2516 $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
2518 if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true") {
2519 $item["bookmark"] = true;
2522 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2523 if ($notice_info && ($notice_info->length > 0)) {
2524 foreach ($notice_info->item(0)->attributes as $attributes) {
2525 if ($attributes->name == "source") {
2526 $item["app"] = strip_tags($attributes->textContent);
2531 $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
2533 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
2534 $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
2535 if ($dsprsig != "") {
2536 $item["dsprsig"] = $dsprsig;
2539 $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
2541 if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "") {
2542 $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
2545 $object = $xpath->query("activity:object", $entry)->item(0);
2546 $item["object"] = self::transformActivity($xpath, $object, "object");
2548 if (trim($item["object"]) != "") {
2549 $r = XML::parseString($item["object"], false);
2550 if (isset($r->type)) {
2551 $item["object-type"] = $r->type;
2555 $target = $xpath->query("activity:target", $entry)->item(0);
2556 $item["target"] = self::transformActivity($xpath, $target, "target");
2558 $categories = $xpath->query("atom:category", $entry);
2560 foreach ($categories as $category) {
2563 foreach ($category->attributes as $attributes) {
2564 if ($attributes->name == "term") {
2565 $term = $attributes->textContent;
2568 if ($attributes->name == "scheme") {
2569 $scheme = $attributes->textContent;
2573 if (($term != "") && ($scheme != "")) {
2574 $parts = explode(":", $scheme);
2575 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2576 $termhash = array_shift($parts);
2577 $termurl = implode(":", $parts);
2579 if (strlen($item["tag"])) {
2580 $item["tag"] .= ",";
2583 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2591 $links = $xpath->query("atom:link", $entry);
2593 self::parseLinks($links, $item);
2596 $item['conversation-uri'] = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
2598 $conv = $xpath->query('ostatus:conversation', $entry);
2599 if (is_object($conv->item(0))) {
2600 foreach ($conv->item(0)->attributes as $attributes) {
2601 if ($attributes->name == "ref") {
2602 $item['conversation-uri'] = $attributes->textContent;
2604 if ($attributes->name == "href") {
2605 $item['conversation-href'] = $attributes->textContent;
2610 // Is it a reply or a top level posting?
2611 $item["parent-uri"] = $item["uri"];
2613 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2614 if (is_object($inreplyto->item(0))) {
2615 foreach ($inreplyto->item(0)->attributes as $attributes) {
2616 if ($attributes->name == "ref") {
2617 $item["parent-uri"] = $attributes->textContent;
2622 // Get the type of the item (Top level post, reply or remote reply)
2623 $entrytype = self::getEntryType($importer, $item);
2625 // Now assign the rest of the values that depend on the type of the message
2626 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2627 if (!isset($item["object-type"])) {
2628 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2631 if ($item["contact-id"] != $owner["contact-id"]) {
2632 $item["contact-id"] = $owner["contact-id"];
2635 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2636 $item["network"] = $owner["network"];
2639 if ($item["contact-id"] != $author["contact-id"]) {
2640 $item["contact-id"] = $author["contact-id"];
2643 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2644 $item["network"] = $author["network"];
2648 if ($entrytype == DFRN::REPLY_RC) {
2649 $item["type"] = "remote-comment";
2651 } elseif ($entrytype == DFRN::TOP_LEVEL) {
2652 if (!isset($item["object-type"])) {
2653 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2657 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2658 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2659 $ev = Event::fromBBCode($item["body"]);
2660 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2661 logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2662 $ev["cid"] = $importer["id"];
2663 $ev["uid"] = $importer["importer_uid"];
2664 $ev["uri"] = $item["uri"];
2665 $ev["edited"] = $item["edited"];
2666 $ev["private"] = $item["private"];
2667 $ev["guid"] = $item["guid"];
2670 "SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2671 dbesc($item["uri"]),
2672 intval($importer["importer_uid"])
2674 if (DBM::is_result($r)) {
2675 $ev["id"] = $r[0]["id"];
2678 $event_id = Event::store($ev);
2679 logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2685 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2686 logger("Exiting because 'processVerbs' told us so", LOGGER_DEBUG);
2690 // Update content if 'updated' changes
2691 if (DBM::is_result($current)) {
2692 if (self::updateContent($current, $item, $importer, $entrytype)) {
2693 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2695 logger("Item " . $item["uri"] . " already existed.", LOGGER_DEBUG);
2700 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2701 $posted_id = Item::insert($item);
2705 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2707 if ($item['uid'] == 0) {
2708 Item::distribute($posted_id);
2713 } else { // $entrytype == DFRN::TOP_LEVEL
2714 if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
2715 logger("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", LOGGER_DEBUG);
2718 if (!link_compare($item["owner-link"], $importer["url"])) {
2720 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2721 * but otherwise there's a possible data mixup on the sender's system.
2722 * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2723 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2725 logger('Correcting item owner.', LOGGER_DEBUG);
2726 $item["owner-link"] = $importer["url"];
2727 $item["owner-id"] = Contact::getIdForURL($importer["url"], 0);
2730 if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2731 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2735 // This is my contact on another system, but it's really me.
2736 // Turn this into a wall post.
2737 $notify = Item::isRemoteSelf($importer, $item);
2739 $posted_id = Item::insert($item, false, $notify);
2742 $posted_id = $notify;
2745 logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2747 if ($item['uid'] == 0) {
2748 Item::distribute($posted_id);
2751 if (stristr($item["verb"], ACTIVITY_POKE)) {
2752 self::doPoke($item, $importer, $posted_id);
2758 * @brief Deletes items
2760 * @param object $xpath XPath object
2761 * @param object $deletion deletion elements
2762 * @param array $importer Record of the importer user mixed with contact of the content
2764 * @todo set proper type-hints
2766 private static function processDeletion($xpath, $deletion, $importer)
2768 logger("Processing deletions");
2771 foreach ($deletion->attributes as $attributes) {
2772 if ($attributes->name == "ref") {
2773 $uri = $attributes->textContent;
2777 if (!$uri || !$importer["id"]) {
2781 $condition = ["`uri` = ? AND `uid` = ? AND NOT `file` LIKE '%[%'", $uri, $importer["importer_uid"]];
2782 $item = dba::selectFirst('item', ['id', 'parent', 'contact-id'], $condition);
2783 if (!DBM::is_result($item)) {
2784 logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", LOGGER_DEBUG);
2788 // When it is a starting post it has to belong to the person that wants to delete it
2789 if (($item['id'] == $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2790 logger("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2794 // Comments can be deleted by the thread owner or comment owner
2795 if (($item['id'] != $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2796 $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2797 if (!dba::exists('item', $condition)) {
2798 logger("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2803 if ($item["deleted"]) {
2807 logger('deleting item '.$item['id'].' uri='.$uri, LOGGER_DEBUG);
2809 Item::delete(['id' => $item['id']]);
2813 * @brief Imports a DFRN message
2815 * @param string $xml The DFRN message
2816 * @param array $importer Record of the importer user mixed with contact of the content
2817 * @param bool $sort_by_date Is used when feeds are polled
2818 * @return integer Import status
2819 * @todo set proper type-hints
2821 public static function import($xml, $importer, $sort_by_date = false)
2827 $doc = new DOMDocument();
2828 @$doc->loadXML($xml);
2830 $xpath = new DOMXPath($doc);
2831 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2832 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2833 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2834 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2835 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2836 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2837 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2838 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2839 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2840 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2843 $header["uid"] = $importer["importer_uid"];
2844 $header["network"] = NETWORK_DFRN;
2845 $header["type"] = "remote";
2846 $header["wall"] = 0;
2847 $header["origin"] = 0;
2848 $header["contact-id"] = $importer["id"];
2850 // Update the contact table if the data has changed
2852 // The "atom:author" is only present in feeds
2853 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2854 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2857 // Only the "dfrn:owner" in the head section contains all data
2858 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2859 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2862 logger("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2864 // is it a public forum? Private forums aren't exposed with this method
2865 $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()")->item(0)->nodeValue);
2867 // The account type is new since 3.5.1
2868 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2869 $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()")->item(0)->nodeValue);
2871 if ($accounttype != $importer["contact-type"]) {
2872 dba::update('contact', ['contact-type' => $accounttype], ['id' => $importer["id"]]);
2874 // A forum contact can either have set "forum" or "prv" - but not both
2875 if (($accounttype == ACCOUNT_TYPE_COMMUNITY) && (($forum != $importer["forum"]) || ($forum == $importer["prv"]))) {
2876 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer["id"]];
2877 dba::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2879 } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
2880 $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2881 dba::update('contact', ['forum' => $forum], $condition);
2885 // We are processing relocations even if we are ignoring a contact
2886 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2887 foreach ($relocations as $relocation) {
2888 self::processRelocation($xpath, $relocation, $importer);
2891 if (($importer["uid"] != 0) && !$importer["readonly"]) {
2892 $mails = $xpath->query("/atom:feed/dfrn:mail");
2893 foreach ($mails as $mail) {
2894 self::processMail($xpath, $mail, $importer);
2897 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2898 foreach ($suggestions as $suggestion) {
2899 self::processSuggestion($xpath, $suggestion, $importer);
2903 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2904 foreach ($deletions as $deletion) {
2905 self::processDeletion($xpath, $deletion, $importer);
2908 if (!$sort_by_date) {
2909 $entries = $xpath->query("/atom:feed/atom:entry");
2910 foreach ($entries as $entry) {
2911 self::processEntry($header, $xpath, $entry, $importer, $xml);
2915 $entries = $xpath->query("/atom:feed/atom:entry");
2916 foreach ($entries as $entry) {
2917 $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2918 $newentries[strtotime($created)] = $entry;
2921 // Now sort after the publishing date
2924 foreach ($newentries as $entry) {
2925 self::processEntry($header, $xpath, $entry, $importer, $xml);
2928 logger("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2934 * @param string $contact_nick contact nickname
2936 public static function autoRedir(App $a, $contact_nick)
2939 if (x($_REQUEST, 'redir') && intval($_REQUEST['redir'])) {
2943 if ((! $contact_nick) || ($contact_nick === $a->user['nickname'])) {
2948 // We need to find out if $contact_nick is a user on this hub, and if so, if I
2949 // am a contact of that user. However, that user may have other contacts with the
2950 // same nickname as me on other hubs or other networks. Exclude these by requiring
2951 // that the contact have a local URL. I will be the only person with my nickname at
2952 // this URL, so if a result is found, then I am a contact of the $contact_nick user.
2954 // We also have to make sure that I'm a legitimate contact--I'm not blocked or pending.
2956 $baseurl = System::baseUrl();
2957 $domain_st = strpos($baseurl, "://");
2958 if ($domain_st === false) {
2961 $baseurl = substr($baseurl, $domain_st + 3);
2962 $nurl = normalise_link($baseurl);
2964 /// @todo Why is there a query for "url" *and* "nurl"? Especially this normalising is strange.
2965 $r = q("SELECT `id` FROM `contact` WHERE `uid` = (SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1)
2966 AND `nick` = '%s' AND NOT `self` AND (`url` LIKE '%%%s%%' OR `nurl` LIKE '%%%s%%') AND NOT `blocked` AND NOT `pending` LIMIT 1",
2967 dbesc($contact_nick),
2968 dbesc($a->user['nickname']),
2972 if ((! DBM::is_result($r)) || $r[0]['id'] == remote_user()) {
2976 $r = q("SELECT * FROM contact WHERE nick = '%s'
2977 AND network = '%s' AND uid = %d AND url LIKE '%%%s%%' LIMIT 1",
2978 dbesc($contact_nick),
2979 dbesc(NETWORK_DFRN),
2980 intval(local_user()),
2983 if (! DBM::is_result($r)) {
2989 $dfrn_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2991 if ($r[0]['duplex'] && $r[0]['issued-id']) {
2992 $orig_id = $r[0]['issued-id'];
2993 $dfrn_id = '1:' . $orig_id;
2995 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
2996 $orig_id = $r[0]['dfrn-id'];
2997 $dfrn_id = '0:' . $orig_id;
3000 // ensure that we've got a valid ID. There may be some edge cases with forums and non-duplex mode
3001 // that may have triggered some of the "went to {profile/intro} and got an RSS feed" issues
3003 if (strlen($dfrn_id) < 3) {
3007 $sec = random_string();
3009 dba::insert('profile_check', ['uid' => local_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id, 'sec' => $sec, 'expire' => time() + 45]);
3011 $url = curPageURL();
3013 logger('auto_redir: ' . $r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
3014 $dest = (($url) ? '&destination_url=' . $url : '');
3015 goaway($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
3016 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest);
3023 * @brief Returns the activity verb
3025 * @param array $item Item array
3027 * @return string activity verb
3029 private static function constructVerb(array $item)
3031 if ($item['verb']) {
3032 return $item['verb'];
3034 return ACTIVITY_POST;
3037 private static function tgroupCheck($uid, $item)
3041 // check that the message originated elsewhere and is a top-level post
3043 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['parent-uri'])) {
3047 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
3050 if (!DBM::is_result($u)) {
3054 $community_page = ($u[0]['page-flags'] == PAGE_COMMUNITY);
3055 $prvgroup = ($u[0]['page-flags'] == PAGE_PRVGROUP);
3057 $link = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
3060 * Diaspora uses their own hardwired link URL in @-tags
3061 * instead of the one we supply with webfinger
3063 $dlink = normalise_link(System::baseUrl() . '/u/' . $u[0]['nickname']);
3065 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
3067 foreach ($matches as $mtch) {
3068 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
3070 logger('mention found: ' . $mtch[2]);
3079 return $community_page || $prvgroup;
3083 * This function returns true if $update has an edited timestamp newer
3084 * than $existing, i.e. $update contains new data which should override
3085 * what's already there. If there is no timestamp yet, the update is
3086 * assumed to be newer. If the update has no timestamp, the existing
3087 * item is assumed to be up-to-date. If the timestamps are equal it
3088 * assumes the update has been seen before and should be ignored.
3091 private static function isEditedTimestampNewer($existing, $update)
3093 if (!x($existing, 'edited') || !$existing['edited']) {
3096 if (!x($update, 'edited') || !$update['edited']) {
3100 $existing_edited = DateTimeFormat::utc($existing['edited']);
3101 $update_edited = DateTimeFormat::utc($update['edited']);
3103 return (strcmp($existing_edited, $update_edited) < 0);