2 namespace Friendica\Protocol;
4 * @file include/dfrn.php
5 * @brief The implementation of the dfrn protocol
7 * @see https://github.com/friendica/friendica/wiki/Protocol and
8 * https://github.com/friendica/friendica/blob/master/spec/dfrn2.pdf
12 use Friendica\Core\Config;
13 use Friendica\Core\System;
14 use Friendica\Core\Worker;
15 use Friendica\Database\DBM;
23 require_once("include/Contact.php");
24 require_once("include/enotify.php");
25 require_once("include/threads.php");
26 require_once("include/socgraph.php");
27 require_once("include/items.php");
28 require_once("include/tags.php");
29 require_once("include/files.php");
30 require_once("include/event.php");
31 require_once("include/text.php");
32 require_once("include/oembed.php");
33 require_once("include/html2bbcode.php");
34 require_once("include/bbcode.php");
37 * @brief This class contain functions to create and send DFRN XML files
42 const DFRN_TOP_LEVEL = 0; // Top level posting
43 const DFRN_REPLY = 1; // Regular reply that is stored locally
44 const DFRN_REPLY_RC = 2; // Reply that will be relayed
47 * @brief Generates the atom entries for delivery.php
49 * This function is used whenever content is transmitted via DFRN.
51 * @param array $items Item elements
52 * @param array $owner Owner record
54 * @return string DFRN entries
55 * @todo Add type-hints
57 public static function entries($items,$owner) {
59 $doc = new DOMDocument('1.0', 'utf-8');
60 $doc->formatOutput = true;
62 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
64 if (! count($items)) {
65 return trim($doc->saveXML());
68 foreach ($items as $item) {
69 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
70 $root->appendChild($entry);
73 return(trim($doc->saveXML()));
77 * @brief Generate an atom feed for the given user
79 * This function is called when another server is pulling data from the user feed.
81 * @param string $dfrn_id DFRN ID from the requesting party
82 * @param string $owner_nick Owner nick name
83 * @param string $last_update Date of the last update
84 * @param int $direction Can be -1, 0 or 1.
85 * @param boolean $onlyheader Output only the header without content? (Default is "no")
87 * @return string DFRN feed entries
89 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false) {
93 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
94 $public_feed = (($dfrn_id) ? false : true);
95 $starred = false; // not yet implemented, possible security issues
98 if ($public_feed && $a->argc > 2) {
99 for ($x = 2; $x < $a->argc; $x++) {
100 if ($a->argv[$x] == 'converse') {
103 if ($a->argv[$x] == 'starred') {
106 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
107 $category = $a->argv[$x+1];
114 // default permissions - anonymous user
116 $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = '' ";
118 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
119 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
120 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
124 if (! DBM::is_result($r)) {
129 $owner_id = $owner['uid'];
130 $owner_nick = $owner['nickname'];
132 $sql_post_table = "";
134 if (! $public_feed) {
139 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
143 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
144 $my_id = '1:' . $dfrn_id;
147 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
148 $my_id = '0:' . $dfrn_id;
155 $r = q("SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
159 if (! DBM::is_result($r)) {
164 require_once('include/security.php');
165 $groups = init_groups_visitor($contact['id']);
167 if (count($groups)) {
168 for ($x = 0; $x < count($groups); $x ++)
169 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
170 $gs = implode('|', $groups);
172 $gs = '<<>>' ; // Impossible to match
175 $sql_extra = sprintf("
176 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
177 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
178 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
179 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
181 intval($contact['id']),
182 intval($contact['id']),
194 if (! strlen($last_update)) {
195 $last_update = 'now -30 days';
198 if (isset($category)) {
199 $sql_post_table = sprintf("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` ",
200 dbesc(protect_sprintf($category)), intval(TERM_OBJ_POST), intval(TERM_CATEGORY), intval($owner_id));
201 //$sql_extra .= file_tag_file_query('item',$category,'category');
206 $sql_extra .= " AND `contact`.`self` = 1 ";
210 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
212 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
213 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
214 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
215 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
216 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
217 FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
218 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
219 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
220 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
221 WHERE `item`.`uid` = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
222 AND `item`.`wall` AND `item`.`changed` > '%s'
224 ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
231 * Will check further below if this actually returned results.
232 * We will provide an empty feed if that is the case.
237 $doc = new DOMDocument('1.0', 'utf-8');
238 $doc->formatOutput = true;
240 $alternatelink = $owner['url'];
242 if (isset($category)) {
243 $alternatelink .= "/category/".$category;
247 $author = "dfrn:owner";
252 $root = self::add_header($doc, $owner, $author, $alternatelink, true);
254 /// @TODO This hook can't work anymore
255 // call_hooks('atom_feed', $atom);
257 if (!DBM::is_result($items) || $onlyheader) {
258 $atom = trim($doc->saveXML());
260 call_hooks('atom_feed_end', $atom);
265 foreach ($items as $item) {
267 // prevent private email from leaking.
268 if ($item['network'] == NETWORK_MAIL) {
272 // public feeds get html, our own nodes use bbcode
276 // catch any email that's in a public conversation and make sure it doesn't leak
277 if ($item['private']) {
284 $entry = self::entry($doc, $type, $item, $owner, true);
285 $root->appendChild($entry);
289 $atom = trim($doc->saveXML());
291 call_hooks('atom_feed_end', $atom);
297 * @brief Generate an atom entry for a given item id
299 * @param int $item_id The item id
300 * @param boolean $conversation Show the conversation. If false show the single post.
302 * @return string DFRN feed entry
304 public static function itemFeed($item_id, $conversation = false) {
306 $condition = '`item`.`parent`';
308 $condition = '`item`.`id`';
311 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
312 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
313 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
314 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
315 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
317 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
318 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
319 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
320 WHERE %s = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
321 AND NOT `item`.`private`",
326 if (!DBM::is_result($r)) {
333 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
334 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
335 WHERE `contact`.`self` AND `user`.`uid` = %d LIMIT 1",
339 if (!DBM::is_result($r)) {
345 $doc = new DOMDocument('1.0', 'utf-8');
346 $doc->formatOutput = true;
350 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
351 $doc->appendChild($root);
353 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
354 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
355 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
356 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
357 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
358 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
359 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
360 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
361 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
363 //$root = self::add_header($doc, $owner, "dfrn:owner", "", false);
365 foreach ($items as $item) {
366 $entry = self::entry($doc, $type, $item, $owner, true, 0);
367 $root->appendChild($entry);
370 $root = self::entry($doc, $type, $item, $owner, true, 0, true);
373 $atom = trim($doc->saveXML());
378 * @brief Create XML text for DFRN mails
380 * @param array $item message elements
381 * @param array $owner Owner record
383 * @return string DFRN mail
384 * @todo Add type-hints
386 public static function mail($item, $owner) {
387 $doc = new DOMDocument('1.0', 'utf-8');
388 $doc->formatOutput = true;
390 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
392 $mail = $doc->createElement("dfrn:mail");
393 $sender = $doc->createElement("dfrn:sender");
395 xml::add_element($doc, $sender, "dfrn:name", $owner['name']);
396 xml::add_element($doc, $sender, "dfrn:uri", $owner['url']);
397 xml::add_element($doc, $sender, "dfrn:avatar", $owner['thumb']);
399 $mail->appendChild($sender);
401 xml::add_element($doc, $mail, "dfrn:id", $item['uri']);
402 xml::add_element($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
403 xml::add_element($doc, $mail, "dfrn:sentdate", datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME));
404 xml::add_element($doc, $mail, "dfrn:subject", $item['title']);
405 xml::add_element($doc, $mail, "dfrn:content", $item['body']);
407 $root->appendChild($mail);
409 return(trim($doc->saveXML()));
413 * @brief Create XML text for DFRN friend suggestions
415 * @param array $item suggestion elements
416 * @param array $owner Owner record
418 * @return string DFRN suggestions
419 * @todo Add type-hints
421 public static function fsuggest($item, $owner) {
422 $doc = new DOMDocument('1.0', 'utf-8');
423 $doc->formatOutput = true;
425 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
427 $suggest = $doc->createElement("dfrn:suggest");
429 xml::add_element($doc, $suggest, "dfrn:url", $item['url']);
430 xml::add_element($doc, $suggest, "dfrn:name", $item['name']);
431 xml::add_element($doc, $suggest, "dfrn:photo", $item['photo']);
432 xml::add_element($doc, $suggest, "dfrn:request", $item['request']);
433 xml::add_element($doc, $suggest, "dfrn:note", $item['note']);
435 $root->appendChild($suggest);
437 return(trim($doc->saveXML()));
441 * @brief Create XML text for DFRN relocations
443 * @param array $owner Owner record
444 * @param int $uid User ID
446 * @return string DFRN relocations
447 * @todo Add type-hints
449 public static function relocate($owner, $uid) {
451 /* get site pubkey. this could be a new installation with no site keys*/
452 $pubkey = Config::get('system','site_pubkey');
454 $res = new_keypair(1024);
455 Config::set('system','site_prvkey', $res['prvkey']);
456 Config::set('system','site_pubkey', $res['pubkey']);
459 $rp = q("SELECT `resource-id` , `scale`, type FROM `photo`
460 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;", $uid);
462 $ext = Photo::supportedTypes();
464 foreach ($rp as $p) {
465 $photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
470 $doc = new DOMDocument('1.0', 'utf-8');
471 $doc->formatOutput = true;
473 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
475 $relocate = $doc->createElement("dfrn:relocate");
477 xml::add_element($doc, $relocate, "dfrn:url", $owner['url']);
478 xml::add_element($doc, $relocate, "dfrn:name", $owner['name']);
479 xml::add_element($doc, $relocate, "dfrn:addr", $owner['addr']);
480 xml::add_element($doc, $relocate, "dfrn:avatar", $owner['avatar']);
481 xml::add_element($doc, $relocate, "dfrn:photo", $photos[4]);
482 xml::add_element($doc, $relocate, "dfrn:thumb", $photos[5]);
483 xml::add_element($doc, $relocate, "dfrn:micro", $photos[6]);
484 xml::add_element($doc, $relocate, "dfrn:request", $owner['request']);
485 xml::add_element($doc, $relocate, "dfrn:confirm", $owner['confirm']);
486 xml::add_element($doc, $relocate, "dfrn:notify", $owner['notify']);
487 xml::add_element($doc, $relocate, "dfrn:poll", $owner['poll']);
488 xml::add_element($doc, $relocate, "dfrn:sitepubkey", Config::get('system','site_pubkey'));
490 $root->appendChild($relocate);
492 return(trim($doc->saveXML()));
496 * @brief Adds the header elements for the DFRN protocol
498 * @param object $doc XML document
499 * @param array $owner Owner record
500 * @param string $authorelement Element name for the author
501 * @param string $alternatelink link to profile or category
502 * @param bool $public Is it a header for public posts?
504 * @return object XML root object
505 * @todo Add type-hints
507 private static function add_header($doc, $owner, $authorelement, $alternatelink = "", $public = false) {
509 if ($alternatelink == "") {
510 $alternatelink = $owner['url'];
513 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
514 $doc->appendChild($root);
516 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
517 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
518 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
519 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
520 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
521 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
522 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
523 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
524 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
526 xml::add_element($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
527 xml::add_element($doc, $root, "title", $owner["name"]);
529 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
530 xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
532 $attributes = array("rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/");
533 xml::add_element($doc, $root, "link", "", $attributes);
535 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $alternatelink);
536 xml::add_element($doc, $root, "link", "", $attributes);
540 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
541 ostatus::hublinks($doc, $root, $owner["nick"]);
543 $attributes = array("rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
544 xml::add_element($doc, $root, "link", "", $attributes);
546 $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
547 xml::add_element($doc, $root, "link", "", $attributes);
549 $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
550 xml::add_element($doc, $root, "link", "", $attributes);
553 // For backward compatibility we keep this element
554 if ($owner['page-flags'] == PAGE_COMMUNITY) {
555 xml::add_element($doc, $root, "dfrn:community", 1);
558 // The former element is replaced by this one
559 xml::add_element($doc, $root, "dfrn:account_type", $owner["account-type"]);
561 /// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
563 xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
565 $author = self::add_author($doc, $owner, $authorelement, $public);
566 $root->appendChild($author);
572 * @brief Adds the author element in the header for the DFRN protocol
574 * @param object $doc XML document
575 * @param array $owner Owner record
576 * @param string $authorelement Element name for the author
578 * @return object XML author object
579 * @todo Add type-hints
581 private static function add_author($doc, $owner, $authorelement, $public) {
583 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
584 $r = q("SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
585 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
586 intval($owner['uid']));
587 if (DBM::is_result($r)) {
593 $author = $doc->createElement($authorelement);
595 $namdate = datetime_convert('UTC', 'UTC', $owner['name-date'].'+00:00', ATOM_TIME);
596 $uridate = datetime_convert('UTC', 'UTC', $owner['uri-date'].'+00:00', ATOM_TIME);
597 $picdate = datetime_convert('UTC', 'UTC', $owner['avatar-date'].'+00:00', ATOM_TIME);
599 $attributes = array();
601 if (!$public || !$hidewall) {
602 $attributes = array("dfrn:updated" => $namdate);
605 xml::add_element($doc, $author, "name", $owner["name"], $attributes);
606 xml::add_element($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
607 xml::add_element($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
609 $attributes = array("rel" => "photo", "type" => "image/jpeg",
610 "media:width" => 175, "media:height" => 175, "href" => $owner['photo']);
612 if (!$public || !$hidewall) {
613 $attributes["dfrn:updated"] = $picdate;
616 xml::add_element($doc, $author, "link", "", $attributes);
618 $attributes["rel"] = "avatar";
619 xml::add_element($doc, $author, "link", "", $attributes);
622 xml::add_element($doc, $author, "dfrn:hide", "true");
625 // The following fields will only be generated if the data isn't meant for a public feed
630 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
633 xml::add_element($doc, $author, "dfrn:birthday", $birthday);
635 // Only show contact details when we are allowed to
636 $r = q("SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
637 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
638 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
640 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
641 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
642 intval($owner['uid']));
643 if (DBM::is_result($r)) {
646 xml::add_element($doc, $author, "poco:displayName", $profile["name"]);
647 xml::add_element($doc, $author, "poco:updated", $namdate);
649 if (trim($profile["dob"]) > '0001-01-01') {
650 xml::add_element($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
653 xml::add_element($doc, $author, "poco:note", $profile["about"]);
654 xml::add_element($doc, $author, "poco:preferredUsername", $profile["nickname"]);
656 $savetz = date_default_timezone_get();
657 date_default_timezone_set($profile["timezone"]);
658 xml::add_element($doc, $author, "poco:utcOffset", date("P"));
659 date_default_timezone_set($savetz);
661 if (trim($profile["homepage"]) != "") {
662 $urls = $doc->createElement("poco:urls");
663 xml::add_element($doc, $urls, "poco:type", "homepage");
664 xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
665 xml::add_element($doc, $urls, "poco:primary", "true");
666 $author->appendChild($urls);
669 if (trim($profile["pub_keywords"]) != "") {
670 $keywords = explode(",", $profile["pub_keywords"]);
672 foreach ($keywords AS $keyword) {
673 xml::add_element($doc, $author, "poco:tags", trim($keyword));
678 if (trim($profile["xmpp"]) != "") {
679 $ims = $doc->createElement("poco:ims");
680 xml::add_element($doc, $ims, "poco:type", "xmpp");
681 xml::add_element($doc, $ims, "poco:value", $profile["xmpp"]);
682 xml::add_element($doc, $ims, "poco:primary", "true");
683 $author->appendChild($ims);
686 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
687 $element = $doc->createElement("poco:address");
689 xml::add_element($doc, $element, "poco:formatted", formatted_location($profile));
691 if (trim($profile["locality"]) != "") {
692 xml::add_element($doc, $element, "poco:locality", $profile["locality"]);
695 if (trim($profile["region"]) != "") {
696 xml::add_element($doc, $element, "poco:region", $profile["region"]);
699 if (trim($profile["country-name"]) != "") {
700 xml::add_element($doc, $element, "poco:country", $profile["country-name"]);
703 $author->appendChild($element);
711 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
713 * @param object $doc XML document
714 * @param string $element Element name for the author
715 * @param string $contact_url Link of the contact
716 * @param array $items Item elements
718 * @return object XML author object
719 * @todo Add type-hints
721 private static function add_entry_author($doc, $element, $contact_url, $item) {
723 $contact = get_contact_details_by_url($contact_url, $item["uid"]);
725 $author = $doc->createElement($element);
726 xml::add_element($doc, $author, "name", $contact["name"]);
727 xml::add_element($doc, $author, "uri", $contact["url"]);
728 xml::add_element($doc, $author, "dfrn:handle", $contact["addr"]);
731 /// - Check real image type and image size
732 /// - Check which of these boths elements we should use
735 "type" => "image/jpeg",
737 "media:height" => 80,
738 "href" => $contact["photo"]);
739 xml::add_element($doc, $author, "link", "", $attributes);
743 "type" => "image/jpeg",
745 "media:height" => 80,
746 "href" => $contact["photo"]);
747 xml::add_element($doc, $author, "link", "", $attributes);
753 * @brief Adds the activity elements
755 * @param object $doc XML document
756 * @param string $element Element name for the activity
757 * @param string $activity activity value
759 * @return object XML activity object
760 * @todo Add type-hints
762 private static function create_activity($doc, $element, $activity) {
765 $entry = $doc->createElement($element);
767 $r = parse_xml_string($activity, false);
772 xml::add_element($doc, $entry, "activity:object-type", $r->type);
775 xml::add_element($doc, $entry, "id", $r->id);
778 xml::add_element($doc, $entry, "title", $r->title);
782 if (substr($r->link, 0, 1) == '<') {
783 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
784 $r->link = str_replace('&', '&', $r->link);
787 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
789 // XML does need a single element as root element so we add a dummy element here
790 $data = parse_xml_string("<dummy>" . $r->link . "</dummy>", false);
791 if (is_object($data)) {
792 foreach ($data->link AS $link) {
793 $attributes = array();
794 foreach ($link->attributes() AS $parameter => $value) {
795 $attributes[$parameter] = $value;
797 xml::add_element($doc, $entry, "link", "", $attributes);
801 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $r->link);
802 xml::add_element($doc, $entry, "link", "", $attributes);
806 xml::add_element($doc, $entry, "content", bbcode($r->content), array("type" => "html"));
816 * @brief Adds the elements for attachments
818 * @param object $doc XML document
819 * @param object $root XML root
820 * @param array $item Item element
822 * @return object XML attachment object
823 * @todo Add type-hints
825 private static function get_attachment($doc, $root, $item) {
826 $arr = explode('[/attach],',$item['attach']);
828 foreach ($arr as $r) {
830 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches);
832 $attributes = array("rel" => "enclosure",
833 "href" => $matches[1],
834 "type" => $matches[3]);
836 if (intval($matches[2])) {
837 $attributes["length"] = intval($matches[2]);
840 if (trim($matches[4]) != "") {
841 $attributes["title"] = trim($matches[4]);
844 xml::add_element($doc, $root, "link", "", $attributes);
851 * @brief Adds the "entry" elements for the DFRN protocol
853 * @param object $doc XML document
854 * @param string $type "text" or "html"
855 * @param array $item Item element
856 * @param array $owner Owner record
857 * @param bool $comment Trigger the sending of the "comment" element
858 * @param int $cid Contact ID of the recipient
859 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
861 * @return object XML entry object
862 * @todo Add type-hints
864 private static function entry($doc, $type, $item, $owner, $comment = false, $cid = 0, $single = false) {
866 $mentioned = array();
868 if (!$item['parent']) {
872 if ($item['deleted']) {
873 $attributes = array("ref" => $item['uri'], "when" => datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME));
874 return xml::create_element($doc, "at:deleted-entry", "", $attributes);
878 $entry = $doc->createElement("entry");
880 $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry');
881 $doc->appendChild($entry);
883 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
884 $entry->setAttribute("xmlns:at", NAMESPACE_TOMB);
885 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
886 $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
887 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
888 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
889 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
890 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
891 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
894 if ($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid']) {
895 $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
897 $body = $item['body'];
900 // Remove the abstract element. It is only locally important.
901 $body = remove_abstract($body);
903 if ($type == 'html') {
906 if ($item['title'] != "") {
907 $htmlbody = "[b]".$item['title']."[/b]\n\n".$htmlbody;
910 $htmlbody = bbcode($htmlbody, false, false, 7);
913 $author = self::add_entry_author($doc, "author", $item["author-link"], $item);
914 $entry->appendChild($author);
916 $dfrnowner = self::add_entry_author($doc, "dfrn:owner", $item["owner-link"], $item);
917 $entry->appendChild($dfrnowner);
919 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
920 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
921 $parent = q("SELECT `guid`,`plink` FROM `item` WHERE `uri` = '%s' AND `uid` = %d", dbesc($parent_item), intval($item['uid']));
922 $attributes = array("ref" => $parent_item, "type" => "text/html",
923 "href" => $parent[0]['plink'],
924 "dfrn:diaspora_guid" => $parent[0]['guid']);
925 xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
928 // Add conversation data. This is used for OStatus
929 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
930 $conversation_uri = $conversation_href;
932 if (isset($parent_item)) {
933 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $item['parent-uri']);
934 if (DBM::is_result($r)) {
935 if ($r['conversation-uri'] != '') {
936 $conversation_uri = $r['conversation-uri'];
938 if ($r['conversation-href'] != '') {
939 $conversation_href = $r['conversation-href'];
945 "href" => $conversation_href,
946 "ref" => $conversation_uri);
948 xml::add_element($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
950 xml::add_element($doc, $entry, "id", $item["uri"]);
951 xml::add_element($doc, $entry, "title", $item["title"]);
953 xml::add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
954 xml::add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
956 // "dfrn:env" is used to read the content
957 xml::add_element($doc, $entry, "dfrn:env", base64url_encode($body, true));
959 // The "content" field is not read by the receiver. We could remove it when the type is "text"
960 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
961 xml::add_element($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), array("type" => $type));
963 // We save this value in "plink". Maybe we should read it from there as well?
964 xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
965 "href" => System::baseUrl()."/display/".$item["guid"]));
967 // "comment-allow" is some old fashioned stuff for old Friendica versions.
968 // It is included in the rewritten code for completeness
970 xml::add_element($doc, $entry, "dfrn:comment-allow", intval($item['last-child']));
973 if ($item['location']) {
974 xml::add_element($doc, $entry, "dfrn:location", $item['location']);
977 if ($item['coord']) {
978 xml::add_element($doc, $entry, "georss:point", $item['coord']);
981 if (($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])) {
982 xml::add_element($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
985 if ($item['extid']) {
986 xml::add_element($doc, $entry, "dfrn:extid", $item['extid']);
989 if ($item['bookmark']) {
990 xml::add_element($doc, $entry, "dfrn:bookmark", "true");
994 xml::add_element($doc, $entry, "statusnet:notice_info", "", array("local_id" => $item['id'], "source" => $item['app']));
997 xml::add_element($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
999 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
1000 // It is needed for relayed comments to Diaspora.
1001 if ($item['signed_text']) {
1002 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
1003 xml::add_element($doc, $entry, "dfrn:diaspora_signature", $sign);
1006 xml::add_element($doc, $entry, "activity:verb", construct_verb($item));
1008 if ($item['object-type'] != "") {
1009 xml::add_element($doc, $entry, "activity:object-type", $item['object-type']);
1010 } elseif ($item['id'] == $item['parent']) {
1011 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1013 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
1016 $actobj = self::create_activity($doc, "activity:object", $item['object']);
1018 $entry->appendChild($actobj);
1021 $actarg = self::create_activity($doc, "activity:target", $item['target']);
1023 $entry->appendChild($actarg);
1026 $tags = item_getfeedtags($item);
1029 foreach ($tags as $t) {
1030 if (($type != 'html') || ($t[0] != "@")) {
1031 xml::add_element($doc, $entry, "category", "", array("scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]));
1037 foreach ($tags as $t) {
1039 $mentioned[$t[1]] = $t[1];
1044 foreach ($mentioned AS $mention) {
1045 $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1046 intval($owner["uid"]),
1047 dbesc(normalise_link($mention)));
1049 if (DBM::is_result($r) && ($r[0]["forum"] || $r[0]["prv"])) {
1050 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1051 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1052 "href" => $mention));
1054 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1055 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1056 "href" => $mention));
1060 self::get_attachment($doc, $entry, $item);
1066 * @brief encrypts data via AES
1068 * @param string $data The data that is to be encrypted
1069 * @param string $key The AES key
1071 * @return string encrypted data
1073 private static function aes_encrypt($data, $key) {
1074 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1078 * @brief decrypts data via AES
1080 * @param string $encrypted The encrypted data
1081 * @param string $key The AES key
1083 * @return string decrypted data
1085 public static function aes_decrypt($encrypted, $key) {
1086 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1090 * @brief Delivers the atom content to the contacts
1092 * @param array $owner Owner record
1093 * @param array $contactr Contact record of the receiver
1094 * @param string $atom Content that will be transmitted
1095 * @param bool $dissolve (to be documented)
1097 * @return int Deliver status. -1 means an error.
1098 * @todo Add array type-hint for $owner, $contact
1100 public static function deliver($owner,$contact,$atom, $dissolve = false) {
1104 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1106 if ($contact['duplex'] && $contact['dfrn-id']) {
1107 $idtosend = '0:' . $orig_id;
1109 if ($contact['duplex'] && $contact['issued-id']) {
1110 $idtosend = '1:' . $orig_id;
1113 $rino = Config::get('system', 'rino_encrypt');
1114 $rino = intval($rino);
1116 logger("Local rino version: ". $rino, LOGGER_DEBUG);
1118 $ssl_val = intval(Config::get('system','ssl_policy'));
1122 case SSL_POLICY_FULL:
1123 $ssl_policy = 'full';
1125 case SSL_POLICY_SELFSIGN:
1126 $ssl_policy = 'self';
1128 case SSL_POLICY_NONE:
1130 $ssl_policy = 'none';
1134 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1136 logger('dfrn_deliver: ' . $url);
1138 $ret = z_fetch_url($url);
1140 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1141 return -2; // timed out
1144 $xml = $ret['body'];
1146 $curl_stat = $a->get_curl_code();
1148 return -3; // timed out
1151 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1157 if (strpos($xml,'<?xml') === false) {
1158 logger('dfrn_deliver: no valid XML returned');
1159 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1163 $res = parse_xml_string($xml);
1165 if ((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id))) {
1166 return (($res->status) ? $res->status : 3);
1169 $postvars = array();
1170 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1171 $challenge = hex2bin((string) $res->challenge);
1172 $perm = (($res->perm) ? $res->perm : null);
1173 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1174 $rino_remote_version = intval($res->rino);
1175 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1177 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
1179 if ($owner['page-flags'] == PAGE_PRVGROUP) {
1183 $final_dfrn_id = '';
1186 if ((($perm == 'rw') && (! intval($contact['writable'])))
1187 || (($perm == 'r') && (intval($contact['writable'])))) {
1188 q("update contact set writable = %d where id = %d",
1189 intval(($perm == 'rw') ? 1 : 0),
1190 intval($contact['id'])
1192 $contact['writable'] = (string) 1 - intval($contact['writable']);
1196 if (($contact['duplex'] && strlen($contact['pubkey']))
1197 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1198 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1199 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
1200 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
1202 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
1203 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
1206 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1208 if (strpos($final_dfrn_id,':') == 1) {
1209 $final_dfrn_id = substr($final_dfrn_id,2);
1212 if ($final_dfrn_id != $orig_id) {
1213 logger('dfrn_deliver: wrong dfrn_id.');
1214 // did not decode properly - cannot trust this site
1218 $postvars['dfrn_id'] = $idtosend;
1219 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1221 $postvars['dissolve'] = '1';
1225 if ((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1226 $postvars['data'] = $atom;
1227 $postvars['perm'] = 'rw';
1229 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1230 $postvars['perm'] = 'r';
1233 $postvars['ssl_policy'] = $ssl_policy;
1236 $postvars['page'] = $page;
1240 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1241 logger('rino version: '. $rino_remote_version);
1243 switch ($rino_remote_version) {
1245 // Deprecated rino version!
1246 $key = openssl_random_pseudo_bytes(16);
1247 $data = self::aes_encrypt($postvars['data'], $key);
1250 // RINO 2 based on php-encryption
1252 $key = Crypto::createNewRandomKey();
1253 } catch (CryptoTestFailed $ex) {
1254 logger('Cannot safely create a key');
1256 } catch (CannotPerformOperation $ex) {
1257 logger('Cannot safely create a key');
1261 $data = Crypto::encrypt($postvars['data'], $key);
1262 } catch (CryptoTestFailed $ex) {
1263 logger('Cannot safely perform encryption');
1265 } catch (CannotPerformOperation $ex) {
1266 logger('Cannot safely perform encryption');
1271 logger("rino: invalid requested verision '$rino_remote_version'");
1275 $postvars['rino'] = $rino_remote_version;
1276 $postvars['data'] = bin2hex($data);
1278 //logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1281 if ($dfrn_version >= 2.1) {
1282 if (($contact['duplex'] && strlen($contact['pubkey']))
1283 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1284 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1285 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1287 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1291 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1292 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1294 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1299 logger('md5 rawkey ' . md5($postvars['key']));
1301 $postvars['key'] = bin2hex($postvars['key']);
1305 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1307 $xml = post_url($contact['notify'], $postvars);
1309 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1311 $curl_stat = $a->get_curl_code();
1312 if ((!$curl_stat) || (!strlen($xml))) {
1313 return -9; // timed out
1316 if (($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after'))) {
1320 if (strpos($xml,'<?xml') === false) {
1321 logger('dfrn_deliver: phase 2: no valid XML returned');
1322 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1326 if ($contact['term-date'] > NULL_DATE) {
1327 logger("dfrn_deliver: $url back from the dead - removing mark for death");
1328 require_once('include/Contact.php');
1329 unmark_for_death($contact);
1332 $res = parse_xml_string($xml);
1334 if (!isset($res->status)) {
1338 if (!empty($res->message)) {
1339 logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1342 return intval($res->status);
1346 * @brief Add new birthday event for this person
1348 * @param array $contact Contact record
1349 * @param string $birthday Birthday of the contact
1350 * @todo Add array type-hint for $contact
1352 private static function birthday_event($contact, $birthday) {
1354 // Check for duplicates
1355 $r = q("SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1356 intval($contact["uid"]),
1357 intval($contact["id"]),
1358 dbesc(datetime_convert("UTC","UTC", $birthday)),
1361 if (DBM::is_result($r)) {
1365 logger("updating birthday: ".$birthday." for contact ".$contact["id"]);
1367 $bdtext = sprintf(t("%s\'s birthday"), $contact["name"]);
1368 $bdtext2 = sprintf(t("Happy Birthday %s"), " [url=".$contact["url"]."]".$contact["name"]."[/url]") ;
1370 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1371 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1372 intval($contact["uid"]),
1373 intval($contact["id"]),
1374 dbesc(datetime_convert()),
1375 dbesc(datetime_convert()),
1376 dbesc(datetime_convert("UTC","UTC", $birthday)),
1377 dbesc(datetime_convert("UTC","UTC", $birthday." + 1 day ")),
1385 * @brief Fetch the author data from head or entry items
1387 * @param object $xpath XPath object
1388 * @param object $context In which context should the data be searched
1389 * @param array $importer Record of the importer user mixed with contact of the content
1390 * @param string $element Element name from which the data is fetched
1391 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1393 * @return Returns an array with relevant data of the author
1394 * @todo Find good type-hints for all parameter
1396 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "") {
1399 $author["name"] = $xpath->evaluate($element."/atom:name/text()", $context)->item(0)->nodeValue;
1400 $author["link"] = $xpath->evaluate($element."/atom:uri/text()", $context)->item(0)->nodeValue;
1402 $r = q("SELECT `id`, `uid`, `url`, `network`, `avatar-date`, `name-date`, `uri-date`, `addr`,
1403 `name`, `nick`, `about`, `location`, `keywords`, `xmpp`, `bdyear`, `bd`, `hidden`, `contact-type`
1404 FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
1405 intval($importer["uid"]), dbesc(normalise_link($author["link"])), dbesc(NETWORK_STATUSNET));
1407 if (DBM::is_result($r)) {
1409 $author["contact-id"] = $r[0]["id"];
1410 $author["network"] = $r[0]["network"];
1413 logger("Contact ".$author["link"]." wasn't found for user ".$importer["uid"]." XML: ".$xml, LOGGER_DEBUG);
1416 $author["contact-id"] = $importer["id"];
1417 $author["network"] = $importer["network"];
1421 // Until now we aren't serving different sizes - but maybe later
1422 $avatarlist = array();
1423 /// @todo check if "avatar" or "photo" would be the best field in the specification
1424 $avatars = $xpath->query($element."/atom:link[@rel='avatar']", $context);
1425 foreach ($avatars AS $avatar) {
1428 foreach ($avatar->attributes AS $attributes) {
1429 /// @TODO Rewrite these similar if () to one switch
1430 if ($attributes->name == "href") {
1431 $href = $attributes->textContent;
1433 if ($attributes->name == "width") {
1434 $width = $attributes->textContent;
1436 if ($attributes->name == "updated") {
1437 $contact["avatar-date"] = $attributes->textContent;
1440 if (($width > 0) && ($href != "")) {
1441 $avatarlist[$width] = $href;
1444 if (count($avatarlist) > 0) {
1445 krsort($avatarlist);
1446 $author["avatar"] = current($avatarlist);
1449 if (DBM::is_result($r) && !$onlyfetch) {
1450 logger("Check if contact details for contact " . $r[0]["id"] . " (" . $r[0]["nick"] . ") have to be updated.", LOGGER_DEBUG);
1452 $poco = array("url" => $contact["url"]);
1454 // When was the last change to name or uri?
1455 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1456 foreach ($name_element->attributes AS $attributes) {
1457 if ($attributes->name == "updated") {
1458 $poco["name-date"] = $attributes->textContent;
1462 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1463 foreach ($link_element->attributes AS $attributes) {
1464 if ($attributes->name == "updated") {
1465 $poco["uri-date"] = $attributes->textContent;
1469 // Update contact data
1470 $value = $xpath->evaluate($element . "/dfrn:handle/text()", $context)->item(0)->nodeValue;
1472 $poco["addr"] = $value;
1475 $value = $xpath->evaluate($element . "/poco:displayName/text()", $context)->item(0)->nodeValue;
1477 $poco["name"] = $value;
1480 $value = $xpath->evaluate($element . "/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
1482 $poco["nick"] = $value;
1485 $value = $xpath->evaluate($element . "/poco:note/text()", $context)->item(0)->nodeValue;
1487 $poco["about"] = $value;
1490 $value = $xpath->evaluate($element . "/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
1492 $poco["location"] = $value;
1495 /// @todo Only search for elements with "poco:type" = "xmpp"
1496 $value = $xpath->evaluate($element . "/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
1498 $poco["xmpp"] = $value;
1501 /// @todo Add support for the following fields that we don't support by now in the contact table:
1502 /// - poco:utcOffset
1508 // If the "hide" element is present then the profile isn't searchable.
1509 $hide = intval($xpath->evaluate($element . "/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
1511 logger("Hidden status for contact " . $contact["url"] . ": " . $hide, LOGGER_DEBUG);
1513 // If the contact isn't searchable then set the contact to "hidden".
1514 // Problem: This can be manually overridden by the user.
1516 $contact["hidden"] = true;
1519 // Save the keywords into the contact table
1521 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1522 foreach ($tagelements AS $tag) {
1523 $tags[$tag->nodeValue] = $tag->nodeValue;
1527 $poco["keywords"] = implode(", ", $tags);
1530 // "dfrn:birthday" contains the birthday converted to UTC
1531 $old_bdyear = $contact["bdyear"];
1533 $birthday = $xpath->evaluate($element . "/dfrn:birthday/text()", $context)->item(0)->nodeValue;
1535 if (strtotime($birthday) > time()) {
1536 $bd_timestamp = strtotime($birthday);
1538 $poco["bdyear"] = date("Y", $bd_timestamp);
1541 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1542 $value = $xpath->evaluate($element . "/poco:birthday/text()", $context)->item(0)->nodeValue;
1544 if (!in_array($value, array("", "0000-00-00", "0001-01-01"))) {
1545 $bdyear = date("Y");
1546 $value = str_replace("0000", $bdyear, $value);
1548 if (strtotime($value) < time()) {
1549 $value = str_replace($bdyear, $bdyear + 1, $value);
1550 $bdyear = $bdyear + 1;
1553 $poco["bd"] = $value;
1556 $contact = array_merge($contact, $poco);
1558 if ($old_bdyear != $contact["bdyear"]) {
1559 self::birthday_event($contact, $birthday);
1562 // Get all field names
1564 foreach ($r[0] AS $field => $data) {
1565 $fields[$field] = $data;
1568 unset($fields["id"]);
1569 unset($fields["uid"]);
1570 unset($fields["url"]);
1571 unset($fields["avatar-date"]);
1572 unset($fields["name-date"]);
1573 unset($fields["uri-date"]);
1575 // Update check for this field has to be done differently
1576 $datefields = array("name-date", "uri-date");
1577 foreach ($datefields AS $field) {
1578 if (strtotime($contact[$field]) > strtotime($r[0][$field])) {
1579 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $r[0][$field] . "'", LOGGER_DEBUG);
1584 foreach ($fields AS $field => $data) {
1585 if ($contact[$field] != $r[0][$field]) {
1586 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $r[0][$field] . "'", LOGGER_DEBUG);
1592 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1594 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1595 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1596 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1597 WHERE `id` = %d AND `network` = '%s'",
1598 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
1599 dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1600 dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
1601 dbesc(DBM::date($contact["name-date"])), dbesc(DBM::date($contact["uri-date"])),
1602 intval($contact["id"]), dbesc($contact["network"]));
1605 update_contact_avatar($author["avatar"], $importer["uid"], $contact["id"],
1606 (strtotime($contact["avatar-date"]) > strtotime($r[0]["avatar-date"])));
1609 * The generation is a sign for the reliability of the provided data.
1610 * It is used in the socgraph.php to prevent that old contact data
1611 * that was relayed over several servers can overwrite contact
1612 * data that we received directly.
1615 $poco["generation"] = 2;
1616 $poco["photo"] = $author["avatar"];
1617 $poco["hide"] = $hide;
1618 $poco["contact-type"] = $contact["contact-type"];
1619 $gcid = update_gcontact($poco);
1621 link_gcontact($gcid, $importer["uid"], $contact["id"]);
1628 * @brief Transforms activity objects into an XML string
1630 * @param object $xpath XPath object
1631 * @param object $activity Activity object
1632 * @param text $element element name
1634 * @return string XML string
1635 * @todo Find good type-hints for all parameter
1637 private static function transform_activity($xpath, $activity, $element) {
1638 if (!is_object($activity)) {
1642 $obj_doc = new DOMDocument("1.0", "utf-8");
1643 $obj_doc->formatOutput = true;
1645 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1647 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1648 xml::add_element($obj_doc, $obj_element, "type", $activity_type);
1650 $id = $xpath->query("atom:id", $activity)->item(0);
1651 if (is_object($id)) {
1652 $obj_element->appendChild($obj_doc->importNode($id, true));
1655 $title = $xpath->query("atom:title", $activity)->item(0);
1656 if (is_object($title)) {
1657 $obj_element->appendChild($obj_doc->importNode($title, true));
1660 $links = $xpath->query("atom:link", $activity);
1661 if (is_object($links)) {
1662 foreach ($links AS $link) {
1663 $obj_element->appendChild($obj_doc->importNode($link, true));
1667 $content = $xpath->query("atom:content", $activity)->item(0);
1668 if (is_object($content)) {
1669 $obj_element->appendChild($obj_doc->importNode($content, true));
1672 $obj_doc->appendChild($obj_element);
1674 $objxml = $obj_doc->saveXML($obj_element);
1676 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1677 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1682 * @brief Processes the mail elements
1684 * @param object $xpath XPath object
1685 * @param object $mail mail elements
1686 * @param array $importer Record of the importer user mixed with contact of the content
1687 * @todo Find good type-hints for all parameter
1689 private static function process_mail($xpath, $mail, $importer) {
1691 logger("Processing mails");
1693 /// @TODO Rewrite this to one statement
1695 $msg["uid"] = $importer["importer_uid"];
1696 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1697 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1698 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1699 $msg["contact-id"] = $importer["id"];
1700 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1701 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1702 $msg["created"] = $xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue;
1703 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1704 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1706 $msg["replied"] = 0;
1708 dba::insert('mail', $msg);
1710 // send notifications.
1711 /// @TODO Arange this mess
1712 $notif_params = array(
1713 "type" => NOTIFY_MAIL,
1714 "notify_flags" => $importer["notify-flags"],
1715 "language" => $importer["language"],
1716 "to_name" => $importer["username"],
1717 "to_email" => $importer["email"],
1718 "uid" => $importer["importer_uid"],
1720 "source_name" => $msg["from-name"],
1721 "source_link" => $importer["url"],
1722 "source_photo" => $importer["thumb"],
1723 "verb" => ACTIVITY_POST,
1727 notification($notif_params);
1729 logger("Mail is processed, notification was sent.");
1733 * @brief Processes the suggestion elements
1735 * @param object $xpath XPath object
1736 * @param object $suggestion suggestion elements
1737 * @param array $importer Record of the importer user mixed with contact of the content
1738 * @todo Find good type-hints for all parameter
1740 private static function process_suggestion($xpath, $suggestion, $importer) {
1743 logger("Processing suggestions");
1745 /// @TODO Rewrite this to one statement
1747 $suggest["uid"] = $importer["importer_uid"];
1748 $suggest["cid"] = $importer["id"];
1749 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1750 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1751 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1752 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1753 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1755 // Does our member already have a friend matching this description?
1757 $r = q("SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1758 dbesc($suggest["name"]),
1759 dbesc(normalise_link($suggest["url"])),
1760 intval($suggest["uid"])
1764 * The valid result means the friend we're about to send a friend
1765 * suggestion already has them in their contact, which means no further
1766 * action is required.
1768 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1770 if (DBM::is_result($r)) {
1774 // Do we already have an fcontact record for this person?
1777 $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1778 dbesc($suggest["url"]),
1779 dbesc($suggest["name"]),
1780 dbesc($suggest["request"])
1782 if (DBM::is_result($r)) {
1785 // OK, we do. Do we already have an introduction for this person ?
1786 $r = q("SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1787 intval($suggest["uid"]),
1792 * The valid result means the friend we're about to send a friend
1793 * suggestion already has them in their contact, which means no further
1794 * action is required.
1796 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1798 if (DBM::is_result($r)) {
1803 $r = q("INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1804 dbesc($suggest["name"]),
1805 dbesc($suggest["url"]),
1806 dbesc($suggest["photo"]),
1807 dbesc($suggest["request"])
1810 $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1811 dbesc($suggest["url"]),
1812 dbesc($suggest["name"]),
1813 dbesc($suggest["request"])
1817 * If no record in fcontact is found, below INSERT statement will not
1818 * link an introduction to it.
1820 if (!DBM::is_result($r)) {
1821 // database record did not get created. Quietly give up.
1827 $hash = random_string();
1829 $r = q("INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1830 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1831 intval($suggest["uid"]),
1833 intval($suggest["cid"]),
1834 dbesc($suggest["body"]),
1836 dbesc(datetime_convert()),
1841 "type" => NOTIFY_SUGGEST,
1842 "notify_flags" => $importer["notify-flags"],
1843 "language" => $importer["language"],
1844 "to_name" => $importer["username"],
1845 "to_email" => $importer["email"],
1846 "uid" => $importer["importer_uid"],
1848 "link" => System::baseUrl()."/notifications/intros",
1849 "source_name" => $importer["name"],
1850 "source_link" => $importer["url"],
1851 "source_photo" => $importer["photo"],
1852 "verb" => ACTIVITY_REQ_FRIEND,
1861 * @brief Processes the relocation elements
1863 * @param object $xpath XPath object
1864 * @param object $relocation relocation elements
1865 * @param array $importer Record of the importer user mixed with contact of the content
1866 * @todo Find good type-hints for all parameter
1868 private static function process_relocation($xpath, $relocation, $importer) {
1870 logger("Processing relocations");
1872 /// @TODO Rewrite this to one statement
1873 $relocate = array();
1874 $relocate["uid"] = $importer["importer_uid"];
1875 $relocate["cid"] = $importer["id"];
1876 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1877 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
1878 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1879 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
1880 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1881 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1882 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1883 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1884 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1885 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1886 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1887 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1889 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
1890 $relocate["avatar"] = $relocate["photo"];
1893 if ($relocate["addr"] == "") {
1894 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
1898 $r = q("SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
1899 intval($importer["id"]),
1900 intval($importer["importer_uid"]));
1902 if (!DBM::is_result($r)) {
1903 logger("Query failed to execute, no result returned in " . __FUNCTION__);
1909 // Update the gcontact entry
1910 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
1912 $x = q("UPDATE `gcontact` SET
1921 WHERE `nurl` = '%s';",
1922 dbesc($relocate["name"]),
1923 dbesc($relocate["avatar"]),
1924 dbesc($relocate["url"]),
1925 dbesc(normalise_link($relocate["url"])),
1926 dbesc($relocate["addr"]),
1927 dbesc($relocate["addr"]),
1928 dbesc($relocate["notify"]),
1929 dbesc($relocate["server_url"]),
1930 dbesc(normalise_link($old["url"])));
1932 // Update the contact table. We try to find every entry.
1933 $x = q("UPDATE `contact` SET
1943 `site-pubkey` = '%s'
1944 WHERE (`id` = %d AND `uid` = %d) OR (`nurl` = '%s');",
1945 dbesc($relocate["name"]),
1946 dbesc($relocate["avatar"]),
1947 dbesc($relocate["url"]),
1948 dbesc(normalise_link($relocate["url"])),
1949 dbesc($relocate["addr"]),
1950 dbesc($relocate["request"]),
1951 dbesc($relocate["confirm"]),
1952 dbesc($relocate["notify"]),
1953 dbesc($relocate["poll"]),
1954 dbesc($relocate["sitepubkey"]),
1955 intval($importer["id"]),
1956 intval($importer["importer_uid"]),
1957 dbesc(normalise_link($old["url"])));
1959 update_contact_avatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
1966 /// @todo This is an extreme performance killer
1968 'owner-link' => array($old["url"], $relocate["url"]),
1969 'author-link' => array($old["url"], $relocate["url"]),
1970 //'owner-avatar' => array($old["photo"], $relocate["photo"]),
1971 //'author-avatar' => array($old["photo"], $relocate["photo"]),
1973 foreach ($fields as $n=>$f) {
1974 $r = q("SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
1976 intval($importer["importer_uid"]));
1978 if (DBM::is_result($r)) {
1979 $x = q("UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1982 intval($importer["importer_uid"]));
1991 /// merge with current record, current contents have priority
1992 /// update record, set url-updated
1993 /// update profile photos
1994 /// schedule a scan?
1999 * @brief Updates an item
2001 * @param array $current the current item record
2002 * @param array $item the new item record
2003 * @param array $importer Record of the importer user mixed with contact of the content
2004 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2005 * @todo set proper type-hints (array?)
2007 private static function update_content($current, $item, $importer, $entrytype) {
2010 if (edited_timestamp_is_newer($current, $item)) {
2012 // do not accept (ignore) an earlier edit than one we currently have.
2013 if (datetime_convert("UTC","UTC",$item["edited"]) < $current["edited"]) {
2017 $fields = array('title' => $item["title"], 'body' => $item["body"],
2018 'tag' => $item["tag"], 'changed' => datetime_convert(),
2019 'edited' => datetime_convert("UTC", "UTC", $item["edited"]));
2021 $condition = array("`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]);
2022 dba::update('item', $fields, $condition);
2024 create_tags_from_itemuri($item["uri"], $importer["importer_uid"]);
2025 update_thread_uri($item["uri"], $importer["importer_uid"]);
2029 if ($entrytype == DFRN_REPLY_RC) {
2030 Worker::add(PRIORITY_HIGH, "notifier","comment-import", $current["id"]);
2034 // update last-child if it changes
2035 if ($item["last-child"] && ($item["last-child"] != $current["last-child"])) {
2036 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2037 dbesc(datetime_convert()),
2038 dbesc($item["parent-uri"]),
2039 intval($importer["importer_uid"])
2041 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` IN (0, %d)",
2042 intval($item["last-child"]),
2043 dbesc(datetime_convert()),
2044 dbesc($item["uri"]),
2045 intval($importer["importer_uid"])
2052 * @brief Detects the entry type of the item
2054 * @param array $importer Record of the importer user mixed with contact of the content
2055 * @param array $item the new item record
2057 * @return int Is it a toplevel entry, a comment or a relayed comment?
2058 * @todo set proper type-hints (array?)
2060 private static function get_entry_type($importer, $item) {
2061 if ($item["parent-uri"] != $item["uri"]) {
2064 if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
2067 logger("possible community action");
2069 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2072 // was the top-level post for this action written by somebody on this site?
2073 // Specifically, the recipient?
2075 $is_a_remote_action = false;
2077 $r = q("SELECT `item`.`parent-uri` FROM `item`
2078 WHERE `item`.`uri` = '%s'
2080 dbesc($item["parent-uri"])
2082 if (DBM::is_result($r)) {
2083 $r = q("SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2084 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2085 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2086 AND `item`.`uid` = %d
2089 dbesc($r[0]["parent-uri"]),
2090 dbesc($r[0]["parent-uri"]),
2091 dbesc($r[0]["parent-uri"]),
2092 intval($importer["importer_uid"])
2094 if (DBM::is_result($r)) {
2095 $is_a_remote_action = true;
2100 * Does this have the characteristics of a community or private group action?
2101 * If it's an action to a wall post on a community/prvgroup page it's a
2102 * valid community action. Also forum_mode makes it valid for sure.
2103 * If neither, it's not.
2106 /// @TODO Maybe merge these if() blocks into one?
2107 if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2108 $is_a_remote_action = false;
2109 logger("not a community action");
2112 if ($is_a_remote_action) {
2113 return DFRN_REPLY_RC;
2118 return DFRN_TOP_LEVEL;
2124 * @brief Send a "poke"
2126 * @param array $item the new item record
2127 * @param array $importer Record of the importer user mixed with contact of the content
2128 * @param int $posted_id The record number of item record that was just posted
2129 * @todo set proper type-hints (array?)
2131 private static function do_poke($item, $importer, $posted_id) {
2132 $verb = urldecode(substr($item["verb"],strpos($item["verb"], "#")+1));
2136 $xo = parse_xml_string($item["object"],false);
2138 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2140 // somebody was poked/prodded. Was it me?
2141 foreach ($xo->link as $l) {
2142 $atts = $l->attributes();
2143 switch ($atts["rel"]) {
2145 $Blink = $atts["href"];
2152 if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2154 // send a notification
2156 "type" => NOTIFY_POKE,
2157 "notify_flags" => $importer["notify-flags"],
2158 "language" => $importer["language"],
2159 "to_name" => $importer["username"],
2160 "to_email" => $importer["email"],
2161 "uid" => $importer["importer_uid"],
2163 "link" => System::baseUrl()."/display/".urlencode(get_item_guid($posted_id)),
2164 "source_name" => stripslashes($item["author-name"]),
2165 "source_link" => $item["author-link"],
2166 "source_photo" => ((link_compare($item["author-link"],$importer["url"]))
2167 ? $importer["thumb"] : $item["author-avatar"]),
2168 "verb" => $item["verb"],
2169 "otype" => "person",
2170 "activity" => $verb,
2171 "parent" => $item["parent"]
2178 * @brief Processes several actions, depending on the verb
2180 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2181 * @param array $importer Record of the importer user mixed with contact of the content
2182 * @param array $item the new item record
2183 * @param bool $is_like Is the verb a "like"?
2185 * @return bool Should the processing of the entries be continued?
2186 * @todo set proper type-hints (array?)
2188 private static function process_verbs($entrytype, $importer, &$item, &$is_like) {
2190 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2192 if (($entrytype == DFRN_TOP_LEVEL)) {
2193 // The filling of the the "contact" variable is done for legcy reasons
2194 // The functions below are partly used by ostatus.php as well - where we have this variable
2195 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2197 $nickname = $contact["nick"];
2199 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2200 // This function once was responsible for DFRN and OStatus.
2201 if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2202 logger("New follower");
2203 new_follower($importer, $contact, $item, $nickname);
2206 if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2207 logger("Lost follower");
2208 lose_follower($importer, $contact, $item);
2211 if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2212 logger("New friend request");
2213 new_follower($importer, $contact, $item, $nickname, true);
2216 if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2217 logger("Lost sharer");
2218 lose_sharer($importer, $contact, $item);
2222 if (($item["verb"] == ACTIVITY_LIKE)
2223 || ($item["verb"] == ACTIVITY_DISLIKE)
2224 || ($item["verb"] == ACTIVITY_ATTEND)
2225 || ($item["verb"] == ACTIVITY_ATTENDNO)
2226 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)) {
2228 $item["type"] = "activity";
2229 $item["gravity"] = GRAVITY_LIKE;
2230 // only one like or dislike per person
2231 // splitted into two queries for performance issues
2232 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `parent-uri` = '%s' AND NOT `deleted` LIMIT 1",
2233 intval($item["uid"]),
2234 dbesc($item["author-link"]),
2235 dbesc($item["verb"]),
2236 dbesc($item["parent-uri"])
2238 if (DBM::is_result($r)) {
2242 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `thr-parent` = '%s' AND NOT `deleted` LIMIT 1",
2243 intval($item["uid"]),
2244 dbesc($item["author-link"]),
2245 dbesc($item["verb"]),
2246 dbesc($item["parent-uri"])
2248 if (DBM::is_result($r)) {
2255 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2257 $xo = parse_xml_string($item["object"],false);
2258 $xt = parse_xml_string($item["target"],false);
2260 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2261 $r = q("SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2263 intval($importer["importer_uid"])
2266 if (!DBM::is_result($r)) {
2267 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2271 // extract tag, if not duplicate, add to parent item
2273 if (!(stristr($r[0]["tag"],trim($xo->content)))) {
2274 q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2275 dbesc($r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2278 create_tags_from_item($r[0]["id"]);
2288 * @brief Processes the link elements
2290 * @param object $links link elements
2291 * @param array $item the item record
2292 * @todo set proper type-hints
2294 private static function parse_links($links, &$item) {
2300 foreach ($links AS $link) {
2301 foreach ($link->attributes AS $attributes) {
2302 /// @TODO Rewrite these repeated (same) if () statements to a switch()
2303 if ($attributes->name == "href") {
2304 $href = $attributes->textContent;
2306 if ($attributes->name == "rel") {
2307 $rel = $attributes->textContent;
2309 if ($attributes->name == "type") {
2310 $type = $attributes->textContent;
2312 if ($attributes->name == "length") {
2313 $length = $attributes->textContent;
2315 if ($attributes->name == "title") {
2316 $title = $attributes->textContent;
2319 if (($rel != "") && ($href != "")) {
2322 $item["plink"] = $href;
2326 if (strlen($item["attach"])) {
2327 $item["attach"] .= ",";
2330 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2338 * @brief Processes the entry elements which contain the items and comments
2340 * @param array $header Array of the header elements that always stay the same
2341 * @param object $xpath XPath object
2342 * @param object $entry entry elements
2343 * @param array $importer Record of the importer user mixed with contact of the content
2344 * @todo Add type-hints
2346 private static function process_entry($header, $xpath, $entry, $importer, $xml) {
2348 logger("Processing entries");
2352 $item["protocol"] = PROTOCOL_DFRN;
2354 $item["source"] = $xml;
2357 $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
2359 $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
2361 $current = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2362 dbesc($item["uri"]),
2363 intval($importer["importer_uid"])
2366 // Is there an existing item?
2367 if (DBM::is_result($current) && edited_timestamp_is_newer($current[0], $item) &&
2368 (datetime_convert("UTC","UTC",$item["edited"]) < $current[0]["edited"])) {
2369 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2374 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2376 $item["owner-name"] = $owner["name"];
2377 $item["owner-link"] = $owner["link"];
2378 $item["owner-avatar"] = $owner["avatar"];
2381 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2383 $item["author-name"] = $author["name"];
2384 $item["author-link"] = $author["link"];
2385 $item["author-avatar"] = $author["avatar"];
2387 $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
2389 $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2391 $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
2392 $item["body"] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$item["body"]);
2393 // make sure nobody is trying to sneak some html tags by us
2394 $item["body"] = notags(base64url_decode($item["body"]));
2396 $item["body"] = limit_body_size($item["body"]);
2398 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2399 if ((strpos($item['body'],'<') !== false) && (strpos($item['body'],'>') !== false)) {
2401 $item['body'] = reltoabs($item['body'],$base_url);
2403 $item['body'] = html2bb_video($item['body']);
2405 $item['body'] = oembed_html2bbcode($item['body']);
2407 $config = HTMLPurifier_Config::createDefault();
2408 $config->set('Cache.DefinitionImpl', null);
2410 // we shouldn't need a whitelist, because the bbcode converter
2411 // will strip out any unsupported tags.
2413 $purifier = new HTMLPurifier($config);
2414 $item['body'] = $purifier->purify($item['body']);
2416 $item['body'] = @html2bbcode($item['body']);
2419 /// @todo We should check for a repeated post and if we know the repeated author.
2421 // We don't need the content element since "dfrn:env" is always present
2422 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2424 $item["last-child"] = $xpath->query("dfrn:comment-allow/text()", $entry)->item(0)->nodeValue;
2425 $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
2427 $georsspoint = $xpath->query("georss:point", $entry);
2429 $item["coord"] = $georsspoint->item(0)->nodeValue;
2432 $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
2434 $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
2436 if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true") {
2437 $item["bookmark"] = true;
2440 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2441 if ($notice_info && ($notice_info->length > 0)) {
2442 foreach ($notice_info->item(0)->attributes AS $attributes) {
2443 if ($attributes->name == "source") {
2444 $item["app"] = strip_tags($attributes->textContent);
2449 $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
2451 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "item_store"
2452 $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
2453 if ($dsprsig != "") {
2454 $item["dsprsig"] = $dsprsig;
2457 $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
2459 if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "") {
2460 $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
2463 $object = $xpath->query("activity:object", $entry)->item(0);
2464 $item["object"] = self::transform_activity($xpath, $object, "object");
2466 if (trim($item["object"]) != "") {
2467 $r = parse_xml_string($item["object"], false);
2468 if (isset($r->type)) {
2469 $item["object-type"] = $r->type;
2473 $target = $xpath->query("activity:target", $entry)->item(0);
2474 $item["target"] = self::transform_activity($xpath, $target, "target");
2476 $categories = $xpath->query("atom:category", $entry);
2478 foreach ($categories AS $category) {
2481 foreach ($category->attributes AS $attributes) {
2482 if ($attributes->name == "term") {
2483 $term = $attributes->textContent;
2486 if ($attributes->name == "scheme") {
2487 $scheme = $attributes->textContent;
2491 if (($term != "") && ($scheme != "")) {
2492 $parts = explode(":", $scheme);
2493 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2494 $termhash = array_shift($parts);
2495 $termurl = implode(":", $parts);
2497 if (strlen($item["tag"])) {
2498 $item["tag"] .= ",";
2501 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2509 $links = $xpath->query("atom:link", $entry);
2511 self::parse_links($links, $item);
2514 $item['conversation-uri'] = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
2516 $conv = $xpath->query('ostatus:conversation', $entry);
2517 if (is_object($conv->item(0))) {
2518 foreach ($conv->item(0)->attributes AS $attributes) {
2519 if ($attributes->name == "ref") {
2520 $item['conversation-uri'] = $attributes->textContent;
2522 if ($attributes->name == "href") {
2523 $item['conversation-href'] = $attributes->textContent;
2528 // Is it a reply or a top level posting?
2529 $item["parent-uri"] = $item["uri"];
2531 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2532 if (is_object($inreplyto->item(0))) {
2533 foreach ($inreplyto->item(0)->attributes AS $attributes) {
2534 if ($attributes->name == "ref") {
2535 $item["parent-uri"] = $attributes->textContent;
2540 // Get the type of the item (Top level post, reply or remote reply)
2541 $entrytype = self::get_entry_type($importer, $item);
2543 // Now assign the rest of the values that depend on the type of the message
2544 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2545 if (!isset($item["object-type"])) {
2546 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2549 if ($item["contact-id"] != $owner["contact-id"]) {
2550 $item["contact-id"] = $owner["contact-id"];
2553 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2554 $item["network"] = $owner["network"];
2557 if ($item["contact-id"] != $author["contact-id"]) {
2558 $item["contact-id"] = $author["contact-id"];
2561 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2562 $item["network"] = $author["network"];
2565 /// @TODO maybe remove this old-lost code then?
2566 // This code was taken from the old DFRN code
2567 // When activated, forums don't work.
2568 // And: Why should we disallow commenting by followers?
2569 // the behaviour is now similar to the Diaspora part.
2570 //if ($importer["rel"] == CONTACT_IS_FOLLOWER) {
2571 // logger("Contact ".$importer["id"]." is only follower. Quitting", LOGGER_DEBUG);
2576 if ($entrytype == DFRN_REPLY_RC) {
2577 $item["type"] = "remote-comment";
2579 } elseif ($entrytype == DFRN_TOP_LEVEL) {
2580 if (!isset($item["object-type"])) {
2581 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2585 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2586 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2587 $ev = bbtoevent($item["body"]);
2588 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2589 logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2590 /// @TODO Mixure of "/' ahead ...
2591 $ev["cid"] = $importer["id"];
2592 $ev["uid"] = $importer["uid"];
2593 $ev["uri"] = $item["uri"];
2594 $ev["edited"] = $item["edited"];
2595 $ev['private'] = $item['private'];
2596 $ev["guid"] = $item["guid"];
2598 $r = q("SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2599 dbesc($item["uri"]),
2600 intval($importer["uid"])
2602 if (DBM::is_result($r)) {
2603 $ev["id"] = $r[0]["id"];
2606 $event_id = event_store($ev);
2607 logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2613 if (!self::process_verbs($entrytype, $importer, $item, $is_like)) {
2614 logger("Exiting because 'process_verbs' told us so", LOGGER_DEBUG);
2618 // Update content if 'updated' changes
2619 if (DBM::is_result($current)) {
2620 if (self::update_content($r[0], $item, $importer, $entrytype)) {
2621 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2623 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2628 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2629 $posted_id = item_store($item);
2634 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2636 $item["id"] = $posted_id;
2638 $r = q("SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2640 intval($importer["importer_uid"])
2642 if (DBM::is_result($r)) {
2643 $parent = $r[0]["parent"];
2644 $parent_uri = $r[0]["parent-uri"];
2648 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2649 dbesc(datetime_convert()),
2650 intval($importer["importer_uid"]),
2651 intval($r[0]["parent"])
2654 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d",
2655 dbesc(datetime_convert()),
2656 intval($importer["importer_uid"]),
2661 if ($posted_id && $parent && ($entrytype == DFRN_REPLY_RC)) {
2662 logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
2663 Worker::add(PRIORITY_HIGH, "notifier", "comment-import", $posted_id);
2668 } else { // $entrytype == DFRN_TOP_LEVEL
2669 if (!link_compare($item["owner-link"],$importer["url"])) {
2671 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2672 * but otherwise there's a possible data mixup on the sender's system.
2673 * the tgroup delivery code called from item_store will correct it if it's a forum,
2674 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2676 logger('Correcting item owner.', LOGGER_DEBUG);
2677 $item["owner-name"] = $importer["senderName"];
2678 $item["owner-link"] = $importer["url"];
2679 $item["owner-avatar"] = $importer["thumb"];
2682 if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!tgroup_check($importer["importer_uid"], $item))) {
2683 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2687 // This is my contact on another system, but it's really me.
2688 // Turn this into a wall post.
2689 $notify = item_is_remote_self($importer, $item);
2691 $posted_id = item_store($item, false, $notify);
2693 logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2695 if (stristr($item["verb"],ACTIVITY_POKE))
2696 self::do_poke($item, $importer, $posted_id);
2701 * @brief Deletes items
2703 * @param object $xpath XPath object
2704 * @param object $deletion deletion elements
2705 * @param array $importer Record of the importer user mixed with contact of the content
2706 * @todo set proper type-hints
2708 private static function process_deletion($xpath, $deletion, $importer) {
2710 logger("Processing deletions");
2712 foreach ($deletion->attributes AS $attributes) {
2713 if ($attributes->name == "ref") {
2714 $uri = $attributes->textContent;
2716 if ($attributes->name == "when") {
2717 $when = $attributes->textContent;
2721 $when = datetime_convert("UTC", "UTC", $when, "Y-m-d H:i:s");
2723 $when = datetime_convert("UTC", "UTC", "now", "Y-m-d H:i:s");
2726 if (!$uri || !$importer["id"]) {
2730 /// @todo Only select the used fields
2731 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` INNER JOIN `contact` on `item`.`contact-id` = `contact`.`id`
2732 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2734 intval($importer["uid"]),
2735 intval($importer["id"])
2737 if (!DBM::is_result($r)) {
2738 logger("Item with uri " . $uri . " from contact " . $importer["id"] . " for user " . $importer["uid"] . " wasn't found.", LOGGER_DEBUG);
2744 $entrytype = self::get_entry_type($importer, $item);
2746 if (!$item["deleted"]) {
2747 logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG);
2752 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2753 logger("Deleting event ".$item["event-id"], LOGGER_DEBUG);
2754 event_delete($item["event-id"]);
2757 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2759 $xo = parse_xml_string($item["object"],false);
2760 $xt = parse_xml_string($item["target"],false);
2762 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2763 $i = q("SELECT `id`, `contact-id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2765 intval($importer["importer_uid"])
2767 if (DBM::is_result($i)) {
2769 // For tags, the owner cannot remove the tag on the author's copy of the post.
2771 $owner_remove = (($item["contact-id"] == $i[0]["contact-id"]) ? true: false);
2772 $author_remove = (($item["origin"] && $item["self"]) ? true : false);
2773 $author_copy = (($item["origin"]) ? true : false);
2775 if ($owner_remove && $author_copy) {
2778 if ($author_remove || $owner_remove) {
2779 $tags = explode(',',$i[0]["tag"]);
2782 foreach ($tags as $tag) {
2783 if (trim($tag) !== trim($xo->body)) {
2784 $newtags[] = trim($tag);
2788 q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2789 dbesc(implode(',', $newtags)),
2792 create_tags_from_item($i[0]["id"]);
2798 if ($entrytype == DFRN_TOP_LEVEL) {
2799 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2800 `body` = '', `title` = ''
2801 WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2803 dbesc(datetime_convert()),
2805 intval($importer["uid"])
2807 create_tags_from_itemuri($uri, $importer["uid"]);
2808 create_files_from_itemuri($uri, $importer["uid"]);
2809 update_thread_uri($uri, $importer["uid"]);
2811 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2812 `body` = '', `title` = ''
2813 WHERE `uri` = '%s' AND `uid` IN (0, %d)",
2815 dbesc(datetime_convert()),
2817 intval($importer["uid"])
2819 create_tags_from_itemuri($uri, $importer["uid"]);
2820 create_files_from_itemuri($uri, $importer["uid"]);
2821 update_thread_uri($uri, $importer["importer_uid"]);
2822 if ($item["last-child"]) {
2823 // ensure that last-child is set in case the comment that had it just got wiped.
2824 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2825 dbesc(datetime_convert()),
2826 dbesc($item["parent-uri"]),
2827 intval($item["uid"])
2829 // who is the last child now?
2830 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
2831 ORDER BY `created` DESC LIMIT 1",
2832 dbesc($item["parent-uri"]),
2833 intval($importer["uid"])
2835 if (DBM::is_result($r)) {
2836 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
2841 // if this is a relayed delete, propagate it to other recipients
2843 if ($entrytype == DFRN_REPLY_RC) {
2844 logger("Notifying followers about deletion of post " . $item["id"], LOGGER_DEBUG);
2845 Worker::add(PRIORITY_HIGH, "notifier","drop", $item["id"]);
2852 * @brief Imports a DFRN message
2854 * @param text $xml The DFRN message
2855 * @param array $importer Record of the importer user mixed with contact of the content
2856 * @param bool $sort_by_date Is used when feeds are polled
2857 * @return integer Import status
2858 * @todo set proper type-hints
2860 public static function import($xml, $importer, $sort_by_date = false) {
2866 $doc = new DOMDocument();
2867 @$doc->loadXML($xml);
2869 $xpath = new DomXPath($doc);
2870 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2871 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2872 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2873 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2874 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2875 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2876 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2877 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2878 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2879 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2882 $header["uid"] = $importer["uid"];
2883 $header["network"] = NETWORK_DFRN;
2884 $header["type"] = "remote";
2885 $header["wall"] = 0;
2886 $header["origin"] = 0;
2887 $header["contact-id"] = $importer["id"];
2889 // Update the contact table if the data has changed
2891 // The "atom:author" is only present in feeds
2892 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2893 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2896 // Only the "dfrn:owner" in the head section contains all data
2897 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2898 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2901 logger("Import DFRN message for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2903 // The account type is new since 3.5.1
2904 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2905 $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()", $context)->item(0)->nodeValue);
2907 if ($accounttype != $importer["contact-type"]) {
2908 dba::update('contact', array('contact-type' => $accounttype), array('id' => $importer["id"]));
2912 // is it a public forum? Private forums aren't supported with this method
2913 // This is deprecated since 3.5.1
2914 $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()", $context)->item(0)->nodeValue);
2916 if ($forum != $importer["forum"]) {
2917 $condition = array('`forum` != ? AND `id` = ?', $forum, $importer["id"]);
2918 dba::update('contact', array('forum' => $forum), $condition);
2921 // We are processing relocations even if we are ignoring a contact
2922 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2923 foreach ($relocations AS $relocation) {
2924 self::process_relocation($xpath, $relocation, $importer);
2927 if ($importer["readonly"]) {
2928 // We aren't receiving stuff from this person. But we will quietly ignore them
2929 // rather than a blatant "go away" message.
2930 logger('ignoring contact '.$importer["id"]);
2934 $mails = $xpath->query("/atom:feed/dfrn:mail");
2935 foreach ($mails AS $mail) {
2936 self::process_mail($xpath, $mail, $importer);
2939 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2940 foreach ($suggestions AS $suggestion) {
2941 self::process_suggestion($xpath, $suggestion, $importer);
2944 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2945 foreach ($deletions AS $deletion) {
2946 self::process_deletion($xpath, $deletion, $importer);
2949 if (!$sort_by_date) {
2950 $entries = $xpath->query("/atom:feed/atom:entry");
2951 foreach ($entries AS $entry) {
2952 self::process_entry($header, $xpath, $entry, $importer, $xml);
2955 $newentries = array();
2956 $entries = $xpath->query("/atom:feed/atom:entry");
2957 foreach ($entries AS $entry) {
2958 $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2959 $newentries[strtotime($created)] = $entry;
2962 // Now sort after the publishing date
2965 foreach ($newentries AS $entry) {
2966 self::process_entry($header, $xpath, $entry, $importer, $xml);
2969 logger("Import done for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);