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