3 require_once('simplepie/simplepie.inc');
4 require_once('include/items.php');
5 function dfrn_notify_post(&$a) {
7 $dfrn_id = ((x($_POST,'dfrn_id')) ? notags(trim($_POST['dfrn_id'])) : '');
8 $dfrn_version = ((x($_POST,'dfrn_version')) ? (float) $_POST['dfrn_version'] : 2.0);
9 $challenge = ((x($_POST,'challenge')) ? notags(trim($_POST['challenge'])) : '');
10 $data = ((x($_POST,'data')) ? $_POST['data'] : '');
11 $key = ((x($_POST,'key')) ? $_POST['key'] : '');
12 $dissolve = ((x($_POST,'dissolve')) ? intval($_POST['dissolve']) : 0);
13 $perm = ((x($_POST,'perm')) ? notags(trim($_POST['perm'])) : 'r');
16 if($dfrn_version >= 2.21) {
17 $writable = (($perm === 'rw') ? 1 : 0);
21 if(strpos($dfrn_id,':') == 1) {
22 $direction = intval(substr($dfrn_id,0,1));
23 $dfrn_id = substr($dfrn_id,2);
26 $r = q("SELECT * FROM `challenge` WHERE `dfrn-id` = '%s' AND `challenge` = '%s' LIMIT 1",
31 logger('dfrn_notify: could not match challenge to dfrn_id ' . $dfrn_id . ' challenge=' . $challenge);
35 $r = q("DELETE FROM `challenge` WHERE `dfrn-id` = '%s' AND `challenge` = '%s' LIMIT 1",
40 // find the local user who owns this relationship.
45 $sql_extra = sprintf(" AND ( `issued-id` = '%s' OR `dfrn-id` = '%s' ) ", dbesc($dfrn_id), dbesc($dfrn_id));
48 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
51 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
59 $r = q("SELECT `contact`.*, `contact`.`uid` AS `importer_uid`,
60 `contact`.`pubkey` AS `cpubkey`,
61 `contact`.`prvkey` AS `cprvkey`,
62 `contact`.`thumb` AS `thumb`,
63 `contact`.`url` as `url`,
64 `contact`.`name` as `senderName`,
67 LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
68 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
69 AND `user`.`nickname` = '%s' $sql_extra LIMIT 1",
74 logger('dfrn_notify: contact not found for dfrn_id ' . $dfrn_id);
79 // $importer in this case contains the contact record for the remote contact joined with the user record of our user.
83 logger('dfrn_notify: received notify from ' . $importer['name'] . ' for ' . $importer['username']);
84 logger('dfrn_notify: data: ' . $data, LOGGER_DATA);
89 * Relationship is dissolved permanently
92 require_once('include/Contact.php');
93 contact_remove($importer['id']);
94 logger('relationship dissolved : ' . $importer['name'] . ' dissolved ' . $importer['username']);
100 $rawkey = hex2bin(trim($key));
101 logger('rino: md5 raw key: ' . md5($rawkey));
104 if($dfrn_version >= 2.1) {
105 if((($importer['duplex']) && strlen($importer['cprvkey'])) || (! strlen($importer['cpubkey']))) {
106 openssl_private_decrypt($rawkey,$final_key,$importer['cprvkey']);
109 openssl_public_decrypt($rawkey,$final_key,$importer['cpubkey']);
113 if((($importer['duplex']) && strlen($importer['cpubkey'])) || (! strlen($importer['cprvkey']))) {
114 openssl_public_decrypt($rawkey,$final_key,$importer['cpubkey']);
117 openssl_private_decrypt($rawkey,$final_key,$importer['cprvkey']);
121 logger('rino: received key : ' . $final_key);
122 $data = aes_decrypt(hex2bin($data),$final_key);
123 logger('rino: decrypted data: ' . $data, LOGGER_DATA);
129 if($importer['readonly']) {
130 // We aren't receiving stuff from this person. But we will quietly ignore them
131 // rather than a blatant "go away" message.
132 logger('dfrn_notify: ignoring');
137 // Consume notification feed. This may differ from consuming a public feed in several ways
138 // - might contain email
139 // - might contain remote followup to our message
140 // - in which case we need to accept it and then notify other conversants
141 // - we may need to send various email notifications
143 $feed = new SimplePie();
144 $feed->set_raw_data($data);
145 $feed->enable_order_by_date(false);
150 $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
151 if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
153 logger('dfrn_notify: private message received');
156 $base = $rawmail[0]['child'][NAMESPACE_DFRN];
159 $msg['uid'] = $importer['importer_uid'];
160 $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
161 $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
162 $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
163 $msg['contact-id'] = $importer['id'];
164 $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
165 $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
168 $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
169 $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
170 $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
174 $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg))
175 . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
177 // send email notification if requested.
179 require_once('bbcode.php');
180 if($importer['notify-flags'] & NOTIFY_MAIL) {
182 // name of the automated email sender
183 $msg['notificationfromname'] = t('Administrator');
184 // noreply address to send from
185 $msg['notificationfromemail'] = t('noreply') . '@' . $a->get_hostname();
188 // process the message body to display properly in text mode
189 // 1) substitute a \n character for the "\" then "n", so it behaves properly (it doesn't come in as a \n character)
190 // 2) remove escape slashes
191 // 3) decode any bbcode from the message editor
192 // 4) decode any encoded html tags
193 // 5) remove html tags
195 = strip_tags(html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n"), "\n",$msg['body']))),ENT_QUOTES,'UTF-8'));
198 // process the message body to display properly in text mode
199 // 1) substitute a <br /> tag for the "\" then "n", so it behaves properly (it doesn't come in as a \n character)
200 // 2) remove escape slashes
201 // 3) decode any bbcode from the message editor
202 // 4) decode any encoded html tags
204 = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r","\\n\\n" ,"\\n"), "<br />\n",$msg['body']))));
206 // load the template for private message notifications
207 $tpl = load_view_file('view/mail_received_html_body_eml.tpl');
208 $email_html_body_tpl = replace_macros($tpl,array(
209 '$siteName' => $a->config['sitename'], // name of this site
210 '$siteurl' => $a->get_baseurl(), // descriptive url of this site
211 '$thumb' => $importer['thumb'], // thumbnail url for sender icon
212 '$email' => $importer['email'], // email address to send to
213 '$url' => $importer['url'], // full url for the site
214 '$from' => $msg['from-name'], // name of the person sending the message
215 '$title' => stripslashes($msg['title']), // subject of the message
216 '$htmlversion' => $msg['htmlversion'], // html version of the message
217 '$mimeboundary' => $msg['mimeboundary'], // mime message divider
218 '$hostname' => $a->get_hostname() // name of this host
221 // load the template for private message notifications
222 $tpl = load_view_file('view/mail_received_text_body_eml.tpl');
223 $email_text_body_tpl = replace_macros($tpl,array(
224 '$siteName' => $a->config['sitename'], // name of this site
225 '$siteurl' => $a->get_baseurl(), // descriptive url of this site
226 '$thumb' => $importer['thumb'], // thumbnail url for sender icon
227 '$email' => $importer['email'], // email address to send to
228 '$url' => $importer['url'], // full url for the site
229 '$from' => $msg['from-name'], // name of the person sending the message
230 '$title' => stripslashes($msg['title']), // subject of the message
231 '$textversion' => $msg['textversion'], // text version of the message
232 '$mimeboundary' => $msg['mimeboundary'], // mime message divider
233 '$hostname' => $a->get_hostname() // name of this host
236 // use the EmailNotification library to send the message
237 require_once("include/EmailNotification.php");
238 EmailNotification::sendTextHtmlEmail(
239 $msg['notificationfromname'],
240 $msg['notificationfromemail'],
241 $msg['notificationfromemail'],
243 t('New mail received at ') . $a->config['sitename'],
244 $email_html_body_tpl,
252 logger('dfrn_notify: feed item count = ' . $feed->get_item_quantity());
254 // process any deleted entries
256 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
257 if(is_array($del_entries) && count($del_entries)) {
258 foreach($del_entries as $dentry) {
260 if(isset($dentry['attribs']['']['ref'])) {
261 $uri = $dentry['attribs']['']['ref'];
263 if(isset($dentry['attribs']['']['when'])) {
264 $when = $dentry['attribs']['']['when'];
265 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
268 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
272 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `contact-id` = %d LIMIT 1",
274 intval($importer['importer_uid']),
275 intval($importer['id'])
281 if(! $item['deleted'])
282 logger('dfrn_notify: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
284 if($item['uri'] == $item['parent-uri']) {
285 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
286 WHERE `parent-uri` = '%s' AND `uid` = %d",
288 dbesc(datetime_convert()),
290 intval($importer['importer_uid'])
294 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
295 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
297 dbesc(datetime_convert()),
299 intval($importer['importer_uid'])
301 if($item['last-child']) {
302 // ensure that last-child is set in case the comment that had it just got wiped.
303 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
304 dbesc(datetime_convert()),
305 dbesc($item['parent-uri']),
308 // who is the last child now?
309 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
310 ORDER BY `created` DESC LIMIT 1",
311 dbesc($item['parent-uri']),
312 intval($importer['importer_uid'])
315 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
327 foreach($feed->get_items() as $item) {
330 $item_id = $item->get_id();
331 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
332 if(isset($rawthread[0]['attribs']['']['ref'])) {
334 $parent_uri = $rawthread[0]['attribs']['']['ref'];
338 if($feed->get_item_quantity() == 1) {
339 logger('dfrn_notify: received remote comment');
341 // remote reply to our post. Import and then notify everybody else.
342 $datarray = get_atom_elements($feed,$item);
343 $datarray['type'] = 'remote-comment';
344 $datarray['wall'] = 1;
345 $datarray['parent-uri'] = $parent_uri;
346 $datarray['uid'] = $importer['importer_uid'];
347 $datarray['contact-id'] = $importer['id'];
348 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
350 $datarray['type'] = 'activity';
351 $datarray['gravity'] = GRAVITY_LIKE;
352 $datarray['last-child'] = 0;
354 $posted_id = item_store($datarray);
358 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
360 intval($importer['importer_uid'])
363 $parent = $r[0]['parent'];
366 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
367 dbesc(datetime_convert()),
368 intval($importer['importer_uid']),
369 intval($r[0]['parent'])
372 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
373 dbesc(datetime_convert()),
374 intval($importer['importer_uid']),
379 if($posted_id && $parent) {
381 proc_run('php',"include/notifier.php","comment-import","$posted_id");
383 if((! $is_like) && ($importer['notify-flags'] & NOTIFY_COMMENT) && (! $importer['self'])) {
384 require_once('bbcode.php');
385 $from = stripslashes($datarray['author-name']);
386 $tpl = load_view_file('view/cmnt_received_eml.tpl');
387 $email_tpl = replace_macros($tpl, array(
388 '$sitename' => $a->config['sitename'],
389 '$siteurl' => $a->get_baseurl(),
390 '$username' => $importer['username'],
391 '$email' => $importer['email'],
392 '$display' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
394 '$body' => html_entity_decode(strip_tags(bbcode(stripslashes($datarray['body']))), ENT_QUOTES, 'UTF-8')
397 $res = mail($importer['email'], sprintf(t('%s commented on an item at %s'), $from , $a->config['sitename']),
398 $email_tpl, "From: " . t('Administrator') . '@' . $a->get_hostname() );
407 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
409 $item_id = $item->get_id();
410 $datarray = get_atom_elements($feed,$item);
412 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
414 intval($importer['importer_uid'])
417 // Update content if 'updated' changes
420 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
421 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
422 dbesc($datarray['body']),
423 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
425 intval($importer['importer_uid'])
429 // update last-child if it changes
431 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
432 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
433 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
434 dbesc(datetime_convert()),
436 intval($importer['importer_uid'])
438 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
439 intval($allow[0]['data']),
440 dbesc(datetime_convert()),
442 intval($importer['importer_uid'])
448 $datarray['parent-uri'] = $parent_uri;
449 $datarray['uid'] = $importer['importer_uid'];
450 $datarray['contact-id'] = $importer['id'];
451 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
452 $datarray['type'] = 'activity';
453 $datarray['gravity'] = GRAVITY_LIKE;
455 $r = item_store($datarray);
457 // find out if our user is involved in this conversation and wants to be notified.
459 if(($datarray['type'] != 'activity') && ($importer['notify-flags'] & NOTIFY_COMMENT)) {
461 $myconv = q("SELECT `author-link` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 ",
463 intval($importer['importer_uid'])
466 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
467 foreach($myconv as $conv) {
468 if(! link_compare($conv['author-link'],$importer_url))
470 require_once('bbcode.php');
471 $from = stripslashes($datarray['author-name']);
472 $tpl = load_view_file('view/cmnt_received_eml.tpl');
473 $email_tpl = replace_macros($tpl, array(
474 '$sitename' => $a->config['sitename'],
475 '$siteurl' => $a->get_baseurl(),
476 '$username' => $importer['username'],
477 '$email' => $importer['email'],
479 '$display' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $r,
480 '$body' => html_entity_decode(strip_tags(bbcode(stripslashes($datarray['body']))), ENT_QUOTES, 'UTF-8')
483 $res = mail($importer['email'], sprintf( t("%s commented on an item at %s") , $from ,$a->config['sitename']),
484 $email_tpl, "From: ".t("Administrator") . "@". $a->get_hostname() );
495 // Head post of a conversation. Have we seen it? If not, import it.
498 $item_id = $item->get_id();
499 $datarray = get_atom_elements($feed,$item);
501 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
503 intval($importer['importer_uid'])
506 // Update content if 'updated' changes
509 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
510 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
511 dbesc($datarray['body']),
512 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
514 intval($importer['importer_uid'])
518 // update last-child if it changes
520 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
521 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
522 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
523 intval($allow[0]['data']),
524 dbesc(datetime_convert()),
526 intval($importer['importer_uid'])
532 $datarray['parent-uri'] = $item_id;
533 $datarray['uid'] = $importer['importer_uid'];
534 $datarray['contact-id'] = $importer['id'];
535 $r = item_store($datarray);
546 function dfrn_notify_content(&$a) {
548 if(x($_GET,'dfrn_id')) {
550 // initial communication from external contact, $direction is their direction.
551 // If this is a duplex communication, ours will be the opposite.
553 $dfrn_id = notags(trim($_GET['dfrn_id']));
554 $dfrn_version = (float) $_GET['dfrn_version'];
556 logger('dfrn_notify: new notification dfrn_id=' . $dfrn_id);
559 if(strpos($dfrn_id,':') == 1) {
560 $direction = intval(substr($dfrn_id,0,1));
561 $dfrn_id = substr($dfrn_id,2);
564 $hash = random_string();
568 $r = q("DELETE FROM `challenge` WHERE `expire` < " . intval(time()));
570 $r = q("INSERT INTO `challenge` ( `challenge`, `dfrn-id`, `expire` )
571 VALUES( '%s', '%s', %d ) ",
577 logger('dfrn_notify: challenge=' . $hash );
582 $sql_extra = sprintf(" AND ( `issued-id` = '%s' OR `dfrn-id` = '%s' ) ", dbesc($dfrn_id), dbesc($dfrn_id));
586 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
587 $my_id = '1:' . $dfrn_id;
590 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
591 $my_id = '0:' . $dfrn_id;
598 $r = q("SELECT `contact`.*, `user`.`nickname` FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
599 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0 AND `user`.`nickname` = '%s' $sql_extra LIMIT 1",
608 $id_str = $my_id . '.' . mt_rand(1000,9999);
610 if((($r[0]['duplex']) && strlen($r[0]['prvkey'])) || (! strlen($r[0]['pubkey']))) {
611 openssl_private_encrypt($hash,$challenge,$r[0]['prvkey']);
612 openssl_private_encrypt($id_str,$encrypted_id,$r[0]['prvkey']);
615 openssl_public_encrypt($hash,$challenge,$r[0]['pubkey']);
616 openssl_public_encrypt($id_str,$encrypted_id,$r[0]['pubkey']);
619 $challenge = bin2hex($challenge);
620 $encrypted_id = bin2hex($encrypted_id);
622 $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
624 $rino_enable = get_config('system','rino_encrypt');
630 header("Content-type: text/xml");
632 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n"
633 . '<dfrn_notify>' . "\r\n"
634 . "\t" . '<status>' . $status . '</status>' . "\r\n"
635 . "\t" . '<dfrn_version>' . DFRN_PROTOCOL_VERSION . '</dfrn_version>' . "\r\n"
636 . "\t" . '<rino>' . $rino . '</rino>' . "\r\n"
637 . "\t" . '<dfrn_id>' . $encrypted_id . '</dfrn_id>' . "\r\n"
638 . "\t" . '<challenge>' . $challenge . '</challenge>' . "\r\n"
639 . '</dfrn_notify>' . "\r\n" ;