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