]> git.mxchange.org Git - friendica.git/blob - mod/dfrn_notify.php
more logging in dfrn_notify
[friendica.git] / mod / dfrn_notify.php
1 <?php
2
3 require_once('simplepie/simplepie.inc');
4 require_once('include/items.php');
5
6
7 function dfrn_notify_post(&$a) {
8
9         $dfrn_id = notags(trim($_POST['dfrn_id']));
10         $dfrn_version = (float) $_POST['dfrn_version'];
11         $challenge = notags(trim($_POST['challenge']));
12         $data = $_POST['data'];
13
14         $direction = (-1);
15         if(strpos($dfrn_id,':') == 1) {
16                 $direction = intval(substr($dfrn_id,0,1));
17                 $dfrn_id = substr($dfrn_id,2);
18         }
19
20         $r = q("SELECT * FROM `challenge` WHERE `dfrn-id` = '%s' AND `challenge` = '%s' LIMIT 1",
21                 dbesc($dfrn_id),
22                 dbesc($challenge)
23         );
24         if(! count($r)) {
25                 logger('dfrn_notify: could not match challenge to dfrn_id ' . $dfrn_id);
26                 xml_status(3);
27         }
28
29         $r = q("DELETE FROM `challenge` WHERE `dfrn-id` = '%s' AND `challenge` = '%s' LIMIT 1",
30                 dbesc($dfrn_id),
31                 dbesc($challenge)
32         );
33
34         // find the local user who owns this relationship.
35
36         $sql_extra = '';
37         switch($direction) {
38                 case (-1):
39                         $sql_extra = sprintf(" AND ( `issued-id` = '%s' OR `dfrn-id` = '%s' ) ", dbesc($dfrn_id), dbesc($dfrn_id));
40                         break;
41                 case 0:
42                         $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
43                         break;
44                 case 1:
45                         $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
46                         break;
47                 default:
48                         xml_status(3);
49                         break; // NOTREACHED
50         }
51                  
52
53         $r = q("SELECT `contact`.*, `contact`.`uid` AS `importer_uid`, `user`.* FROM `contact` 
54                 LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid` 
55                 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0 
56                 AND `user`.`nickname` = '%s' $sql_extra LIMIT 1",
57                 dbesc($a->argv[1])
58         );
59
60         if(! count($r)) {
61                 logger('dfrn_notify: contact not found for dfrn_id ' . $dfrn_id);
62                 xml_status(3);
63                 //NOTREACHED
64         }
65
66         $importer = $r[0];
67
68         logger('dfrn_notify: received notify from ' . $importer['name'] . ' for ' . $importer['username']);
69         logger('dfrn_notify: data: ' . $data, LOGGER_DATA);
70
71         if($importer['readonly']) {
72                 // We aren't receiving stuff from this person. But we will quietly ignore them
73                 // rather than a blatant "go away" message.
74                 logger('dfrn_notify: ignoring');
75                 xml_status(0);
76                 //NOTREACHED
77         }
78
79         // Consume notification feed. This may differ from consuming a public feed in several ways
80         // - might contain email
81         // - might contain remote followup to our message
82         //              - in which case we need to accept it and then notify other conversants
83         // - we may need to send various email notifications
84
85         $feed = new SimplePie();
86         $feed->set_raw_data($data);
87         $feed->enable_order_by_date(false);
88         $feed->init();
89
90         $ismail = false;
91
92         $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
93         if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
94
95                 logger('dfrn_notify: private message received');
96
97                 $ismail = true;
98                 $base = $rawmail[0]['child'][NAMESPACE_DFRN];
99
100                 $msg = array();
101                 $msg['uid'] = $importer['importer_uid'];
102                 $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
103                 $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
104                 $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
105                 $msg['contact-id'] = $importer['id'];
106                 $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
107                 $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
108                 $msg['delivered'] = 1;
109                 $msg['seen'] = 0;
110                 $msg['replied'] = 0;
111                 $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
112                 $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
113                 $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
114                 
115                 dbesc_array($msg);
116
117                 $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg)) 
118                         . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
119
120                 // send email notification if requested.
121
122                 require_once('bbcode.php');
123                 if($importer['notify-flags'] & NOTIFY_MAIL) {
124
125                         $body = html_entity_decode(strip_tags(bbcode(stripslashes($msg['body']))),ENT_QUOTES,'UTF-8');
126
127                         if(function_exists('quoted_printable_encode'))
128                                 $body = quoted_printable_encode($body);
129                         else
130                                 $body = qp($body);
131
132                         $tpl = load_view_file('view/mail_received_eml.tpl');                    
133                         $email_tpl = replace_macros($tpl, array(
134                                 '$sitename' => $a->config['sitename'],
135                                 '$siteurl' =>  $a->get_baseurl(),
136                                 '$username' => $importer['username'],
137                                 '$email' => $importer['email'],
138                                 '$from' => $msg['from-name'],
139                                 '$title' => stripslashes($msg['title']),
140                                 '$body' => $body
141                         ));
142
143                         $res = mail($importer['email'], t('New mail received at ') . $a->config['sitename'],
144                                 $email_tpl, 'From: ' . t('Administrator') . '@' . $a->get_hostname() . "\r\n"
145                                         . 'MIME-Version: 1.0' . "\r\n"
146                                         . 'Content-type: text/plain; charset=UTF-8' . "\r\n" 
147                                         . 'Content-transfer-encoding: quoted-printable' . "\r\n"
148                         );
149                 }
150                 xml_status(0);
151                 // NOTREACHED
152         }       
153
154         foreach($feed->get_items() as $item) {
155
156                 $deleted = false;
157
158                 $rawdelete = $item->get_item_tags( NAMESPACE_TOMB , 'deleted-entry');
159                 if(isset($rawdelete[0]['attribs']['']['ref'])) {
160                         $uri = $rawthread[0]['attribs']['']['ref'];
161                         $deleted = true;
162                         if(isset($rawdelete[0]['attribs']['']['when'])) {
163                                 $when = $rawthread[0]['attribs']['']['when'];
164                                 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
165                         }
166                         else
167                                 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
168                 }
169                 if($deleted) {
170                         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
171                                 dbesc($uri),
172                                 intval($importer['importer_uid'])
173                         );
174                         if(count($r)) {
175                                 $item = $r[0];
176                                 if($item['uri'] == $item['parent-uri']) {
177                                         $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
178                                                 WHERE `parent-uri` = '%s' AND `uid` = %d",
179                                                 dbesc($when),
180                                                 dbesc(datetime_convert()),
181                                                 dbesc($item['uri']),
182                                                 intval($importer['importer_uid'])
183                                         );
184                                 }
185                                 else {
186                                         $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' 
187                                                 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
188                                                 dbesc($when),
189                                                 dbesc(datetime_convert()),
190                                                 dbesc($uri),
191                                                 intval($importer['importer_uid'])
192                                         );
193                                         if($item['last-child']) {
194                                                 // ensure that last-child is set in case the comment that had it just got wiped.
195                                                 $q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
196                                                         dbesc(datetime_convert()),
197                                                         dbesc($item['parent-uri']),
198                                                         intval($item['uid'])
199                                                 );
200                                                 // who is the last child now? 
201                                                 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
202                                                         ORDER BY `created` DESC LIMIT 1",
203                                                                 dbesc($item['parent-uri']),
204                                                                 intval($importer['importer_uid'])
205                                                 );
206                                                 if(count($r)) {
207                                                         q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
208                                                                 intval($r[0]['id'])
209                                                         );
210                                                 }       
211                                         }
212                                 }
213                         }       
214                         continue;
215                 }
216
217                 $is_reply = false;              
218                 $item_id = $item->get_id();
219                 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
220                 if(isset($rawthread[0]['attribs']['']['ref'])) {
221                         $is_reply = true;
222                         $parent_uri = $rawthread[0]['attribs']['']['ref'];
223                 }
224
225                 if($is_reply) {
226                         if($feed->get_item_quantity() == 1) {
227                                 // remote reply to our post. Import and then notify everybody else.
228                                 $datarray = get_atom_elements($feed,$item);
229                                 $datarray['type'] = 'remote-comment';
230                                 $datarray['wall'] = 1;
231                                 $datarray['parent-uri'] = $parent_uri;
232                                 $datarray['uid'] = $importer['importer_uid'];
233                                 $datarray['contact-id'] = $importer['id'];
234                                 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
235                                         $datarray['type'] = 'activity';
236                                         $datarray['gravity'] = GRAVITY_LIKE;
237                                 }
238                                 $posted_id = item_store($datarray);
239
240                                 if($posted_id) {
241                                         $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
242                                                 intval($posted_id),
243                                                 intval($importer['importer_uid'])
244                                         );
245                                         if(count($r)) {
246                                                 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
247                                                         dbesc(datetime_convert()),
248                                                         intval($importer['importer_uid']),
249                                                         intval($r[0]['parent'])
250                                                 );
251                                         }
252                                         $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
253                                                         dbesc(datetime_convert()),
254                                                         intval($importer['importer_uid']),
255                                                         intval($posted_id)
256                                         );
257
258                                         if($datarray['type'] == 'remote-comment') {
259                                                 $php_path = ((strlen($a->config['php_path'])) ? $a->config['php_path'] : 'php');
260
261                                                 proc_close(proc_open("\"$php_path\" \"include/notifier.php\" \"comment-import\" \"$posted_id\" &", 
262                                                         array(),$foo));
263
264                                                 if(($importer['notify-flags'] & NOTIFY_COMMENT) && (! $importer['self'])) {
265                                                         require_once('bbcode.php');
266                                                         $from = stripslashes($datarray['author-name']);
267                                                         $tpl = load_view_file('view/cmnt_received_eml.tpl');                    
268                                                         $email_tpl = replace_macros($tpl, array(
269                                                                 '$sitename' => $a->config['sitename'],
270                                                                 '$siteurl' =>  $a->get_baseurl(),
271                                                                 '$username' => $importer['username'],
272                                                                 '$email' => $importer['email'],
273                                                                 '$display' => $a->get_baseurl() . '/display/' . $posted_id, 
274                                                                 '$from' => $from,
275                                                         '$body' => strip_tags(bbcode(stripslashes($datarray['body'])))
276                                                         ));
277         
278                                                         $res = mail($importer['email'], $from . t(" commented on your item at ") . $a->config['sitename'],
279                                                                 $email_tpl,t("From: Administrator@") . $a->get_hostname() );
280                                                 }
281                                         }
282                                 }
283                                 xml_status(0);
284                                 // NOTREACHED
285
286                         }
287                         else {
288                                 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
289
290                                 $item_id = $item->get_id();
291
292                                 $r = q("SELECT `uid`, `last-child`, `edited` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
293                                         dbesc($item_id),
294                                         intval($importer['importer_uid'])
295                                 );
296                                 // FIXME update content if 'updated' changes
297                                 if(count($r)) {
298                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
299                                         if($allow && $allow[0]['data'] != $r[0]['last-child']) {
300                                                 $r = q("UPDATE `item` SET `last-child` = %d, `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
301                                                         intval($allow[0]['data']),
302                                                         dbesc(datetime_convert()),
303                                                         dbesc($item_id),
304                                                         intval($importer['importer_uid'])
305                                                 );
306                                         }
307                                         continue;
308                                 }
309                                 $datarray = get_atom_elements($feed,$item);
310                                 $datarray['parent-uri'] = $parent_uri;
311                                 $datarray['uid'] = $importer['importer_uid'];
312                                 $datarray['contact-id'] = $importer['id'];
313                                 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
314                                         $datarray['type'] = 'activity';
315                                         $datarray['gravity'] = GRAVITY_LIKE;
316                                 }
317
318                                 $r = item_store($datarray);
319
320                                 // find out if our user is involved in this conversation and wants to be notified.
321                         
322                                 if(($datarray['type'] != 'activity') && ($importer['notify-flags'] & NOTIFY_COMMENT)) {
323
324                                         $myconv = q("SELECT `author-link` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d",
325                                                 dbesc($parent_uri),
326                                                 intval($importer['importer_uid'])
327                                         );
328                                         if(count($myconv)) {
329                                                 foreach($myconv as $conv) {
330                                                         if($conv['author-link'] != $importer['url'])
331                                                                 continue;
332                                                         require_once('bbcode.php');
333                                                         $from = stripslashes($datarray['author-name']);
334                                                         $tpl = load_view_file('view/cmnt_received_eml.tpl');                    
335                                                         $email_tpl = replace_macros($tpl, array(
336                                                                 '$sitename' => $a->config['sitename'],
337                                                                 '$siteurl' =>  $a->get_baseurl(),
338                                                                 '$username' => $importer['username'],
339                                                                 '$email' => $importer['email'],
340                                                                 '$from' => $from,
341                                                                 '$display' => $a->get_baseurl() . '/display' . $r,
342                                                                 '$body' => strip_tags(bbcode(stripslashes($datarray['body'])))
343                                                         ));
344
345                                                         $res = mail($importer['email'], $from . t(" commented on an item at ") 
346                                                                 . $a->config['sitename'],
347                                                                 $email_tpl,t("From: Administrator@") . $a->get_hostname() );
348                                                         break;
349                                                 }
350                                         }
351                                 }
352                                 continue;
353                         }
354                 }
355                 else {
356                         // Head post of a conversation. Have we seen it? If not, import it.
357
358                         $item_id = $item->get_id();
359                         $r = q("SELECT `uid`, `last-child`, `edited` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
360                                 dbesc($item_id),
361                                 intval($importer['importer_uid'])
362                         );
363                         if(count($r)) {
364                                 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
365                                 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
366                                         $r = q("UPDATE `item` SET `last-child` = %d, `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
367                                                 intval($allow[0]['data']),
368                                                 dbesc(datetime_convert()),
369                                                 dbesc($item_id),
370                                                 intval($importer['importer_uid'])
371                                         );
372                                 }
373                                 continue;
374                         }
375
376
377                         $datarray = get_atom_elements($feed,$item);
378                         $datarray['parent-uri'] = $item_id;
379                         $datarray['uid'] = $importer['importer_uid'];
380                         $datarray['contact-id'] = $importer['id'];
381                         $r = item_store($datarray);
382                         continue;
383                 }
384         }
385
386         xml_status(0);
387         // NOTREACHED
388
389 }
390
391
392 function dfrn_notify_content(&$a) {
393
394         if(x($_GET,'dfrn_id')) {
395
396                 // initial communication from external contact, $direction is their direction.
397                 // If this is a duplex communication, ours will be the opposite.
398
399                 $dfrn_id = notags(trim($_GET['dfrn_id']));
400                 $dfrn_version = (float) $_GET['dfrn_version'];
401
402                 logger('dfrn_notify: new notification dfrn_id=' . $dfrn_id);
403
404                 $direction = (-1);
405                 if(strpos($dfrn_id,':') == 1) {
406                         $direction = intval(substr($dfrn_id,0,1));
407                         $dfrn_id = substr($dfrn_id,2);
408                 }
409
410                 $hash = random_string();
411
412                 $status = 0;
413
414                 $r = q("DELETE FROM `challenge` WHERE `expire` < " . intval(time()));
415
416                 $r = q("INSERT INTO `challenge` ( `challenge`, `dfrn-id`, `expire` )
417                         VALUES( '%s', '%s', '%s') ",
418                         dbesc($hash),
419                         dbesc($dfrn_id),
420                         intval(time() + 60 )
421                 );
422
423
424                 $sql_extra = '';
425                 switch($direction) {
426                         case (-1):
427                                 $sql_extra = sprintf(" AND ( `issued-id` = '%s' OR `dfrn-id` = '%s' ) ", dbesc($dfrn_id), dbesc($dfrn_id));
428                                 $my_id = $dfrn_id;
429                                 break;
430                         case 0:
431                                 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
432                                 $my_id = '1:' . $dfrn_id;
433                                 break;
434                         case 1:
435                                 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
436                                 $my_id = '0:' . $dfrn_id;
437                                 break;
438                         default:
439                                 $status = 1;
440                                 break; // NOTREACHED
441                 }
442
443                 $r = q("SELECT `contact`.*, `user`.`nickname` FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid` 
444                                 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0 AND `user`.`nickname` = '%s' $sql_extra LIMIT 1",
445                                 dbesc($a->argv[1])
446                 );
447
448                 if(! count($r))
449                         $status = 1;
450
451                 $challenge = '';
452                 $encrypted_id = '';
453                 $id_str = $my_id . '.' . mt_rand(1000,9999);
454
455                 if((($r[0]['duplex']) && strlen($r[0]['pubkey'])) || (! strlen($r[0]['prvkey']))) {
456                         openssl_public_encrypt($hash,$challenge,$r[0]['pubkey']);
457                         openssl_public_encrypt($id_str,$encrypted_id,$r[0]['pubkey']);
458                 }
459                 else {
460                         openssl_private_encrypt($hash,$challenge,$r[0]['prvkey']);
461                         openssl_private_encrypt($id_str,$encrypted_id,$r[0]['prvkey']);
462                 }
463
464                 $challenge    = bin2hex($challenge);
465                 $encrypted_id = bin2hex($encrypted_id);
466
467                 header("Content-type: text/xml");
468
469                 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" 
470                         . '<dfrn_notify>' . "\r\n"
471                         . "\t" . '<status>' . $status . '</status>' . "\r\n"
472                         . "\t" . '<dfrn_version>' . DFRN_PROTOCOL_VERSION . '</dfrn_version>' . "\r\n"
473                         . "\t" . '<dfrn_id>' . $encrypted_id . '</dfrn_id>' . "\r\n" 
474                         . "\t" . '<challenge>' . $challenge . '</challenge>' . "\r\n"
475                         . '</dfrn_notify>' . "\r\n" ;
476
477                 killme();
478         }
479
480 }