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