]> git.mxchange.org Git - friendica.git/blob - mod/dfrn_notify.php
send unfollow before removing ostatus contact
[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['seen'] = 0;
109                 $msg['replied'] = 0;
110                 $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
111                 $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
112                 $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
113                 
114                 dbesc_array($msg);
115
116                 $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg)) 
117                         . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
118
119                 // send email notification if requested.
120
121                 require_once('bbcode.php');
122                 if($importer['notify-flags'] & NOTIFY_MAIL) {
123
124                         $body = html_entity_decode(strip_tags(bbcode(stripslashes($msg['body']))),ENT_QUOTES,'UTF-8');
125
126                         if(function_exists('quoted_printable_encode'))
127                                 $body = quoted_printable_encode($body);
128                         else
129                                 $body = qp($body);
130
131                         $tpl = load_view_file('view/mail_received_eml.tpl');                    
132                         $email_tpl = replace_macros($tpl, array(
133                                 '$sitename' => $a->config['sitename'],
134                                 '$siteurl' =>  $a->get_baseurl(),
135                                 '$username' => $importer['username'],
136                                 '$email' => $importer['email'],
137                                 '$from' => $msg['from-name'],
138                                 '$title' => stripslashes($msg['title']),
139                                 '$body' => $body
140                         ));
141
142                         $res = mail($importer['email'], t('New mail received at ') . $a->config['sitename'],
143                                 $email_tpl, 'From: ' . t('Administrator') . '@' . $a->get_hostname() . "\r\n"
144                                         . 'MIME-Version: 1.0' . "\r\n"
145                                         . 'Content-type: text/plain; charset=UTF-8' . "\r\n" 
146                                         . 'Content-transfer-encoding: quoted-printable' . "\r\n"
147                         );
148                 }
149                 xml_status(0);
150                 // NOTREACHED
151         }       
152
153         foreach($feed->get_items() as $item) {
154
155                 $deleted = false;
156
157                 $rawdelete = $item->get_item_tags( NAMESPACE_TOMB , 'deleted-entry');
158                 if(isset($rawdelete[0]['attribs']['']['ref'])) {
159                         $uri = $rawthread[0]['attribs']['']['ref'];
160                         $deleted = true;
161                         if(isset($rawdelete[0]['attribs']['']['when'])) {
162                                 $when = $rawthread[0]['attribs']['']['when'];
163                                 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
164                         }
165                         else
166                                 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
167                 }
168                 if($deleted) {
169                         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
170                                 dbesc($uri),
171                                 intval($importer['importer_uid'])
172                         );
173                         if(count($r)) {
174                                 $item = $r[0];
175                                 if($item['uri'] == $item['parent-uri']) {
176                                         $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
177                                                 WHERE `parent-uri` = '%s' AND `uid` = %d",
178                                                 dbesc($when),
179                                                 dbesc(datetime_convert()),
180                                                 dbesc($item['uri']),
181                                                 intval($importer['importer_uid'])
182                                         );
183                                 }
184                                 else {
185                                         $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' 
186                                                 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
187                                                 dbesc($when),
188                                                 dbesc(datetime_convert()),
189                                                 dbesc($uri),
190                                                 intval($importer['importer_uid'])
191                                         );
192                                         if($item['last-child']) {
193                                                 // ensure that last-child is set in case the comment that had it just got wiped.
194                                                 $q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
195                                                         dbesc(datetime_convert()),
196                                                         dbesc($item['parent-uri']),
197                                                         intval($item['uid'])
198                                                 );
199                                                 // who is the last child now? 
200                                                 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
201                                                         ORDER BY `created` DESC LIMIT 1",
202                                                                 dbesc($item['parent-uri']),
203                                                                 intval($importer['importer_uid'])
204                                                 );
205                                                 if(count($r)) {
206                                                         q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
207                                                                 intval($r[0]['id'])
208                                                         );
209                                                 }       
210                                         }
211                                 }
212                         }       
213                         continue;
214                 }
215
216                 $is_reply = false;              
217                 $item_id = $item->get_id();
218                 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
219                 if(isset($rawthread[0]['attribs']['']['ref'])) {
220                         $is_reply = true;
221                         $parent_uri = $rawthread[0]['attribs']['']['ref'];
222                 }
223
224                 if($is_reply) {
225                         if($feed->get_item_quantity() == 1) {
226                                 // remote reply to our post. Import and then notify everybody else.
227                                 $datarray = get_atom_elements($feed,$item);
228                                 $datarray['type'] = 'remote-comment';
229                                 $datarray['wall'] = 1;
230                                 $datarray['parent-uri'] = $parent_uri;
231                                 $datarray['uid'] = $importer['importer_uid'];
232                                 $datarray['contact-id'] = $importer['id'];
233                                 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
234                                         $datarray['type'] = 'activity';
235                                         $datarray['gravity'] = GRAVITY_LIKE;
236                                 }
237                                 $posted_id = item_store($datarray);
238
239                                 if($posted_id) {
240                                         $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
241                                                 intval($posted_id),
242                                                 intval($importer['importer_uid'])
243                                         );
244                                         if(count($r)) {
245                                                 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
246                                                         dbesc(datetime_convert()),
247                                                         intval($importer['importer_uid']),
248                                                         intval($r[0]['parent'])
249                                                 );
250                                         }
251                                         $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
252                                                         dbesc(datetime_convert()),
253                                                         intval($importer['importer_uid']),
254                                                         intval($posted_id)
255                                         );
256
257                                         if($datarray['type'] == 'remote-comment') {
258                                                 $php_path = ((strlen($a->config['php_path'])) ? $a->config['php_path'] : 'php');
259
260                                                 proc_close(proc_open("\"$php_path\" \"include/notifier.php\" \"comment-import\" \"$posted_id\" &", 
261                                                         array(),$foo));
262
263                                                 if(($importer['notify-flags'] & NOTIFY_COMMENT) && (! $importer['self'])) {
264                                                         require_once('bbcode.php');
265                                                         $from = stripslashes($datarray['author-name']);
266                                                         $tpl = load_view_file('view/cmnt_received_eml.tpl');                    
267                                                         $email_tpl = replace_macros($tpl, array(
268                                                                 '$sitename' => $a->config['sitename'],
269                                                                 '$siteurl' =>  $a->get_baseurl(),
270                                                                 '$username' => $importer['username'],
271                                                                 '$email' => $importer['email'],
272                                                                 '$display' => $a->get_baseurl() . '/display/' . $posted_id, 
273                                                                 '$from' => $from,
274                                                         '$body' => strip_tags(bbcode(stripslashes($datarray['body'])))
275                                                         ));
276         
277                                                         $res = mail($importer['email'], $from . t(" commented on your item at ") . $a->config['sitename'],
278                                                                 $email_tpl,t("From: Administrator@") . $a->get_hostname() );
279                                                 }
280                                         }
281                                 }
282                                 xml_status(0);
283                                 // NOTREACHED
284
285                         }
286                         else {
287                                 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
288
289                                 $item_id = $item->get_id();
290
291                                 $r = q("SELECT `uid`, `last-child`, `edited` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
292                                         dbesc($item_id),
293                                         intval($importer['importer_uid'])
294                                 );
295                                 // FIXME update content if 'updated' changes
296                                 if(count($r)) {
297                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
298                                         if($allow && $allow[0]['data'] != $r[0]['last-child']) {
299                                                 $r = q("UPDATE `item` SET `last-child` = %d, `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
300                                                         intval($allow[0]['data']),
301                                                         dbesc(datetime_convert()),
302                                                         dbesc($item_id),
303                                                         intval($importer['importer_uid'])
304                                                 );
305                                         }
306                                         continue;
307                                 }
308                                 $datarray = get_atom_elements($feed,$item);
309                                 $datarray['parent-uri'] = $parent_uri;
310                                 $datarray['uid'] = $importer['importer_uid'];
311                                 $datarray['contact-id'] = $importer['id'];
312                                 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
313                                         $datarray['type'] = 'activity';
314                                         $datarray['gravity'] = GRAVITY_LIKE;
315                                 }
316
317                                 $r = item_store($datarray);
318
319                                 // find out if our user is involved in this conversation and wants to be notified.
320                         
321                                 if(($datarray['type'] != 'activity') && ($importer['notify-flags'] & NOTIFY_COMMENT)) {
322
323                                         $myconv = q("SELECT `author-link` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d",
324                                                 dbesc($parent_uri),
325                                                 intval($importer['importer_uid'])
326                                         );
327                                         if(count($myconv)) {
328                                                 foreach($myconv as $conv) {
329                                                         if($conv['author-link'] != $importer['url'])
330                                                                 continue;
331                                                         require_once('bbcode.php');
332                                                         $from = stripslashes($datarray['author-name']);
333                                                         $tpl = load_view_file('view/cmnt_received_eml.tpl');                    
334                                                         $email_tpl = replace_macros($tpl, array(
335                                                                 '$sitename' => $a->config['sitename'],
336                                                                 '$siteurl' =>  $a->get_baseurl(),
337                                                                 '$username' => $importer['username'],
338                                                                 '$email' => $importer['email'],
339                                                                 '$from' => $from,
340                                                                 '$display' => $a->get_baseurl() . '/display' . $r,
341                                                                 '$body' => strip_tags(bbcode(stripslashes($datarray['body'])))
342                                                         ));
343
344                                                         $res = mail($importer['email'], $from . t(" commented on an item at ") 
345                                                                 . $a->config['sitename'],
346                                                                 $email_tpl,t("From: Administrator@") . $a->get_hostname() );
347                                                         break;
348                                                 }
349                                         }
350                                 }
351                                 continue;
352                         }
353                 }
354                 else {
355                         // Head post of a conversation. Have we seen it? If not, import it.
356
357                         $item_id = $item->get_id();
358                         $r = q("SELECT `uid`, `last-child`, `edited` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
359                                 dbesc($item_id),
360                                 intval($importer['importer_uid'])
361                         );
362                         if(count($r)) {
363                                 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
364                                 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
365                                         $r = q("UPDATE `item` SET `last-child` = %d, `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
366                                                 intval($allow[0]['data']),
367                                                 dbesc(datetime_convert()),
368                                                 dbesc($item_id),
369                                                 intval($importer['importer_uid'])
370                                         );
371                                 }
372                                 continue;
373                         }
374
375
376                         $datarray = get_atom_elements($feed,$item);
377                         $datarray['parent-uri'] = $item_id;
378                         $datarray['uid'] = $importer['importer_uid'];
379                         $datarray['contact-id'] = $importer['id'];
380                         $r = item_store($datarray);
381                         continue;
382                 }
383         }
384
385         xml_status(0);
386         // NOTREACHED
387
388 }
389
390
391 function dfrn_notify_content(&$a) {
392
393         if(x($_GET,'dfrn_id')) {
394
395                 // initial communication from external contact, $direction is their direction.
396                 // If this is a duplex communication, ours will be the opposite.
397
398                 $dfrn_id = notags(trim($_GET['dfrn_id']));
399                 $dfrn_version = (float) $_GET['dfrn_version'];
400
401                 logger('dfrn_notify: new notification dfrn_id=' . $dfrn_id);
402
403                 $direction = (-1);
404                 if(strpos($dfrn_id,':') == 1) {
405                         $direction = intval(substr($dfrn_id,0,1));
406                         $dfrn_id = substr($dfrn_id,2);
407                 }
408
409                 $hash = random_string();
410
411                 $status = 0;
412
413                 $r = q("DELETE FROM `challenge` WHERE `expire` < " . intval(time()));
414
415                 $r = q("INSERT INTO `challenge` ( `challenge`, `dfrn-id`, `expire` )
416                         VALUES( '%s', '%s', '%s') ",
417                         dbesc($hash),
418                         dbesc($dfrn_id),
419                         intval(time() + 60 )
420                 );
421
422
423                 $sql_extra = '';
424                 switch($direction) {
425                         case (-1):
426                                 $sql_extra = sprintf(" AND ( `issued-id` = '%s' OR `dfrn-id` = '%s' ) ", dbesc($dfrn_id), dbesc($dfrn_id));
427                                 $my_id = $dfrn_id;
428                                 break;
429                         case 0:
430                                 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
431                                 $my_id = '1:' . $dfrn_id;
432                                 break;
433                         case 1:
434                                 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
435                                 $my_id = '0:' . $dfrn_id;
436                                 break;
437                         default:
438                                 $status = 1;
439                                 break; // NOTREACHED
440                 }
441
442                 $r = q("SELECT `contact`.*, `user`.`nickname` FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid` 
443                                 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0 AND `user`.`nickname` = '%s' $sql_extra LIMIT 1",
444                                 dbesc($a->argv[1])
445                 );
446
447                 if(! count($r))
448                         $status = 1;
449
450                 $challenge = '';
451                 $encrypted_id = '';
452                 $id_str = $my_id . '.' . mt_rand(1000,9999);
453
454                 if((($r[0]['duplex']) && strlen($r[0]['pubkey'])) || (! strlen($r[0]['prvkey']))) {
455                         openssl_public_encrypt($hash,$challenge,$r[0]['pubkey']);
456                         openssl_public_encrypt($id_str,$encrypted_id,$r[0]['pubkey']);
457                 }
458                 else {
459                         openssl_private_encrypt($hash,$challenge,$r[0]['prvkey']);
460                         openssl_private_encrypt($id_str,$encrypted_id,$r[0]['prvkey']);
461                 }
462
463                 $challenge    = bin2hex($challenge);
464                 $encrypted_id = bin2hex($encrypted_id);
465
466                 header("Content-type: text/xml");
467
468                 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" 
469                         . '<dfrn_notify>' . "\r\n"
470                         . "\t" . '<status>' . $status . '</status>' . "\r\n"
471                         . "\t" . '<dfrn_version>' . DFRN_PROTOCOL_VERSION . '</dfrn_version>' . "\r\n"
472                         . "\t" . '<dfrn_id>' . $encrypted_id . '</dfrn_id>' . "\r\n" 
473                         . "\t" . '<challenge>' . $challenge . '</challenge>' . "\r\n"
474                         . '</dfrn_notify>' . "\r\n" ;
475
476                 killme();
477         }
478
479 }