]> git.mxchange.org Git - friendica.git/blob - src/Worker/Delivery.php
4387f28b79d40855504f6354084fe0c72f00fdc7
[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 class Delivery {
23         public static function execute($cmd, $item_id, $contact_id) {
24                 global $a;
25
26                 logger('Invoked: ' . $cmd . ': ' . $item_id . ' to ' . $contact_id, LOGGER_DEBUG);
27
28                 $top_level = false;
29                 $followup = false;
30                 $public_message = false;
31
32                 if ($cmd == DELIVER_MAIL) {
33                         $target_item = dba::selectFirst('mail', [], ['id' => $item_id]);
34                         if (!DBM::is_result($message)) {
35                                 return;
36                         }
37                         $uid = $target_item['uid'];
38                 } elseif ($cmd == DELIVER_SUGGESTION) {
39                         $target_item = dba::selectFirst('fsuggest', [], ['id' => $item_id]);
40                         if (!DBM::is_result($message)) {
41                                 return;
42                         }
43                         $uid = $target_item['uid'];
44                 } elseif ($cmd == DELIVER_RELOCATION) {
45                         $uid = $item_id;
46                 } else {
47                         $item = dba::selectFirst('item', ['parent'], ['id' => $item_id]);
48                         if (!DBM::is_result($item) || empty($item['parent'])) {
49                                 return;
50                         }
51                         $parent_id = intval($item['parent']);
52
53                         $itemdata = dba::p("SELECT `item`.*, `contact`.`uid` AS `cuid`,
54                                                         `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
55                                                 FROM `item`
56                                                 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
57                                                 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
58                                                 WHERE `item`.`id` IN (?, ?) AND `visible` AND NOT `moderated`
59                                                 ORDER BY `item`.`id`",
60                                         $item_id, $parent_id);
61                         $items = [];
62                         while ($item = dba::fetch($itemdata)) {
63                                 if ($item['id'] == $parent_id) {
64                                         $parent = $item;
65                                 }
66                                 if ($item['id'] == $item_id) {
67                                         $target_item = $item;
68                                 }
69                                 $items[] = $item;
70                         }
71                         dba::close($itemdata);
72
73                         $uid = $target_item['cuid'];
74
75                         // avoid race condition with deleting entries
76                         if ($items[0]['deleted']) {
77                                 foreach ($items as $item) {
78                                         $item['deleted'] = 1;
79                                 }
80                         }
81
82                         // When commenting too fast after delivery, a post wasn't recognized as top level post.
83                         // The count then showed more than one entry. The additional check should help.
84                         // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
85                         if ((($parent['id'] == $item_id) || (count($items) == 1)) && ($parent['uri'] === $parent['parent-uri'])) {
86                                 logger('Top level post');
87                                 $top_level = true;
88                         }
89
90                         // This is IMPORTANT!!!!
91
92                         // We will only send a "notify owner to relay" or followup message if the referenced post
93                         // originated on our system by virtue of having our hostname somewhere
94                         // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
95                         // if $parent['wall'] == 1 we will already have the parent message in our array
96                         // and we will relay the whole lot.
97
98                         $localhost = $a->get_hostname();
99                         if (strpos($localhost, ':')) {
100                                 $localhost = substr($localhost, 0, strpos($localhost, ':'));
101                         }
102                         /**
103                          *
104                          * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
105                          * have been known to cause runaway conditions which affected several servers, along with
106                          * permissions issues.
107                          *
108                          */
109
110                         if (!$top_level && ($parent['wall'] == 0) && stristr($target_item['uri'], $localhost)) {
111                                 logger('Followup ' . $target_item["guid"], LOGGER_DEBUG);
112                                 // local followup to remote post
113                                 $followup = true;
114                         }
115
116                         if (empty($parent['allow_cid'])
117                                 && empty($parent['allow_gid'])
118                                 && empty($parent['deny_cid'])
119                                 && empty($parent['deny_gid'])
120                                 && !$parent["private"]) {
121                                 $public_message = true;
122                         }
123                 }
124
125                 $owner = User::getOwnerDataById($uid);
126                 if (!DBM::is_result($owner)) {
127                         return;
128                 }
129
130                 // We don't deliver our items to blocked or pending contacts, and not to ourselves either
131                 $contact = dba::selectFirst('contact', [],
132                         ['id' => $contact_id, 'blocked' => false, 'pending' => false, 'self' => false]
133                 );
134                 if (!DBM::is_result($contact)) {
135                         return;
136                 }
137
138                 // Transmit via Diaspora if the thread had started as Diaspora post
139                 // This is done since the uri wouldn't match (Diaspora doesn't transmit it)
140                 if (isset($parent) && ($parent['network'] == NETWORK_DIASPORA) && ($contact['network'] == NETWORK_DFRN)) {
141                         $contact['network'] = NETWORK_DIASPORA;
142                 }
143
144                 logger("Delivering " . $cmd . " followup=$followup - via network " . $contact['network']);
145
146                 switch ($contact['network']) {
147
148                         case NETWORK_DFRN:
149                                 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
150                                 break;
151
152                         case NETWORK_DIASPORA:
153                                 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
154                                 break;
155
156                         case NETWORK_OSTATUS:
157                                 // Do not send to otatus if we are not configured to send to public networks
158                                 if ($owner['prvnets']) {
159                                         break;
160                                 }
161                                 if (Config::get('system','ostatus_disabled') || Config::get('system','dfrn_only')) {
162                                         break;
163                                 }
164
165                                 // There is currently no code here to distribute anything to OStatus.
166                                 // This is done in "notifier.php" (See "url_recipients" and "push_notify")
167                                 break;
168
169                         case NETWORK_MAIL:
170                                 self::deliverMail($cmd, $contact, $owner, $target_item);
171                                 break;
172
173                         default:
174                                 break;
175                 }
176
177                 return;
178         }
179
180         private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
181         {
182                 logger('Deliver ' . $target_item["guid"] . ' via DFRN to ' . $contact['addr']);
183
184                 if ($cmd == DELIVER_MAIL) {
185                         $item = $target_item;
186                         $item['body'] = Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
187                         $atom = DFRN::mail($item, $owner);
188                 } elseif ($cmd == DELIVER_SUGGESTION) {
189                         $item = $target_item;
190                         $atom = DFRN::fsuggest($item, $owner);
191                         dba::delete('fsuggest', ['id' => $item['id']]);
192                 } elseif ($cmd == DELIVER_RELOCATION) {
193                         $atom = DFRN::relocate($owner, $owner['uid']);
194                 } elseif ($followup) {
195                         $msgitems = [$target_item];
196                         $atom = DFRN::entries($msgitems, $owner);
197                 } else {
198                         $msgitems = [];
199                         foreach ($items as $item) {
200                                 // Only add the parent when we don't delete other items.
201                                 if (($target_item['id'] == $item['id']) || ($cmd != DELIVER_DELETION)) {
202                                         $item["entry:comment-allow"] = true;
203                                         $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
204                                         $msgitems[] = $item;
205                                 }
206                         }
207                         $atom = DFRN::entries($msgitems,$owner);
208                 }
209
210                 logger('Notifier entry: ' . $contact["url"] . ' ' . $target_item["guid"] . ' entry: ' . $atom, LOGGER_DATA);
211
212                 $basepath =  implode('/', array_slice(explode('/',$contact['url']),0,3));
213
214                 // perform local delivery if we are on the same site
215
216                 if (link_compare($basepath, System::baseUrl())) {
217                         $condition = ['nurl' => normalise_link($contact['url']), 'self' => true];
218                         $target_self = dba::selectFirst('contact', ['uid'], $condition);
219                         if (!DBM::is_result($target_self)) {
220                                 return;
221                         }
222                         $target_uid = $target_self['uid'];
223
224                         // Check if the user has got this contact
225                         $cid = Contact::getIdForURL($owner['url'], $target_uid);
226                         if (!$cid) {
227                                 // Otherwise there should be a public contact
228                                 $cid = Contact::getIdForURL($owner['url']);
229                                 if (!$cid) {
230                                         return;
231                                 }
232                         }
233
234                         // We now have some contact, so we fetch it
235                         $target_importer = dba::fetch_first("SELECT *, `name` as `senderName`
236                                                         FROM `contact`
237                                                         WHERE NOT `blocked` AND `id` = ? LIMIT 1",
238                                                         $cid);
239
240                         // This should never fail
241                         if (!DBM::is_result($target_importer)) {
242                                 return;
243                         }
244
245                         // Set the user id. This is important if this is a public contact
246                         $target_importer['importer_uid']  = $target_uid;
247                         DFRN::import($atom, $target_importer);
248                         return;
249                 }
250
251                 if ($items[0]['uid'] == 0) {
252                         $deliver_status = DFRN::transmit($owner, $contact, $atom);
253                         if ($deliver_status < 200) {
254                                 // Transmit via Diaspora if not possible via Friendica
255                                 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
256                                 return;
257                         }
258                 } else {
259                         $deliver_status = DFRN::deliver($owner, $contact, $atom);
260                 }
261
262                 logger('Delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
263
264                 if ($deliver_status < 0) {
265                         logger('Delivery failed: queuing message ' . $target_item["guid"] );
266                         Queue::add($contact['id'], NETWORK_DFRN, $atom, false, $target_item['guid']);
267                 }
268
269                 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
270                         // We successfully delivered a message, the contact is alive
271                         Contact::unmarkForArchival($contact);
272                 } else {
273                         // The message could not be delivered. We mark the contact as "dead"
274                         Contact::markForArchival($contact);
275                 }
276         }
277
278         private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
279         {
280                 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
281                 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != ACCOUNT_TYPE_COMMUNITY);
282
283                 if ($public_message) {
284                         $loc = 'public batch ' . $contact['batch'];
285                 } else {
286                         $loc = $contact['addr'];
287                 }
288
289                 logger('Deliver ' . $target_item["guid"] . ' via Diaspora to ' . $loc);
290
291                 if (Config::get('system', 'dfrn_only') || !Config::get('system', 'diaspora_enabled')) {
292                         return;
293                 }
294                 if ($cmd == DELIVER_MAIL) {
295                         Diaspora::sendMail($target_item, $owner, $contact);
296                         return;
297                 }
298
299                 if ($cmd == DELIVER_SUGGESTION) {
300                         return;
301                 }
302                 if (!$contact['pubkey'] && !$public_message) {
303                         return;
304                 }
305                 if (($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
306                         // top-level retraction
307                         logger('diaspora retract: ' . $loc);
308                         Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
309                         return;
310                 } elseif ($cmd == DELIVER_RELOCATION) {
311                         Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
312                         return;
313                 } elseif ($followup) {
314                         // send comments and likes to owner to relay
315                         logger('diaspora followup: ' . $loc);
316                         Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
317                         return;
318                 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
319                         // we are the relay - send comments, likes and relayable_retractions to our conversants
320                         logger('diaspora relay: ' . $loc);
321                         Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
322                         return;
323                 } elseif ($top_level && !$walltowall) {
324                         // currently no workable solution for sending walltowall
325                         logger('diaspora status: ' . $loc);
326                         Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
327                         return;
328                 }
329
330                 logger('Unknown mode ' . $cmd . ' for ' . $loc);
331         }
332
333         private static function deliverMail($cmd, $contact, $owner, $target_item)
334         {
335                 global $a;
336
337                 if (Config::get('system','dfrn_only')) {
338                         return;
339                 }
340                 // WARNING: does not currently convert to RFC2047 header encodings, etc.
341
342                 $addr = $contact['addr'];
343                 if (!strlen($addr)) {
344                         return;
345                 }
346
347                 if (!in_array($cmd, [DELIVER_POST, DELIVER_COMMENT])) {
348                         return;
349                 }
350
351                 $local_user = dba::selectFirst('user', [], ['uid' => $owner['uid']]);
352                 if (!DBM::is_result($local_user)) {
353                         return;
354                 }
355
356                 logger('Deliver ' . $target_item["guid"] . ' via mail to ' . $contact['addr']);
357
358                 $reply_to = '';
359                 $mailacct = dba::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
360                 if (DBM::is_result($mailacct) && !empty($mailacct['reply_to'])) {
361                         $reply_to = $mailacct['reply_to'];
362                 }
363
364                 $subject  = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : L10n::t("\x28no subject\x29"));
365
366                 // only expose our real email address to true friends
367
368                 if (($contact['rel'] == CONTACT_IS_FRIEND) && !$contact['blocked']) {
369                         if ($reply_to) {
370                                 $headers  = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to.'>' . "\n";
371                                 $headers .= 'Sender: ' . $local_user['email'] . "\n";
372                         } else {
373                                 $headers  = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8').' <' . $local_user['email'] . '>' . "\n";
374                         }
375                 } else {
376                         $headers  = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <noreply@' . $a->get_hostname() . '>' . "\n";
377                 }
378
379                 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
380
381                 if ($target_item['uri'] !== $target_item['parent-uri']) {
382                         $headers .= "References: <" . Email::iri2msgid($target_item["parent-uri"]) . ">";
383
384                         // If Threading is enabled, write down the correct parent
385                         if (($target_item["thr-parent"] != "") && ($target_item["thr-parent"] != $target_item["parent-uri"])) {
386                                 $headers .= " <".Email::iri2msgid($target_item["thr-parent"]).">";
387                         }
388                         $headers .= "\n";
389
390                         if (empty($target_item['title'])) {
391                                 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
392                                 $title = dba::selectFirst('item', ['title'], $condition);
393                                 if (DBM::is_result($title) && ($title['title'] != '')) {
394                                         $subject = $title['title'];
395                                 } else {
396                                         $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
397                                         $title = dba::selectFirst('item', ['title'], $condition);
398                                         if (DBM::is_result($title) && ($title['title'] != '')) {
399                                                 $subject = $title['title'];
400                                         }
401                                 }
402                         }
403                         if (strncasecmp($subject,  'RE:', 3)) {
404                                 $subject = 'Re: ' . $subject;
405                         }
406                 }
407                 Email::send($addr, $subject, $headers, $target_item);
408         }
409 }