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