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);
15 if(strpos($dfrn_id,':') == 1) {
16 $direction = intval(substr($dfrn_id,0,1));
17 $dfrn_id = substr($dfrn_id,2);
20 $r = q("SELECT * FROM `challenge` WHERE `dfrn-id` = '%s' AND `challenge` = '%s' LIMIT 1",
25 logger('dfrn_notify: could not match challenge to dfrn_id ' . $dfrn_id . ' challenge=' . $challenge);
29 $r = q("DELETE FROM `challenge` WHERE `dfrn-id` = '%s' AND `challenge` = '%s' LIMIT 1",
34 // find the local user who owns this relationship.
39 $sql_extra = sprintf(" AND ( `issued-id` = '%s' OR `dfrn-id` = '%s' ) ", dbesc($dfrn_id), dbesc($dfrn_id));
42 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
45 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
53 $r = q("SELECT `contact`.*, `contact`.`uid` AS `importer_uid`,
54 `contact`.`pubkey` AS `cpubkey`,
55 `contact`.`prvkey` AS `cprvkey`,
56 `contact`.`thumb` AS `thumb`,
57 `contact`.`url` as `url`,
58 `contact`.`name` as `senderName`,
61 LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
62 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
63 AND `user`.`nickname` = '%s' $sql_extra LIMIT 1",
68 logger('dfrn_notify: contact not found for dfrn_id ' . $dfrn_id);
73 // $importer in this case contains the contact record for the remote contact joined with the user record of our user.
77 logger('dfrn_notify: received notify from ' . $importer['name'] . ' for ' . $importer['username']);
78 logger('dfrn_notify: data: ' . $data, LOGGER_DATA);
83 * Relationship is dissolved permanently
86 require_once('include/Contact.php');
87 contact_remove($importer['id']);
88 logger('relationship dissolved : ' . $importer['name'] . ' dissolved ' . $importer['username']);
94 $rawkey = hex2bin(trim($key));
95 logger('rino: md5 raw key: ' . md5($rawkey));
98 if($dfrn_version >= 2.1) {
99 if((($importer['duplex']) && strlen($importer['cprvkey'])) || (! strlen($importer['cpubkey']))) {
100 openssl_private_decrypt($rawkey,$final_key,$importer['cprvkey']);
103 openssl_public_decrypt($rawkey,$final_key,$importer['cpubkey']);
107 if((($importer['duplex']) && strlen($importer['cpubkey'])) || (! strlen($importer['cprvkey']))) {
108 openssl_public_decrypt($rawkey,$final_key,$importer['cpubkey']);
111 openssl_private_decrypt($rawkey,$final_key,$importer['cprvkey']);
115 logger('rino: received key : ' . $final_key);
116 $data = aes_decrypt(hex2bin($data),$final_key);
117 logger('rino: decrypted data: ' . $data, LOGGER_DATA);
123 if($importer['readonly']) {
124 // We aren't receiving stuff from this person. But we will quietly ignore them
125 // rather than a blatant "go away" message.
126 logger('dfrn_notify: ignoring');
131 // Consume notification feed. This may differ from consuming a public feed in several ways
132 // - might contain email
133 // - might contain remote followup to our message
134 // - in which case we need to accept it and then notify other conversants
135 // - we may need to send various email notifications
137 $feed = new SimplePie();
138 $feed->set_raw_data($data);
139 $feed->enable_order_by_date(false);
144 $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
145 if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
147 logger('dfrn_notify: private message received');
150 $base = $rawmail[0]['child'][NAMESPACE_DFRN];
153 $msg['uid'] = $importer['importer_uid'];
154 $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
155 $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
156 $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
157 $msg['contact-id'] = $importer['id'];
158 $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
159 $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
162 $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
163 $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
164 $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
168 $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg))
169 . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
171 // send email notification if requested.
173 require_once('bbcode.php');
174 if($importer['notify-flags'] & NOTIFY_MAIL) {
176 // name of the automated email sender
177 $msg['notificationfromname'] = t('Administrator');
178 // noreply address to send from
179 $msg['notificationfromemail'] = t('noreply') . '@' . $a->get_hostname();
182 // process the message body to display properly in text mode
183 // 1) substitute a \n character for the "\" then "n", so it behaves properly (it doesn't come in as a \n character)
184 // 2) remove escape slashes
185 // 3) decode any bbcode from the message editor
186 // 4) decode any encoded html tags
187 // 5) remove html tags
189 = strip_tags(html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n"), "\n",$msg['body']))),ENT_QUOTES,'UTF-8'));
192 // process the message body to display properly in text mode
193 // 1) substitute a <br /> tag for the "\" then "n", so it behaves properly (it doesn't come in as a \n character)
194 // 2) remove escape slashes
195 // 3) decode any bbcode from the message editor
196 // 4) decode any encoded html tags
198 = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r","\\n\\n" ,"\\n"), "<br />\n",$msg['body']))));
200 // load the template for private message notifications
201 $tpl = load_view_file('view/mail_received_html_body_eml.tpl');
202 $email_html_body_tpl = replace_macros($tpl,array(
203 '$siteName' => $a->config['sitename'], // name of this site
204 '$siteurl' => $a->get_baseurl(), // descriptive url of this site
205 '$thumb' => $importer['thumb'], // thumbnail url for sender icon
206 '$email' => $importer['email'], // email address to send to
207 '$url' => $importer['url'], // full url for the site
208 '$from' => $msg['from-name'], // name of the person sending the message
209 '$title' => stripslashes($msg['title']), // subject of the message
210 '$htmlversion' => $msg['htmlversion'], // html version of the message
211 '$mimeboundary' => $msg['mimeboundary'], // mime message divider
212 '$hostname' => $a->get_hostname() // name of this host
215 // load the template for private message notifications
216 $tpl = load_view_file('view/mail_received_text_body_eml.tpl');
217 $email_text_body_tpl = replace_macros($tpl,array(
218 '$siteName' => $a->config['sitename'], // name of this site
219 '$siteurl' => $a->get_baseurl(), // descriptive url of this site
220 '$thumb' => $importer['thumb'], // thumbnail url for sender icon
221 '$email' => $importer['email'], // email address to send to
222 '$url' => $importer['url'], // full url for the site
223 '$from' => $msg['from-name'], // name of the person sending the message
224 '$title' => stripslashes($msg['title']), // subject of the message
225 '$textversion' => $msg['textversion'], // text version of the message
226 '$mimeboundary' => $msg['mimeboundary'], // mime message divider
227 '$hostname' => $a->get_hostname() // name of this host
230 // use the EmailNotification library to send the message
231 require_once("include/EmailNotification.php");
232 EmailNotification::sendTextHtmlEmail(
233 $msg['notificationfromname'],
234 $msg['notificationfromemail'],
235 $msg['notificationfromemail'],
237 t('New mail received at ') . $a->config['sitename'],
238 $email_html_body_tpl,
246 logger('dfrn_notify: feed item count = ' . $feed->get_item_quantity());
248 // process any deleted entries
250 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
251 if(is_array($del_entries) && count($del_entries)) {
252 foreach($del_entries as $dentry) {
254 if(isset($dentry['attribs']['']['ref'])) {
255 $uri = $dentry['attribs']['']['ref'];
257 if(isset($dentry['attribs']['']['when'])) {
258 $when = $dentry['attribs']['']['when'];
259 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
262 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
266 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `contact-id` = %d LIMIT 1",
268 intval($importer['importer_uid']),
269 intval($importer['id'])
275 if(! $item['deleted'])
276 logger('dfrn_notify: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
278 if($item['uri'] == $item['parent-uri']) {
279 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
280 WHERE `parent-uri` = '%s' AND `uid` = %d",
282 dbesc(datetime_convert()),
284 intval($importer['importer_uid'])
288 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
289 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
291 dbesc(datetime_convert()),
293 intval($importer['importer_uid'])
295 if($item['last-child']) {
296 // ensure that last-child is set in case the comment that had it just got wiped.
297 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
298 dbesc(datetime_convert()),
299 dbesc($item['parent-uri']),
302 // who is the last child now?
303 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
304 ORDER BY `created` DESC LIMIT 1",
305 dbesc($item['parent-uri']),
306 intval($importer['importer_uid'])
309 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
321 foreach($feed->get_items() as $item) {
324 $item_id = $item->get_id();
325 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
326 if(isset($rawthread[0]['attribs']['']['ref'])) {
328 $parent_uri = $rawthread[0]['attribs']['']['ref'];
332 if($feed->get_item_quantity() == 1) {
333 logger('dfrn_notify: received remote comment');
335 // remote reply to our post. Import and then notify everybody else.
336 $datarray = get_atom_elements($feed,$item);
337 $datarray['type'] = 'remote-comment';
338 $datarray['wall'] = 1;
339 $datarray['parent-uri'] = $parent_uri;
340 $datarray['uid'] = $importer['importer_uid'];
341 $datarray['contact-id'] = $importer['id'];
342 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
344 $datarray['type'] = 'activity';
345 $datarray['gravity'] = GRAVITY_LIKE;
346 $datarray['last-child'] = 0;
348 $posted_id = item_store($datarray);
352 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
354 intval($importer['importer_uid'])
357 $parent = $r[0]['parent'];
360 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
361 dbesc(datetime_convert()),
362 intval($importer['importer_uid']),
363 intval($r[0]['parent'])
366 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
367 dbesc(datetime_convert()),
368 intval($importer['importer_uid']),
373 if($posted_id && $parent) {
375 proc_run('php',"include/notifier.php","comment-import","$posted_id");
377 if((! $is_like) && ($importer['notify-flags'] & NOTIFY_COMMENT) && (! $importer['self'])) {
378 require_once('bbcode.php');
379 $from = stripslashes($datarray['author-name']);
380 $tpl = load_view_file('view/cmnt_received_eml.tpl');
381 $email_tpl = replace_macros($tpl, array(
382 '$sitename' => $a->config['sitename'],
383 '$siteurl' => $a->get_baseurl(),
384 '$username' => $importer['username'],
385 '$email' => $importer['email'],
386 '$display' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
388 '$body' => html_entity_decode(strip_tags(bbcode(stripslashes($datarray['body']))), ENT_QUOTES, 'UTF-8')
391 $res = mail($importer['email'], sprintf(t('%s commented on an item at %s'), $from , $a->config['sitename']),
392 $email_tpl, "From: " . t('Administrator') . '@' . $a->get_hostname() );
401 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
403 $item_id = $item->get_id();
404 $datarray = get_atom_elements($feed,$item);
406 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
408 intval($importer['importer_uid'])
411 // Update content if 'updated' changes
414 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
415 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
416 dbesc($datarray['body']),
417 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
419 intval($importer['importer_uid'])
423 // update last-child if it changes
425 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
426 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
427 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
428 dbesc(datetime_convert()),
430 intval($importer['importer_uid'])
432 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
433 intval($allow[0]['data']),
434 dbesc(datetime_convert()),
436 intval($importer['importer_uid'])
442 $datarray['parent-uri'] = $parent_uri;
443 $datarray['uid'] = $importer['importer_uid'];
444 $datarray['contact-id'] = $importer['id'];
445 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
446 $datarray['type'] = 'activity';
447 $datarray['gravity'] = GRAVITY_LIKE;
449 $r = item_store($datarray);
451 // find out if our user is involved in this conversation and wants to be notified.
453 if(($datarray['type'] != 'activity') && ($importer['notify-flags'] & NOTIFY_COMMENT)) {
455 $myconv = q("SELECT `author-link` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 ",
457 intval($importer['importer_uid'])
460 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
461 foreach($myconv as $conv) {
462 if(! link_compare($conv['author-link'],$importer_url))
464 require_once('bbcode.php');
465 $from = stripslashes($datarray['author-name']);
466 $tpl = load_view_file('view/cmnt_received_eml.tpl');
467 $email_tpl = replace_macros($tpl, array(
468 '$sitename' => $a->config['sitename'],
469 '$siteurl' => $a->get_baseurl(),
470 '$username' => $importer['username'],
471 '$email' => $importer['email'],
473 '$display' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $r,
474 '$body' => html_entity_decode(strip_tags(bbcode(stripslashes($datarray['body']))), ENT_QUOTES, 'UTF-8')
477 $res = mail($importer['email'], sprintf( t("%s commented on an item at %s") , $from ,$a->config['sitename']),
478 $email_tpl, "From: ".t("Administrator") . "@". $a->get_hostname() );
489 // Head post of a conversation. Have we seen it? If not, import it.
492 $item_id = $item->get_id();
493 $datarray = get_atom_elements($feed,$item);
495 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
497 intval($importer['importer_uid'])
500 // Update content if 'updated' changes
503 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
504 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
505 dbesc($datarray['body']),
506 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
508 intval($importer['importer_uid'])
512 // update last-child if it changes
514 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
515 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
516 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
517 intval($allow[0]['data']),
518 dbesc(datetime_convert()),
520 intval($importer['importer_uid'])
526 $datarray['parent-uri'] = $item_id;
527 $datarray['uid'] = $importer['importer_uid'];
528 $datarray['contact-id'] = $importer['id'];
529 $r = item_store($datarray);
540 function dfrn_notify_content(&$a) {
542 if(x($_GET,'dfrn_id')) {
544 // initial communication from external contact, $direction is their direction.
545 // If this is a duplex communication, ours will be the opposite.
547 $dfrn_id = notags(trim($_GET['dfrn_id']));
548 $dfrn_version = (float) $_GET['dfrn_version'];
550 logger('dfrn_notify: new notification dfrn_id=' . $dfrn_id);
553 if(strpos($dfrn_id,':') == 1) {
554 $direction = intval(substr($dfrn_id,0,1));
555 $dfrn_id = substr($dfrn_id,2);
558 $hash = random_string();
562 $r = q("DELETE FROM `challenge` WHERE `expire` < " . intval(time()));
564 $r = q("INSERT INTO `challenge` ( `challenge`, `dfrn-id`, `expire` )
565 VALUES( '%s', '%s', %d ) ",
571 logger('dfrn_notify: challenge=' . $hash );
576 $sql_extra = sprintf(" AND ( `issued-id` = '%s' OR `dfrn-id` = '%s' ) ", dbesc($dfrn_id), dbesc($dfrn_id));
580 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
581 $my_id = '1:' . $dfrn_id;
584 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
585 $my_id = '0:' . $dfrn_id;
592 $r = q("SELECT `contact`.*, `user`.`nickname` FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
593 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0 AND `user`.`nickname` = '%s' $sql_extra LIMIT 1",
602 $id_str = $my_id . '.' . mt_rand(1000,9999);
604 if((($r[0]['duplex']) && strlen($r[0]['prvkey'])) || (! strlen($r[0]['pubkey']))) {
605 openssl_private_encrypt($hash,$challenge,$r[0]['prvkey']);
606 openssl_private_encrypt($id_str,$encrypted_id,$r[0]['prvkey']);
609 openssl_public_encrypt($hash,$challenge,$r[0]['pubkey']);
610 openssl_public_encrypt($id_str,$encrypted_id,$r[0]['pubkey']);
613 $challenge = bin2hex($challenge);
614 $encrypted_id = bin2hex($encrypted_id);
616 $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
618 $rino_enable = get_config('system','rino_encrypt');
624 header("Content-type: text/xml");
626 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n"
627 . '<dfrn_notify>' . "\r\n"
628 . "\t" . '<status>' . $status . '</status>' . "\r\n"
629 . "\t" . '<dfrn_version>' . DFRN_PROTOCOL_VERSION . '</dfrn_version>' . "\r\n"
630 . "\t" . '<rino>' . $rino . '</rino>' . "\r\n"
631 . "\t" . '<dfrn_id>' . $encrypted_id . '</dfrn_id>' . "\r\n"
632 . "\t" . '<challenge>' . $challenge . '</challenge>' . "\r\n"
633 . '</dfrn_notify>' . "\r\n" ;