]> git.mxchange.org Git - friendica.git/blob - mod/dfrn_notify.php
clean up w3c validation and layout for priv mail and lang selector
[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? 
455                         // Specifically, the recipient? 
456
457                         $r = q("select `item`.`id` from `item` 
458                                 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id` 
459                                 WHERE `contact`.`self` = 1 AND `item`.`uri` = '%s' AND `item`.`uid` = %d LIMIT 1",
460                                 dbesc($parent_uri),
461                                 intval($importer['importer_uid'])
462                         );
463                         if($r && count($r)) {   
464
465                                 logger('dfrn_notify: received remote comment');
466                                 $is_like = false;
467                                 // remote reply to our post. Import and then notify everybody else.
468                                 $datarray = get_atom_elements($feed,$item);
469                                 $datarray['type'] = 'remote-comment';
470                                 $datarray['wall'] = 1;
471                                 $datarray['parent-uri'] = $parent_uri;
472                                 $datarray['uid'] = $importer['importer_uid'];
473                                 $datarray['contact-id'] = $importer['id'];
474                                 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
475                                         $is_like = true;
476                                         $datarray['type'] = 'activity';
477                                         $datarray['gravity'] = GRAVITY_LIKE;
478                                         $datarray['last-child'] = 0;
479                                 }
480                                 $posted_id = item_store($datarray);
481                                 $parent = 0;
482
483                                 if($posted_id) {
484                                         $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
485                                                 intval($posted_id),
486                                                 intval($importer['importer_uid'])
487                                         );
488                                         if(count($r))
489                                                 $parent = $r[0]['parent'];
490                         
491                                         if(! $is_like) {
492                                                 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
493                                                         dbesc(datetime_convert()),
494                                                         intval($importer['importer_uid']),
495                                                         intval($r[0]['parent'])
496                                                 );
497
498                                                 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
499                                                         dbesc(datetime_convert()),
500                                                         intval($importer['importer_uid']),
501                                                         intval($posted_id)
502                                                 );
503                                         }
504
505                                         if($posted_id && $parent) {
506                                 
507                                                 proc_run('php',"include/notifier.php","comment-import","$posted_id");
508                                         
509                                                 if((! $is_like) && ($importer['notify-flags'] & NOTIFY_COMMENT) && (! $importer['self'])) {
510                                                         push_lang($importer['language']);
511                                                         require_once('bbcode.php');
512                                                         $from = stripslashes($datarray['author-name']);
513
514                                                         // name of the automated email sender
515                                                         $msg['notificationfromname']    = stripslashes($datarray['author-name']);;
516                                                         // noreply address to send from
517                                                         $msg['notificationfromemail']   = t('noreply') . '@' . $a->get_hostname();                              
518
519                                                         // text version
520                                                         // process the message body to display properly in text mode
521                                                         $msg['textversion']
522                                                                 = html_entity_decode(strip_tags(bbcode(stripslashes($datarray['body']))), ENT_QUOTES, 'UTF-8');
523                                 
524                                                         // html version
525                                                         // process the message body to display properly in text mode
526                                                         $msg['htmlversion']     
527                                                                 = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r","\\n\\n" ,"\\n"), "<br />\n",$datarray['body']))));
528
529                                                         $imgtouse = ((link_compare($datarray['author-link'],$importer['url'])) ? $importer['thumb'] : $datarray['author-avatar']);
530
531                                                         // load the template for private message notifications
532                                                         $tpl = get_intltext_template('cmnt_received_html_body_eml.tpl');
533                                                         $email_html_body_tpl = replace_macros($tpl,array(
534                                                                 '$username'     => $importer['username'],
535                                                                 '$sitename'             => $a->config['sitename'],                      // name of this site
536                                                                 '$siteurl'              => $a->get_baseurl(),                           // descriptive url of this site
537                                                                 '$thumb'                => $imgtouse,                                           // thumbnail url for sender icon
538                                                                 '$email'                => $importer['email'],                          // email address to send to
539                                                                 '$url'                  => $datarray['author-link'],            // full url for the site
540                                                                 '$from'                 => $from,                                                       // name of the person sending the message
541                                                                 '$body'                 => $msg['htmlversion'],                         // html version of the message
542                                                                 '$display'              => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
543                                                         ));
544                         
545                                                         // load the template for private message notifications
546                                                         $tpl = get_intltext_template('cmnt_received_text_body_eml.tpl');
547                                                         $email_text_body_tpl = replace_macros($tpl,array(
548                                                                 '$username'     => $importer['username'],
549                                                                 '$sitename'             => $a->config['sitename'],                      // name of this site
550                                                                 '$siteurl'              => $a->get_baseurl(),                           // descriptive url of this site
551                                                                 '$thumb'                => $imgtouse,                                           // thumbnail url for sender icon
552                                                                 '$email'                => $importer['email'],                          // email address to send to
553                                                                 '$url'                  => $datarray['author-link'],            // full url for the site
554                                                                 '$from'                 => $from,                                                       // name of the person sending the message
555                                                                 '$body'                 => $msg['textversion'],                         // text version of the message
556                                                                 '$display'              => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
557                                                         ));
558
559                                                         // use the EmailNotification library to send the message
560                                                         require_once("include/EmailNotification.php");
561                                                         EmailNotification::sendTextHtmlEmail(
562                                                                 $msg['notificationfromname'],
563                                                                 t("Administrator") . '@' . $a->get_hostname(),
564                                                                 t("noreply") . '@' . $a->get_hostname(),
565                                                                 $importer['email'],
566                                                                 sprintf( t('%s commented on an item at %s'), $from , $a->config['sitename']),
567                                                                 $email_html_body_tpl,
568                                                                 $email_text_body_tpl
569                                                         );
570                                                         pop_lang();
571                                                 }
572                                         }
573                                         xml_status(0);
574                                         // NOTREACHED
575                                 }
576                         }
577                         else {
578
579                                 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
580
581                                 $item_id  = $item->get_id();
582                                 $datarray = get_atom_elements($feed,$item);
583
584                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
585                                         dbesc($item_id),
586                                         intval($importer['importer_uid'])
587                                 );
588
589                                 // Update content if 'updated' changes
590
591                                 if(count($r)) {
592                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
593                                                 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
594                                                         dbesc($datarray['body']),
595                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
596                                                         dbesc($item_id),
597                                                         intval($importer['importer_uid'])
598                                                 );
599                                         }
600
601                                         // update last-child if it changes
602
603                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
604                                         if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
605                                                 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
606                                                         dbesc(datetime_convert()),
607                                                         dbesc($parent_uri),
608                                                         intval($importer['importer_uid'])
609                                                 );
610                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s'  WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
611                                                         intval($allow[0]['data']),
612                                                         dbesc(datetime_convert()),
613                                                         dbesc($item_id),
614                                                         intval($importer['importer_uid'])
615                                                 );
616                                         }
617                                         continue;
618                                 }
619
620                                 $datarray['parent-uri'] = $parent_uri;
621                                 $datarray['uid'] = $importer['importer_uid'];
622                                 $datarray['contact-id'] = $importer['id'];
623                                 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
624                                         $datarray['type'] = 'activity';
625                                         $datarray['gravity'] = GRAVITY_LIKE;
626                                 }
627                                 $posted_id = item_store($datarray);
628
629                                 // find out if our user is involved in this conversation and wants to be notified.
630                         
631                                 if(($datarray['type'] != 'activity') && ($importer['notify-flags'] & NOTIFY_COMMENT)) {
632
633                                         $myconv = q("SELECT `author-link`, `author-avatar` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 ",
634                                                 dbesc($parent_uri),
635                                                 intval($importer['importer_uid'])
636                                         );
637                                         if(count($myconv)) {
638                                                 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
639                                                 foreach($myconv as $conv) {
640                                                         if(! link_compare($conv['author-link'],$importer_url))
641                                                                 continue;
642
643                                                         push_lang($importer['language']);
644                                                         require_once('bbcode.php');
645                                                         $from = stripslashes($datarray['author-name']);
646                                                         
647                                                         // name of the automated email sender
648                                                         $msg['notificationfromname']    = stripslashes($datarray['author-name']);;
649                                                         // noreply address to send from
650                                                         $msg['notificationfromemail']   = t('noreply') . '@' . $a->get_hostname();                              
651
652                                                         // text version
653                                                         // process the message body to display properly in text mode
654                                                         $msg['textversion']
655                                                                 = html_entity_decode(strip_tags(bbcode(stripslashes($datarray['body']))), ENT_QUOTES, 'UTF-8');
656                                 
657                                                         // html version
658                                                         // process the message body to display properly in text mode
659                                                         $msg['htmlversion']     
660                                                                 = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r","\\n\\n" ,"\\n"), "<br />\n",$datarray['body']))));
661
662                                                         $imgtouse = ((link_compare($datarray['author-link'],$importer['url'])) ? $importer['thumb'] : $datarray['author-avatar']);
663
664
665                                                         // load the template for private message notifications
666                                                         $tpl = get_intltext_template('cmnt_received_html_body_eml.tpl');
667                                                         $email_html_body_tpl = replace_macros($tpl,array(
668                                                                 '$username'     => $importer['username'],
669                                                                 '$sitename'             => $a->config['sitename'],                              // name of this site
670                                                                 '$siteurl'              => $a->get_baseurl(),                                   // descriptive url of this site
671                                                                 '$thumb'                => $imgtouse,                                                   // thumbnail url for sender icon
672                                                                 '$url'                  => $datarray['author-link'],                    // full url for the site
673                                                                 '$from'                 => $from,                                                               // name of the person sending the message
674                                                                 '$body'                 => $msg['htmlversion'],                                 // html version of the message
675                                                                 '$display'              => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
676                                                         ));
677                         
678                                                         // load the template for private message notifications
679                                                         $tpl = get_intltext_template('cmnt_received_text_body_eml.tpl');
680                                                         $email_text_body_tpl = replace_macros($tpl,array(
681                                                                 '$username'     => $importer['username'],
682                                                                 '$sitename'             => $a->config['sitename'],                              // name of this site
683                                                                 '$siteurl'              => $a->get_baseurl(),                                   // descriptive url of this site
684                                                                 '$thumb'                => $imgtouse,                                                   // thumbnail url for sender icon
685                                                                 '$url'                  => $datarray['author-link'],                    // full url for the site
686                                                                 '$from'                 => $from,                                                               // name of the person sending the message
687                                                                 '$body'                 => $msg['textversion'],                                 // text version of the message
688                                                                 '$display'              => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
689                                                         ));
690
691                                                         // use the EmailNotification library to send the message
692                                                         require_once("include/EmailNotification.php");
693                                                         EmailNotification::sendTextHtmlEmail(
694                                                                 $msg['notificationfromname'],
695                                                                 t("Administrator@") . $a->get_hostname(),
696                                                                 t("noreply") . '@' . $a->get_hostname(),
697                                                                 $importer['email'],
698                                                                 sprintf( t('%s commented on an item at %s'), $from , $a->config['sitename']),
699                                                                 $email_html_body_tpl,
700                                                                 $email_text_body_tpl
701                                                         );
702                                                         pop_lang();
703                                                         break;
704                                                 }
705                                         }
706                                 }
707                                 continue;
708                         }
709                 }
710
711                 else {
712
713                         // Head post of a conversation. Have we seen it? If not, import it.
714
715
716                         $item_id  = $item->get_id();
717                         $datarray = get_atom_elements($feed,$item);
718
719                         if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
720                                 $ev = bbtoevent($datarray['body']);
721                                 if(x($ev,'desc') && x($ev,'start')) {
722                                         $ev['cid'] = $importer['id'];
723                                         $ev['uid'] = $importer['uid'];
724                                         $ev['uri'] = $item_id;
725                                         $ev['edited'] = $datarray['edited'];
726                                         $ev['private'] = $datarray['private'];
727
728                                         $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
729                                                 dbesc($item_id),
730                                                 intval($importer['uid'])
731                                         );
732                                         if(count($r))
733                                                 $ev['id'] = $r[0]['id'];
734                                         $xyz = event_store($ev);
735                                         continue;
736                                 }
737                         }
738
739                         $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
740                                 dbesc($item_id),
741                                 intval($importer['importer_uid'])
742                         );
743
744                         // Update content if 'updated' changes
745
746                         if(count($r)) {
747                                 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
748                                         $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
749                                                 dbesc($datarray['body']),
750                                                 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
751                                                 dbesc($item_id),
752                                                 intval($importer['importer_uid'])
753                                         );
754                                 }
755
756                                 // update last-child if it changes
757
758                                 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
759                                 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
760                                         $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
761                                                 intval($allow[0]['data']),
762                                                 dbesc(datetime_convert()),
763                                                 dbesc($item_id),
764                                                 intval($importer['importer_uid'])
765                                         );
766                                 }
767                                 continue;
768                         }
769
770                         // This is my contact on another system, but it's really me.
771                         // Turn this into a wall post.
772
773                         if($contact['remote_self'])
774                                 $datarray['wall'] = 1;
775
776                         $datarray['parent-uri'] = $item_id;
777                         $datarray['uid'] = $importer['importer_uid'];
778                         $datarray['contact-id'] = $importer['id'];
779                         $r = item_store($datarray);
780                         continue;
781                 }
782         }
783
784         xml_status(0);
785         // NOTREACHED
786
787 }
788
789
790 function dfrn_notify_content(&$a) {
791
792         if(x($_GET,'dfrn_id')) {
793
794                 // initial communication from external contact, $direction is their direction.
795                 // If this is a duplex communication, ours will be the opposite.
796
797                 $dfrn_id = notags(trim($_GET['dfrn_id']));
798                 $dfrn_version = (float) $_GET['dfrn_version'];
799
800                 logger('dfrn_notify: new notification dfrn_id=' . $dfrn_id);
801
802                 $direction = (-1);
803                 if(strpos($dfrn_id,':') == 1) {
804                         $direction = intval(substr($dfrn_id,0,1));
805                         $dfrn_id = substr($dfrn_id,2);
806                 }
807
808                 $hash = random_string();
809
810                 $status = 0;
811
812                 $r = q("DELETE FROM `challenge` WHERE `expire` < " . intval(time()));
813
814                 $r = q("INSERT INTO `challenge` ( `challenge`, `dfrn-id`, `expire` )
815                         VALUES( '%s', '%s', %d ) ",
816                         dbesc($hash),
817                         dbesc($dfrn_id),
818                         intval(time() + 90 )
819                 );
820
821                 logger('dfrn_notify: challenge=' . $hash, LOGGER_DEBUG );
822
823                 $sql_extra = '';
824                 switch($direction) {
825                         case (-1):
826                                 $sql_extra = sprintf(" AND ( `issued-id` = '%s' OR `dfrn-id` = '%s' ) ", dbesc($dfrn_id), dbesc($dfrn_id));
827                                 $my_id = $dfrn_id;
828                                 break;
829                         case 0:
830                                 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
831                                 $my_id = '1:' . $dfrn_id;
832                                 break;
833                         case 1:
834                                 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
835                                 $my_id = '0:' . $dfrn_id;
836                                 break;
837                         default:
838                                 $status = 1;
839                                 break; // NOTREACHED
840                 }
841
842                 $r = q("SELECT `contact`.*, `user`.`nickname` FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid` 
843                                 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0 AND `user`.`nickname` = '%s' 
844                                 AND `user`.`account_expired` = 0 $sql_extra LIMIT 1",
845                                 dbesc($a->argv[1])
846                 );
847
848                 if(! count($r))
849                         $status = 1;
850
851                 $challenge = '';
852                 $encrypted_id = '';
853                 $id_str = $my_id . '.' . mt_rand(1000,9999);
854
855                 $prv_key = trim($r[0]['prvkey']);
856                 $pub_key = trim($r[0]['pubkey']);
857                 $dplx = intval($r[0]['duplex']);
858
859                 if((($dplx) && (strlen($prv_key))) || ((strlen($prv_key)) && (!(strlen($pub_key))))) {
860                         openssl_private_encrypt($hash,$challenge,$prv_key);
861                         openssl_private_encrypt($id_str,$encrypted_id,$prv_key);
862                 }
863                 elseif(strlen($pub_key)) {
864                         openssl_public_encrypt($hash,$challenge,$pub_key);
865                         openssl_public_encrypt($id_str,$encrypted_id,$pub_key);
866                 }
867                 else
868                         $status = 1;
869
870                 $challenge    = bin2hex($challenge);
871                 $encrypted_id = bin2hex($encrypted_id);
872
873                 $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
874
875                 $rino_enable = get_config('system','rino_encrypt');
876
877                 if(! $rino_enable)
878                         $rino = 0;
879
880
881                 header("Content-type: text/xml");
882
883                 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" 
884                         . '<dfrn_notify>' . "\r\n"
885                         . "\t" . '<status>' . $status . '</status>' . "\r\n"
886                         . "\t" . '<dfrn_version>' . DFRN_PROTOCOL_VERSION . '</dfrn_version>' . "\r\n"
887                         . "\t" . '<rino>' . $rino . '</rino>' . "\r\n" 
888                         . "\t" . '<dfrn_id>' . $encrypted_id . '</dfrn_id>' . "\r\n" 
889                         . "\t" . '<challenge>' . $challenge . '</challenge>' . "\r\n"
890                         . '</dfrn_notify>' . "\r\n" ;
891
892                 killme();
893         }
894
895 }