]> git.mxchange.org Git - friendica.git/blob - mod/dfrn_notify.php
bug #96 move libraries to library - better alignment of like rotator
[friendica.git] / mod / dfrn_notify.php
1 <?php
2
3 require_once('library/simplepie/simplepie.inc');
4 require_once('include/items.php');
5 require_once('include/event.php');
6
7
8 function dfrn_notify_post(&$a) {
9
10         $dfrn_id      = ((x($_POST,'dfrn_id'))      ? notags(trim($_POST['dfrn_id']))   : '');
11         $dfrn_version = ((x($_POST,'dfrn_version')) ? (float) $_POST['dfrn_version']    : 2.0);
12         $challenge    = ((x($_POST,'challenge'))    ? notags(trim($_POST['challenge'])) : '');
13         $data         = ((x($_POST,'data'))         ? $_POST['data']                    : '');
14         $key          = ((x($_POST,'key'))          ? $_POST['key']                     : '');
15         $dissolve     = ((x($_POST,'dissolve'))     ? intval($_POST['dissolve'])        :  0);
16         $perm         = ((x($_POST,'perm'))         ? notags(trim($_POST['perm']))      : 'r');
17
18         $writable = (-1);
19         if($dfrn_version >= 2.21) {
20                 $writable = (($perm === 'rw') ? 1 : 0);
21         }
22
23         $direction = (-1);
24         if(strpos($dfrn_id,':') == 1) {
25                 $direction = intval(substr($dfrn_id,0,1));
26                 $dfrn_id = substr($dfrn_id,2);
27         }
28
29         $r = q("SELECT * FROM `challenge` WHERE `dfrn-id` = '%s' AND `challenge` = '%s' LIMIT 1",
30                 dbesc($dfrn_id),
31                 dbesc($challenge)
32         );
33         if(! count($r)) {
34                 logger('dfrn_notify: could not match challenge to dfrn_id ' . $dfrn_id . ' challenge=' . $challenge);
35                 xml_status(3);
36         }
37
38         $r = q("DELETE FROM `challenge` WHERE `dfrn-id` = '%s' AND `challenge` = '%s' LIMIT 1",
39                 dbesc($dfrn_id),
40                 dbesc($challenge)
41         );
42
43         // find the local user who owns this relationship.
44
45         $sql_extra = '';
46         switch($direction) {
47                 case (-1):
48                         $sql_extra = sprintf(" AND ( `issued-id` = '%s' OR `dfrn-id` = '%s' ) ", dbesc($dfrn_id), dbesc($dfrn_id));
49                         break;
50                 case 0:
51                         $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
52                         break;
53                 case 1:
54                         $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
55                         break;
56                 default:
57                         xml_status(3);
58                         break; // NOTREACHED
59         }
60                  
61
62         $r = q("SELECT  `contact`.*, `contact`.`uid` AS `importer_uid`, 
63                                         `contact`.`pubkey` AS `cpubkey`, 
64                                         `contact`.`prvkey` AS `cprvkey`, 
65                                         `contact`.`thumb` AS `thumb`, 
66                                         `contact`.`url` as `url`,
67                                         `contact`.`name` as `senderName`,
68                                         `user`.* 
69                         FROM `contact` 
70                         LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid` 
71                         WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0 
72                                 AND `user`.`nickname` = '%s' $sql_extra LIMIT 1",
73                 dbesc($a->argv[1])
74         );
75
76         if(! count($r)) {
77                 logger('dfrn_notify: contact not found for dfrn_id ' . $dfrn_id);
78                 xml_status(3);
79                 //NOTREACHED
80         }
81
82         // $importer in this case contains the contact record for the remote contact joined with the user record of our user. 
83
84         $importer = $r[0];
85
86         if(($writable != (-1)) && ($writable != $importer['writable'])) {
87                 q("UPDATE `contact` SET `writable` = %d WHERE `id` = %d LIMIT 1",
88                         intval($writable),
89                         intval($importer['id'])
90                 );
91                 $importer['writable'] = $writable;
92         }
93
94         logger('dfrn_notify: received notify from ' . $importer['name'] . ' for ' . $importer['username']);
95         logger('dfrn_notify: data: ' . $data, LOGGER_DATA);
96
97         if($dissolve == 1) {
98
99                 /**
100                  * Relationship is dissolved permanently
101                  */
102
103                 require_once('include/Contact.php'); 
104                 contact_remove($importer['id']);
105                 logger('relationship dissolved : ' . $importer['name'] . ' dissolved ' . $importer['username']);
106                 xml_status(0);
107
108         }
109
110         if(strlen($key)) {
111                 $rawkey = hex2bin(trim($key));
112                 logger('rino: md5 raw key: ' . md5($rawkey));
113                 $final_key = '';
114
115                 if($dfrn_version >= 2.1) {
116                         if((($importer['duplex']) && strlen($importer['cprvkey'])) || (! strlen($importer['cpubkey']))) {
117                                 openssl_private_decrypt($rawkey,$final_key,$importer['cprvkey']);
118                         }
119                         else {
120                                 openssl_public_decrypt($rawkey,$final_key,$importer['cpubkey']);
121                         }
122                 }
123                 else {
124                         if((($importer['duplex']) && strlen($importer['cpubkey'])) || (! strlen($importer['cprvkey']))) {
125                                 openssl_public_decrypt($rawkey,$final_key,$importer['cpubkey']);
126                         }
127                         else {
128                                 openssl_private_decrypt($rawkey,$final_key,$importer['cprvkey']);
129                         }
130                 }
131
132                 logger('rino: received key : ' . $final_key);
133                 $data = aes_decrypt(hex2bin($data),$final_key);
134                 logger('rino: decrypted data: ' . $data, LOGGER_DATA);
135         }
136
137
138         if($importer['readonly']) {
139                 // We aren't receiving stuff from this person. But we will quietly ignore them
140                 // rather than a blatant "go away" message.
141                 logger('dfrn_notify: ignoring');
142                 xml_status(0);
143                 //NOTREACHED
144         }
145
146         // Consume notification feed. This may differ from consuming a public feed in several ways
147         // - might contain email or friend suggestions
148         // - might contain remote followup to our message
149         //              - in which case we need to accept it and then notify other conversants
150         // - we may need to send various email notifications
151
152         $feed = new SimplePie();
153         $feed->set_raw_data($data);
154         $feed->enable_order_by_date(false);
155         $feed->init();
156
157         // handle friend suggestion notification
158
159         $sugg = $feed->get_feed_tags( NAMESPACE_DFRN, 'suggest' );
160         if(isset($sugg[0]['child'][NAMESPACE_DFRN])) {
161                 $base = $sugg[0]['child'][NAMESPACE_DFRN];
162                 $fsugg = array();
163                 $fsugg['uid'] = $importer['importer_uid'];
164                 $fsugg['cid'] = $importer['id'];
165                 $fsugg['name'] = notags(unxmlify($base['name'][0]['data']));
166                 $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data']));
167                 $fsugg['url'] = notags(unxmlify($base['url'][0]['data']));
168                 $fsugg['request'] = notags(unxmlify($base['request'][0]['data']));
169                 $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data']));
170
171                 // Does our member already have a friend matching this description?
172
173                 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `url` = '%s' AND `uid` = %d LIMIT 1",
174                         dbesc($fsugg['name']),
175                         dbesc($fsugg['url']),
176                         intval($fsugg['uid'])
177                 );
178                 if(count($r))
179                         xml_status(0);
180
181                 // Do we already have an fcontact record for this person?
182
183                 $fid = 0;
184                 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
185                         dbesc($fsugg['url']),
186                         dbesc($fsugg['name']),
187                         dbesc($fsugg['request'])
188                 );
189                 if(count($r)) {
190                         $fid = $r[0]['id'];
191                 }
192                 if(! $fid)
193                         $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ",
194                         dbesc($fsugg['name']),
195                         dbesc($fsugg['url']),
196                         dbesc($fsugg['photo']),
197                         dbesc($fsugg['request'])
198                 );
199                 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
200                         dbesc($fsugg['url']),
201                         dbesc($fsugg['name']),
202                         dbesc($fsugg['request'])
203                 );
204                 if(count($r)) {
205                         $fid = $r[0]['id'];
206                 }
207                 // database record did not get created. Quietly give up.
208                 else
209                         xml_status(0);
210
211                 $hash = random_string();
212  
213                 $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )
214                         VALUES( %d, %d, %d, '%s', '%s', '%s', %d )",
215                         intval($fsugg['uid']),
216                         intval($fid),
217                         intval($fsugg['cid']),
218                         dbesc($fsugg['body']),
219                         dbesc($hash),
220                         dbesc(datetime_convert()),
221                         intval(0)
222                 );
223
224                 // TODO - send email notify (which may require a new notification preference)
225
226                 xml_status(0);
227         }
228
229         $ismail = false;
230
231         $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
232         if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
233
234                 logger('dfrn_notify: private message received');
235
236                 $ismail = true;
237                 $base = $rawmail[0]['child'][NAMESPACE_DFRN];
238
239                 $msg = array();
240                 $msg['uid'] = $importer['importer_uid'];
241                 $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
242                 $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
243                 $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
244                 $msg['contact-id'] = $importer['id'];
245                 $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
246                 $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
247                 $msg['seen'] = 0;
248                 $msg['replied'] = 0;
249                 $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
250                 $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
251                 $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
252                 
253                 dbesc_array($msg);
254
255                 $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg)) 
256                         . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
257
258                 // send email notification if requested.
259
260                 require_once('bbcode.php');
261                 if($importer['notify-flags'] & NOTIFY_MAIL) {
262
263                         push_lang($importer['language']);
264
265                         // name of the automated email sender
266                         $msg['notificationfromname']    = t('Administrator');
267                         // noreply address to send from
268                         $msg['notificationfromemail']   = t('noreply') . '@' . $a->get_hostname();                              
269
270                         // text version
271                         // process the message body to display properly in text mode
272                         //              1) substitute a \n character for the "\" then "n", so it behaves properly (it doesn't come in as a \n character)
273                         //              2) remove escape slashes
274                         //              3) decode any bbcode from the message editor
275                         //              4) decode any encoded html tags
276                         //              5) remove html tags
277                         $msg['textversion']
278                                 = strip_tags(html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n"), "\n",$msg['body']))),ENT_QUOTES,'UTF-8'));
279                                 
280                         // html version
281                         // process the message body to display properly in text mode
282                         //              1) substitute a <br /> tag for the "\" then "n", so it behaves properly (it doesn't come in as a \n character)
283                         //              2) remove escape slashes
284                         //              3) decode any bbcode from the message editor
285                         //              4) decode any encoded html tags
286                         $msg['htmlversion']     
287                                 = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r","\\n\\n" ,"\\n"), "<br />\n",$msg['body']))));
288
289                         // load the template for private message notifications
290                         $tpl = get_intltext_template('mail_received_html_body_eml.tpl');
291                         $email_html_body_tpl = replace_macros($tpl,array(
292                                 '$username'     => $importer['username'],
293                                 '$siteName'             => $a->config['sitename'],                      // name of this site
294                                 '$siteurl'              => $a->get_baseurl(),                           // descriptive url of this site
295                                 '$thumb'                => $importer['thumb'],                          // thumbnail url for sender icon
296                                 '$email'                => $importer['email'],                          // email address to send to
297                                 '$url'                  => $importer['url'],                            // full url for the site
298                                 '$from'                 => $msg['from-name'],                           // name of the person sending the message
299                                 '$title'                => stripslashes($msg['title']),                 // subject of the message
300                                 '$htmlversion'  => $msg['htmlversion'],                                 // html version of the message
301                                 '$mimeboundary' => $msg['mimeboundary'],                                // mime message divider
302                                 '$hostname'             => $a->get_hostname()                           // name of this host
303                         ));
304                         
305                         // load the template for private message notifications
306                         $tpl = get_intltext_template('mail_received_text_body_eml.tpl');
307                         $email_text_body_tpl = replace_macros($tpl,array(
308                                 '$username'     => $importer['username'],
309                                 '$siteName'             => $a->config['sitename'],                      // name of this site
310                                 '$siteurl'              => $a->get_baseurl(),                           // descriptive url of this site
311                                 '$thumb'                => $importer['thumb'],                          // thumbnail url for sender icon
312                                 '$email'                => $importer['email'],                          // email address to send to
313                                 '$url'                  => $importer['url'],                            // full url for the site
314                                 '$from'                 => $msg['from-name'],                           // name of the person sending the message
315                                 '$title'                => stripslashes($msg['title']),                 // subject of the message
316                                 '$textversion'  => $msg['textversion'],                                 // text version of the message
317                                 '$mimeboundary' => $msg['mimeboundary'],                                // mime message divider
318                                 '$hostname'             => $a->get_hostname()                           // name of this host
319                         ));
320
321                         // use the EmailNotification library to send the message
322                         require_once("include/EmailNotification.php");
323                         EmailNotification::sendTextHtmlEmail(
324                                 $msg['notificationfromname'],
325                                 $msg['notificationfromemail'],
326                                 $msg['notificationfromemail'],
327                                 $importer['email'],
328                                 t('New mail received at ') . $a->config['sitename'],
329                                 $email_html_body_tpl,
330                                 $email_text_body_tpl
331                         );
332
333                         pop_lang();
334                 }
335                 xml_status(0);
336                 // NOTREACHED
337         }       
338         
339         logger('dfrn_notify: feed item count = ' . $feed->get_item_quantity());
340
341         // process any deleted entries
342
343         $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
344         if(is_array($del_entries) && count($del_entries)) {
345                 foreach($del_entries as $dentry) {
346                         $deleted = false;
347                         if(isset($dentry['attribs']['']['ref'])) {
348                                 $uri = $dentry['attribs']['']['ref'];
349                                 $deleted = true;
350                                 if(isset($dentry['attribs']['']['when'])) {
351                                         $when = $dentry['attribs']['']['when'];
352                                         $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
353                                 }
354                                 else
355                                         $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
356                         }
357                         if($deleted) {
358
359                                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `contact-id` = %d LIMIT 1",
360                                         dbesc($uri),
361                                         intval($importer['importer_uid']),
362                                         intval($importer['id'])
363                                 );
364
365                                 if(count($r)) {
366                                         $item = $r[0];
367
368                                         if(! $item['deleted'])
369                                                 logger('dfrn_notify: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
370
371                                         if($item['uri'] == $item['parent-uri']) {
372                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
373                                                         WHERE `parent-uri` = '%s' AND `uid` = %d",
374                                                         dbesc($when),
375                                                         dbesc(datetime_convert()),
376                                                         dbesc($item['uri']),
377                                                         intval($importer['importer_uid'])
378                                                 );
379                                         }
380                                         else {
381                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' 
382                                                         WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
383                                                         dbesc($when),
384                                                         dbesc(datetime_convert()),
385                                                         dbesc($uri),
386                                                         intval($importer['importer_uid'])
387                                                 );
388                                                 if($item['last-child']) {
389                                                         // ensure that last-child is set in case the comment that had it just got wiped.
390                                                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
391                                                                 dbesc(datetime_convert()),
392                                                                 dbesc($item['parent-uri']),
393                                                                 intval($item['uid'])
394                                                         );
395                                                         // who is the last child now? 
396                                                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
397                                                                 ORDER BY `created` DESC LIMIT 1",
398                                                                         dbesc($item['parent-uri']),
399                                                                         intval($importer['importer_uid'])
400                                                         );
401                                                         if(count($r)) {
402                                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
403                                                                         intval($r[0]['id'])
404                                                                 );
405                                                         }       
406                                                 }
407                                         }       
408                                 }
409                         }
410                 }
411         }
412
413
414         foreach($feed->get_items() as $item) {
415
416                 $is_reply = false;              
417                 $item_id = $item->get_id();
418                 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
419                 if(isset($rawthread[0]['attribs']['']['ref'])) {
420                         $is_reply = true;
421                         $parent_uri = $rawthread[0]['attribs']['']['ref'];
422                 }
423
424                 if($is_reply) {
425                         if($feed->get_item_quantity() == 1) {
426                                 logger('dfrn_notify: received remote comment');
427                                 $is_like = false;
428                                 // remote reply to our post. Import and then notify everybody else.
429                                 $datarray = get_atom_elements($feed,$item);
430                                 $datarray['type'] = 'remote-comment';
431                                 $datarray['wall'] = 1;
432                                 $datarray['parent-uri'] = $parent_uri;
433                                 $datarray['uid'] = $importer['importer_uid'];
434                                 $datarray['contact-id'] = $importer['id'];
435                                 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
436                                         $is_like = true;
437                                         $datarray['type'] = 'activity';
438                                         $datarray['gravity'] = GRAVITY_LIKE;
439                                         $datarray['last-child'] = 0;
440                                 }
441                                 $posted_id = item_store($datarray);
442                                 $parent = 0;
443
444                                 if($posted_id) {
445                                         $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
446                                                 intval($posted_id),
447                                                 intval($importer['importer_uid'])
448                                         );
449                                         if(count($r))
450                                                 $parent = $r[0]['parent'];
451                         
452                                         if(! $is_like) {
453                                                 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
454                                                         dbesc(datetime_convert()),
455                                                         intval($importer['importer_uid']),
456                                                         intval($r[0]['parent'])
457                                                 );
458
459                                                 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
460                                                         dbesc(datetime_convert()),
461                                                         intval($importer['importer_uid']),
462                                                         intval($posted_id)
463                                                 );
464                                         }
465
466                                         if($posted_id && $parent) {
467                                 
468                                                 proc_run('php',"include/notifier.php","comment-import","$posted_id");
469                                         
470                                                 if((! $is_like) && ($importer['notify-flags'] & NOTIFY_COMMENT) && (! $importer['self'])) {
471                                                         push_lang($importer['language']);
472                                                         require_once('bbcode.php');
473                                                         $from = stripslashes($datarray['author-name']);
474
475                                                         // name of the automated email sender
476                                                         $msg['notificationfromname']    = stripslashes($datarray['author-name']);;
477                                                         // noreply address to send from
478                                                         $msg['notificationfromemail']   = t('noreply') . '@' . $a->get_hostname();                              
479
480                                                         // text version
481                                                         // process the message body to display properly in text mode
482                                                         $msg['textversion']
483                                                                 = html_entity_decode(strip_tags(bbcode(stripslashes($datarray['body']))), ENT_QUOTES, 'UTF-8');
484                                 
485                                                         // html version
486                                                         // process the message body to display properly in text mode
487                                                         $msg['htmlversion']     
488                                                                 = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r","\\n\\n" ,"\\n"), "<br />\n",$datarray['body']))));
489
490                                                         // load the template for private message notifications
491                                                         $tpl = get_intltext_template('cmnt_received_html_body_eml.tpl');
492                                                         $email_html_body_tpl = replace_macros($tpl,array(
493                                                                 '$username'     => $importer['username'],
494                                                                 '$sitename'             => $a->config['sitename'],                      // name of this site
495                                                                 '$siteurl'              => $a->get_baseurl(),                           // descriptive url of this site
496                                                                 '$thumb'                => $datarray['author-avatar'],                  // thumbnail url for sender icon
497                                                                 '$email'                => $importer['email'],                          // email address to send to
498                                                                 '$url'                  => $datarray['author-link'],                    // full url for the site
499                                                                 '$from'                 => $from,                                       // name of the person sending the message
500                                                                 '$body'                 => $msg['htmlversion'],                 // html version of the message
501                                                                 '$display'              => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
502                                                         ));
503                         
504                                                         // load the template for private message notifications
505                                                         $tpl = get_intltext_template('cmnt_received_text_body_eml.tpl');
506                                                         $email_text_body_tpl = replace_macros($tpl,array(
507                                                                 '$username'     => $importer['username'],
508                                                                 '$sitename'             => $a->config['sitename'],                      // name of this site
509                                                                 '$siteurl'              => $a->get_baseurl(),                           // descriptive url of this site
510                                                                 '$thumb'                => $datarray['author-avatar'],                  // thumbnail url for sender icon
511                                                                 '$email'                => $importer['email'],                          // email address to send to
512                                                                 '$url'                  => $datarray['author-link'],                    // full url for the site
513                                                                 '$from'                 => $from,                                       // name of the person sending the message
514                                                                 '$body'                 => $msg['textversion'],                         // text version of the message
515                                                                 '$display'              => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
516                                                         ));
517
518                                                         // use the EmailNotification library to send the message
519                                                         require_once("include/EmailNotification.php");
520                                                         EmailNotification::sendTextHtmlEmail(
521                                                                 $msg['notificationfromname'],
522                                                                 t("Administrator") . '@' . $a->get_hostname(),
523                                                                 t("noreply") . '@' . $a->get_hostname(),
524                                                                 $importer['email'],
525                                                                 sprintf( t('%s commented on an item at %s'), $from , $a->config['sitename']),
526                                                                 $email_html_body_tpl,
527                                                                 $email_text_body_tpl
528                                                         );
529                                                         pop_lang();
530                                                 }
531                                         }
532                                         xml_status(0);
533                                         // NOTREACHED
534                                 }
535                         }
536                         else {
537
538                                 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
539
540                                 $item_id  = $item->get_id();
541                                 $datarray = get_atom_elements($feed,$item);
542
543                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
544                                         dbesc($item_id),
545                                         intval($importer['importer_uid'])
546                                 );
547
548                                 // Update content if 'updated' changes
549
550                                 if(count($r)) {
551                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
552                                                 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
553                                                         dbesc($datarray['body']),
554                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
555                                                         dbesc($item_id),
556                                                         intval($importer['importer_uid'])
557                                                 );
558                                         }
559
560                                         // update last-child if it changes
561
562                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
563                                         if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
564                                                 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
565                                                         dbesc(datetime_convert()),
566                                                         dbesc($parent_uri),
567                                                         intval($importer['importer_uid'])
568                                                 );
569                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s'  WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
570                                                         intval($allow[0]['data']),
571                                                         dbesc(datetime_convert()),
572                                                         dbesc($item_id),
573                                                         intval($importer['importer_uid'])
574                                                 );
575                                         }
576                                         continue;
577                                 }
578
579                                 $datarray['parent-uri'] = $parent_uri;
580                                 $datarray['uid'] = $importer['importer_uid'];
581                                 $datarray['contact-id'] = $importer['id'];
582                                 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
583                                         $datarray['type'] = 'activity';
584                                         $datarray['gravity'] = GRAVITY_LIKE;
585                                 }
586                                 $posted_id = item_store($datarray);
587
588                                 // find out if our user is involved in this conversation and wants to be notified.
589                         
590                                 if(($datarray['type'] != 'activity') && ($importer['notify-flags'] & NOTIFY_COMMENT)) {
591
592                                         $myconv = q("SELECT `author-link`, `author-avatar` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 ",
593                                                 dbesc($parent_uri),
594                                                 intval($importer['importer_uid'])
595                                         );
596                                         if(count($myconv)) {
597                                                 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
598                                                 foreach($myconv as $conv) {
599                                                         if(! link_compare($conv['author-link'],$importer_url))
600                                                                 continue;
601
602                                                         push_lang($importer['language']);
603                                                         require_once('bbcode.php');
604                                                         $from = stripslashes($datarray['author-name']);
605                                                         
606                                                         // name of the automated email sender
607                                                         $msg['notificationfromname']    = stripslashes($datarray['author-name']);;
608                                                         // noreply address to send from
609                                                         $msg['notificationfromemail']   = t('noreply') . '@' . $a->get_hostname();                              
610
611                                                         // text version
612                                                         // process the message body to display properly in text mode
613                                                         $msg['textversion']
614                                                                 = html_entity_decode(strip_tags(bbcode(stripslashes($datarray['body']))), ENT_QUOTES, 'UTF-8');
615                                 
616                                                         // html version
617                                                         // process the message body to display properly in text mode
618                                                         $msg['htmlversion']     
619                                                                 = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r","\\n\\n" ,"\\n"), "<br />\n",$datarray['body']))));
620
621                                                         // load the template for private message notifications
622                                                         $tpl = get_intltext_template('cmnt_received_html_body_eml.tpl');
623                                                         $email_html_body_tpl = replace_macros($tpl,array(
624                                                                 '$username'     => $importer['username'],
625                                                                 '$sitename'             => $a->config['sitename'],                              // name of this site
626                                                                 '$siteurl'              => $a->get_baseurl(),                                   // descriptive url of this site
627                                                                 '$thumb'                => $datarray['author-avatar'],                          // thumbnail url for sender icon
628                                                                 '$url'                  => $datarray['author-link'],                            // full url for the site
629                                                                 '$from'                 => $from,                                               // name of the person sending the message
630                                                                 '$body'                 => $msg['htmlversion'],                                 // html version of the message
631                                                                 '$display'              => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
632                                                         ));
633                         
634                                                         // load the template for private message notifications
635                                                         $tpl = get_intltext_template('cmnt_received_text_body_eml.tpl');
636                                                         $email_text_body_tpl = replace_macros($tpl,array(
637                                                                 '$username'     => $importer['username'],
638                                                                 '$sitename'             => $a->config['sitename'],                              // name of this site
639                                                                 '$siteurl'              => $a->get_baseurl(),                                   // descriptive url of this site
640                                                                 '$thumb'                => $datarray['author-avatar'],                          // thumbnail url for sender icon
641                                                                 '$url'                  => $datarray['author-link'],                            // full url for the site
642                                                                 '$from'                 => $from,                                               // name of the person sending the message
643                                                                 '$body'                 => $msg['textversion'],                                 // text version of the message
644                                                                 '$display'              => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
645                                                         ));
646
647                                                         // use the EmailNotification library to send the message
648                                                         require_once("include/EmailNotification.php");
649                                                         EmailNotification::sendTextHtmlEmail(
650                                                                 $msg['notificationfromname'],
651                                                                 t("Administrator@") . $a->get_hostname(),
652                                                                 t("noreply") . '@' . $a->get_hostname(),
653                                                                 $importer['email'],
654                                                                 sprintf( t('%s commented on an item at %s'), $from , $a->config['sitename']),
655                                                                 $email_html_body_tpl,
656                                                                 $email_text_body_tpl
657                                                         );
658                                                         pop_lang();
659                                                         break;
660                                                 }
661                                         }
662                                 }
663                                 continue;
664                         }
665                 }
666
667                 else {
668
669                         // Head post of a conversation. Have we seen it? If not, import it.
670
671
672                         $item_id  = $item->get_id();
673                         $datarray = get_atom_elements($feed,$item);
674
675                         if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
676                                 $ev = bbtoevent($datarray['body']);
677                                 if(x($ev,'desc') && x($ev,'start')) {
678                                         $ev['cid'] = $importer['id'];
679                                         $ev['uid'] = $importer['uid'];
680                                         $ev['uri'] = $item_id;
681                                         $ev['edited'] = $datarray['edited'];
682
683                                         $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
684                                                 dbesc($item_id),
685                                                 intval($importer['uid'])
686                                         );
687                                         if(count($r))
688                                                 $ev['id'] = $r[0]['id'];
689                                         $xyz = event_store($ev);
690                                         continue;
691                                 }
692                         }
693
694                         $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
695                                 dbesc($item_id),
696                                 intval($importer['importer_uid'])
697                         );
698
699                         // Update content if 'updated' changes
700
701                         if(count($r)) {
702                                 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
703                                         $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
704                                                 dbesc($datarray['body']),
705                                                 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
706                                                 dbesc($item_id),
707                                                 intval($importer['importer_uid'])
708                                         );
709                                 }
710
711                                 // update last-child if it changes
712
713                                 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
714                                 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
715                                         $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
716                                                 intval($allow[0]['data']),
717                                                 dbesc(datetime_convert()),
718                                                 dbesc($item_id),
719                                                 intval($importer['importer_uid'])
720                                         );
721                                 }
722                                 continue;
723                         }
724
725                         $datarray['parent-uri'] = $item_id;
726                         $datarray['uid'] = $importer['importer_uid'];
727                         $datarray['contact-id'] = $importer['id'];
728                         $r = item_store($datarray);
729                         continue;
730                 }
731         }
732
733         xml_status(0);
734         // NOTREACHED
735
736 }
737
738
739 function dfrn_notify_content(&$a) {
740
741         if(x($_GET,'dfrn_id')) {
742
743                 // initial communication from external contact, $direction is their direction.
744                 // If this is a duplex communication, ours will be the opposite.
745
746                 $dfrn_id = notags(trim($_GET['dfrn_id']));
747                 $dfrn_version = (float) $_GET['dfrn_version'];
748
749                 logger('dfrn_notify: new notification dfrn_id=' . $dfrn_id);
750
751                 $direction = (-1);
752                 if(strpos($dfrn_id,':') == 1) {
753                         $direction = intval(substr($dfrn_id,0,1));
754                         $dfrn_id = substr($dfrn_id,2);
755                 }
756
757                 $hash = random_string();
758
759                 $status = 0;
760
761                 $r = q("DELETE FROM `challenge` WHERE `expire` < " . intval(time()));
762
763                 $r = q("INSERT INTO `challenge` ( `challenge`, `dfrn-id`, `expire` )
764                         VALUES( '%s', '%s', %d ) ",
765                         dbesc($hash),
766                         dbesc($dfrn_id),
767                         intval(time() + 90 )
768                 );
769
770                 logger('dfrn_notify: challenge=' . $hash );
771
772                 $sql_extra = '';
773                 switch($direction) {
774                         case (-1):
775                                 $sql_extra = sprintf(" AND ( `issued-id` = '%s' OR `dfrn-id` = '%s' ) ", dbesc($dfrn_id), dbesc($dfrn_id));
776                                 $my_id = $dfrn_id;
777                                 break;
778                         case 0:
779                                 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
780                                 $my_id = '1:' . $dfrn_id;
781                                 break;
782                         case 1:
783                                 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
784                                 $my_id = '0:' . $dfrn_id;
785                                 break;
786                         default:
787                                 $status = 1;
788                                 break; // NOTREACHED
789                 }
790
791                 $r = q("SELECT `contact`.*, `user`.`nickname` FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid` 
792                                 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0 AND `user`.`nickname` = '%s' $sql_extra LIMIT 1",
793                                 dbesc($a->argv[1])
794                 );
795
796                 if(! count($r))
797                         $status = 1;
798
799                 $challenge = '';
800                 $encrypted_id = '';
801                 $id_str = $my_id . '.' . mt_rand(1000,9999);
802
803                 if((($r[0]['duplex']) && strlen($r[0]['prvkey'])) || (! strlen($r[0]['pubkey']))) {
804                         openssl_private_encrypt($hash,$challenge,$r[0]['prvkey']);
805                         openssl_private_encrypt($id_str,$encrypted_id,$r[0]['prvkey']);
806                 }
807                 else {
808                         openssl_public_encrypt($hash,$challenge,$r[0]['pubkey']);
809                         openssl_public_encrypt($id_str,$encrypted_id,$r[0]['pubkey']);
810                 }
811
812                 $challenge    = bin2hex($challenge);
813                 $encrypted_id = bin2hex($encrypted_id);
814
815                 $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
816
817                 $rino_enable = get_config('system','rino_encrypt');
818
819                 if(! $rino_enable)
820                         $rino = 0;
821
822
823                 header("Content-type: text/xml");
824
825                 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" 
826                         . '<dfrn_notify>' . "\r\n"
827                         . "\t" . '<status>' . $status . '</status>' . "\r\n"
828                         . "\t" . '<dfrn_version>' . DFRN_PROTOCOL_VERSION . '</dfrn_version>' . "\r\n"
829                         . "\t" . '<rino>' . $rino . '</rino>' . "\r\n" 
830                         . "\t" . '<dfrn_id>' . $encrypted_id . '</dfrn_id>' . "\r\n" 
831                         . "\t" . '<challenge>' . $challenge . '</challenge>' . "\r\n"
832                         . '</dfrn_notify>' . "\r\n" ;
833
834                 killme();
835         }
836
837 }