]> git.mxchange.org Git - friendica.git/blob - src/Worker/Delivery.php
e98d66a08b46952627fccac390a764df29aa2ecb
[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/items.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                 $mail = false;
31                 $fsuggest = false;
32                 $relocate = false;
33                 $top_level = false;
34                 $recipients = [];
35                 $followup = false;
36
37                 $normal_mode = true;
38
39                 $item = null;
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 === 'suggest') {
56                         $normal_mode = false;
57                         $fsuggest = true;
58
59                         $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1",
60                                 intval($item_id)
61                         );
62                         if (!count($suggest)) {
63                                 return;
64                         }
65                         $uid = $suggest[0]['uid'];
66                         $recipients[] = $suggest[0]['cid'];
67                         $item = $suggest[0];
68                 } elseif ($cmd === 'relocate') {
69                         $normal_mode = false;
70                         $relocate = true;
71                         $uid = $item_id;
72                 } else {
73                         // find ancestors
74                         $target_item = dba::fetch_first("SELECT `item`.*, `contact`.`uid` AS `cuid` FROM `item`
75                                                         INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
76                                                         WHERE `item`.`id` = ? AND `visible` AND NOT `moderated`", $item_id);
77
78                         if (!DBM::is_result($target_item) || !intval($target_item['parent'])) {
79                                 return;
80                         }
81
82                         $parent_id = intval($target_item['parent']);
83                         $uid = $target_item['cuid'];
84                         $updated = $target_item['edited'];
85
86                         $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
87                                 FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d AND visible = 1 AND moderated = 0 ORDER BY `id` ASC",
88                                 intval($parent_id)
89                         );
90
91                         if (!count($items)) {
92                                 return;
93                         }
94
95                         $icontacts = null;
96                         $contacts_arr = [];
97                         foreach ($items as $item) {
98                                 if (!in_array($item['contact-id'],$contacts_arr)) {
99                                         $contacts_arr[] = intval($item['contact-id']);
100                                 }
101                         }
102                         if (count($contacts_arr)) {
103                                 $str_contacts = implode(',',$contacts_arr);
104                                 $icontacts = q("SELECT * FROM `contact`
105                                         WHERE `id` IN ( $str_contacts ) "
106                                 );
107                         }
108                         if ( !($icontacts && count($icontacts))) {
109                                 return;
110                         }
111
112                         // avoid race condition with deleting entries
113
114                         if ($items[0]['deleted']) {
115                                 foreach ($items as $item) {
116                                         $item['deleted'] = 1;
117                                 }
118                         }
119
120                         // When commenting too fast after delivery, a post wasn't recognized as top level post.
121                         // The count then showed more than one entry. The additional check should help.
122                         // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
123                         if ((($items[0]['id'] == $item_id) || (count($items) == 1)) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
124                                 logger('delivery: top level post');
125                                 $top_level = true;
126                         }
127                 }
128
129                 $owner = User::getOwnerDataById($uid);
130                 if (!$owner) {
131                         return;
132                 }
133
134                 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
135                 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != ACCOUNT_TYPE_COMMUNITY);
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                 // We don't deliver our items to blocked or pending contacts, and not to ourselves either
185                 $contact = dba::selectFirst('contact', [],
186                         ['id' => $contact_id, 'blocked' => false, 'pending' => false, 'self' => false]
187                 );
188                 if (!DBM::is_result($contact)) {
189                         return;
190                 }
191
192                 $deliver_status = 0;
193
194                 // Transmit via Diaspora if not possible via Friendica
195                 if (($item['uid'] == 0) && ($contact['network'] == NETWORK_DFRN)) {
196                         $contact['network'] = NETWORK_DIASPORA;
197                 }
198
199                 logger("main delivery by delivery: followup=$followup mail=$mail fsuggest=$fsuggest relocate=$relocate - network ".$contact['network']);
200
201                 switch ($contact['network']) {
202
203                         case NETWORK_DFRN:
204                                 logger('notifier: '.$target_item["guid"].' dfrndelivery: '.$contact['name']);
205
206                                 if ($mail) {
207                                         $item['body'] = Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
208                                         $atom = DFRN::mail($item, $owner);
209                                 } elseif ($fsuggest) {
210                                         $atom = DFRN::fsuggest($item, $owner);
211                                         q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1", intval($item['id']));
212                                 } elseif ($relocate) {
213                                         $atom = DFRN::relocate($owner, $uid);
214                                 } elseif ($followup) {
215                                         $msgitems = [];
216                                         foreach ($items as $item) {  // there is only one item
217                                                 if (!$item['parent']) {
218                                                         return;
219                                                 }
220                                                 if ($item['id'] == $item_id) {
221                                                         logger('followup: item: '. print_r($item,true), LOGGER_DATA);
222                                                         $msgitems[] = $item;
223                                                 }
224                                         }
225                                         $atom = DFRN::entries($msgitems,$owner);
226                                 } else {
227                                         $msgitems = [];
228                                         foreach ($items as $item) {
229                                                 if (!$item['parent']) {
230                                                         return;
231                                                 }
232
233                                                 // private emails may be in included in public conversations. Filter them.
234                                                 if ($public_message && $item['private']) {
235                                                         return;
236                                                 }
237
238                                                 $item_contact = self::getItemContact($item,$icontacts);
239                                                 if (!$item_contact) {
240                                                         return;
241                                                 }
242
243                                                 if ($normal_mode) {
244                                                         // Only add the parent when we don't delete other items.
245                                                         if ($item_id == $item['id'] || (($item['id'] == $item['parent']) && ($cmd != 'drop'))) {
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
326                                 if ($deliver_status < 200) {
327                                         // The message could not be delivered. We mark the contact as "dead"
328                                         Contact::markForArchival($contact);
329                                 } else {
330                                         // We successfully delivered a message, the contact is alive
331                                         Contact::unmarkForArchival($contact);
332                                 }
333
334                                 break;
335
336                         case NETWORK_OSTATUS:
337                                 // Do not send to otatus if we are not configured to send to public networks
338                                 if ($owner['prvnets']) {
339                                         break;
340                                 }
341                                 if (Config::get('system','ostatus_disabled') || Config::get('system','dfrn_only')) {
342                                         break;
343                                 }
344
345                                 // There is currently no code here to distribute anything to OStatus.
346                                 // This is done in "notifier.php" (See "url_recipients" and "push_notify")
347                                 break;
348
349                         case NETWORK_MAIL:
350
351                                 if (Config::get('system','dfrn_only')) {
352                                         break;
353                                 }
354                                 // WARNING: does not currently convert to RFC2047 header encodings, etc.
355
356                                 $addr = $contact['addr'];
357                                 if (!strlen($addr)) {
358                                         break;
359                                 }
360
361                                 if ($cmd === 'wall-new' || $cmd === 'comment-new') {
362                                         $it = null;
363                                         if ($cmd === 'wall-new') {
364                                                 $it = $items[0];
365                                         } else {
366                                                 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
367                                                         intval($item_id)
368                                                 );
369                                                 if (DBM::is_result($r)) {
370                                                         $it = $r[0];
371                                                 }
372                                         }
373                                         if (!$it) {
374                                                 break;
375                                         }
376
377                                         $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
378                                                 intval($uid)
379                                         );
380                                         if (!count($local_user)) {
381                                                 break;
382                                         }
383
384                                         $reply_to = '';
385                                         $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
386                                                 intval($uid)
387                                         );
388                                         if ($r1 && $r1[0]['reply_to']) {
389                                                 $reply_to = $r1[0]['reply_to'];
390                                         }
391
392                                         $subject  = (($it['title']) ? Email::encodeHeader($it['title'],'UTF-8') : L10n::t("\x28no subject\x29")) ;
393
394                                         // only expose our real email address to true friends
395
396                                         if (($contact['rel'] == CONTACT_IS_FRIEND) && !$contact['blocked']) {
397                                                 if ($reply_to) {
398                                                         $headers  = 'From: '.Email::encodeHeader($local_user[0]['username'],'UTF-8').' <'.$reply_to.'>'."\n";
399                                                         $headers .= 'Sender: '.$local_user[0]['email']."\n";
400                                                 } else {
401                                                         $headers  = 'From: '.Email::encodeHeader($local_user[0]['username'],'UTF-8').' <'.$local_user[0]['email'].'>'."\n";
402                                                 }
403                                         } else {
404                                                 $headers  = 'From: '. Email::encodeHeader($local_user[0]['username'],'UTF-8') .' <'. L10n::t('noreply') .'@'.$a->get_hostname() .'>'. "\n";
405                                         }
406
407                                         //if ($reply_to)
408                                         //      $headers .= 'Reply-to: '.$reply_to . "\n";
409
410                                         $headers .= 'Message-Id: <'. Email::iri2msgid($it['uri']).'>'. "\n";
411
412                                         //logger("Mail: uri: ".$it['uri']." parent-uri ".$it['parent-uri'], LOGGER_DEBUG);
413                                         //logger("Mail: Data: ".print_r($it, true), LOGGER_DEBUG);
414                                         //logger("Mail: Data: ".print_r($it, true), LOGGER_DATA);
415
416                                         if ($it['uri'] !== $it['parent-uri']) {
417                                                 $headers .= "References: <".Email::iri2msgid($it["parent-uri"]).">";
418
419                                                 // If Threading is enabled, write down the correct parent
420                                                 if (($it["thr-parent"] != "") && ($it["thr-parent"] != $it["parent-uri"])) {
421                                                         $headers .= " <".Email::iri2msgid($it["thr-parent"]).">";
422                                                 }
423                                                 $headers .= "\n";
424
425                                                 if (!$it['title']) {
426                                                         $r = q("SELECT `title` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
427                                                                 dbesc($it['parent-uri']),
428                                                                 intval($uid));
429
430                                                         if (DBM::is_result($r) && ($r[0]['title'] != '')) {
431                                                                 $subject = $r[0]['title'];
432                                                         } else {
433                                                                 $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d LIMIT 1",
434                                                                         dbesc($it['parent-uri']),
435                                                                         intval($uid));
436
437                                                                 if (DBM::is_result($r) && ($r[0]['title'] != '')) {
438                                                                         $subject = $r[0]['title'];
439                                                                 }
440                                                         }
441                                                 }
442                                                 if (strncasecmp($subject,'RE:',3)) {
443                                                         $subject = 'Re: '.$subject;
444                                                 }
445                                         }
446                                         Email::send($addr, $subject, $headers, $it);
447                                 }
448                                 break;
449
450                         case NETWORK_DIASPORA:
451                                 if ($public_message) {
452                                         $loc = 'public batch '.$contact['batch'];
453                                 } else {
454                                         $loc = $contact['name'];
455                                 }
456
457                                 logger('delivery: diaspora batch deliver: '.$loc);
458
459                                 if (Config::get('system','dfrn_only') || !Config::get('system','diaspora_enabled')) {
460                                         break;
461                                 }
462                                 if ($mail) {
463                                         Diaspora::sendMail($item,$owner,$contact);
464                                         break;
465                                 }
466
467                                 if (!$normal_mode) {
468                                         break;
469                                 }
470                                 if (!$contact['pubkey'] && !$public_message) {
471                                         break;
472                                 }
473                                 if (($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
474                                         // top-level retraction
475                                         logger('diaspora retract: '.$loc);
476                                         Diaspora::sendRetraction($target_item,$owner,$contact,$public_message);
477                                         break;
478                                 } elseif ($relocate) {
479                                         Diaspora::sendAccountMigration($owner, $contact, $uid);
480                                         break;
481                                 } elseif ($followup) {
482                                         // send comments and likes to owner to relay
483                                         logger('diaspora followup: '.$loc);
484                                         Diaspora::sendFollowup($target_item,$owner,$contact,$public_message);
485                                         break;
486                                 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
487                                         // we are the relay - send comments, likes and relayable_retractions to our conversants
488                                         logger('diaspora relay: '.$loc);
489                                         Diaspora::sendRelay($target_item,$owner,$contact,$public_message);
490                                         break;
491                                 } elseif ($top_level && !$walltowall) {
492                                         // currently no workable solution for sending walltowall
493                                         logger('diaspora status: '.$loc);
494                                         Diaspora::sendStatus($target_item,$owner,$contact,$public_message);
495                                         break;
496                                 }
497
498                                 logger('delivery: diaspora unknown mode: '.$contact['name']);
499
500                                 break;
501
502                         default:
503                                 break;
504                 }
505
506                 return;
507         }
508
509         private static function getItemContact($item, $contacts)
510         {
511                 if (!count($contacts) || !is_array($item)) {
512                         return false;
513                 }
514                 foreach ($contacts as $contact) {
515                         if ($contact['id'] == $item['contact-id']) {
516                                 return $contact;
517                         }
518                 }
519                 return false;
520         }
521 }