]> git.mxchange.org Git - friendica.git/blob - mod/dfrn_notify.php
d7166f6aec7fc5fe455b19d2001315884b8abde2
[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         logger('dfrn_notify: feed item count = ' . $feed->get_item_quantity());
154
155         foreach($feed->get_items() as $item) {
156
157                 $deleted = false;
158
159                 $rawdelete = $item->get_item_tags( NAMESPACE_TOMB , 'deleted-entry');
160                 if(isset($rawdelete[0]['attribs']['']['ref'])) {
161                         $uri = $rawthread[0]['attribs']['']['ref'];
162                         $deleted = true;
163                         if(isset($rawdelete[0]['attribs']['']['when'])) {
164                                 $when = $rawthread[0]['attribs']['']['when'];
165                                 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
166                         }
167                         else
168                                 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
169                 }
170                 if($deleted) {
171                         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
172                                 dbesc($uri),
173                                 intval($importer['importer_uid'])
174                         );
175                         if(count($r)) {
176                                 $item = $r[0];
177                                 if($item['uri'] == $item['parent-uri']) {
178                                         $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
179                                                 WHERE `parent-uri` = '%s' AND `uid` = %d",
180                                                 dbesc($when),
181                                                 dbesc(datetime_convert()),
182                                                 dbesc($item['uri']),
183                                                 intval($importer['importer_uid'])
184                                         );
185                                 }
186                                 else {
187                                         $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' 
188                                                 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
189                                                 dbesc($when),
190                                                 dbesc(datetime_convert()),
191                                                 dbesc($uri),
192                                                 intval($importer['importer_uid'])
193                                         );
194                                         if($item['last-child']) {
195                                                 // ensure that last-child is set in case the comment that had it just got wiped.
196                                                 $q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
197                                                         dbesc(datetime_convert()),
198                                                         dbesc($item['parent-uri']),
199                                                         intval($item['uid'])
200                                                 );
201                                                 // who is the last child now? 
202                                                 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
203                                                         ORDER BY `created` DESC LIMIT 1",
204                                                                 dbesc($item['parent-uri']),
205                                                                 intval($importer['importer_uid'])
206                                                 );
207                                                 if(count($r)) {
208                                                         q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
209                                                                 intval($r[0]['id'])
210                                                         );
211                                                 }       
212                                         }
213                                 }
214                         }       
215                         continue;
216                 }
217
218                 $is_reply = false;              
219                 $item_id = $item->get_id();
220                 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
221                 if(isset($rawthread[0]['attribs']['']['ref'])) {
222                         $is_reply = true;
223                         $parent_uri = $rawthread[0]['attribs']['']['ref'];
224                 }
225
226                 if($is_reply) {
227                         if($feed->get_item_quantity() == 1) {
228                                 logger('dfrn_notify: received remote comment');
229                                 // remote reply to our post. Import and then notify everybody else.
230                                 $datarray = get_atom_elements($feed,$item);
231                                 $datarray['type'] = 'remote-comment';
232                                 $datarray['wall'] = 1;
233                                 $datarray['parent-uri'] = $parent_uri;
234                                 $datarray['uid'] = $importer['importer_uid'];
235                                 $datarray['contact-id'] = $importer['id'];
236                                 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
237                                         $datarray['type'] = 'activity';
238                                         $datarray['gravity'] = GRAVITY_LIKE;
239                                 }
240                                 $posted_id = item_store($datarray);
241
242                                 if($posted_id) {
243                                         $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
244                                                 intval($posted_id),
245                                                 intval($importer['importer_uid'])
246                                         );
247                                         if(count($r)) {
248                                                 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
249                                                         dbesc(datetime_convert()),
250                                                         intval($importer['importer_uid']),
251                                                         intval($r[0]['parent'])
252                                                 );
253                                         }
254                                         $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
255                                                         dbesc(datetime_convert()),
256                                                         intval($importer['importer_uid']),
257                                                         intval($posted_id)
258                                         );
259
260                                         $php_path = ((strlen($a->config['php_path'])) ? $a->config['php_path'] : 'php');
261
262                                         proc_close(proc_open("\"$php_path\" \"include/notifier.php\" \"comment-import\" \"$posted_id\" &", 
263                                                 array(),$foo));
264
265                                         if(($importer['notify-flags'] & NOTIFY_COMMENT) && (! $importer['self'])) {
266                                                 require_once('bbcode.php');
267                                                 $from = stripslashes($datarray['author-name']);
268                                                 $tpl = load_view_file('view/cmnt_received_eml.tpl');                    
269                                                 $email_tpl = replace_macros($tpl, array(
270                                                         '$sitename' => $a->config['sitename'],
271                                                         '$siteurl' =>  $a->get_baseurl(),
272                                                         '$username' => $importer['username'],
273                                                         '$email' => $importer['email'],
274                                                         '$display' => $a->get_baseurl() . '/display/' . $posted_id, 
275                                                         '$from' => $from,
276                                                         '$body' => strip_tags(bbcode(stripslashes($datarray['body'])))
277                                                 ));
278         
279                                                 $res = mail($importer['email'], $from . t(" commented on your item at ") . $a->config['sitename'],
280                                                         $email_tpl,t("From: Administrator@") . $a->get_hostname() );
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 }