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