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