]> git.mxchange.org Git - friendica.git/blob - include/delivery.php
Merge remote branch 'upstream/master'
[friendica.git] / include / delivery.php
1 <?php
2 require_once("boot.php");
3 require_once('include/queue_fn.php');
4 require_once('include/html2plain.php');
5
6 function delivery_run($argv, $argc){
7         global $a, $db;
8
9         if(is_null($a)){
10                 $a = new App;
11         }
12
13         if(is_null($db)) {
14                 @include(".htconfig.php");
15                 require_once("dba.php");
16                 $db = new dba($db_host, $db_user, $db_pass, $db_data);
17                         unset($db_host, $db_user, $db_pass, $db_data);
18         }
19
20         require_once("session.php");
21         require_once("datetime.php");
22         require_once('include/items.php');
23         require_once('include/bbcode.php');
24         require_once('include/diaspora.php');
25         require_once('include/email.php');
26
27         load_config('config');
28         load_config('system');
29
30         load_hooks();
31
32         if($argc < 3)
33                 return;
34
35         $a->set_baseurl(get_config('system','url'));
36
37         logger('delivery: invoked: ' . print_r($argv,true), LOGGER_DEBUG);
38
39         $cmd        = $argv[1];
40         $item_id    = intval($argv[2]);
41         $contact_id = intval($argv[3]);
42
43         // Some other process may have delivered this item already.
44
45         $r = q("select * from deliverq where cmd = '%s' and item = %d and contact = %d limit 1",
46                 dbesc($cmd),
47                 dbesc($item_id),
48                 dbesc($contact_id)
49         );
50         if(! count($r)) {
51                 return;
52         }       
53
54         // It's ours to deliver. Remove it from the queue.
55
56         q("delete from deliverq where cmd = '%s' and item = %d and contact = %d limit 1",
57                 dbesc($cmd),
58                 dbesc($item_id),
59                 dbesc($contact_id)
60         );
61
62         if((! $item_id) || (! $contact_id))
63                 return;
64
65         $expire = false;
66         $top_level = false;
67         $recipients = array();
68         $url_recipients = array();
69
70         $normal_mode = true;
71
72         $recipients[] = $contact_id;
73
74         if($cmd === 'expire') {
75                 $normal_mode = false;
76                 $expire = true;
77                 $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1 
78                         AND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 30 MINUTE",
79                         intval($item_id)
80                 );
81                 $uid = $item_id;
82                 $item_id = 0;
83                 if(! count($items))
84                         return;
85         }
86         else {
87
88                 // find ancestors
89                 $r = q("SELECT * FROM `item` WHERE `id` = %d and visible = 1 and moderated = 0 LIMIT 1",
90                         intval($item_id)
91                 );
92
93                 if((! count($r)) || (! intval($r[0]['parent']))) {
94                         return;
95                 }
96
97                 $target_item = $r[0];
98                 $parent_id = intval($r[0]['parent']);
99                 $uid = $r[0]['uid'];
100                 $updated = $r[0]['edited'];
101
102                 if(! $parent_id)
103                         return;
104
105
106                 $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer` 
107                         FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d and visible = 1 and moderated = 0 ORDER BY `id` ASC",
108                         intval($parent_id)
109                 );
110
111                 if(! count($items)) {
112                         return;
113                 }
114
115                 $icontacts = null;
116                 $contacts_arr = array();
117                 foreach($items as $item)
118                         if(! in_array($item['contact-id'],$contacts_arr))
119                                 $contacts_arr[] = intval($item['contact-id']);
120                 if(count($contacts_arr)) {
121                         $str_contacts = implode(',',$contacts_arr); 
122                         $icontacts = q("SELECT * FROM `contact` 
123                                 WHERE `id` IN ( $str_contacts ) "
124                         );
125                 }
126                 if( ! ($icontacts && count($icontacts)))
127                         return;
128
129                 // avoid race condition with deleting entries
130
131                 if($items[0]['deleted']) {
132                         foreach($items as $item)
133                                 $item['deleted'] = 1;
134                 }
135
136                 if((count($items) == 1) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
137                         logger('delivery: top level post');
138                         $top_level = true;
139                 }
140         }
141
142         $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`, 
143                 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`, 
144                 `user`.`page-flags`, `user`.`prvnets`
145                 FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid` 
146                 WHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
147                 intval($uid)
148         );
149
150         if(! count($r))
151                 return;
152
153         $owner = $r[0];
154
155         $walltowall = ((($top_level) && ($owner['id'] != $items[0]['contact-id'])) ? true : false);
156
157         $public_message = true;
158
159         // fill this in with a single salmon slap if applicable
160
161         $slap = '';
162
163         require_once('include/group.php');
164
165         $parent = $items[0];
166
167                 // This is IMPORTANT!!!!
168
169                 // We will only send a "notify owner to relay" or followup message if the referenced post
170                 // originated on our system by virtue of having our hostname somewhere
171                 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
172                 // if $parent['wall'] == 1 we will already have the parent message in our array
173                 // and we will relay the whole lot.
174  
175                 // expire sends an entire group of expire messages and cannot be forwarded.
176                 // However the conversation owner will be a part of the conversation and will 
177                 // be notified during this run.
178                 // Other DFRN conversation members will be alerted during polled updates.
179
180                 // Diaspora members currently are not notified of expirations, and other networks have
181                 // either limited or no ability to process deletions. We should at least fix Diaspora 
182                 // by stringing togther an array of retractions and sending them onward.
183                  
184         
185         $localhost = $a->get_hostname();
186         if(strpos($localhost,':'))
187                 $localhost = substr($localhost,0,strpos($localhost,':'));
188
189                 /**
190                  *
191                  * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes 
192                  * have been known to cause runaway conditions which affected several servers, along with 
193                  * permissions issues. 
194                  *
195                  */
196  
197         if((! $top_level) && ($parent['wall'] == 0) && (! $expire) && (stristr($target_item['uri'],$localhost))) {
198                 logger('relay denied for delivery agent.');
199
200                 /* no relay allowed for direct contact delivery */
201                 return;
202         }
203
204         if((strlen($parent['allow_cid'])) 
205                 || (strlen($parent['allow_gid'])) 
206                 || (strlen($parent['deny_cid'])) 
207                 || (strlen($parent['deny_gid']))) {
208                 $public_message = false; // private recipients, not public
209         }
210
211         $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `blocked` = 0 AND `pending` = 0",
212                 intval($contact_id)
213         );
214
215         if(count($r))
216                 $contact = $r[0];
217         
218         $hubxml = feed_hublinks();
219
220         logger('notifier: slaps: ' . print_r($slaps,true), LOGGER_DATA);
221
222         require_once('include/salmon.php');
223
224         if($contact['self'])
225                 return;
226
227         $deliver_status = 0;
228
229         switch($contact['network']) {
230
231                 case NETWORK_DFRN :
232                         logger('notifier: dfrndelivery: ' . $contact['name']);
233
234                         $feed_template = get_markup_template('atom_feed.tpl');
235                         $mail_template = get_markup_template('atom_mail.tpl');
236
237                         $atom = '';
238
239
240                         $birthday = feed_birthday($owner['uid'],$owner['timezone']);
241
242                         if(strlen($birthday))
243                                 $birthday = '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>';
244
245                         $atom .= replace_macros($feed_template, array(
246                                         '$version'      => xmlify(FRIENDICA_VERSION),
247                                         '$feed_id'      => xmlify($a->get_baseurl() . '/profile/' . $owner['nickname'] ),
248                                         '$feed_title'   => xmlify($owner['name']),
249                                         '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', $updated . '+00:00' , ATOM_TIME)) ,
250                                         '$hub'          => $hubxml,
251                                         '$salmon'       => '',  // private feed, we don't use salmon here
252                                         '$name'         => xmlify($owner['name']),
253                                         '$profile_page' => xmlify($owner['url']),
254                                         '$photo'        => xmlify($owner['photo']),
255                                         '$thumb'        => xmlify($owner['thumb']),
256                                         '$picdate'      => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
257                                         '$uridate'      => xmlify(datetime_convert('UTC','UTC',$owner['uri-date']    . '+00:00' , ATOM_TIME)) ,
258                                         '$namdate'      => xmlify(datetime_convert('UTC','UTC',$owner['name-date']   . '+00:00' , ATOM_TIME)) ,
259                                         '$birthday'     => $birthday
260                         ));
261
262                         foreach($items as $item) {
263                                 if(! $item['parent'])
264                                         continue;
265
266                                 // private emails may be in included in public conversations. Filter them.
267                                 if(($public_message) && $item['private'])
268                                         continue;
269
270                                 $item_contact = get_item_contact($item,$icontacts);
271                                 if(! $item_contact)
272                                         continue;
273
274                                 if($normal_mode) {
275                                         if($item_id == $item['id'] || $item['id'] == $item['parent'])
276                                                 $atom .= atom_entry($item,'text',null,$owner,true);
277                                 }
278                                 else
279                                         $atom .= atom_entry($item,'text',null,$owner,true);
280
281                         }
282
283                         $atom .= '</feed>' . "\r\n";
284
285                         logger('notifier: ' . $atom, LOGGER_DATA);
286                         $basepath =  implode('/', array_slice(explode('/',$contact['url']),0,3));
287
288                         // perform local delivery if we are on the same site
289
290                         if(link_compare($basepath,$a->get_baseurl())) {
291
292                                 $nickname = basename($contact['url']);
293                                 if($contact['issued-id'])
294                                         $sql_extra = sprintf(" AND `dfrn-id` = '%s' ", dbesc($contact['issued-id']));
295                                 else
296                                         $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($contact['dfrn-id']));
297
298                                 $x = q("SELECT  `contact`.*, `contact`.`uid` AS `importer_uid`, 
299                                         `contact`.`pubkey` AS `cpubkey`, 
300                                         `contact`.`prvkey` AS `cprvkey`, 
301                                         `contact`.`thumb` AS `thumb`, 
302                                         `contact`.`url` as `url`,
303                                         `contact`.`name` as `senderName`,
304                                         `user`.* 
305                                         FROM `contact` 
306                                         LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid` 
307                                         WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
308                                         AND `contact`.`network` = '%s' AND `user`.`nickname` = '%s'
309                                         $sql_extra
310                                         AND `user`.`account_expired` = 0 LIMIT 1",
311                                         dbesc(NETWORK_DFRN),
312                                         dbesc($nickname)
313                                 );
314
315                                 if(count($x)) {
316                                         if($owner['page-flags'] == PAGE_COMMUNITY && ! $x[0]['writable']) {
317                                                 q("update contact set writable = 1 where id = %d limit 1",
318                                                         intval($x[0]['id'])
319                                                 );
320                                                 $x[0]['writable'] = 1;
321                                         }
322
323                                         require_once('library/simplepie/simplepie.inc');
324                                         logger('mod-delivery: local delivery');
325                                         local_delivery($x[0],$atom);
326                                         break;
327                                 }
328                         }
329
330                         $deliver_status = dfrn_deliver($owner,$contact,$atom);
331
332                         logger('notifier: dfrn_delivery returns ' . $deliver_status);
333
334                         if($deliver_status == (-1)) {
335                                 logger('notifier: delivery failed: queuing message');
336                                 add_to_queue($contact['id'],NETWORK_DFRN,$atom);
337                         }
338                         break;
339
340                 case NETWORK_OSTATUS :
341
342                         // Do not send to otatus if we are not configured to send to public networks
343                         if($owner['prvnets'])
344                                 break;
345                         if(get_config('system','ostatus_disabled') || get_config('system','dfrn_only'))
346                                 break;
347
348                         // only send salmon if public - e.g. if it's ok to notify
349                         // a public hub, it's ok to send a salmon
350
351                         if(($public_message) && (! $expire)) {
352                                 $slaps = array();
353
354                                 foreach($items as $item) {
355                                         if(! $item['parent'])
356                                                 continue;
357
358                                         // private emails may be in included in public conversations. Filter them.
359                                         if(($public_message) && $item['private'])
360                                                 continue;
361
362                                         $item_contact = get_item_contact($item,$icontacts);
363                                         if(! $item_contact)
364                                                 continue;
365
366                                         if(($top_level) && ($public_message) && ($item['author-link'] === $item['owner-link']) && (! $expire)) 
367                                                 $slaps[] = atom_entry($item,'html',null,$owner,true);
368                                 }
369
370                                 logger('notifier: slapdelivery: ' . $contact['name']);
371                                 foreach($slaps as $slappy) {
372                                         if($contact['notify']) {
373                                                 $deliver_status = slapper($owner,$contact['notify'],$slappy);
374                                                 if($deliver_status == (-1)) {
375                                                         // queue message for redelivery
376                                                         add_to_queue($contact['id'],NETWORK_OSTATUS,$slappy);
377                                                 }
378                                         }
379                                 }
380                         }
381
382                         break;
383
384                 case NETWORK_MAIL :
385                 case NETWORK_MAIL2:
386
387                         if(get_config('system','dfrn_only'))
388                                 break;
389                         // WARNING: does not currently convert to RFC2047 header encodings, etc.
390
391                         $addr = $contact['addr'];
392                         if(! strlen($addr))
393                                 break;
394
395                         if($cmd === 'wall-new' || $cmd === 'comment-new') {
396
397                                 $it = null;
398                                 if($cmd === 'wall-new') 
399                                         $it = $items[0];
400                                 else {
401                                         $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1", 
402                                                 intval($argv[2]),
403                                                 intval($uid)
404                                         );
405                                         if(count($r))
406                                                 $it = $r[0];
407                                 }
408                                 if(! $it)
409                                         break;
410                                         
411
412                                 $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
413                                         intval($uid)
414                                 );
415                                 if(! count($local_user))
416                                         break;
417                                         
418                                 $reply_to = '';
419                                 $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
420                                         intval($uid)
421                                 );
422                                 if($r1 && $r1[0]['reply_to'])
423                                         $reply_to = $r1[0]['reply_to'];
424
425                                 $subject  = (($it['title']) ? email_header_encode($it['title'],'UTF-8') : t("\x28no subject\x29")) ;
426
427                                 // only expose our real email address to true friends
428
429                                 if(($contact['rel'] == CONTACT_IS_FRIEND) && (! $contact['blocked']))
430                                         $headers  = 'From: ' . email_header_encode($local_user[0]['username'],'UTF-8') . ' <' . $local_user[0]['email'] . '>' . "\n";
431                                 else
432                                         $headers  = 'From: ' . email_header_encode($local_user[0]['username'],'UTF-8') . ' <' . t('noreply') . '@' . $a->get_hostname() . '>' . "\n";
433
434                                 if($reply_to)
435                                         $headers .= 'Reply-to: ' . $reply_to . "\n";
436
437                                 // for testing purposes: Collect exported mails
438                                 $file = tempnam("/tmp/friendica/", "mail-out-");
439                                 file_put_contents($file, json_encode($it));
440
441                                 $headers .= 'Message-Id: <' . iri2msgid($it['uri']). '>' . "\n";
442
443                                 //logger("Mail: uri: ".$it['uri']." parent-uri ".$it['parent-uri'], LOGGER_DEBUG);
444                                 //logger("Mail: Data: ".print_r($it, true), LOGGER_DEBUG);
445                                 //logger("Mail: Data: ".print_r($it, true), LOGGER_DATA);
446
447                                 if($it['uri'] !== $it['parent-uri']) {
448                                         $headers .= 'References: <' . iri2msgid($it['parent-uri']) . '>' . "\n";
449                                         if(! strlen($it['title'])) {
450                                                 $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' LIMIT 1",
451                                                         dbesc($it['parent-uri'])
452                                                 );
453                                                 if(count($r)) {
454                                                         $subtitle = $r[0]['title'];
455                                                         if($subtitle) {
456                                                                 if(strncasecmp($subtitle,'RE:',3))
457                                                                         $subject = $subtitle;
458                                                                 else
459                                                                         $subject = 'Re: ' . $subtitle;
460                                                         }
461                                                 }
462                                         }
463                                 }
464                                 /*$headers .= 'MIME-Version: 1.0' . "\n";
465                                 //$headers .= 'Content-Type: text/html; charset=UTF-8' . "\n";
466                                 $headers .= 'Content-Type: text/plain; charset=UTF-8' . "\n";
467                                 $headers .= 'Content-Transfer-Encoding: 8bit' . "\n\n";
468                                 $html    = prepare_body($it);
469                                 //$message = '<html><body>' . $html . '</body></html>';
470                                 $message = html2plain($html);
471                                 logger('notifier: email delivery to ' . $addr);
472                                 mail($addr, $subject, $message, $headers);*/
473                                 email_send($addr, $subject, $headers, $it);
474                         }
475                         break;
476
477                 case NETWORK_DIASPORA :
478                         if($public_message)
479                                 $loc = 'public batch ' . $contact['batch'];
480                         else 
481                                 $loc = $contact['name'];
482
483                         logger('delivery: diaspora batch deliver: ' . $loc);
484
485                         if(get_config('system','dfrn_only') || (! get_config('system','diaspora_enabled')) || (! $normal_mode))
486                                 break;
487
488                         if((! $contact['pubkey']) && (! $public_message))
489                                 break;
490
491                         if($target_item['verb'] === ACTIVITY_DISLIKE) {
492                                 // unsupported
493                                 break;
494                         }
495                         elseif(($target_item['deleted']) && ($target_item['verb'] !== ACTIVITY_LIKE)) {
496                         logger('delivery: diaspora retract: ' . $loc);
497                                 // diaspora delete, 
498                                 diaspora_send_retraction($target_item,$owner,$contact,$public_message);
499                                 break;
500                         }
501                         elseif($target_item['parent'] != $target_item['id']) {
502
503                         logger('delivery: diaspora relay: ' . $loc);
504
505                                 // we are the relay - send comments, likes and unlikes to our conversants
506                                 diaspora_send_relay($target_item,$owner,$contact,$public_message);
507                                 break;
508                         }               
509                         elseif(($top_level) && (! $walltowall)) {
510                                 // currently no workable solution for sending walltowall
511                                 logger('delivery: diaspora status: ' . $loc);
512                                 diaspora_send_status($target_item,$owner,$contact,$public_message);
513                                 break;
514                         }
515
516                         logger('delivery: diaspora unknown mode: ' . $contact['name']);
517
518                         break;
519
520                 case NETWORK_FEED :
521                 case NETWORK_FACEBOOK :
522                         if(get_config('system','dfrn_only'))
523                                 break;
524                 default:
525                         break;
526         }
527
528         return;
529 }
530
531 if (array_search(__file__,get_included_files())===0){
532   delivery_run($argv,$argc);
533   killme();
534 }