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