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