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