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