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