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