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