]> git.mxchange.org Git - friendica.git/blob - mod/dfrn_notify.php
Admin users page. some fix to template processor.
[friendica.git] / mod / dfrn_notify.php
1 <?php
2
3 require_once('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
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         $ismail = false;
158
159         $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
160         if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
161
162                 logger('dfrn_notify: private message received');
163
164                 $ismail = true;
165                 $base = $rawmail[0]['child'][NAMESPACE_DFRN];
166
167                 $msg = array();
168                 $msg['uid'] = $importer['importer_uid'];
169                 $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
170                 $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
171                 $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
172                 $msg['contact-id'] = $importer['id'];
173                 $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
174                 $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
175                 $msg['seen'] = 0;
176                 $msg['replied'] = 0;
177                 $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
178                 $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
179                 $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
180                 
181                 dbesc_array($msg);
182
183                 $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg)) 
184                         . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
185
186                 // send email notification if requested.
187
188                 require_once('bbcode.php');
189                 if($importer['notify-flags'] & NOTIFY_MAIL) {
190
191                         push_lang($importer['language']);
192
193                         // name of the automated email sender
194                         $msg['notificationfromname']    = t('Administrator');
195                         // noreply address to send from
196                         $msg['notificationfromemail']   = t('noreply') . '@' . $a->get_hostname();                              
197
198                         // text version
199                         // process the message body to display properly in text mode
200                         //              1) substitute a \n character for the "\" then "n", so it behaves properly (it doesn't come in as a \n character)
201                         //              2) remove escape slashes
202                         //              3) decode any bbcode from the message editor
203                         //              4) decode any encoded html tags
204                         //              5) remove html tags
205                         $msg['textversion']
206                                 = strip_tags(html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n"), "\n",$msg['body']))),ENT_QUOTES,'UTF-8'));
207                                 
208                         // html version
209                         // process the message body to display properly in text mode
210                         //              1) substitute a <br /> tag for the "\" then "n", so it behaves properly (it doesn't come in as a \n character)
211                         //              2) remove escape slashes
212                         //              3) decode any bbcode from the message editor
213                         //              4) decode any encoded html tags
214                         $msg['htmlversion']     
215                                 = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r","\\n\\n" ,"\\n"), "<br />\n",$msg['body']))));
216
217                         // load the template for private message notifications
218                         $tpl = get_intltext_template('mail_received_html_body_eml.tpl');
219                         $email_html_body_tpl = replace_macros($tpl,array(
220                                 '$siteName'             => $a->config['sitename'],                      // name of this site
221                                 '$siteurl'              => $a->get_baseurl(),                           // descriptive url of this site
222                                 '$thumb'                => $importer['thumb'],                          // thumbnail url for sender icon
223                                 '$email'                => $importer['email'],                          // email address to send to
224                                 '$url'                  => $importer['url'],                            // full url for the site
225                                 '$from'                 => $msg['from-name'],                           // name of the person sending the message
226                                 '$title'                => stripslashes($msg['title']),                 // subject of the message
227                                 '$htmlversion'  => $msg['htmlversion'],                                 // html version of the message
228                                 '$mimeboundary' => $msg['mimeboundary'],                                // mime message divider
229                                 '$hostname'             => $a->get_hostname()                           // name of this host
230                         ));
231                         
232                         // load the template for private message notifications
233                         $tpl = get_intltext_template('mail_received_text_body_eml.tpl');
234                         $email_text_body_tpl = replace_macros($tpl,array(
235                                 '$siteName'             => $a->config['sitename'],                      // name of this site
236                                 '$siteurl'              => $a->get_baseurl(),                           // descriptive url of this site
237                                 '$thumb'                => $importer['thumb'],                          // thumbnail url for sender icon
238                                 '$email'                => $importer['email'],                          // email address to send to
239                                 '$url'                  => $importer['url'],                            // full url for the site
240                                 '$from'                 => $msg['from-name'],                           // name of the person sending the message
241                                 '$title'                => stripslashes($msg['title']),                 // subject of the message
242                                 '$textversion'  => $msg['textversion'],                                 // text version of the message
243                                 '$mimeboundary' => $msg['mimeboundary'],                                // mime message divider
244                                 '$hostname'             => $a->get_hostname()                           // name of this host
245                         ));
246
247                         // use the EmailNotification library to send the message
248                         require_once("include/EmailNotification.php");
249                         EmailNotification::sendTextHtmlEmail(
250                                 $msg['notificationfromname'],
251                                 $msg['notificationfromemail'],
252                                 $msg['notificationfromemail'],
253                                 $importer['email'],
254                                 t('New mail received at ') . $a->config['sitename'],
255                                 $email_html_body_tpl,
256                                 $email_text_body_tpl
257                         );
258
259                         pop_lang();
260                 }
261                 xml_status(0);
262                 // NOTREACHED
263         }       
264         
265         logger('dfrn_notify: feed item count = ' . $feed->get_item_quantity());
266
267         // process any deleted entries
268
269         $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
270         if(is_array($del_entries) && count($del_entries)) {
271                 foreach($del_entries as $dentry) {
272                         $deleted = false;
273                         if(isset($dentry['attribs']['']['ref'])) {
274                                 $uri = $dentry['attribs']['']['ref'];
275                                 $deleted = true;
276                                 if(isset($dentry['attribs']['']['when'])) {
277                                         $when = $dentry['attribs']['']['when'];
278                                         $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
279                                 }
280                                 else
281                                         $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
282                         }
283                         if($deleted) {
284
285                                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `contact-id` = %d LIMIT 1",
286                                         dbesc($uri),
287                                         intval($importer['importer_uid']),
288                                         intval($importer['id'])
289                                 );
290
291                                 if(count($r)) {
292                                         $item = $r[0];
293
294                                         if(! $item['deleted'])
295                                                 logger('dfrn_notify: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
296
297                                         if($item['uri'] == $item['parent-uri']) {
298                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
299                                                         WHERE `parent-uri` = '%s' AND `uid` = %d",
300                                                         dbesc($when),
301                                                         dbesc(datetime_convert()),
302                                                         dbesc($item['uri']),
303                                                         intval($importer['importer_uid'])
304                                                 );
305                                         }
306                                         else {
307                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' 
308                                                         WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
309                                                         dbesc($when),
310                                                         dbesc(datetime_convert()),
311                                                         dbesc($uri),
312                                                         intval($importer['importer_uid'])
313                                                 );
314                                                 if($item['last-child']) {
315                                                         // ensure that last-child is set in case the comment that had it just got wiped.
316                                                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
317                                                                 dbesc(datetime_convert()),
318                                                                 dbesc($item['parent-uri']),
319                                                                 intval($item['uid'])
320                                                         );
321                                                         // who is the last child now? 
322                                                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
323                                                                 ORDER BY `created` DESC LIMIT 1",
324                                                                         dbesc($item['parent-uri']),
325                                                                         intval($importer['importer_uid'])
326                                                         );
327                                                         if(count($r)) {
328                                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
329                                                                         intval($r[0]['id'])
330                                                                 );
331                                                         }       
332                                                 }
333                                         }       
334                                 }
335                         }
336                 }
337         }
338
339
340         foreach($feed->get_items() as $item) {
341
342                 $is_reply = false;              
343                 $item_id = $item->get_id();
344                 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
345                 if(isset($rawthread[0]['attribs']['']['ref'])) {
346                         $is_reply = true;
347                         $parent_uri = $rawthread[0]['attribs']['']['ref'];
348                 }
349
350                 if($is_reply) {
351                         if($feed->get_item_quantity() == 1) {
352                                 logger('dfrn_notify: received remote comment');
353                                 $is_like = false;
354                                 // remote reply to our post. Import and then notify everybody else.
355                                 $datarray = get_atom_elements($feed,$item);
356                                 $datarray['type'] = 'remote-comment';
357                                 $datarray['wall'] = 1;
358                                 $datarray['parent-uri'] = $parent_uri;
359                                 $datarray['uid'] = $importer['importer_uid'];
360                                 $datarray['contact-id'] = $importer['id'];
361                                 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
362                                         $is_like = true;
363                                         $datarray['type'] = 'activity';
364                                         $datarray['gravity'] = GRAVITY_LIKE;
365                                         $datarray['last-child'] = 0;
366                                 }
367                                 $posted_id = item_store($datarray);
368                                 $parent = 0;
369
370                                 if($posted_id) {
371                                         $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
372                                                 intval($posted_id),
373                                                 intval($importer['importer_uid'])
374                                         );
375                                         if(count($r))
376                                                 $parent = $r[0]['parent'];
377                         
378                                         if(! $is_like) {
379                                                 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
380                                                         dbesc(datetime_convert()),
381                                                         intval($importer['importer_uid']),
382                                                         intval($r[0]['parent'])
383                                                 );
384
385                                                 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
386                                                         dbesc(datetime_convert()),
387                                                         intval($importer['importer_uid']),
388                                                         intval($posted_id)
389                                                 );
390                                         }
391
392                                         if($posted_id && $parent) {
393                                 
394                                                 proc_run('php',"include/notifier.php","comment-import","$posted_id");
395                                         
396                                                 if((! $is_like) && ($importer['notify-flags'] & NOTIFY_COMMENT) && (! $importer['self'])) {
397                                                         push_lang($importer['language']);
398                                                         require_once('bbcode.php');
399                                                         $from = stripslashes($datarray['author-name']);
400
401                                                         // name of the automated email sender
402                                                         $msg['notificationfromname']    = stripslashes($datarray['author-name']);;
403                                                         // noreply address to send from
404                                                         $msg['notificationfromemail']   = t('noreply') . '@' . $a->get_hostname();                              
405
406                                                         // text version
407                                                         // process the message body to display properly in text mode
408                                                         $msg['textversion']
409                                                                 = html_entity_decode(strip_tags(bbcode(stripslashes($datarray['body']))), ENT_QUOTES, 'UTF-8');
410                                 
411                                                         // html version
412                                                         // process the message body to display properly in text mode
413                                                         $msg['htmlversion']     
414                                                                 = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r","\\n\\n" ,"\\n"), "<br />\n",$datarray['body']))));
415
416                                                         // load the template for private message notifications
417                                                         $tpl = get_intltext_template('cmnt_received_html_body_eml.tpl');
418                                                         $email_html_body_tpl = replace_macros($tpl,array(
419                                                                 '$sitename'             => $a->config['sitename'],                      // name of this site
420                                                                 '$siteurl'              => $a->get_baseurl(),                           // descriptive url of this site
421                                                                 '$thumb'                => $datarray['author-avatar'],                  // thumbnail url for sender icon
422                                                                 '$email'                => $importer['email'],                          // email address to send to
423                                                                 '$url'                  => $datarray['author-link'],                    // full url for the site
424                                                                 '$from'                 => $from,                                       // name of the person sending the message
425                                                                 '$body'                 => $msg['htmlversion'],                 // html version of the message
426                                                                 '$display'              => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
427                                                         ));
428                         
429                                                         // load the template for private message notifications
430                                                         $tpl = get_intltext_template('cmnt_received_text_body_eml.tpl');
431                                                         $email_text_body_tpl = replace_macros($tpl,array(
432                                                                 '$sitename'             => $a->config['sitename'],                      // name of this site
433                                                                 '$siteurl'              => $a->get_baseurl(),                           // descriptive url of this site
434                                                                 '$thumb'                => $datarray['author-avatar'],                  // thumbnail url for sender icon
435                                                                 '$email'                => $importer['email'],                          // email address to send to
436                                                                 '$url'                  => $datarray['author-link'],                    // full url for the site
437                                                                 '$from'                 => $from,                                       // name of the person sending the message
438                                                                 '$body'                 => $msg['textversion'],                         // text version of the message
439                                                                 '$display'              => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
440                                                         ));
441
442                                                         // use the EmailNotification library to send the message
443                                                         require_once("include/EmailNotification.php");
444                                                         EmailNotification::sendTextHtmlEmail(
445                                                                 $msg['notificationfromname'],
446                                                                 t("Administrator") . '@' . $a->get_hostname(),
447                                                                 t("noreply") . '@' . $a->get_hostname(),
448                                                                 $importer['email'],
449                                                                 sprintf( t('%s commented on an item at %s'), $from , $a->config['sitename']),
450                                                                 $email_html_body_tpl,
451                                                                 $email_text_body_tpl
452                                                         );
453                                                         pop_lang();
454                                                 }
455                                         }
456                                         xml_status(0);
457                                         // NOTREACHED
458                                 }
459                         }
460                         else {
461
462                                 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
463
464                                 $item_id  = $item->get_id();
465                                 $datarray = get_atom_elements($feed,$item);
466
467                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
468                                         dbesc($item_id),
469                                         intval($importer['importer_uid'])
470                                 );
471
472                                 // Update content if 'updated' changes
473
474                                 if(count($r)) {
475                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
476                                                 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
477                                                         dbesc($datarray['body']),
478                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
479                                                         dbesc($item_id),
480                                                         intval($importer['importer_uid'])
481                                                 );
482                                         }
483
484                                         // update last-child if it changes
485
486                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
487                                         if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
488                                                 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
489                                                         dbesc(datetime_convert()),
490                                                         dbesc($parent_uri),
491                                                         intval($importer['importer_uid'])
492                                                 );
493                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s'  WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
494                                                         intval($allow[0]['data']),
495                                                         dbesc(datetime_convert()),
496                                                         dbesc($item_id),
497                                                         intval($importer['importer_uid'])
498                                                 );
499                                         }
500                                         continue;
501                                 }
502
503                                 $datarray['parent-uri'] = $parent_uri;
504                                 $datarray['uid'] = $importer['importer_uid'];
505                                 $datarray['contact-id'] = $importer['id'];
506                                 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
507                                         $datarray['type'] = 'activity';
508                                         $datarray['gravity'] = GRAVITY_LIKE;
509                                 }
510                                 $posted_id = item_store($datarray);
511
512                                 // find out if our user is involved in this conversation and wants to be notified.
513                         
514                                 if(($datarray['type'] != 'activity') && ($importer['notify-flags'] & NOTIFY_COMMENT)) {
515
516                                         $myconv = q("SELECT `author-link`, `author-avatar` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 ",
517                                                 dbesc($parent_uri),
518                                                 intval($importer['importer_uid'])
519                                         );
520                                         if(count($myconv)) {
521                                                 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
522                                                 foreach($myconv as $conv) {
523                                                         if(! link_compare($conv['author-link'],$importer_url))
524                                                                 continue;
525
526                                                         push_lang($importer['language']);
527                                                         require_once('bbcode.php');
528                                                         $from = stripslashes($datarray['author-name']);
529                                                         
530                                                         // name of the automated email sender
531                                                         $msg['notificationfromname']    = stripslashes($datarray['author-name']);;
532                                                         // noreply address to send from
533                                                         $msg['notificationfromemail']   = t('noreply') . '@' . $a->get_hostname();                              
534
535                                                         // text version
536                                                         // process the message body to display properly in text mode
537                                                         $msg['textversion']
538                                                                 = html_entity_decode(strip_tags(bbcode(stripslashes($datarray['body']))), ENT_QUOTES, 'UTF-8');
539                                 
540                                                         // html version
541                                                         // process the message body to display properly in text mode
542                                                         $msg['htmlversion']     
543                                                                 = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r","\\n\\n" ,"\\n"), "<br />\n",$datarray['body']))));
544
545                                                         // load the template for private message notifications
546                                                         $tpl = get_intltext_template('cmnt_received_html_body_eml.tpl');
547                                                         $email_html_body_tpl = replace_macros($tpl,array(
548                                                                 '$sitename'             => $a->config['sitename'],                              // name of this site
549                                                                 '$siteurl'              => $a->get_baseurl(),                                   // descriptive url of this site
550                                                                 '$thumb'                => $datarray['author-avatar'],                          // thumbnail url for sender icon
551                                                                 '$url'                  => $datarray['author-link'],                            // full url for the site
552                                                                 '$from'                 => $from,                                               // name of the person sending the message
553                                                                 '$body'                 => $msg['htmlversion'],                                 // html version of the message
554                                                                 '$display'              => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
555                                                         ));
556                         
557                                                         // load the template for private message notifications
558                                                         $tpl = get_intltext_template('cmnt_received_text_body_eml.tpl');
559                                                         $email_text_body_tpl = replace_macros($tpl,array(
560                                                                 '$sitename'             => $a->config['sitename'],                              // name of this site
561                                                                 '$siteurl'              => $a->get_baseurl(),                                   // descriptive url of this site
562                                                                 '$thumb'                => $datarray['author-avatar'],                          // thumbnail url for sender icon
563                                                                 '$url'                  => $datarray['author-link'],                            // full url for the site
564                                                                 '$from'                 => $from,                                               // name of the person sending the message
565                                                                 '$body'                 => $msg['textversion'],                                 // text version of the message
566                                                                 '$display'              => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
567                                                         ));
568
569                                                         // use the EmailNotification library to send the message
570                                                         require_once("include/EmailNotification.php");
571                                                         EmailNotification::sendTextHtmlEmail(
572                                                                 $msg['notificationfromname'],
573                                                                 t("Administrator@") . $a->get_hostname(),
574                                                                 t("noreply") . '@' . $a->get_hostname(),
575                                                                 $importer['email'],
576                                                                 sprintf( t('%s commented on an item at %s'), $from , $a->config['sitename']),
577                                                                 $email_html_body_tpl,
578                                                                 $email_text_body_tpl
579                                                         );
580                                                         pop_lang();
581                                                         break;
582                                                 }
583                                         }
584                                 }
585                                 continue;
586                         }
587                 }
588
589                 else {
590
591                         // Head post of a conversation. Have we seen it? If not, import it.
592
593
594                         $item_id  = $item->get_id();
595                         $datarray = get_atom_elements($feed,$item);
596
597                         if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
598                                 $ev = bbtoevent($datarray['body']);
599                                 if(x($ev,'desc') && x($ev,'start')) {
600                                         $ev['cid'] = $importer['id'];
601                                         $ev['uid'] = $importer['uid'];
602                                         $ev['uri'] = $item_id;
603
604                                         $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
605                                                 dbesc($item_id),
606                                                 intval($importer['uid'])
607                                         );
608                                         if(count($r))
609                                                 $ev['id'] = $r[0]['id'];
610                                         $xyz = event_store($ev);
611                                         continue;
612                                 }
613                         }
614
615                         $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
616                                 dbesc($item_id),
617                                 intval($importer['importer_uid'])
618                         );
619
620                         // Update content if 'updated' changes
621
622                         if(count($r)) {
623                                 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
624                                         $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
625                                                 dbesc($datarray['body']),
626                                                 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
627                                                 dbesc($item_id),
628                                                 intval($importer['importer_uid'])
629                                         );
630                                 }
631
632                                 // update last-child if it changes
633
634                                 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
635                                 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
636                                         $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
637                                                 intval($allow[0]['data']),
638                                                 dbesc(datetime_convert()),
639                                                 dbesc($item_id),
640                                                 intval($importer['importer_uid'])
641                                         );
642                                 }
643                                 continue;
644                         }
645
646                         $datarray['parent-uri'] = $item_id;
647                         $datarray['uid'] = $importer['importer_uid'];
648                         $datarray['contact-id'] = $importer['id'];
649                         $r = item_store($datarray);
650                         continue;
651                 }
652         }
653
654         xml_status(0);
655         // NOTREACHED
656
657 }
658
659
660 function dfrn_notify_content(&$a) {
661
662         if(x($_GET,'dfrn_id')) {
663
664                 // initial communication from external contact, $direction is their direction.
665                 // If this is a duplex communication, ours will be the opposite.
666
667                 $dfrn_id = notags(trim($_GET['dfrn_id']));
668                 $dfrn_version = (float) $_GET['dfrn_version'];
669
670                 logger('dfrn_notify: new notification dfrn_id=' . $dfrn_id);
671
672                 $direction = (-1);
673                 if(strpos($dfrn_id,':') == 1) {
674                         $direction = intval(substr($dfrn_id,0,1));
675                         $dfrn_id = substr($dfrn_id,2);
676                 }
677
678                 $hash = random_string();
679
680                 $status = 0;
681
682                 $r = q("DELETE FROM `challenge` WHERE `expire` < " . intval(time()));
683
684                 $r = q("INSERT INTO `challenge` ( `challenge`, `dfrn-id`, `expire` )
685                         VALUES( '%s', '%s', %d ) ",
686                         dbesc($hash),
687                         dbesc($dfrn_id),
688                         intval(time() + 90 )
689                 );
690
691                 logger('dfrn_notify: challenge=' . $hash );
692
693                 $sql_extra = '';
694                 switch($direction) {
695                         case (-1):
696                                 $sql_extra = sprintf(" AND ( `issued-id` = '%s' OR `dfrn-id` = '%s' ) ", dbesc($dfrn_id), dbesc($dfrn_id));
697                                 $my_id = $dfrn_id;
698                                 break;
699                         case 0:
700                                 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
701                                 $my_id = '1:' . $dfrn_id;
702                                 break;
703                         case 1:
704                                 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
705                                 $my_id = '0:' . $dfrn_id;
706                                 break;
707                         default:
708                                 $status = 1;
709                                 break; // NOTREACHED
710                 }
711
712                 $r = q("SELECT `contact`.*, `user`.`nickname` FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid` 
713                                 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0 AND `user`.`nickname` = '%s' $sql_extra LIMIT 1",
714                                 dbesc($a->argv[1])
715                 );
716
717                 if(! count($r))
718                         $status = 1;
719
720                 $challenge = '';
721                 $encrypted_id = '';
722                 $id_str = $my_id . '.' . mt_rand(1000,9999);
723
724                 if((($r[0]['duplex']) && strlen($r[0]['prvkey'])) || (! strlen($r[0]['pubkey']))) {
725                         openssl_private_encrypt($hash,$challenge,$r[0]['prvkey']);
726                         openssl_private_encrypt($id_str,$encrypted_id,$r[0]['prvkey']);
727                 }
728                 else {
729                         openssl_public_encrypt($hash,$challenge,$r[0]['pubkey']);
730                         openssl_public_encrypt($id_str,$encrypted_id,$r[0]['pubkey']);
731                 }
732
733                 $challenge    = bin2hex($challenge);
734                 $encrypted_id = bin2hex($encrypted_id);
735
736                 $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
737
738                 $rino_enable = get_config('system','rino_encrypt');
739
740                 if(! $rino_enable)
741                         $rino = 0;
742
743
744                 header("Content-type: text/xml");
745
746                 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" 
747                         . '<dfrn_notify>' . "\r\n"
748                         . "\t" . '<status>' . $status . '</status>' . "\r\n"
749                         . "\t" . '<dfrn_version>' . DFRN_PROTOCOL_VERSION . '</dfrn_version>' . "\r\n"
750                         . "\t" . '<rino>' . $rino . '</rino>' . "\r\n" 
751                         . "\t" . '<dfrn_id>' . $encrypted_id . '</dfrn_id>' . "\r\n" 
752                         . "\t" . '<challenge>' . $challenge . '</challenge>' . "\r\n"
753                         . '</dfrn_notify>' . "\r\n" ;
754
755                 killme();
756         }
757
758 }