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 if(($writable != (-1)) && ($writable != $importer['writable'])) {
84 q("UPDATE `contact` SET `writable` = %d WHERE `id` = %d LIMIT 1",
86 intval($importer['id'])
88 $importer['writable'] = $writable;
91 logger('dfrn_notify: received notify from ' . $importer['name'] . ' for ' . $importer['username']);
92 logger('dfrn_notify: data: ' . $data, LOGGER_DATA);
97 * Relationship is dissolved permanently
100 require_once('include/Contact.php');
101 contact_remove($importer['id']);
102 logger('relationship dissolved : ' . $importer['name'] . ' dissolved ' . $importer['username']);
108 $rawkey = hex2bin(trim($key));
109 logger('rino: md5 raw key: ' . md5($rawkey));
112 if($dfrn_version >= 2.1) {
113 if((($importer['duplex']) && strlen($importer['cprvkey'])) || (! strlen($importer['cpubkey']))) {
114 openssl_private_decrypt($rawkey,$final_key,$importer['cprvkey']);
117 openssl_public_decrypt($rawkey,$final_key,$importer['cpubkey']);
121 if((($importer['duplex']) && strlen($importer['cpubkey'])) || (! strlen($importer['cprvkey']))) {
122 openssl_public_decrypt($rawkey,$final_key,$importer['cpubkey']);
125 openssl_private_decrypt($rawkey,$final_key,$importer['cprvkey']);
129 logger('rino: received key : ' . $final_key);
130 $data = aes_decrypt(hex2bin($data),$final_key);
131 logger('rino: decrypted data: ' . $data, LOGGER_DATA);
135 if($importer['readonly']) {
136 // We aren't receiving stuff from this person. But we will quietly ignore them
137 // rather than a blatant "go away" message.
138 logger('dfrn_notify: ignoring');
143 // Consume notification feed. This may differ from consuming a public feed in several ways
144 // - might contain email
145 // - might contain remote followup to our message
146 // - in which case we need to accept it and then notify other conversants
147 // - we may need to send various email notifications
149 $feed = new SimplePie();
150 $feed->set_raw_data($data);
151 $feed->enable_order_by_date(false);
156 $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
157 if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
159 logger('dfrn_notify: private message received');
162 $base = $rawmail[0]['child'][NAMESPACE_DFRN];
165 $msg['uid'] = $importer['importer_uid'];
166 $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
167 $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
168 $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
169 $msg['contact-id'] = $importer['id'];
170 $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
171 $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
174 $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
175 $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
176 $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
180 $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg))
181 . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
183 // send email notification if requested.
185 require_once('bbcode.php');
186 if($importer['notify-flags'] & NOTIFY_MAIL) {
188 // name of the automated email sender
189 $msg['notificationfromname'] = t('Administrator');
190 // noreply address to send from
191 $msg['notificationfromemail'] = t('noreply') . '@' . $a->get_hostname();
194 // process the message body to display properly in text mode
195 // 1) substitute a \n character for the "\" then "n", so it behaves properly (it doesn't come in as a \n character)
196 // 2) remove escape slashes
197 // 3) decode any bbcode from the message editor
198 // 4) decode any encoded html tags
199 // 5) remove html tags
201 = strip_tags(html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n"), "\n",$msg['body']))),ENT_QUOTES,'UTF-8'));
204 // process the message body to display properly in text mode
205 // 1) substitute a <br /> tag for the "\" then "n", so it behaves properly (it doesn't come in as a \n character)
206 // 2) remove escape slashes
207 // 3) decode any bbcode from the message editor
208 // 4) decode any encoded html tags
210 = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r","\\n\\n" ,"\\n"), "<br />\n",$msg['body']))));
212 // load the template for private message notifications
213 $tpl = load_view_file('view/mail_received_html_body_eml.tpl');
214 $email_html_body_tpl = replace_macros($tpl,array(
215 '$siteName' => $a->config['sitename'], // name of this site
216 '$siteurl' => $a->get_baseurl(), // descriptive url of this site
217 '$thumb' => $importer['thumb'], // thumbnail url for sender icon
218 '$email' => $importer['email'], // email address to send to
219 '$url' => $importer['url'], // full url for the site
220 '$from' => $msg['from-name'], // name of the person sending the message
221 '$title' => stripslashes($msg['title']), // subject of the message
222 '$htmlversion' => $msg['htmlversion'], // html version of the message
223 '$mimeboundary' => $msg['mimeboundary'], // mime message divider
224 '$hostname' => $a->get_hostname() // name of this host
227 // load the template for private message notifications
228 $tpl = load_view_file('view/mail_received_text_body_eml.tpl');
229 $email_text_body_tpl = replace_macros($tpl,array(
230 '$siteName' => $a->config['sitename'], // name of this site
231 '$siteurl' => $a->get_baseurl(), // descriptive url of this site
232 '$thumb' => $importer['thumb'], // thumbnail url for sender icon
233 '$email' => $importer['email'], // email address to send to
234 '$url' => $importer['url'], // full url for the site
235 '$from' => $msg['from-name'], // name of the person sending the message
236 '$title' => stripslashes($msg['title']), // subject of the message
237 '$textversion' => $msg['textversion'], // text version of the message
238 '$mimeboundary' => $msg['mimeboundary'], // mime message divider
239 '$hostname' => $a->get_hostname() // name of this host
242 // use the EmailNotification library to send the message
243 require_once("include/EmailNotification.php");
244 EmailNotification::sendTextHtmlEmail(
245 $msg['notificationfromname'],
246 $msg['notificationfromemail'],
247 $msg['notificationfromemail'],
249 t('New mail received at ') . $a->config['sitename'],
250 $email_html_body_tpl,
258 logger('dfrn_notify: feed item count = ' . $feed->get_item_quantity());
260 // process any deleted entries
262 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
263 if(is_array($del_entries) && count($del_entries)) {
264 foreach($del_entries as $dentry) {
266 if(isset($dentry['attribs']['']['ref'])) {
267 $uri = $dentry['attribs']['']['ref'];
269 if(isset($dentry['attribs']['']['when'])) {
270 $when = $dentry['attribs']['']['when'];
271 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
274 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
278 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `contact-id` = %d LIMIT 1",
280 intval($importer['importer_uid']),
281 intval($importer['id'])
287 if(! $item['deleted'])
288 logger('dfrn_notify: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
290 if($item['uri'] == $item['parent-uri']) {
291 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
292 WHERE `parent-uri` = '%s' AND `uid` = %d",
294 dbesc(datetime_convert()),
296 intval($importer['importer_uid'])
300 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
301 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
303 dbesc(datetime_convert()),
305 intval($importer['importer_uid'])
307 if($item['last-child']) {
308 // ensure that last-child is set in case the comment that had it just got wiped.
309 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
310 dbesc(datetime_convert()),
311 dbesc($item['parent-uri']),
314 // who is the last child now?
315 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
316 ORDER BY `created` DESC LIMIT 1",
317 dbesc($item['parent-uri']),
318 intval($importer['importer_uid'])
321 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
333 foreach($feed->get_items() as $item) {
336 $item_id = $item->get_id();
337 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
338 if(isset($rawthread[0]['attribs']['']['ref'])) {
340 $parent_uri = $rawthread[0]['attribs']['']['ref'];
344 if($feed->get_item_quantity() == 1) {
345 logger('dfrn_notify: received remote comment');
347 // remote reply to our post. Import and then notify everybody else.
348 $datarray = get_atom_elements($feed,$item);
349 $datarray['type'] = 'remote-comment';
350 $datarray['wall'] = 1;
351 $datarray['parent-uri'] = $parent_uri;
352 $datarray['uid'] = $importer['importer_uid'];
353 $datarray['contact-id'] = $importer['id'];
354 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
356 $datarray['type'] = 'activity';
357 $datarray['gravity'] = GRAVITY_LIKE;
358 $datarray['last-child'] = 0;
360 $posted_id = item_store($datarray);
364 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
366 intval($importer['importer_uid'])
369 $parent = $r[0]['parent'];
372 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
373 dbesc(datetime_convert()),
374 intval($importer['importer_uid']),
375 intval($r[0]['parent'])
378 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
379 dbesc(datetime_convert()),
380 intval($importer['importer_uid']),
385 if($posted_id && $parent) {
387 proc_run('php',"include/notifier.php","comment-import","$posted_id");
389 if((! $is_like) && ($importer['notify-flags'] & NOTIFY_COMMENT) && (! $importer['self'])) {
390 require_once('bbcode.php');
391 $from = stripslashes($datarray['author-name']);
392 $tpl = load_view_file('view/cmnt_received_eml.tpl');
393 $email_tpl = replace_macros($tpl, array(
394 '$sitename' => $a->config['sitename'],
395 '$siteurl' => $a->get_baseurl(),
396 '$username' => $importer['username'],
397 '$email' => $importer['email'],
398 '$display' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
400 '$body' => html_entity_decode(strip_tags(bbcode(stripslashes($datarray['body']))), ENT_QUOTES, 'UTF-8')
403 $res = mail($importer['email'], sprintf(t('%s commented on an item at %s'), $from , $a->config['sitename']),
405 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
406 . 'Content-type: text/plain; charset=UTF-8' . "\n"
407 . 'Content-transfer-encoding: 8bit' );
417 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
419 $item_id = $item->get_id();
420 $datarray = get_atom_elements($feed,$item);
422 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
424 intval($importer['importer_uid'])
427 // Update content if 'updated' changes
430 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
431 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
432 dbesc($datarray['body']),
433 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
435 intval($importer['importer_uid'])
439 // update last-child if it changes
441 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
442 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
443 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
444 dbesc(datetime_convert()),
446 intval($importer['importer_uid'])
448 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
449 intval($allow[0]['data']),
450 dbesc(datetime_convert()),
452 intval($importer['importer_uid'])
458 $datarray['parent-uri'] = $parent_uri;
459 $datarray['uid'] = $importer['importer_uid'];
460 $datarray['contact-id'] = $importer['id'];
461 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
462 $datarray['type'] = 'activity';
463 $datarray['gravity'] = GRAVITY_LIKE;
465 $r = item_store($datarray);
467 // find out if our user is involved in this conversation and wants to be notified.
469 if(($datarray['type'] != 'activity') && ($importer['notify-flags'] & NOTIFY_COMMENT)) {
471 $myconv = q("SELECT `author-link` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 ",
473 intval($importer['importer_uid'])
476 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
477 foreach($myconv as $conv) {
478 if(! link_compare($conv['author-link'],$importer_url))
480 require_once('bbcode.php');
481 $from = stripslashes($datarray['author-name']);
482 $tpl = load_view_file('view/cmnt_received_eml.tpl');
483 $email_tpl = replace_macros($tpl, array(
484 '$sitename' => $a->config['sitename'],
485 '$siteurl' => $a->get_baseurl(),
486 '$username' => $importer['username'],
487 '$email' => $importer['email'],
489 '$display' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $r,
490 '$body' => html_entity_decode(strip_tags(bbcode(stripslashes($datarray['body']))), ENT_QUOTES, 'UTF-8')
493 $res = mail($importer['email'], sprintf( t("%s commented on an item at %s") , $from ,$a->config['sitename']),
495 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
496 . 'Content-type: text/plain; charset=UTF-8' . "\n"
497 . 'Content-transfer-encoding: 8bit' );
509 // Head post of a conversation. Have we seen it? If not, import it.
512 $item_id = $item->get_id();
513 $datarray = get_atom_elements($feed,$item);
515 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
517 intval($importer['importer_uid'])
520 // Update content if 'updated' changes
523 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
524 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
525 dbesc($datarray['body']),
526 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
528 intval($importer['importer_uid'])
532 // update last-child if it changes
534 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
535 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
536 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
537 intval($allow[0]['data']),
538 dbesc(datetime_convert()),
540 intval($importer['importer_uid'])
546 $datarray['parent-uri'] = $item_id;
547 $datarray['uid'] = $importer['importer_uid'];
548 $datarray['contact-id'] = $importer['id'];
549 $r = item_store($datarray);
560 function dfrn_notify_content(&$a) {
562 if(x($_GET,'dfrn_id')) {
564 // initial communication from external contact, $direction is their direction.
565 // If this is a duplex communication, ours will be the opposite.
567 $dfrn_id = notags(trim($_GET['dfrn_id']));
568 $dfrn_version = (float) $_GET['dfrn_version'];
570 logger('dfrn_notify: new notification dfrn_id=' . $dfrn_id);
573 if(strpos($dfrn_id,':') == 1) {
574 $direction = intval(substr($dfrn_id,0,1));
575 $dfrn_id = substr($dfrn_id,2);
578 $hash = random_string();
582 $r = q("DELETE FROM `challenge` WHERE `expire` < " . intval(time()));
584 $r = q("INSERT INTO `challenge` ( `challenge`, `dfrn-id`, `expire` )
585 VALUES( '%s', '%s', %d ) ",
591 logger('dfrn_notify: challenge=' . $hash );
596 $sql_extra = sprintf(" AND ( `issued-id` = '%s' OR `dfrn-id` = '%s' ) ", dbesc($dfrn_id), dbesc($dfrn_id));
600 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
601 $my_id = '1:' . $dfrn_id;
604 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
605 $my_id = '0:' . $dfrn_id;
612 $r = q("SELECT `contact`.*, `user`.`nickname` FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
613 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0 AND `user`.`nickname` = '%s' $sql_extra LIMIT 1",
622 $id_str = $my_id . '.' . mt_rand(1000,9999);
624 if((($r[0]['duplex']) && strlen($r[0]['prvkey'])) || (! strlen($r[0]['pubkey']))) {
625 openssl_private_encrypt($hash,$challenge,$r[0]['prvkey']);
626 openssl_private_encrypt($id_str,$encrypted_id,$r[0]['prvkey']);
629 openssl_public_encrypt($hash,$challenge,$r[0]['pubkey']);
630 openssl_public_encrypt($id_str,$encrypted_id,$r[0]['pubkey']);
633 $challenge = bin2hex($challenge);
634 $encrypted_id = bin2hex($encrypted_id);
636 $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
638 $rino_enable = get_config('system','rino_encrypt');
644 header("Content-type: text/xml");
646 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n"
647 . '<dfrn_notify>' . "\r\n"
648 . "\t" . '<status>' . $status . '</status>' . "\r\n"
649 . "\t" . '<dfrn_version>' . DFRN_PROTOCOL_VERSION . '</dfrn_version>' . "\r\n"
650 . "\t" . '<rino>' . $rino . '</rino>' . "\r\n"
651 . "\t" . '<dfrn_id>' . $encrypted_id . '</dfrn_id>' . "\r\n"
652 . "\t" . '<challenge>' . $challenge . '</challenge>' . "\r\n"
653 . '</dfrn_notify>' . "\r\n" ;