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 Check and possibly rewrite a post if it was a dedicated forum post
1993 * @param array $item the new item record
1995 * @return boolean Was the post be rewritten?
1997 private static function rewriteDedicatedForumPost($item) {
1998 $fields = array('author-link', 'allow_cid', 'contact-id', 'private', 'wall', 'id', 'parent');
1999 $condition = array('uri' => $item['uri'], 'uid' => $item['uid']);
2000 $existing = dba::select('item', $fields, $condition, array('limit' => 1));
2001 if (!dbm::is_result($existing)) {
2005 // Only rewrite if the former post was a private starting post
2006 if (!$existing['wall'] || !$existing['private'] || ($existing['id'] != $existing['parent'])) {
2010 // Is the post only directed to a sigle forum
2011 if ($existing['allow_cid'] != '<'.$item['contact-id'].'>') {
2015 $fields = array('id');
2016 $condition = array('uid' => $item['uid'], 'self' => true);
2017 $self = dba::select('contact', $fields, $condition, array('limit' => 1));
2018 if (!dbm::is_result($self)) {
2022 // is the original item created by the "self" user.
2023 if ($self['id'] != $existing['contact-id']) {
2027 $fields = array('forum', 'prv');
2028 $condition = array('id' => $item['contact-id']);
2029 $contact = dba::select('contact', $fields, $condition, array('limit' => 1));
2030 if (!dbm::is_result($contact)) {
2034 // Is the post from a forum?
2035 if (!$contact['forum'] && !$contact['prv']) {
2039 /// @todo There is an ugly downside of this whole rewrite process: These items loose the ability to be edited by the user.
2040 logger('Item '.$item['uri'].' will be rewritten.', LOGGER_DEBUG);
2042 $item = store_conversation($item);
2043 unset($fields['dsprsig']);
2045 // Rewrite to a public post if it comes from a public forum
2046 if ($contact['forum']) {
2047 $item['allow_cid'] = '';
2048 $item['allow_gid'] = '';
2049 $item['deny_cid'] = '';
2050 $item['deny_gid'] = '';
2051 $item['private'] = false;
2054 $item['wall'] = false;
2056 $item["owner-id"] = get_contact($item["owner-link"], 0);
2058 $condition = array('uri' => $item["uri"], 'uid' => $item["uid"]);
2059 dba::update('item', $item, $condition);
2061 add_thread($existing['id']);
2066 * @brief Updates an item
2068 * @param array $current the current item record
2069 * @param array $item the new item record
2070 * @param array $importer Record of the importer user mixed with contact of the content
2071 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2072 * @todo set proper type-hints (array?)
2074 private static function update_content($current, $item, $importer, $entrytype) {
2077 if (edited_timestamp_is_newer($current, $item)) {
2079 // do not accept (ignore) an earlier edit than one we currently have.
2080 if (datetime_convert("UTC","UTC",$item["edited"]) < $current["edited"]) {
2084 if (!self::rewriteDedicatedForumPost($item)) {
2085 $fields = array('title' => $item["title"], 'body' => $item["body"],
2086 'tag' => $item["tag"], 'changed' => datetime_convert(),
2087 'edited' => datetime_convert("UTC", "UTC", $item["edited"]));
2089 $condition = array("`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]);
2090 dba::update('item', $fields, $condition);
2093 create_tags_from_itemuri($item["uri"], $importer["importer_uid"]);
2094 update_thread_uri($item["uri"], $importer["importer_uid"]);
2098 if ($entrytype == DFRN_REPLY_RC) {
2099 proc_run(PRIORITY_HIGH, "include/notifier.php","comment-import", $current["id"]);
2103 // update last-child if it changes
2104 if ($item["last-child"] && ($item["last-child"] != $current["last-child"])) {
2105 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2106 dbesc(datetime_convert()),
2107 dbesc($item["parent-uri"]),
2108 intval($importer["importer_uid"])
2110 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` IN (0, %d)",
2111 intval($item["last-child"]),
2112 dbesc(datetime_convert()),
2113 dbesc($item["uri"]),
2114 intval($importer["importer_uid"])
2121 * @brief Detects the entry type of the item
2123 * @param array $importer Record of the importer user mixed with contact of the content
2124 * @param array $item the new item record
2126 * @return int Is it a toplevel entry, a comment or a relayed comment?
2127 * @todo set proper type-hints (array?)
2129 private static function get_entry_type($importer, $item) {
2130 if ($item["parent-uri"] != $item["uri"]) {
2133 if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
2136 logger("possible community action");
2138 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2141 // was the top-level post for this action written by somebody on this site?
2142 // Specifically, the recipient?
2144 $is_a_remote_action = false;
2146 $r = q("SELECT `item`.`parent-uri` FROM `item`
2147 WHERE `item`.`uri` = '%s'
2149 dbesc($item["parent-uri"])
2151 if (dbm::is_result($r)) {
2152 $r = q("SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2153 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2154 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2155 AND `item`.`uid` = %d
2158 dbesc($r[0]["parent-uri"]),
2159 dbesc($r[0]["parent-uri"]),
2160 dbesc($r[0]["parent-uri"]),
2161 intval($importer["importer_uid"])
2163 if (dbm::is_result($r)) {
2164 $is_a_remote_action = true;
2169 * Does this have the characteristics of a community or private group action?
2170 * If it's an action to a wall post on a community/prvgroup page it's a
2171 * valid community action. Also forum_mode makes it valid for sure.
2172 * If neither, it's not.
2175 /// @TODO Maybe merge these if() blocks into one?
2176 if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2177 $is_a_remote_action = false;
2178 logger("not a community action");
2181 if ($is_a_remote_action) {
2182 return DFRN_REPLY_RC;
2187 return DFRN_TOP_LEVEL;
2193 * @brief Send a "poke"
2195 * @param array $item the new item record
2196 * @param array $importer Record of the importer user mixed with contact of the content
2197 * @param int $posted_id The record number of item record that was just posted
2198 * @todo set proper type-hints (array?)
2200 private static function do_poke($item, $importer, $posted_id) {
2201 $verb = urldecode(substr($item["verb"],strpos($item["verb"], "#")+1));
2205 $xo = parse_xml_string($item["object"],false);
2207 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2209 // somebody was poked/prodded. Was it me?
2210 foreach ($xo->link as $l) {
2211 $atts = $l->attributes();
2212 switch ($atts["rel"]) {
2214 $Blink = $atts["href"];
2221 if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2223 // send a notification
2225 "type" => NOTIFY_POKE,
2226 "notify_flags" => $importer["notify-flags"],
2227 "language" => $importer["language"],
2228 "to_name" => $importer["username"],
2229 "to_email" => $importer["email"],
2230 "uid" => $importer["importer_uid"],
2232 "link" => System::baseUrl()."/display/".urlencode(get_item_guid($posted_id)),
2233 "source_name" => stripslashes($item["author-name"]),
2234 "source_link" => $item["author-link"],
2235 "source_photo" => ((link_compare($item["author-link"],$importer["url"]))
2236 ? $importer["thumb"] : $item["author-avatar"]),
2237 "verb" => $item["verb"],
2238 "otype" => "person",
2239 "activity" => $verb,
2240 "parent" => $item["parent"]
2247 * @brief Processes several actions, depending on the verb
2249 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2250 * @param array $importer Record of the importer user mixed with contact of the content
2251 * @param array $item the new item record
2252 * @param bool $is_like Is the verb a "like"?
2254 * @return bool Should the processing of the entries be continued?
2255 * @todo set proper type-hints (array?)
2257 private static function process_verbs($entrytype, $importer, &$item, &$is_like) {
2259 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2261 if (($entrytype == DFRN_TOP_LEVEL)) {
2262 // The filling of the the "contact" variable is done for legcy reasons
2263 // The functions below are partly used by ostatus.php as well - where we have this variable
2264 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2266 $nickname = $contact["nick"];
2268 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2269 // This function once was responsible for DFRN and OStatus.
2270 if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2271 logger("New follower");
2272 new_follower($importer, $contact, $item, $nickname);
2275 if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2276 logger("Lost follower");
2277 lose_follower($importer, $contact, $item);
2280 if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2281 logger("New friend request");
2282 new_follower($importer, $contact, $item, $nickname, true);
2285 if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2286 logger("Lost sharer");
2287 lose_sharer($importer, $contact, $item);
2291 if (($item["verb"] == ACTIVITY_LIKE)
2292 || ($item["verb"] == ACTIVITY_DISLIKE)
2293 || ($item["verb"] == ACTIVITY_ATTEND)
2294 || ($item["verb"] == ACTIVITY_ATTENDNO)
2295 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)) {
2297 $item["type"] = "activity";
2298 $item["gravity"] = GRAVITY_LIKE;
2299 // only one like or dislike per person
2300 // splitted into two queries for performance issues
2301 $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",
2302 intval($item["uid"]),
2303 dbesc($item["author-link"]),
2304 dbesc($item["verb"]),
2305 dbesc($item["parent-uri"])
2307 if (dbm::is_result($r)) {
2311 $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",
2312 intval($item["uid"]),
2313 dbesc($item["author-link"]),
2314 dbesc($item["verb"]),
2315 dbesc($item["parent-uri"])
2317 if (dbm::is_result($r)) {
2324 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2326 $xo = parse_xml_string($item["object"],false);
2327 $xt = parse_xml_string($item["target"],false);
2329 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2330 $r = q("SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2332 intval($importer["importer_uid"])
2335 if (!dbm::is_result($r)) {
2336 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2340 // extract tag, if not duplicate, add to parent item
2342 if (!(stristr($r[0]["tag"],trim($xo->content)))) {
2343 q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2344 dbesc($r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2347 create_tags_from_item($r[0]["id"]);
2357 * @brief Processes the link elements
2359 * @param object $links link elements
2360 * @param array $item the item record
2361 * @todo set proper type-hints
2363 private static function parse_links($links, &$item) {
2369 foreach ($links AS $link) {
2370 foreach ($link->attributes AS $attributes) {
2371 /// @TODO Rewrite these repeated (same) if () statements to a switch()
2372 if ($attributes->name == "href") {
2373 $href = $attributes->textContent;
2375 if ($attributes->name == "rel") {
2376 $rel = $attributes->textContent;
2378 if ($attributes->name == "type") {
2379 $type = $attributes->textContent;
2381 if ($attributes->name == "length") {
2382 $length = $attributes->textContent;
2384 if ($attributes->name == "title") {
2385 $title = $attributes->textContent;
2388 if (($rel != "") && ($href != "")) {
2391 $item["plink"] = $href;
2395 if (strlen($item["attach"])) {
2396 $item["attach"] .= ",";
2399 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2407 * @brief Processes the entry elements which contain the items and comments
2409 * @param array $header Array of the header elements that always stay the same
2410 * @param object $xpath XPath object
2411 * @param object $entry entry elements
2412 * @param array $importer Record of the importer user mixed with contact of the content
2413 * @todo Add type-hints
2415 private static function process_entry($header, $xpath, $entry, $importer, $xml) {
2417 logger("Processing entries");
2421 $item["protocol"] = PROTOCOL_DFRN;
2423 $item["source"] = $xml;
2426 $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
2428 $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
2430 $current = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2431 dbesc($item["uri"]),
2432 intval($importer["importer_uid"])
2435 // Is there an existing item?
2436 if (dbm::is_result($current) && edited_timestamp_is_newer($current[0], $item) &&
2437 (datetime_convert("UTC","UTC",$item["edited"]) < $current[0]["edited"])) {
2438 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2443 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2445 $item["owner-name"] = $owner["name"];
2446 $item["owner-link"] = $owner["link"];
2447 $item["owner-avatar"] = $owner["avatar"];
2450 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2452 $item["author-name"] = $author["name"];
2453 $item["author-link"] = $author["link"];
2454 $item["author-avatar"] = $author["avatar"];
2456 $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
2458 $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2460 $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
2461 $item["body"] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$item["body"]);
2462 // make sure nobody is trying to sneak some html tags by us
2463 $item["body"] = notags(base64url_decode($item["body"]));
2465 $item["body"] = limit_body_size($item["body"]);
2467 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2468 if ((strpos($item['body'],'<') !== false) && (strpos($item['body'],'>') !== false)) {
2470 $item['body'] = reltoabs($item['body'],$base_url);
2472 $item['body'] = html2bb_video($item['body']);
2474 $item['body'] = oembed_html2bbcode($item['body']);
2476 $config = HTMLPurifier_Config::createDefault();
2477 $config->set('Cache.DefinitionImpl', null);
2479 // we shouldn't need a whitelist, because the bbcode converter
2480 // will strip out any unsupported tags.
2482 $purifier = new HTMLPurifier($config);
2483 $item['body'] = $purifier->purify($item['body']);
2485 $item['body'] = @html2bbcode($item['body']);
2488 /// @todo We should check for a repeated post and if we know the repeated author.
2490 // We don't need the content element since "dfrn:env" is always present
2491 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2493 $item["last-child"] = $xpath->query("dfrn:comment-allow/text()", $entry)->item(0)->nodeValue;
2494 $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
2496 $georsspoint = $xpath->query("georss:point", $entry);
2498 $item["coord"] = $georsspoint->item(0)->nodeValue;
2501 $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
2503 $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
2505 if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true") {
2506 $item["bookmark"] = true;
2509 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2510 if ($notice_info && ($notice_info->length > 0)) {
2511 foreach ($notice_info->item(0)->attributes AS $attributes) {
2512 if ($attributes->name == "source") {
2513 $item["app"] = strip_tags($attributes->textContent);
2518 $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
2520 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "item_store"
2521 $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
2522 if ($dsprsig != "") {
2523 $item["dsprsig"] = $dsprsig;
2526 $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
2528 if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "") {
2529 $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
2532 $object = $xpath->query("activity:object", $entry)->item(0);
2533 $item["object"] = self::transform_activity($xpath, $object, "object");
2535 if (trim($item["object"]) != "") {
2536 $r = parse_xml_string($item["object"], false);
2537 if (isset($r->type)) {
2538 $item["object-type"] = $r->type;
2542 $target = $xpath->query("activity:target", $entry)->item(0);
2543 $item["target"] = self::transform_activity($xpath, $target, "target");
2545 $categories = $xpath->query("atom:category", $entry);
2547 foreach ($categories AS $category) {
2550 foreach ($category->attributes AS $attributes) {
2551 if ($attributes->name == "term") {
2552 $term = $attributes->textContent;
2555 if ($attributes->name == "scheme") {
2556 $scheme = $attributes->textContent;
2560 if (($term != "") && ($scheme != "")) {
2561 $parts = explode(":", $scheme);
2562 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2563 $termhash = array_shift($parts);
2564 $termurl = implode(":", $parts);
2566 if (strlen($item["tag"])) {
2567 $item["tag"] .= ",";
2570 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2578 $links = $xpath->query("atom:link", $entry);
2580 self::parse_links($links, $item);
2583 $item['conversation-uri'] = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
2585 $conv = $xpath->query('ostatus:conversation', $entry);
2586 if (is_object($conv->item(0))) {
2587 foreach ($conv->item(0)->attributes AS $attributes) {
2588 if ($attributes->name == "ref") {
2589 $item['conversation-uri'] = $attributes->textContent;
2591 if ($attributes->name == "href") {
2592 $item['conversation-href'] = $attributes->textContent;
2597 // Is it a reply or a top level posting?
2598 $item["parent-uri"] = $item["uri"];
2600 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2601 if (is_object($inreplyto->item(0))) {
2602 foreach ($inreplyto->item(0)->attributes AS $attributes) {
2603 if ($attributes->name == "ref") {
2604 $item["parent-uri"] = $attributes->textContent;
2609 // Get the type of the item (Top level post, reply or remote reply)
2610 $entrytype = self::get_entry_type($importer, $item);
2612 // Now assign the rest of the values that depend on the type of the message
2613 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2614 if (!isset($item["object-type"])) {
2615 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2618 if ($item["contact-id"] != $owner["contact-id"]) {
2619 $item["contact-id"] = $owner["contact-id"];
2622 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2623 $item["network"] = $owner["network"];
2626 if ($item["contact-id"] != $author["contact-id"]) {
2627 $item["contact-id"] = $author["contact-id"];
2630 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2631 $item["network"] = $author["network"];
2634 /// @TODO maybe remove this old-lost code then?
2635 // This code was taken from the old DFRN code
2636 // When activated, forums don't work.
2637 // And: Why should we disallow commenting by followers?
2638 // the behaviour is now similar to the Diaspora part.
2639 //if ($importer["rel"] == CONTACT_IS_FOLLOWER) {
2640 // logger("Contact ".$importer["id"]." is only follower. Quitting", LOGGER_DEBUG);
2645 if ($entrytype == DFRN_REPLY_RC) {
2646 $item["type"] = "remote-comment";
2648 } elseif ($entrytype == DFRN_TOP_LEVEL) {
2649 if (!isset($item["object-type"])) {
2650 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2654 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2655 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2656 $ev = bbtoevent($item["body"]);
2657 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2658 logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2659 /// @TODO Mixure of "/' ahead ...
2660 $ev["cid"] = $importer["id"];
2661 $ev["uid"] = $importer["uid"];
2662 $ev["uri"] = $item["uri"];
2663 $ev["edited"] = $item["edited"];
2664 $ev['private'] = $item['private'];
2665 $ev["guid"] = $item["guid"];
2667 $r = q("SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2668 dbesc($item["uri"]),
2669 intval($importer["uid"])
2671 if (dbm::is_result($r)) {
2672 $ev["id"] = $r[0]["id"];
2675 $event_id = event_store($ev);
2676 logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2682 if (!self::process_verbs($entrytype, $importer, $item, $is_like)) {
2683 logger("Exiting because 'process_verbs' told us so", LOGGER_DEBUG);
2687 // Update content if 'updated' changes
2688 if (dbm::is_result($current)) {
2689 if (self::update_content($r[0], $item, $importer, $entrytype)) {
2690 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2692 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2697 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2698 $posted_id = item_store($item);
2703 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2705 $item["id"] = $posted_id;
2707 $r = q("SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2709 intval($importer["importer_uid"])
2711 if (dbm::is_result($r)) {
2712 $parent = $r[0]["parent"];
2713 $parent_uri = $r[0]["parent-uri"];
2717 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2718 dbesc(datetime_convert()),
2719 intval($importer["importer_uid"]),
2720 intval($r[0]["parent"])
2723 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d",
2724 dbesc(datetime_convert()),
2725 intval($importer["importer_uid"]),
2730 if ($posted_id && $parent && ($entrytype == DFRN_REPLY_RC)) {
2731 logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
2732 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $posted_id);
2737 } else { // $entrytype == DFRN_TOP_LEVEL
2738 if (!link_compare($item["owner-link"],$importer["url"])) {
2740 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2741 * but otherwise there's a possible data mixup on the sender's system.
2742 * the tgroup delivery code called from item_store will correct it if it's a forum,
2743 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2745 logger('Correcting item owner.', LOGGER_DEBUG);
2746 $item["owner-name"] = $importer["senderName"];
2747 $item["owner-link"] = $importer["url"];
2748 $item["owner-avatar"] = $importer["thumb"];
2751 if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!tgroup_check($importer["importer_uid"], $item))) {
2752 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2756 // This is my contact on another system, but it's really me.
2757 // Turn this into a wall post.
2758 $notify = item_is_remote_self($importer, $item);
2760 $posted_id = item_store($item, false, $notify);
2762 logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2764 if (stristr($item["verb"],ACTIVITY_POKE))
2765 self::do_poke($item, $importer, $posted_id);
2770 * @brief Deletes items
2772 * @param object $xpath XPath object
2773 * @param object $deletion deletion elements
2774 * @param array $importer Record of the importer user mixed with contact of the content
2775 * @todo set proper type-hints
2777 private static function process_deletion($xpath, $deletion, $importer) {
2779 logger("Processing deletions");
2781 foreach ($deletion->attributes AS $attributes) {
2782 if ($attributes->name == "ref") {
2783 $uri = $attributes->textContent;
2785 if ($attributes->name == "when") {
2786 $when = $attributes->textContent;
2790 $when = datetime_convert("UTC", "UTC", $when, "Y-m-d H:i:s");
2792 $when = datetime_convert("UTC", "UTC", "now", "Y-m-d H:i:s");
2795 if (!$uri || !$importer["id"]) {
2799 /// @todo Only select the used fields
2800 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` INNER JOIN `contact` on `item`.`contact-id` = `contact`.`id`
2801 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2803 intval($importer["uid"]),
2804 intval($importer["id"])
2806 if (!dbm::is_result($r)) {
2807 logger("Item with uri " . $uri . " from contact " . $importer["id"] . " for user " . $importer["uid"] . " wasn't found.", LOGGER_DEBUG);
2813 $entrytype = self::get_entry_type($importer, $item);
2815 if (!$item["deleted"]) {
2816 logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG);
2821 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2822 logger("Deleting event ".$item["event-id"], LOGGER_DEBUG);
2823 event_delete($item["event-id"]);
2826 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2828 $xo = parse_xml_string($item["object"],false);
2829 $xt = parse_xml_string($item["target"],false);
2831 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2832 $i = q("SELECT `id`, `contact-id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2834 intval($importer["importer_uid"])
2836 if (dbm::is_result($i)) {
2838 // For tags, the owner cannot remove the tag on the author's copy of the post.
2840 $owner_remove = (($item["contact-id"] == $i[0]["contact-id"]) ? true: false);
2841 $author_remove = (($item["origin"] && $item["self"]) ? true : false);
2842 $author_copy = (($item["origin"]) ? true : false);
2844 if ($owner_remove && $author_copy) {
2847 if ($author_remove || $owner_remove) {
2848 $tags = explode(',',$i[0]["tag"]);
2851 foreach ($tags as $tag) {
2852 if (trim($tag) !== trim($xo->body)) {
2853 $newtags[] = trim($tag);
2857 q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2858 dbesc(implode(',', $newtags)),
2861 create_tags_from_item($i[0]["id"]);
2867 if ($entrytype == DFRN_TOP_LEVEL) {
2868 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2869 `body` = '', `title` = ''
2870 WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2872 dbesc(datetime_convert()),
2874 intval($importer["uid"])
2876 create_tags_from_itemuri($uri, $importer["uid"]);
2877 create_files_from_itemuri($uri, $importer["uid"]);
2878 update_thread_uri($uri, $importer["uid"]);
2880 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2881 `body` = '', `title` = ''
2882 WHERE `uri` = '%s' AND `uid` IN (0, %d)",
2884 dbesc(datetime_convert()),
2886 intval($importer["uid"])
2888 create_tags_from_itemuri($uri, $importer["uid"]);
2889 create_files_from_itemuri($uri, $importer["uid"]);
2890 update_thread_uri($uri, $importer["importer_uid"]);
2891 if ($item["last-child"]) {
2892 // ensure that last-child is set in case the comment that had it just got wiped.
2893 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2894 dbesc(datetime_convert()),
2895 dbesc($item["parent-uri"]),
2896 intval($item["uid"])
2898 // who is the last child now?
2899 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
2900 ORDER BY `created` DESC LIMIT 1",
2901 dbesc($item["parent-uri"]),
2902 intval($importer["uid"])
2904 if (dbm::is_result($r)) {
2905 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
2910 // if this is a relayed delete, propagate it to other recipients
2912 if ($entrytype == DFRN_REPLY_RC) {
2913 logger("Notifying followers about deletion of post " . $item["id"], LOGGER_DEBUG);
2914 proc_run(PRIORITY_HIGH, "include/notifier.php","drop", $item["id"]);
2921 * @brief Imports a DFRN message
2923 * @param text $xml The DFRN message
2924 * @param array $importer Record of the importer user mixed with contact of the content
2925 * @param bool $sort_by_date Is used when feeds are polled
2926 * @return integer Import status
2927 * @todo set proper type-hints
2929 public static function import($xml, $importer, $sort_by_date = false) {
2935 $doc = new DOMDocument();
2936 @$doc->loadXML($xml);
2938 $xpath = new DomXPath($doc);
2939 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2940 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2941 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2942 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2943 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2944 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2945 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2946 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2947 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2948 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2951 $header["uid"] = $importer["uid"];
2952 $header["network"] = NETWORK_DFRN;
2953 $header["type"] = "remote";
2954 $header["wall"] = 0;
2955 $header["origin"] = 0;
2956 $header["contact-id"] = $importer["id"];
2958 // Update the contact table if the data has changed
2960 // The "atom:author" is only present in feeds
2961 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2962 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2965 // Only the "dfrn:owner" in the head section contains all data
2966 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2967 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2970 logger("Import DFRN message for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2972 // The account type is new since 3.5.1
2973 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2974 $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()", $context)->item(0)->nodeValue);
2976 if ($accounttype != $importer["contact-type"]) {
2977 dba::update('contact', array('contact-type' => $accounttype), array('id' => $importer["id"]));
2981 // is it a public forum? Private forums aren't supported with this method
2982 // This is deprecated since 3.5.1
2983 $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()", $context)->item(0)->nodeValue);
2985 if ($forum != $importer["forum"]) {
2986 $condition = array('`forum` != ? AND `id` = ?', $forum, $importer["id"]);
2987 dba::update('contact', array('forum' => $forum), $condition);
2990 // We are processing relocations even if we are ignoring a contact
2991 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2992 foreach ($relocations AS $relocation) {
2993 self::process_relocation($xpath, $relocation, $importer);
2996 if ($importer["readonly"]) {
2997 // We aren't receiving stuff from this person. But we will quietly ignore them
2998 // rather than a blatant "go away" message.
2999 logger('ignoring contact '.$importer["id"]);
3003 $mails = $xpath->query("/atom:feed/dfrn:mail");
3004 foreach ($mails AS $mail) {
3005 self::process_mail($xpath, $mail, $importer);
3008 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
3009 foreach ($suggestions AS $suggestion) {
3010 self::process_suggestion($xpath, $suggestion, $importer);
3013 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
3014 foreach ($deletions AS $deletion) {
3015 self::process_deletion($xpath, $deletion, $importer);
3018 if (!$sort_by_date) {
3019 $entries = $xpath->query("/atom:feed/atom:entry");
3020 foreach ($entries AS $entry) {
3021 self::process_entry($header, $xpath, $entry, $importer, $xml);
3024 $newentries = array();
3025 $entries = $xpath->query("/atom:feed/atom:entry");
3026 foreach ($entries AS $entry) {
3027 $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
3028 $newentries[strtotime($created)] = $entry;
3031 // Now sort after the publishing date
3034 foreach ($newentries AS $entry) {
3035 self::process_entry($header, $xpath, $entry, $importer, $xml);
3038 logger("Import done for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);