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
11 use Friendica\Core\System;
13 require_once("include/Contact.php");
14 require_once("include/ostatus.php");
15 require_once("include/enotify.php");
16 require_once("include/threads.php");
17 require_once("include/socgraph.php");
18 require_once("include/items.php");
19 require_once("include/tags.php");
20 require_once("include/files.php");
21 require_once("include/event.php");
22 require_once("include/text.php");
23 require_once("include/oembed.php");
24 require_once("include/html2bbcode.php");
25 require_once("include/bbcode.php");
26 require_once("include/xml.php");
29 * @brief This class contain functions to create and send DFRN XML files
34 const DFRN_TOP_LEVEL = 0; // Top level posting
35 const DFRN_REPLY = 1; // Regular reply that is stored locally
36 const DFRN_REPLY_RC = 2; // Reply that will be relayed
39 * @brief Generates the atom entries for delivery.php
41 * This function is used whenever content is transmitted via DFRN.
43 * @param array $items Item elements
44 * @param array $owner Owner record
46 * @return string DFRN entries
47 * @todo Add type-hints
49 public static function entries($items,$owner) {
51 $doc = new DOMDocument('1.0', 'utf-8');
52 $doc->formatOutput = true;
54 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
56 if (! count($items)) {
57 return trim($doc->saveXML());
60 foreach ($items as $item) {
61 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
62 $root->appendChild($entry);
65 return(trim($doc->saveXML()));
69 * @brief Generate an atom feed for the given user
71 * This function is called when another server is pulling data from the user feed.
73 * @param string $dfrn_id DFRN ID from the requesting party
74 * @param string $owner_nick Owner nick name
75 * @param string $last_update Date of the last update
76 * @param int $direction Can be -1, 0 or 1.
77 * @param boolean $onlyheader Output only the header without content? (Default is "no")
79 * @return string DFRN feed entries
81 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false) {
85 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
86 $public_feed = (($dfrn_id) ? false : true);
87 $starred = false; // not yet implemented, possible security issues
90 if ($public_feed && $a->argc > 2) {
91 for ($x = 2; $x < $a->argc; $x++) {
92 if ($a->argv[$x] == 'converse') {
95 if ($a->argv[$x] == 'starred') {
98 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
99 $category = $a->argv[$x+1];
106 // default permissions - anonymous user
108 $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = '' ";
110 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
111 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
112 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
116 if (! dbm::is_result($r)) {
121 $owner_id = $owner['uid'];
122 $owner_nick = $owner['nickname'];
124 $sql_post_table = "";
126 if (! $public_feed) {
131 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
135 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
136 $my_id = '1:' . $dfrn_id;
139 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
140 $my_id = '0:' . $dfrn_id;
147 $r = q("SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
151 if (! dbm::is_result($r)) {
156 require_once('include/security.php');
157 $groups = init_groups_visitor($contact['id']);
159 if (count($groups)) {
160 for ($x = 0; $x < count($groups); $x ++)
161 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
162 $gs = implode('|', $groups);
164 $gs = '<<>>' ; // Impossible to match
167 $sql_extra = sprintf("
168 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
169 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
170 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
171 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
173 intval($contact['id']),
174 intval($contact['id']),
186 if (! strlen($last_update)) {
187 $last_update = 'now -30 days';
190 if (isset($category)) {
191 $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` ",
192 dbesc(protect_sprintf($category)), intval(TERM_OBJ_POST), intval(TERM_CATEGORY), intval($owner_id));
193 //$sql_extra .= file_tag_file_query('item',$category,'category');
198 $sql_extra .= " AND `contact`.`self` = 1 ";
202 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
204 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
205 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
206 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
207 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
208 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
209 FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
210 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
211 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
212 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
213 WHERE `item`.`uid` = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
214 AND `item`.`wall` AND `item`.`changed` > '%s'
216 ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
223 * Will check further below if this actually returned results.
224 * We will provide an empty feed if that is the case.
229 $doc = new DOMDocument('1.0', 'utf-8');
230 $doc->formatOutput = true;
232 $alternatelink = $owner['url'];
234 if (isset($category)) {
235 $alternatelink .= "/category/".$category;
239 $author = "dfrn:owner";
244 $root = self::add_header($doc, $owner, $author, $alternatelink, true);
246 /// @TODO This hook can't work anymore
247 // call_hooks('atom_feed', $atom);
249 if (!dbm::is_result($items) || $onlyheader) {
250 $atom = trim($doc->saveXML());
252 call_hooks('atom_feed_end', $atom);
257 foreach ($items as $item) {
259 // prevent private email from leaking.
260 if ($item['network'] == NETWORK_MAIL) {
264 // public feeds get html, our own nodes use bbcode
268 // catch any email that's in a public conversation and make sure it doesn't leak
269 if ($item['private']) {
276 $entry = self::entry($doc, $type, $item, $owner, true);
277 $root->appendChild($entry);
281 $atom = trim($doc->saveXML());
283 call_hooks('atom_feed_end', $atom);
289 * @brief Generate an atom entry for a given item id
291 * @param int $item_id The item id
292 * @param boolean $conversation Show the conversation. If false show the single post.
294 * @return string DFRN feed entry
296 public static function itemFeed($item_id, $conversation = false) {
298 $condition = '`item`.`parent`';
300 $condition = '`item`.`id`';
303 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
304 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
305 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
306 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
307 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
309 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
310 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
311 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
312 WHERE %s = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
313 AND NOT `item`.`private`",
318 if (!dbm::is_result($r)) {
325 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
326 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
327 WHERE `contact`.`self` AND `user`.`uid` = %d LIMIT 1",
331 if (!dbm::is_result($r)) {
337 $doc = new DOMDocument('1.0', 'utf-8');
338 $doc->formatOutput = true;
342 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
343 $doc->appendChild($root);
345 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
346 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
347 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
348 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
349 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
350 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
351 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
352 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
353 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
355 //$root = self::add_header($doc, $owner, "dfrn:owner", "", false);
357 foreach ($items as $item) {
358 $entry = self::entry($doc, $type, $item, $owner, true, 0);
359 $root->appendChild($entry);
362 $root = self::entry($doc, $type, $item, $owner, true, 0, true);
365 $atom = trim($doc->saveXML());
370 * @brief Create XML text for DFRN mails
372 * @param array $item message elements
373 * @param array $owner Owner record
375 * @return string DFRN mail
376 * @todo Add type-hints
378 public static function mail($item, $owner) {
379 $doc = new DOMDocument('1.0', 'utf-8');
380 $doc->formatOutput = true;
382 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
384 $mail = $doc->createElement("dfrn:mail");
385 $sender = $doc->createElement("dfrn:sender");
387 xml::add_element($doc, $sender, "dfrn:name", $owner['name']);
388 xml::add_element($doc, $sender, "dfrn:uri", $owner['url']);
389 xml::add_element($doc, $sender, "dfrn:avatar", $owner['thumb']);
391 $mail->appendChild($sender);
393 xml::add_element($doc, $mail, "dfrn:id", $item['uri']);
394 xml::add_element($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
395 xml::add_element($doc, $mail, "dfrn:sentdate", datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME));
396 xml::add_element($doc, $mail, "dfrn:subject", $item['title']);
397 xml::add_element($doc, $mail, "dfrn:content", $item['body']);
399 $root->appendChild($mail);
401 return(trim($doc->saveXML()));
405 * @brief Create XML text for DFRN friend suggestions
407 * @param array $item suggestion elements
408 * @param array $owner Owner record
410 * @return string DFRN suggestions
411 * @todo Add type-hints
413 public static function fsuggest($item, $owner) {
414 $doc = new DOMDocument('1.0', 'utf-8');
415 $doc->formatOutput = true;
417 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
419 $suggest = $doc->createElement("dfrn:suggest");
421 xml::add_element($doc, $suggest, "dfrn:url", $item['url']);
422 xml::add_element($doc, $suggest, "dfrn:name", $item['name']);
423 xml::add_element($doc, $suggest, "dfrn:photo", $item['photo']);
424 xml::add_element($doc, $suggest, "dfrn:request", $item['request']);
425 xml::add_element($doc, $suggest, "dfrn:note", $item['note']);
427 $root->appendChild($suggest);
429 return(trim($doc->saveXML()));
433 * @brief Create XML text for DFRN relocations
435 * @param array $owner Owner record
436 * @param int $uid User ID
438 * @return string DFRN relocations
439 * @todo Add type-hints
441 public static function relocate($owner, $uid) {
443 /* get site pubkey. this could be a new installation with no site keys*/
444 $pubkey = get_config('system','site_pubkey');
446 $res = new_keypair(1024);
447 set_config('system','site_prvkey', $res['prvkey']);
448 set_config('system','site_pubkey', $res['pubkey']);
451 $rp = q("SELECT `resource-id` , `scale`, type FROM `photo`
452 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;", $uid);
454 $ext = Photo::supportedTypes();
456 foreach ($rp as $p) {
457 $photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
462 $doc = new DOMDocument('1.0', 'utf-8');
463 $doc->formatOutput = true;
465 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
467 $relocate = $doc->createElement("dfrn:relocate");
469 xml::add_element($doc, $relocate, "dfrn:url", $owner['url']);
470 xml::add_element($doc, $relocate, "dfrn:name", $owner['name']);
471 xml::add_element($doc, $relocate, "dfrn:addr", $owner['addr']);
472 xml::add_element($doc, $relocate, "dfrn:avatar", $owner['avatar']);
473 xml::add_element($doc, $relocate, "dfrn:photo", $photos[4]);
474 xml::add_element($doc, $relocate, "dfrn:thumb", $photos[5]);
475 xml::add_element($doc, $relocate, "dfrn:micro", $photos[6]);
476 xml::add_element($doc, $relocate, "dfrn:request", $owner['request']);
477 xml::add_element($doc, $relocate, "dfrn:confirm", $owner['confirm']);
478 xml::add_element($doc, $relocate, "dfrn:notify", $owner['notify']);
479 xml::add_element($doc, $relocate, "dfrn:poll", $owner['poll']);
480 xml::add_element($doc, $relocate, "dfrn:sitepubkey", get_config('system','site_pubkey'));
482 $root->appendChild($relocate);
484 return(trim($doc->saveXML()));
488 * @brief Adds the header elements for the DFRN protocol
490 * @param object $doc XML document
491 * @param array $owner Owner record
492 * @param string $authorelement Element name for the author
493 * @param string $alternatelink link to profile or category
494 * @param bool $public Is it a header for public posts?
496 * @return object XML root object
497 * @todo Add type-hints
499 private static function add_header($doc, $owner, $authorelement, $alternatelink = "", $public = false) {
501 if ($alternatelink == "") {
502 $alternatelink = $owner['url'];
505 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
506 $doc->appendChild($root);
508 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
509 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
510 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
511 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
512 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
513 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
514 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
515 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
516 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
518 xml::add_element($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
519 xml::add_element($doc, $root, "title", $owner["name"]);
521 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
522 xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
524 $attributes = array("rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/");
525 xml::add_element($doc, $root, "link", "", $attributes);
527 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $alternatelink);
528 xml::add_element($doc, $root, "link", "", $attributes);
532 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
533 ostatus::hublinks($doc, $root, $owner["nick"]);
535 $attributes = array("rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
536 xml::add_element($doc, $root, "link", "", $attributes);
538 $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
539 xml::add_element($doc, $root, "link", "", $attributes);
541 $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
542 xml::add_element($doc, $root, "link", "", $attributes);
545 // For backward compatibility we keep this element
546 if ($owner['page-flags'] == PAGE_COMMUNITY) {
547 xml::add_element($doc, $root, "dfrn:community", 1);
550 // The former element is replaced by this one
551 xml::add_element($doc, $root, "dfrn:account_type", $owner["account-type"]);
553 /// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
555 xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
557 $author = self::add_author($doc, $owner, $authorelement, $public);
558 $root->appendChild($author);
564 * @brief Adds the author element in the header for the DFRN protocol
566 * @param object $doc XML document
567 * @param array $owner Owner record
568 * @param string $authorelement Element name for the author
570 * @return object XML author object
571 * @todo Add type-hints
573 private static function add_author($doc, $owner, $authorelement, $public) {
575 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
576 $r = q("SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
577 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
578 intval($owner['uid']));
579 if (dbm::is_result($r)) {
585 $author = $doc->createElement($authorelement);
587 $namdate = datetime_convert('UTC', 'UTC', $owner['name-date'].'+00:00', ATOM_TIME);
588 $uridate = datetime_convert('UTC', 'UTC', $owner['uri-date'].'+00:00', ATOM_TIME);
589 $picdate = datetime_convert('UTC', 'UTC', $owner['avatar-date'].'+00:00', ATOM_TIME);
591 $attributes = array();
593 if (!$public || !$hidewall) {
594 $attributes = array("dfrn:updated" => $namdate);
597 xml::add_element($doc, $author, "name", $owner["name"], $attributes);
598 xml::add_element($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
599 xml::add_element($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
601 $attributes = array("rel" => "photo", "type" => "image/jpeg",
602 "media:width" => 175, "media:height" => 175, "href" => $owner['photo']);
604 if (!$public || !$hidewall) {
605 $attributes["dfrn:updated"] = $picdate;
608 xml::add_element($doc, $author, "link", "", $attributes);
610 $attributes["rel"] = "avatar";
611 xml::add_element($doc, $author, "link", "", $attributes);
614 xml::add_element($doc, $author, "dfrn:hide", "true");
617 // The following fields will only be generated if the data isn't meant for a public feed
622 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
625 xml::add_element($doc, $author, "dfrn:birthday", $birthday);
627 // Only show contact details when we are allowed to
628 $r = q("SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
629 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
630 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
632 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
633 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
634 intval($owner['uid']));
635 if (dbm::is_result($r)) {
638 xml::add_element($doc, $author, "poco:displayName", $profile["name"]);
639 xml::add_element($doc, $author, "poco:updated", $namdate);
641 if (trim($profile["dob"]) > '0001-01-01') {
642 xml::add_element($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
645 xml::add_element($doc, $author, "poco:note", $profile["about"]);
646 xml::add_element($doc, $author, "poco:preferredUsername", $profile["nickname"]);
648 $savetz = date_default_timezone_get();
649 date_default_timezone_set($profile["timezone"]);
650 xml::add_element($doc, $author, "poco:utcOffset", date("P"));
651 date_default_timezone_set($savetz);
653 if (trim($profile["homepage"]) != "") {
654 $urls = $doc->createElement("poco:urls");
655 xml::add_element($doc, $urls, "poco:type", "homepage");
656 xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
657 xml::add_element($doc, $urls, "poco:primary", "true");
658 $author->appendChild($urls);
661 if (trim($profile["pub_keywords"]) != "") {
662 $keywords = explode(",", $profile["pub_keywords"]);
664 foreach ($keywords AS $keyword) {
665 xml::add_element($doc, $author, "poco:tags", trim($keyword));
670 if (trim($profile["xmpp"]) != "") {
671 $ims = $doc->createElement("poco:ims");
672 xml::add_element($doc, $ims, "poco:type", "xmpp");
673 xml::add_element($doc, $ims, "poco:value", $profile["xmpp"]);
674 xml::add_element($doc, $ims, "poco:primary", "true");
675 $author->appendChild($ims);
678 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
679 $element = $doc->createElement("poco:address");
681 xml::add_element($doc, $element, "poco:formatted", formatted_location($profile));
683 if (trim($profile["locality"]) != "") {
684 xml::add_element($doc, $element, "poco:locality", $profile["locality"]);
687 if (trim($profile["region"]) != "") {
688 xml::add_element($doc, $element, "poco:region", $profile["region"]);
691 if (trim($profile["country-name"]) != "") {
692 xml::add_element($doc, $element, "poco:country", $profile["country-name"]);
695 $author->appendChild($element);
703 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
705 * @param object $doc XML document
706 * @param string $element Element name for the author
707 * @param string $contact_url Link of the contact
708 * @param array $items Item elements
710 * @return object XML author object
711 * @todo Add type-hints
713 private static function add_entry_author($doc, $element, $contact_url, $item) {
715 $contact = get_contact_details_by_url($contact_url, $item["uid"]);
717 $author = $doc->createElement($element);
718 xml::add_element($doc, $author, "name", $contact["name"]);
719 xml::add_element($doc, $author, "uri", $contact["url"]);
720 xml::add_element($doc, $author, "dfrn:handle", $contact["addr"]);
723 /// - Check real image type and image size
724 /// - Check which of these boths elements we should use
727 "type" => "image/jpeg",
729 "media:height" => 80,
730 "href" => $contact["photo"]);
731 xml::add_element($doc, $author, "link", "", $attributes);
735 "type" => "image/jpeg",
737 "media:height" => 80,
738 "href" => $contact["photo"]);
739 xml::add_element($doc, $author, "link", "", $attributes);
745 * @brief Adds the activity elements
747 * @param object $doc XML document
748 * @param string $element Element name for the activity
749 * @param string $activity activity value
751 * @return object XML activity object
752 * @todo Add type-hints
754 private static function create_activity($doc, $element, $activity) {
757 $entry = $doc->createElement($element);
759 $r = parse_xml_string($activity, false);
764 xml::add_element($doc, $entry, "activity:object-type", $r->type);
767 xml::add_element($doc, $entry, "id", $r->id);
770 xml::add_element($doc, $entry, "title", $r->title);
774 if (substr($r->link, 0, 1) == '<') {
775 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
776 $r->link = str_replace('&', '&', $r->link);
779 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
781 // XML does need a single element as root element so we add a dummy element here
782 $data = parse_xml_string("<dummy>" . $r->link . "</dummy>", false);
783 if (is_object($data)) {
784 foreach ($data->link AS $link) {
785 $attributes = array();
786 foreach ($link->attributes() AS $parameter => $value) {
787 $attributes[$parameter] = $value;
789 xml::add_element($doc, $entry, "link", "", $attributes);
793 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $r->link);
794 xml::add_element($doc, $entry, "link", "", $attributes);
798 xml::add_element($doc, $entry, "content", bbcode($r->content), array("type" => "html"));
808 * @brief Adds the elements for attachments
810 * @param object $doc XML document
811 * @param object $root XML root
812 * @param array $item Item element
814 * @return object XML attachment object
815 * @todo Add type-hints
817 private static function get_attachment($doc, $root, $item) {
818 $arr = explode('[/attach],',$item['attach']);
820 foreach ($arr as $r) {
822 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches);
824 $attributes = array("rel" => "enclosure",
825 "href" => $matches[1],
826 "type" => $matches[3]);
828 if (intval($matches[2])) {
829 $attributes["length"] = intval($matches[2]);
832 if (trim($matches[4]) != "") {
833 $attributes["title"] = trim($matches[4]);
836 xml::add_element($doc, $root, "link", "", $attributes);
843 * @brief Adds the "entry" elements for the DFRN protocol
845 * @param object $doc XML document
846 * @param string $type "text" or "html"
847 * @param array $item Item element
848 * @param array $owner Owner record
849 * @param bool $comment Trigger the sending of the "comment" element
850 * @param int $cid Contact ID of the recipient
851 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
853 * @return object XML entry object
854 * @todo Add type-hints
856 private static function entry($doc, $type, $item, $owner, $comment = false, $cid = 0, $single = false) {
858 $mentioned = array();
860 if (!$item['parent']) {
864 if ($item['deleted']) {
865 $attributes = array("ref" => $item['uri'], "when" => datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME));
866 return xml::create_element($doc, "at:deleted-entry", "", $attributes);
870 $entry = $doc->createElement("entry");
872 $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry');
873 $doc->appendChild($entry);
875 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
876 $entry->setAttribute("xmlns:at", NAMESPACE_TOMB);
877 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
878 $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
879 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
880 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
881 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
882 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
883 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
886 if ($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid']) {
887 $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
889 $body = $item['body'];
892 // Remove the abstract element. It is only locally important.
893 $body = remove_abstract($body);
895 if ($type == 'html') {
898 if ($item['title'] != "") {
899 $htmlbody = "[b]".$item['title']."[/b]\n\n".$htmlbody;
902 $htmlbody = bbcode($htmlbody, false, false, 7);
905 $author = self::add_entry_author($doc, "author", $item["author-link"], $item);
906 $entry->appendChild($author);
908 $dfrnowner = self::add_entry_author($doc, "dfrn:owner", $item["owner-link"], $item);
909 $entry->appendChild($dfrnowner);
911 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
912 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
913 $parent = q("SELECT `guid`,`plink` FROM `item` WHERE `uri` = '%s' AND `uid` = %d", dbesc($parent_item), intval($item['uid']));
914 $attributes = array("ref" => $parent_item, "type" => "text/html",
915 "href" => $parent[0]['plink'],
916 "dfrn:diaspora_guid" => $parent[0]['guid']);
917 xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
920 // Add conversation data. This is used for OStatus
921 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
922 $conversation_uri = $conversation_href;
924 if (isset($parent_item)) {
925 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $item['parent-uri']);
926 if (dbm::is_result($r)) {
927 if ($r['conversation-uri'] != '') {
928 $conversation_uri = $r['conversation-uri'];
930 if ($r['conversation-href'] != '') {
931 $conversation_href = $r['conversation-href'];
937 "href" => $conversation_href,
938 "ref" => $conversation_uri);
940 xml::add_element($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
942 xml::add_element($doc, $entry, "id", $item["uri"]);
943 xml::add_element($doc, $entry, "title", $item["title"]);
945 xml::add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
946 xml::add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
948 // "dfrn:env" is used to read the content
949 xml::add_element($doc, $entry, "dfrn:env", base64url_encode($body, true));
951 // The "content" field is not read by the receiver. We could remove it when the type is "text"
952 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
953 xml::add_element($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), array("type" => $type));
955 // We save this value in "plink". Maybe we should read it from there as well?
956 xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
957 "href" => System::baseUrl()."/display/".$item["guid"]));
959 // "comment-allow" is some old fashioned stuff for old Friendica versions.
960 // It is included in the rewritten code for completeness
962 xml::add_element($doc, $entry, "dfrn:comment-allow", intval($item['last-child']));
965 if ($item['location']) {
966 xml::add_element($doc, $entry, "dfrn:location", $item['location']);
969 if ($item['coord']) {
970 xml::add_element($doc, $entry, "georss:point", $item['coord']);
973 if (($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])) {
974 xml::add_element($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
977 if ($item['extid']) {
978 xml::add_element($doc, $entry, "dfrn:extid", $item['extid']);
981 if ($item['bookmark']) {
982 xml::add_element($doc, $entry, "dfrn:bookmark", "true");
986 xml::add_element($doc, $entry, "statusnet:notice_info", "", array("local_id" => $item['id'], "source" => $item['app']));
989 xml::add_element($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
991 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
992 // It is needed for relayed comments to Diaspora.
993 if ($item['signed_text']) {
994 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
995 xml::add_element($doc, $entry, "dfrn:diaspora_signature", $sign);
998 xml::add_element($doc, $entry, "activity:verb", construct_verb($item));
1000 if ($item['object-type'] != "") {
1001 xml::add_element($doc, $entry, "activity:object-type", $item['object-type']);
1002 } elseif ($item['id'] == $item['parent']) {
1003 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1005 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
1008 $actobj = self::create_activity($doc, "activity:object", $item['object']);
1010 $entry->appendChild($actobj);
1013 $actarg = self::create_activity($doc, "activity:target", $item['target']);
1015 $entry->appendChild($actarg);
1018 $tags = item_getfeedtags($item);
1021 foreach ($tags as $t) {
1022 if (($type != 'html') || ($t[0] != "@")) {
1023 xml::add_element($doc, $entry, "category", "", array("scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]));
1029 foreach ($tags as $t) {
1031 $mentioned[$t[1]] = $t[1];
1036 foreach ($mentioned AS $mention) {
1037 $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1038 intval($owner["uid"]),
1039 dbesc(normalise_link($mention)));
1041 if (dbm::is_result($r) && ($r[0]["forum"] || $r[0]["prv"])) {
1042 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1043 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1044 "href" => $mention));
1046 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1047 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1048 "href" => $mention));
1052 self::get_attachment($doc, $entry, $item);
1058 * @brief encrypts data via AES
1060 * @param string $data The data that is to be encrypted
1061 * @param string $key The AES key
1063 * @return string encrypted data
1065 private static function aes_encrypt($data, $key) {
1066 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1070 * @brief decrypts data via AES
1072 * @param string $encrypted The encrypted data
1073 * @param string $key The AES key
1075 * @return string decrypted data
1077 public static function aes_decrypt($encrypted, $key) {
1078 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1082 * @brief Delivers the atom content to the contacts
1084 * @param array $owner Owner record
1085 * @param array $contactr Contact record of the receiver
1086 * @param string $atom Content that will be transmitted
1087 * @param bool $dissolve (to be documented)
1089 * @return int Deliver status. -1 means an error.
1090 * @todo Add array type-hint for $owner, $contact
1092 public static function deliver($owner,$contact,$atom, $dissolve = false) {
1096 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1098 if ($contact['duplex'] && $contact['dfrn-id']) {
1099 $idtosend = '0:' . $orig_id;
1101 if ($contact['duplex'] && $contact['issued-id']) {
1102 $idtosend = '1:' . $orig_id;
1105 $rino = get_config('system', 'rino_encrypt');
1106 $rino = intval($rino);
1108 logger("Local rino version: ". $rino, LOGGER_DEBUG);
1110 $ssl_val = intval(get_config('system','ssl_policy'));
1114 case SSL_POLICY_FULL:
1115 $ssl_policy = 'full';
1117 case SSL_POLICY_SELFSIGN:
1118 $ssl_policy = 'self';
1120 case SSL_POLICY_NONE:
1122 $ssl_policy = 'none';
1126 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1128 logger('dfrn_deliver: ' . $url);
1130 $ret = z_fetch_url($url);
1132 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1133 return -2; // timed out
1136 $xml = $ret['body'];
1138 $curl_stat = $a->get_curl_code();
1140 return -3; // timed out
1143 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1149 if (strpos($xml,'<?xml') === false) {
1150 logger('dfrn_deliver: no valid XML returned');
1151 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1155 $res = parse_xml_string($xml);
1157 if ((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id))) {
1158 return (($res->status) ? $res->status : 3);
1161 $postvars = array();
1162 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1163 $challenge = hex2bin((string) $res->challenge);
1164 $perm = (($res->perm) ? $res->perm : null);
1165 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1166 $rino_remote_version = intval($res->rino);
1167 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1169 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
1171 if ($owner['page-flags'] == PAGE_PRVGROUP) {
1175 $final_dfrn_id = '';
1178 if ((($perm == 'rw') && (! intval($contact['writable'])))
1179 || (($perm == 'r') && (intval($contact['writable'])))) {
1180 q("update contact set writable = %d where id = %d",
1181 intval(($perm == 'rw') ? 1 : 0),
1182 intval($contact['id'])
1184 $contact['writable'] = (string) 1 - intval($contact['writable']);
1188 if (($contact['duplex'] && strlen($contact['pubkey']))
1189 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1190 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1191 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
1192 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
1194 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
1195 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
1198 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1200 if (strpos($final_dfrn_id,':') == 1) {
1201 $final_dfrn_id = substr($final_dfrn_id,2);
1204 if ($final_dfrn_id != $orig_id) {
1205 logger('dfrn_deliver: wrong dfrn_id.');
1206 // did not decode properly - cannot trust this site
1210 $postvars['dfrn_id'] = $idtosend;
1211 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1213 $postvars['dissolve'] = '1';
1217 if ((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1218 $postvars['data'] = $atom;
1219 $postvars['perm'] = 'rw';
1221 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1222 $postvars['perm'] = 'r';
1225 $postvars['ssl_policy'] = $ssl_policy;
1228 $postvars['page'] = $page;
1232 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1233 logger('rino version: '. $rino_remote_version);
1235 switch ($rino_remote_version) {
1237 // Deprecated rino version!
1238 $key = openssl_random_pseudo_bytes(16);
1239 $data = self::aes_encrypt($postvars['data'], $key);
1242 // RINO 2 based on php-encryption
1244 $key = Crypto::createNewRandomKey();
1245 } catch (CryptoTestFailed $ex) {
1246 logger('Cannot safely create a key');
1248 } catch (CannotPerformOperation $ex) {
1249 logger('Cannot safely create a key');
1253 $data = Crypto::encrypt($postvars['data'], $key);
1254 } catch (CryptoTestFailed $ex) {
1255 logger('Cannot safely perform encryption');
1257 } catch (CannotPerformOperation $ex) {
1258 logger('Cannot safely perform encryption');
1263 logger("rino: invalid requested verision '$rino_remote_version'");
1267 $postvars['rino'] = $rino_remote_version;
1268 $postvars['data'] = bin2hex($data);
1270 //logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1273 if ($dfrn_version >= 2.1) {
1274 if (($contact['duplex'] && strlen($contact['pubkey']))
1275 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1276 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1277 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1279 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1283 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1284 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1286 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1291 logger('md5 rawkey ' . md5($postvars['key']));
1293 $postvars['key'] = bin2hex($postvars['key']);
1297 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1299 $xml = post_url($contact['notify'], $postvars);
1301 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1303 $curl_stat = $a->get_curl_code();
1304 if ((!$curl_stat) || (!strlen($xml))) {
1305 return -9; // timed out
1308 if (($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after'))) {
1312 if (strpos($xml,'<?xml') === false) {
1313 logger('dfrn_deliver: phase 2: no valid XML returned');
1314 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1318 if ($contact['term-date'] > NULL_DATE) {
1319 logger("dfrn_deliver: $url back from the dead - removing mark for death");
1320 require_once('include/Contact.php');
1321 unmark_for_death($contact);
1324 $res = parse_xml_string($xml);
1326 if (!isset($res->status)) {
1330 if (!empty($res->message)) {
1331 logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1334 return intval($res->status);
1338 * @brief Add new birthday event for this person
1340 * @param array $contact Contact record
1341 * @param string $birthday Birthday of the contact
1342 * @todo Add array type-hint for $contact
1344 private static function birthday_event($contact, $birthday) {
1346 // Check for duplicates
1347 $r = q("SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1348 intval($contact["uid"]),
1349 intval($contact["id"]),
1350 dbesc(datetime_convert("UTC","UTC", $birthday)),
1353 if (dbm::is_result($r)) {
1357 logger("updating birthday: ".$birthday." for contact ".$contact["id"]);
1359 $bdtext = sprintf(t("%s\'s birthday"), $contact["name"]);
1360 $bdtext2 = sprintf(t("Happy Birthday %s"), " [url=".$contact["url"]."]".$contact["name"]."[/url]") ;
1362 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1363 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1364 intval($contact["uid"]),
1365 intval($contact["id"]),
1366 dbesc(datetime_convert()),
1367 dbesc(datetime_convert()),
1368 dbesc(datetime_convert("UTC","UTC", $birthday)),
1369 dbesc(datetime_convert("UTC","UTC", $birthday." + 1 day ")),
1377 * @brief Fetch the author data from head or entry items
1379 * @param object $xpath XPath object
1380 * @param object $context In which context should the data be searched
1381 * @param array $importer Record of the importer user mixed with contact of the content
1382 * @param string $element Element name from which the data is fetched
1383 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1385 * @return Returns an array with relevant data of the author
1386 * @todo Find good type-hints for all parameter
1388 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "") {
1391 $author["name"] = $xpath->evaluate($element."/atom:name/text()", $context)->item(0)->nodeValue;
1392 $author["link"] = $xpath->evaluate($element."/atom:uri/text()", $context)->item(0)->nodeValue;
1394 $r = q("SELECT `id`, `uid`, `url`, `network`, `avatar-date`, `name-date`, `uri-date`, `addr`,
1395 `name`, `nick`, `about`, `location`, `keywords`, `xmpp`, `bdyear`, `bd`, `hidden`, `contact-type`
1396 FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
1397 intval($importer["uid"]), dbesc(normalise_link($author["link"])), dbesc(NETWORK_STATUSNET));
1399 if (dbm::is_result($r)) {
1401 $author["contact-id"] = $r[0]["id"];
1402 $author["network"] = $r[0]["network"];
1405 logger("Contact ".$author["link"]." wasn't found for user ".$importer["uid"]." XML: ".$xml, LOGGER_DEBUG);
1408 $author["contact-id"] = $importer["id"];
1409 $author["network"] = $importer["network"];
1413 // Until now we aren't serving different sizes - but maybe later
1414 $avatarlist = array();
1415 /// @todo check if "avatar" or "photo" would be the best field in the specification
1416 $avatars = $xpath->query($element."/atom:link[@rel='avatar']", $context);
1417 foreach ($avatars AS $avatar) {
1420 foreach ($avatar->attributes AS $attributes) {
1421 /// @TODO Rewrite these similar if () to one switch
1422 if ($attributes->name == "href") {
1423 $href = $attributes->textContent;
1425 if ($attributes->name == "width") {
1426 $width = $attributes->textContent;
1428 if ($attributes->name == "updated") {
1429 $contact["avatar-date"] = $attributes->textContent;
1432 if (($width > 0) && ($href != "")) {
1433 $avatarlist[$width] = $href;
1436 if (count($avatarlist) > 0) {
1437 krsort($avatarlist);
1438 $author["avatar"] = current($avatarlist);
1441 if (dbm::is_result($r) && !$onlyfetch) {
1442 logger("Check if contact details for contact " . $r[0]["id"] . " (" . $r[0]["nick"] . ") have to be updated.", LOGGER_DEBUG);
1444 $poco = array("url" => $contact["url"]);
1446 // When was the last change to name or uri?
1447 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1448 foreach ($name_element->attributes AS $attributes) {
1449 if ($attributes->name == "updated") {
1450 $poco["name-date"] = $attributes->textContent;
1454 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1455 foreach ($link_element->attributes AS $attributes) {
1456 if ($attributes->name == "updated") {
1457 $poco["uri-date"] = $attributes->textContent;
1461 // Update contact data
1462 $value = $xpath->evaluate($element . "/dfrn:handle/text()", $context)->item(0)->nodeValue;
1464 $poco["addr"] = $value;
1467 $value = $xpath->evaluate($element . "/poco:displayName/text()", $context)->item(0)->nodeValue;
1469 $poco["name"] = $value;
1472 $value = $xpath->evaluate($element . "/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
1474 $poco["nick"] = $value;
1477 $value = $xpath->evaluate($element . "/poco:note/text()", $context)->item(0)->nodeValue;
1479 $poco["about"] = $value;
1482 $value = $xpath->evaluate($element . "/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
1484 $poco["location"] = $value;
1487 /// @todo Only search for elements with "poco:type" = "xmpp"
1488 $value = $xpath->evaluate($element . "/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
1490 $poco["xmpp"] = $value;
1493 /// @todo Add support for the following fields that we don't support by now in the contact table:
1494 /// - poco:utcOffset
1500 // If the "hide" element is present then the profile isn't searchable.
1501 $hide = intval($xpath->evaluate($element . "/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
1503 logger("Hidden status for contact " . $contact["url"] . ": " . $hide, LOGGER_DEBUG);
1505 // If the contact isn't searchable then set the contact to "hidden".
1506 // Problem: This can be manually overridden by the user.
1508 $contact["hidden"] = true;
1511 // Save the keywords into the contact table
1513 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1514 foreach ($tagelements AS $tag) {
1515 $tags[$tag->nodeValue] = $tag->nodeValue;
1519 $poco["keywords"] = implode(", ", $tags);
1522 // "dfrn:birthday" contains the birthday converted to UTC
1523 $old_bdyear = $contact["bdyear"];
1525 $birthday = $xpath->evaluate($element . "/dfrn:birthday/text()", $context)->item(0)->nodeValue;
1527 if (strtotime($birthday) > time()) {
1528 $bd_timestamp = strtotime($birthday);
1530 $poco["bdyear"] = date("Y", $bd_timestamp);
1533 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1534 $value = $xpath->evaluate($element . "/poco:birthday/text()", $context)->item(0)->nodeValue;
1536 if (!in_array($value, array("", "0000-00-00", "0001-01-01"))) {
1537 $bdyear = date("Y");
1538 $value = str_replace("0000", $bdyear, $value);
1540 if (strtotime($value) < time()) {
1541 $value = str_replace($bdyear, $bdyear + 1, $value);
1542 $bdyear = $bdyear + 1;
1545 $poco["bd"] = $value;
1548 $contact = array_merge($contact, $poco);
1550 if ($old_bdyear != $contact["bdyear"]) {
1551 self::birthday_event($contact, $birthday);
1554 // Get all field names
1556 foreach ($r[0] AS $field => $data) {
1557 $fields[$field] = $data;
1560 unset($fields["id"]);
1561 unset($fields["uid"]);
1562 unset($fields["url"]);
1563 unset($fields["avatar-date"]);
1564 unset($fields["name-date"]);
1565 unset($fields["uri-date"]);
1567 // Update check for this field has to be done differently
1568 $datefields = array("name-date", "uri-date");
1569 foreach ($datefields AS $field) {
1570 if (strtotime($contact[$field]) > strtotime($r[0][$field])) {
1571 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $r[0][$field] . "'", LOGGER_DEBUG);
1576 foreach ($fields AS $field => $data) {
1577 if ($contact[$field] != $r[0][$field]) {
1578 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $r[0][$field] . "'", LOGGER_DEBUG);
1584 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1586 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1587 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1588 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1589 WHERE `id` = %d AND `network` = '%s'",
1590 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
1591 dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1592 dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
1593 dbesc(dbm::date($contact["name-date"])), dbesc(dbm::date($contact["uri-date"])),
1594 intval($contact["id"]), dbesc($contact["network"]));
1597 update_contact_avatar($author["avatar"], $importer["uid"], $contact["id"],
1598 (strtotime($contact["avatar-date"]) > strtotime($r[0]["avatar-date"])));
1601 * The generation is a sign for the reliability of the provided data.
1602 * It is used in the socgraph.php to prevent that old contact data
1603 * that was relayed over several servers can overwrite contact
1604 * data that we received directly.
1607 $poco["generation"] = 2;
1608 $poco["photo"] = $author["avatar"];
1609 $poco["hide"] = $hide;
1610 $poco["contact-type"] = $contact["contact-type"];
1611 $gcid = update_gcontact($poco);
1613 link_gcontact($gcid, $importer["uid"], $contact["id"]);
1620 * @brief Transforms activity objects into an XML string
1622 * @param object $xpath XPath object
1623 * @param object $activity Activity object
1624 * @param text $element element name
1626 * @return string XML string
1627 * @todo Find good type-hints for all parameter
1629 private static function transform_activity($xpath, $activity, $element) {
1630 if (!is_object($activity)) {
1634 $obj_doc = new DOMDocument("1.0", "utf-8");
1635 $obj_doc->formatOutput = true;
1637 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1639 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1640 xml::add_element($obj_doc, $obj_element, "type", $activity_type);
1642 $id = $xpath->query("atom:id", $activity)->item(0);
1643 if (is_object($id)) {
1644 $obj_element->appendChild($obj_doc->importNode($id, true));
1647 $title = $xpath->query("atom:title", $activity)->item(0);
1648 if (is_object($title)) {
1649 $obj_element->appendChild($obj_doc->importNode($title, true));
1652 $links = $xpath->query("atom:link", $activity);
1653 if (is_object($links)) {
1654 foreach ($links AS $link) {
1655 $obj_element->appendChild($obj_doc->importNode($link, true));
1659 $content = $xpath->query("atom:content", $activity)->item(0);
1660 if (is_object($content)) {
1661 $obj_element->appendChild($obj_doc->importNode($content, true));
1664 $obj_doc->appendChild($obj_element);
1666 $objxml = $obj_doc->saveXML($obj_element);
1668 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1669 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1674 * @brief Processes the mail elements
1676 * @param object $xpath XPath object
1677 * @param object $mail mail elements
1678 * @param array $importer Record of the importer user mixed with contact of the content
1679 * @todo Find good type-hints for all parameter
1681 private static function process_mail($xpath, $mail, $importer) {
1683 logger("Processing mails");
1685 /// @TODO Rewrite this to one statement
1687 $msg["uid"] = $importer["importer_uid"];
1688 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1689 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1690 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1691 $msg["contact-id"] = $importer["id"];
1692 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1693 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1694 $msg["created"] = $xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue;
1695 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1696 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1698 $msg["replied"] = 0;
1700 dba::insert('mail', $msg);
1702 // send notifications.
1703 /// @TODO Arange this mess
1704 $notif_params = array(
1705 "type" => NOTIFY_MAIL,
1706 "notify_flags" => $importer["notify-flags"],
1707 "language" => $importer["language"],
1708 "to_name" => $importer["username"],
1709 "to_email" => $importer["email"],
1710 "uid" => $importer["importer_uid"],
1712 "source_name" => $msg["from-name"],
1713 "source_link" => $importer["url"],
1714 "source_photo" => $importer["thumb"],
1715 "verb" => ACTIVITY_POST,
1719 notification($notif_params);
1721 logger("Mail is processed, notification was sent.");
1725 * @brief Processes the suggestion elements
1727 * @param object $xpath XPath object
1728 * @param object $suggestion suggestion elements
1729 * @param array $importer Record of the importer user mixed with contact of the content
1730 * @todo Find good type-hints for all parameter
1732 private static function process_suggestion($xpath, $suggestion, $importer) {
1735 logger("Processing suggestions");
1737 /// @TODO Rewrite this to one statement
1739 $suggest["uid"] = $importer["importer_uid"];
1740 $suggest["cid"] = $importer["id"];
1741 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1742 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1743 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1744 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1745 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1747 // Does our member already have a friend matching this description?
1749 $r = q("SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1750 dbesc($suggest["name"]),
1751 dbesc(normalise_link($suggest["url"])),
1752 intval($suggest["uid"])
1756 * The valid result means the friend we're about to send a friend
1757 * suggestion already has them in their contact, which means no further
1758 * action is required.
1760 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1762 if (dbm::is_result($r)) {
1766 // Do we already have an fcontact record for this person?
1769 $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1770 dbesc($suggest["url"]),
1771 dbesc($suggest["name"]),
1772 dbesc($suggest["request"])
1774 if (dbm::is_result($r)) {
1777 // OK, we do. Do we already have an introduction for this person ?
1778 $r = q("SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1779 intval($suggest["uid"]),
1784 * The valid result means the friend we're about to send a friend
1785 * suggestion already has them in their contact, which means no further
1786 * action is required.
1788 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1790 if (dbm::is_result($r)) {
1795 $r = q("INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1796 dbesc($suggest["name"]),
1797 dbesc($suggest["url"]),
1798 dbesc($suggest["photo"]),
1799 dbesc($suggest["request"])
1802 $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1803 dbesc($suggest["url"]),
1804 dbesc($suggest["name"]),
1805 dbesc($suggest["request"])
1809 * If no record in fcontact is found, below INSERT statement will not
1810 * link an introduction to it.
1812 if (!dbm::is_result($r)) {
1813 // database record did not get created. Quietly give up.
1819 $hash = random_string();
1821 $r = q("INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1822 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1823 intval($suggest["uid"]),
1825 intval($suggest["cid"]),
1826 dbesc($suggest["body"]),
1828 dbesc(datetime_convert()),
1833 "type" => NOTIFY_SUGGEST,
1834 "notify_flags" => $importer["notify-flags"],
1835 "language" => $importer["language"],
1836 "to_name" => $importer["username"],
1837 "to_email" => $importer["email"],
1838 "uid" => $importer["importer_uid"],
1840 "link" => System::baseUrl()."/notifications/intros",
1841 "source_name" => $importer["name"],
1842 "source_link" => $importer["url"],
1843 "source_photo" => $importer["photo"],
1844 "verb" => ACTIVITY_REQ_FRIEND,
1853 * @brief Processes the relocation elements
1855 * @param object $xpath XPath object
1856 * @param object $relocation relocation elements
1857 * @param array $importer Record of the importer user mixed with contact of the content
1858 * @todo Find good type-hints for all parameter
1860 private static function process_relocation($xpath, $relocation, $importer) {
1862 logger("Processing relocations");
1864 /// @TODO Rewrite this to one statement
1865 $relocate = array();
1866 $relocate["uid"] = $importer["importer_uid"];
1867 $relocate["cid"] = $importer["id"];
1868 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1869 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
1870 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1871 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
1872 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1873 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1874 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1875 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1876 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1877 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1878 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1879 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1881 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
1882 $relocate["avatar"] = $relocate["photo"];
1885 if ($relocate["addr"] == "") {
1886 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
1890 $r = q("SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
1891 intval($importer["id"]),
1892 intval($importer["importer_uid"]));
1894 if (!dbm::is_result($r)) {
1895 logger("Query failed to execute, no result returned in " . __FUNCTION__);
1901 // Update the gcontact entry
1902 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
1904 $x = q("UPDATE `gcontact` SET
1913 WHERE `nurl` = '%s';",
1914 dbesc($relocate["name"]),
1915 dbesc($relocate["avatar"]),
1916 dbesc($relocate["url"]),
1917 dbesc(normalise_link($relocate["url"])),
1918 dbesc($relocate["addr"]),
1919 dbesc($relocate["addr"]),
1920 dbesc($relocate["notify"]),
1921 dbesc($relocate["server_url"]),
1922 dbesc(normalise_link($old["url"])));
1924 // Update the contact table. We try to find every entry.
1925 $x = q("UPDATE `contact` SET
1935 `site-pubkey` = '%s'
1936 WHERE (`id` = %d AND `uid` = %d) OR (`nurl` = '%s');",
1937 dbesc($relocate["name"]),
1938 dbesc($relocate["avatar"]),
1939 dbesc($relocate["url"]),
1940 dbesc(normalise_link($relocate["url"])),
1941 dbesc($relocate["addr"]),
1942 dbesc($relocate["request"]),
1943 dbesc($relocate["confirm"]),
1944 dbesc($relocate["notify"]),
1945 dbesc($relocate["poll"]),
1946 dbesc($relocate["sitepubkey"]),
1947 intval($importer["id"]),
1948 intval($importer["importer_uid"]),
1949 dbesc(normalise_link($old["url"])));
1951 update_contact_avatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
1958 /// @todo This is an extreme performance killer
1960 'owner-link' => array($old["url"], $relocate["url"]),
1961 'author-link' => array($old["url"], $relocate["url"]),
1962 //'owner-avatar' => array($old["photo"], $relocate["photo"]),
1963 //'author-avatar' => array($old["photo"], $relocate["photo"]),
1965 foreach ($fields as $n=>$f) {
1966 $r = q("SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
1968 intval($importer["importer_uid"]));
1970 if (dbm::is_result($r)) {
1971 $x = q("UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1974 intval($importer["importer_uid"]));
1983 /// merge with current record, current contents have priority
1984 /// update record, set url-updated
1985 /// update profile photos
1986 /// schedule a scan?
1991 * @brief Updates an item
1993 * @param array $current the current item record
1994 * @param array $item the new item record
1995 * @param array $importer Record of the importer user mixed with contact of the content
1996 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
1997 * @todo set proper type-hints (array?)
1999 private static function update_content($current, $item, $importer, $entrytype) {
2002 if (edited_timestamp_is_newer($current, $item)) {
2004 // do not accept (ignore) an earlier edit than one we currently have.
2005 if (datetime_convert("UTC","UTC",$item["edited"]) < $current["edited"]) {
2009 $fields = array('title' => $item["title"], 'body' => $item["body"],
2010 'tag' => $item["tag"], 'changed' => datetime_convert(),
2011 'edited' => datetime_convert("UTC", "UTC", $item["edited"]));
2013 $condition = array("`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]);
2014 dba::update('item', $fields, $condition);
2016 create_tags_from_itemuri($item["uri"], $importer["importer_uid"]);
2017 update_thread_uri($item["uri"], $importer["importer_uid"]);
2021 if ($entrytype == DFRN_REPLY_RC) {
2022 proc_run(PRIORITY_HIGH, "include/notifier.php","comment-import", $current["id"]);
2026 // update last-child if it changes
2027 if ($item["last-child"] && ($item["last-child"] != $current["last-child"])) {
2028 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2029 dbesc(datetime_convert()),
2030 dbesc($item["parent-uri"]),
2031 intval($importer["importer_uid"])
2033 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` IN (0, %d)",
2034 intval($item["last-child"]),
2035 dbesc(datetime_convert()),
2036 dbesc($item["uri"]),
2037 intval($importer["importer_uid"])
2044 * @brief Detects the entry type of the item
2046 * @param array $importer Record of the importer user mixed with contact of the content
2047 * @param array $item the new item record
2049 * @return int Is it a toplevel entry, a comment or a relayed comment?
2050 * @todo set proper type-hints (array?)
2052 private static function get_entry_type($importer, $item) {
2053 if ($item["parent-uri"] != $item["uri"]) {
2056 if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
2059 logger("possible community action");
2061 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2064 // was the top-level post for this action written by somebody on this site?
2065 // Specifically, the recipient?
2067 $is_a_remote_action = false;
2069 $r = q("SELECT `item`.`parent-uri` FROM `item`
2070 WHERE `item`.`uri` = '%s'
2072 dbesc($item["parent-uri"])
2074 if (dbm::is_result($r)) {
2075 $r = q("SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2076 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2077 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2078 AND `item`.`uid` = %d
2081 dbesc($r[0]["parent-uri"]),
2082 dbesc($r[0]["parent-uri"]),
2083 dbesc($r[0]["parent-uri"]),
2084 intval($importer["importer_uid"])
2086 if (dbm::is_result($r)) {
2087 $is_a_remote_action = true;
2092 * Does this have the characteristics of a community or private group action?
2093 * If it's an action to a wall post on a community/prvgroup page it's a
2094 * valid community action. Also forum_mode makes it valid for sure.
2095 * If neither, it's not.
2098 /// @TODO Maybe merge these if() blocks into one?
2099 if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2100 $is_a_remote_action = false;
2101 logger("not a community action");
2104 if ($is_a_remote_action) {
2105 return DFRN_REPLY_RC;
2110 return DFRN_TOP_LEVEL;
2116 * @brief Send a "poke"
2118 * @param array $item the new item record
2119 * @param array $importer Record of the importer user mixed with contact of the content
2120 * @param int $posted_id The record number of item record that was just posted
2121 * @todo set proper type-hints (array?)
2123 private static function do_poke($item, $importer, $posted_id) {
2124 $verb = urldecode(substr($item["verb"],strpos($item["verb"], "#")+1));
2128 $xo = parse_xml_string($item["object"],false);
2130 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2132 // somebody was poked/prodded. Was it me?
2133 foreach ($xo->link as $l) {
2134 $atts = $l->attributes();
2135 switch ($atts["rel"]) {
2137 $Blink = $atts["href"];
2144 if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2146 // send a notification
2148 "type" => NOTIFY_POKE,
2149 "notify_flags" => $importer["notify-flags"],
2150 "language" => $importer["language"],
2151 "to_name" => $importer["username"],
2152 "to_email" => $importer["email"],
2153 "uid" => $importer["importer_uid"],
2155 "link" => System::baseUrl()."/display/".urlencode(get_item_guid($posted_id)),
2156 "source_name" => stripslashes($item["author-name"]),
2157 "source_link" => $item["author-link"],
2158 "source_photo" => ((link_compare($item["author-link"],$importer["url"]))
2159 ? $importer["thumb"] : $item["author-avatar"]),
2160 "verb" => $item["verb"],
2161 "otype" => "person",
2162 "activity" => $verb,
2163 "parent" => $item["parent"]
2170 * @brief Processes several actions, depending on the verb
2172 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2173 * @param array $importer Record of the importer user mixed with contact of the content
2174 * @param array $item the new item record
2175 * @param bool $is_like Is the verb a "like"?
2177 * @return bool Should the processing of the entries be continued?
2178 * @todo set proper type-hints (array?)
2180 private static function process_verbs($entrytype, $importer, &$item, &$is_like) {
2182 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2184 if (($entrytype == DFRN_TOP_LEVEL)) {
2185 // The filling of the the "contact" variable is done for legcy reasons
2186 // The functions below are partly used by ostatus.php as well - where we have this variable
2187 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2189 $nickname = $contact["nick"];
2191 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2192 // This function once was responsible for DFRN and OStatus.
2193 if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2194 logger("New follower");
2195 new_follower($importer, $contact, $item, $nickname);
2198 if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2199 logger("Lost follower");
2200 lose_follower($importer, $contact, $item);
2203 if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2204 logger("New friend request");
2205 new_follower($importer, $contact, $item, $nickname, true);
2208 if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2209 logger("Lost sharer");
2210 lose_sharer($importer, $contact, $item);
2214 if (($item["verb"] == ACTIVITY_LIKE)
2215 || ($item["verb"] == ACTIVITY_DISLIKE)
2216 || ($item["verb"] == ACTIVITY_ATTEND)
2217 || ($item["verb"] == ACTIVITY_ATTENDNO)
2218 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)) {
2220 $item["type"] = "activity";
2221 $item["gravity"] = GRAVITY_LIKE;
2222 // only one like or dislike per person
2223 // splitted into two queries for performance issues
2224 $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",
2225 intval($item["uid"]),
2226 dbesc($item["author-link"]),
2227 dbesc($item["verb"]),
2228 dbesc($item["parent-uri"])
2230 if (dbm::is_result($r)) {
2234 $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",
2235 intval($item["uid"]),
2236 dbesc($item["author-link"]),
2237 dbesc($item["verb"]),
2238 dbesc($item["parent-uri"])
2240 if (dbm::is_result($r)) {
2247 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2249 $xo = parse_xml_string($item["object"],false);
2250 $xt = parse_xml_string($item["target"],false);
2252 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2253 $r = q("SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2255 intval($importer["importer_uid"])
2258 if (!dbm::is_result($r)) {
2259 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2263 // extract tag, if not duplicate, add to parent item
2265 if (!(stristr($r[0]["tag"],trim($xo->content)))) {
2266 q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2267 dbesc($r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2270 create_tags_from_item($r[0]["id"]);
2280 * @brief Processes the link elements
2282 * @param object $links link elements
2283 * @param array $item the item record
2284 * @todo set proper type-hints
2286 private static function parse_links($links, &$item) {
2292 foreach ($links AS $link) {
2293 foreach ($link->attributes AS $attributes) {
2294 /// @TODO Rewrite these repeated (same) if () statements to a switch()
2295 if ($attributes->name == "href") {
2296 $href = $attributes->textContent;
2298 if ($attributes->name == "rel") {
2299 $rel = $attributes->textContent;
2301 if ($attributes->name == "type") {
2302 $type = $attributes->textContent;
2304 if ($attributes->name == "length") {
2305 $length = $attributes->textContent;
2307 if ($attributes->name == "title") {
2308 $title = $attributes->textContent;
2311 if (($rel != "") && ($href != "")) {
2314 $item["plink"] = $href;
2318 if (strlen($item["attach"])) {
2319 $item["attach"] .= ",";
2322 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2330 * @brief Processes the entry elements which contain the items and comments
2332 * @param array $header Array of the header elements that always stay the same
2333 * @param object $xpath XPath object
2334 * @param object $entry entry elements
2335 * @param array $importer Record of the importer user mixed with contact of the content
2336 * @todo Add type-hints
2338 private static function process_entry($header, $xpath, $entry, $importer, $xml) {
2340 logger("Processing entries");
2344 $item["protocol"] = PROTOCOL_DFRN;
2346 $item["source"] = $xml;
2349 $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
2351 $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
2353 $current = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2354 dbesc($item["uri"]),
2355 intval($importer["importer_uid"])
2358 // Is there an existing item?
2359 if (dbm::is_result($current) && edited_timestamp_is_newer($current[0], $item) &&
2360 (datetime_convert("UTC","UTC",$item["edited"]) < $current[0]["edited"])) {
2361 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2366 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2368 $item["owner-name"] = $owner["name"];
2369 $item["owner-link"] = $owner["link"];
2370 $item["owner-avatar"] = $owner["avatar"];
2373 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2375 $item["author-name"] = $author["name"];
2376 $item["author-link"] = $author["link"];
2377 $item["author-avatar"] = $author["avatar"];
2379 $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
2381 $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2383 $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
2384 $item["body"] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$item["body"]);
2385 // make sure nobody is trying to sneak some html tags by us
2386 $item["body"] = notags(base64url_decode($item["body"]));
2388 $item["body"] = limit_body_size($item["body"]);
2390 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2391 if ((strpos($item['body'],'<') !== false) && (strpos($item['body'],'>') !== false)) {
2393 $item['body'] = reltoabs($item['body'],$base_url);
2395 $item['body'] = html2bb_video($item['body']);
2397 $item['body'] = oembed_html2bbcode($item['body']);
2399 $config = HTMLPurifier_Config::createDefault();
2400 $config->set('Cache.DefinitionImpl', null);
2402 // we shouldn't need a whitelist, because the bbcode converter
2403 // will strip out any unsupported tags.
2405 $purifier = new HTMLPurifier($config);
2406 $item['body'] = $purifier->purify($item['body']);
2408 $item['body'] = @html2bbcode($item['body']);
2411 /// @todo We should check for a repeated post and if we know the repeated author.
2413 // We don't need the content element since "dfrn:env" is always present
2414 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2416 $item["last-child"] = $xpath->query("dfrn:comment-allow/text()", $entry)->item(0)->nodeValue;
2417 $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
2419 $georsspoint = $xpath->query("georss:point", $entry);
2421 $item["coord"] = $georsspoint->item(0)->nodeValue;
2424 $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
2426 $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
2428 if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true") {
2429 $item["bookmark"] = true;
2432 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2433 if ($notice_info && ($notice_info->length > 0)) {
2434 foreach ($notice_info->item(0)->attributes AS $attributes) {
2435 if ($attributes->name == "source") {
2436 $item["app"] = strip_tags($attributes->textContent);
2441 $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
2443 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "item_store"
2444 $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
2445 if ($dsprsig != "") {
2446 $item["dsprsig"] = $dsprsig;
2449 $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
2451 if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "") {
2452 $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
2455 $object = $xpath->query("activity:object", $entry)->item(0);
2456 $item["object"] = self::transform_activity($xpath, $object, "object");
2458 if (trim($item["object"]) != "") {
2459 $r = parse_xml_string($item["object"], false);
2460 if (isset($r->type)) {
2461 $item["object-type"] = $r->type;
2465 $target = $xpath->query("activity:target", $entry)->item(0);
2466 $item["target"] = self::transform_activity($xpath, $target, "target");
2468 $categories = $xpath->query("atom:category", $entry);
2470 foreach ($categories AS $category) {
2473 foreach ($category->attributes AS $attributes) {
2474 if ($attributes->name == "term") {
2475 $term = $attributes->textContent;
2478 if ($attributes->name == "scheme") {
2479 $scheme = $attributes->textContent;
2483 if (($term != "") && ($scheme != "")) {
2484 $parts = explode(":", $scheme);
2485 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2486 $termhash = array_shift($parts);
2487 $termurl = implode(":", $parts);
2489 if (strlen($item["tag"])) {
2490 $item["tag"] .= ",";
2493 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2501 $links = $xpath->query("atom:link", $entry);
2503 self::parse_links($links, $item);
2506 $item['conversation-uri'] = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
2508 $conv = $xpath->query('ostatus:conversation', $entry);
2509 if (is_object($conv->item(0))) {
2510 foreach ($conv->item(0)->attributes AS $attributes) {
2511 if ($attributes->name == "ref") {
2512 $item['conversation-uri'] = $attributes->textContent;
2514 if ($attributes->name == "href") {
2515 $item['conversation-href'] = $attributes->textContent;
2520 // Is it a reply or a top level posting?
2521 $item["parent-uri"] = $item["uri"];
2523 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2524 if (is_object($inreplyto->item(0))) {
2525 foreach ($inreplyto->item(0)->attributes AS $attributes) {
2526 if ($attributes->name == "ref") {
2527 $item["parent-uri"] = $attributes->textContent;
2532 // Get the type of the item (Top level post, reply or remote reply)
2533 $entrytype = self::get_entry_type($importer, $item);
2535 // Now assign the rest of the values that depend on the type of the message
2536 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2537 if (!isset($item["object-type"])) {
2538 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2541 if ($item["contact-id"] != $owner["contact-id"]) {
2542 $item["contact-id"] = $owner["contact-id"];
2545 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2546 $item["network"] = $owner["network"];
2549 if ($item["contact-id"] != $author["contact-id"]) {
2550 $item["contact-id"] = $author["contact-id"];
2553 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2554 $item["network"] = $author["network"];
2557 /// @TODO maybe remove this old-lost code then?
2558 // This code was taken from the old DFRN code
2559 // When activated, forums don't work.
2560 // And: Why should we disallow commenting by followers?
2561 // the behaviour is now similar to the Diaspora part.
2562 //if ($importer["rel"] == CONTACT_IS_FOLLOWER) {
2563 // logger("Contact ".$importer["id"]." is only follower. Quitting", LOGGER_DEBUG);
2568 if ($entrytype == DFRN_REPLY_RC) {
2569 $item["type"] = "remote-comment";
2571 } elseif ($entrytype == DFRN_TOP_LEVEL) {
2572 if (!isset($item["object-type"])) {
2573 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2577 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2578 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2579 $ev = bbtoevent($item["body"]);
2580 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2581 logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2582 /// @TODO Mixure of "/' ahead ...
2583 $ev["cid"] = $importer["id"];
2584 $ev["uid"] = $importer["uid"];
2585 $ev["uri"] = $item["uri"];
2586 $ev["edited"] = $item["edited"];
2587 $ev['private'] = $item['private'];
2588 $ev["guid"] = $item["guid"];
2590 $r = q("SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2591 dbesc($item["uri"]),
2592 intval($importer["uid"])
2594 if (dbm::is_result($r)) {
2595 $ev["id"] = $r[0]["id"];
2598 $event_id = event_store($ev);
2599 logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2605 if (!self::process_verbs($entrytype, $importer, $item, $is_like)) {
2606 logger("Exiting because 'process_verbs' told us so", LOGGER_DEBUG);
2610 // Update content if 'updated' changes
2611 if (dbm::is_result($current)) {
2612 if (self::update_content($r[0], $item, $importer, $entrytype)) {
2613 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2615 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2620 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2621 $posted_id = item_store($item);
2626 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2628 $item["id"] = $posted_id;
2630 $r = q("SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2632 intval($importer["importer_uid"])
2634 if (dbm::is_result($r)) {
2635 $parent = $r[0]["parent"];
2636 $parent_uri = $r[0]["parent-uri"];
2640 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2641 dbesc(datetime_convert()),
2642 intval($importer["importer_uid"]),
2643 intval($r[0]["parent"])
2646 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d",
2647 dbesc(datetime_convert()),
2648 intval($importer["importer_uid"]),
2653 if ($posted_id && $parent && ($entrytype == DFRN_REPLY_RC)) {
2654 logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
2655 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $posted_id);
2660 } else { // $entrytype == DFRN_TOP_LEVEL
2661 if (!link_compare($item["owner-link"],$importer["url"])) {
2663 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2664 * but otherwise there's a possible data mixup on the sender's system.
2665 * the tgroup delivery code called from item_store will correct it if it's a forum,
2666 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2668 logger('Correcting item owner.', LOGGER_DEBUG);
2669 $item["owner-name"] = $importer["senderName"];
2670 $item["owner-link"] = $importer["url"];
2671 $item["owner-avatar"] = $importer["thumb"];
2674 if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!tgroup_check($importer["importer_uid"], $item))) {
2675 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2679 // This is my contact on another system, but it's really me.
2680 // Turn this into a wall post.
2681 $notify = item_is_remote_self($importer, $item);
2683 $posted_id = item_store($item, false, $notify);
2685 logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2687 if (stristr($item["verb"],ACTIVITY_POKE))
2688 self::do_poke($item, $importer, $posted_id);
2693 * @brief Deletes items
2695 * @param object $xpath XPath object
2696 * @param object $deletion deletion elements
2697 * @param array $importer Record of the importer user mixed with contact of the content
2698 * @todo set proper type-hints
2700 private static function process_deletion($xpath, $deletion, $importer) {
2702 logger("Processing deletions");
2704 foreach ($deletion->attributes AS $attributes) {
2705 if ($attributes->name == "ref") {
2706 $uri = $attributes->textContent;
2708 if ($attributes->name == "when") {
2709 $when = $attributes->textContent;
2713 $when = datetime_convert("UTC", "UTC", $when, "Y-m-d H:i:s");
2715 $when = datetime_convert("UTC", "UTC", "now", "Y-m-d H:i:s");
2718 if (!$uri || !$importer["id"]) {
2722 /// @todo Only select the used fields
2723 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` INNER JOIN `contact` on `item`.`contact-id` = `contact`.`id`
2724 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2726 intval($importer["uid"]),
2727 intval($importer["id"])
2729 if (!dbm::is_result($r)) {
2730 logger("Item with uri " . $uri . " from contact " . $importer["id"] . " for user " . $importer["uid"] . " wasn't found.", LOGGER_DEBUG);
2736 $entrytype = self::get_entry_type($importer, $item);
2738 if (!$item["deleted"]) {
2739 logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG);
2744 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2745 logger("Deleting event ".$item["event-id"], LOGGER_DEBUG);
2746 event_delete($item["event-id"]);
2749 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2751 $xo = parse_xml_string($item["object"],false);
2752 $xt = parse_xml_string($item["target"],false);
2754 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2755 $i = q("SELECT `id`, `contact-id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2757 intval($importer["importer_uid"])
2759 if (dbm::is_result($i)) {
2761 // For tags, the owner cannot remove the tag on the author's copy of the post.
2763 $owner_remove = (($item["contact-id"] == $i[0]["contact-id"]) ? true: false);
2764 $author_remove = (($item["origin"] && $item["self"]) ? true : false);
2765 $author_copy = (($item["origin"]) ? true : false);
2767 if ($owner_remove && $author_copy) {
2770 if ($author_remove || $owner_remove) {
2771 $tags = explode(',',$i[0]["tag"]);
2774 foreach ($tags as $tag) {
2775 if (trim($tag) !== trim($xo->body)) {
2776 $newtags[] = trim($tag);
2780 q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2781 dbesc(implode(',', $newtags)),
2784 create_tags_from_item($i[0]["id"]);
2790 if ($entrytype == DFRN_TOP_LEVEL) {
2791 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2792 `body` = '', `title` = ''
2793 WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2795 dbesc(datetime_convert()),
2797 intval($importer["uid"])
2799 create_tags_from_itemuri($uri, $importer["uid"]);
2800 create_files_from_itemuri($uri, $importer["uid"]);
2801 update_thread_uri($uri, $importer["uid"]);
2803 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2804 `body` = '', `title` = ''
2805 WHERE `uri` = '%s' AND `uid` IN (0, %d)",
2807 dbesc(datetime_convert()),
2809 intval($importer["uid"])
2811 create_tags_from_itemuri($uri, $importer["uid"]);
2812 create_files_from_itemuri($uri, $importer["uid"]);
2813 update_thread_uri($uri, $importer["importer_uid"]);
2814 if ($item["last-child"]) {
2815 // ensure that last-child is set in case the comment that had it just got wiped.
2816 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2817 dbesc(datetime_convert()),
2818 dbesc($item["parent-uri"]),
2819 intval($item["uid"])
2821 // who is the last child now?
2822 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
2823 ORDER BY `created` DESC LIMIT 1",
2824 dbesc($item["parent-uri"]),
2825 intval($importer["uid"])
2827 if (dbm::is_result($r)) {
2828 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
2833 // if this is a relayed delete, propagate it to other recipients
2835 if ($entrytype == DFRN_REPLY_RC) {
2836 logger("Notifying followers about deletion of post " . $item["id"], LOGGER_DEBUG);
2837 proc_run(PRIORITY_HIGH, "include/notifier.php","drop", $item["id"]);
2844 * @brief Imports a DFRN message
2846 * @param text $xml The DFRN message
2847 * @param array $importer Record of the importer user mixed with contact of the content
2848 * @param bool $sort_by_date Is used when feeds are polled
2849 * @return integer Import status
2850 * @todo set proper type-hints
2852 public static function import($xml, $importer, $sort_by_date = false) {
2858 $doc = new DOMDocument();
2859 @$doc->loadXML($xml);
2861 $xpath = new DomXPath($doc);
2862 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2863 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2864 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2865 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2866 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2867 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2868 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2869 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2870 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2871 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2874 $header["uid"] = $importer["uid"];
2875 $header["network"] = NETWORK_DFRN;
2876 $header["type"] = "remote";
2877 $header["wall"] = 0;
2878 $header["origin"] = 0;
2879 $header["contact-id"] = $importer["id"];
2881 // Update the contact table if the data has changed
2883 // The "atom:author" is only present in feeds
2884 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2885 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2888 // Only the "dfrn:owner" in the head section contains all data
2889 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2890 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2893 logger("Import DFRN message for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2895 // The account type is new since 3.5.1
2896 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2897 $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()", $context)->item(0)->nodeValue);
2899 if ($accounttype != $importer["contact-type"]) {
2900 dba::update('contact', array('contact-type' => $accounttype), array('id' => $importer["id"]));
2904 // is it a public forum? Private forums aren't supported with this method
2905 // This is deprecated since 3.5.1
2906 $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()", $context)->item(0)->nodeValue);
2908 if ($forum != $importer["forum"]) {
2909 $condition = array('`forum` != ? AND `id` = ?', $forum, $importer["id"]);
2910 dba::update('contact', array('forum' => $forum), $condition);
2913 // We are processing relocations even if we are ignoring a contact
2914 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2915 foreach ($relocations AS $relocation) {
2916 self::process_relocation($xpath, $relocation, $importer);
2919 if ($importer["readonly"]) {
2920 // We aren't receiving stuff from this person. But we will quietly ignore them
2921 // rather than a blatant "go away" message.
2922 logger('ignoring contact '.$importer["id"]);
2926 $mails = $xpath->query("/atom:feed/dfrn:mail");
2927 foreach ($mails AS $mail) {
2928 self::process_mail($xpath, $mail, $importer);
2931 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2932 foreach ($suggestions AS $suggestion) {
2933 self::process_suggestion($xpath, $suggestion, $importer);
2936 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2937 foreach ($deletions AS $deletion) {
2938 self::process_deletion($xpath, $deletion, $importer);
2941 if (!$sort_by_date) {
2942 $entries = $xpath->query("/atom:feed/atom:entry");
2943 foreach ($entries AS $entry) {
2944 self::process_entry($header, $xpath, $entry, $importer, $xml);
2947 $newentries = array();
2948 $entries = $xpath->query("/atom:feed/atom:entry");
2949 foreach ($entries AS $entry) {
2950 $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2951 $newentries[strtotime($created)] = $entry;
2954 // Now sort after the publishing date
2957 foreach ($newentries AS $entry) {
2958 self::process_entry($header, $xpath, $entry, $importer, $xml);
2961 logger("Import done for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);