459660f4ea795f1492107df8eda54890b8769392
[friendica.git/.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\Logger;
11 use Friendica\Core\Protocol;
12 use Friendica\Core\System;
13 use Friendica\Database\DBA;
14 use Friendica\Model\Contact;
15 use Friendica\Model\Item;
16 use Friendica\Model\Queue;
17 use Friendica\Model\User;
18 use Friendica\Protocol\DFRN;
19 use Friendica\Protocol\Diaspora;
20 use Friendica\Protocol\Email;
21 use Friendica\Util\Strings;
22 use Friendica\Util\Network;
23
24 class Delivery extends BaseObject
25 {
26         const MAIL          = 'mail';
27         const SUGGESTION    = 'suggest';
28         const RELOCATION    = 'relocate';
29         const DELETION      = 'drop';
30         const POST          = 'wall-new';
31         const COMMENT       = 'comment-new';
32         const REMOVAL       = 'removeme';
33         const PROFILEUPDATE = 'profileupdate';
34
35         public static function execute($cmd, $item_id, $contact_id)
36         {
37                 Logger::log('Invoked: ' . $cmd . ': ' . $item_id . ' to ' . $contact_id, Logger::DEBUG);
38
39                 $top_level = false;
40                 $followup = false;
41                 $public_message = false;
42
43                 $items = [];
44                 if ($cmd == self::MAIL) {
45                         $target_item = DBA::selectFirst('mail', [], ['id' => $item_id]);
46                         if (!DBA::isResult($target_item)) {
47                                 return;
48                         }
49                         $uid = $target_item['uid'];
50                 } elseif ($cmd == self::SUGGESTION) {
51                         $target_item = DBA::selectFirst('fsuggest', [], ['id' => $item_id]);
52                         if (!DBA::isResult($target_item)) {
53                                 return;
54                         }
55                         $uid = $target_item['uid'];
56                 } elseif ($cmd == self::RELOCATION) {
57                         $uid = $item_id;
58                         $target_item = [];
59                 } else {
60                         $item = Item::selectFirst(['parent'], ['id' => $item_id]);
61                         if (!DBA::isResult($item) || empty($item['parent'])) {
62                                 return;
63                         }
64                         $parent_id = intval($item['parent']);
65
66                         $condition = ['id' => [$item_id, $parent_id], 'moderated' => false];
67                         $params = ['order' => ['id']];
68                         $itemdata = Item::select([], $condition, $params);
69
70                         while ($item = Item::fetch($itemdata)) {
71                                 if ($item['id'] == $parent_id) {
72                                         $parent = $item;
73                                 }
74                                 if ($item['id'] == $item_id) {
75                                         $target_item = $item;
76                                 }
77                                 $items[] = $item;
78                         }
79                         DBA::close($itemdata);
80
81                         if (empty($target_item)) {
82                                 Logger::log('Item ' . $item_id . "wasn't found. Quitting here.");
83                                 return;
84                         }
85
86                         if (empty($parent)) {
87                                 Logger::log('Parent ' . $parent_id . ' for item ' . $item_id . "wasn't found. Quitting here.");
88                                 return;
89                         }
90
91                         $uid = $target_item['contact-uid'];
92
93                         // avoid race condition with deleting entries
94                         if ($items[0]['deleted']) {
95                                 foreach ($items as $item) {
96                                         $item['deleted'] = 1;
97                                 }
98                         }
99
100                         // When commenting too fast after delivery, a post wasn't recognized as top level post.
101                         // The count then showed more than one entry. The additional check should help.
102                         // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
103                         if ((($parent['id'] == $item_id) || (count($items) == 1)) && ($parent['uri'] === $parent['parent-uri'])) {
104                                 Logger::log('Top level post');
105                                 $top_level = true;
106                         }
107
108                         // This is IMPORTANT!!!!
109
110                         // We will only send a "notify owner to relay" or followup message if the referenced post
111                         // originated on our system by virtue of having our hostname somewhere
112                         // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
113                         // if $parent['wall'] == 1 we will already have the parent message in our array
114                         // and we will relay the whole lot.
115
116                         $localhost = self::getApp()->getHostName();
117                         if (strpos($localhost, ':')) {
118                                 $localhost = substr($localhost, 0, strpos($localhost, ':'));
119                         }
120                         /**
121                          *
122                          * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
123                          * have been known to cause runaway conditions which affected several servers, along with
124                          * permissions issues.
125                          *
126                          */
127
128                         if (!$top_level && ($parent['wall'] == 0) && stristr($target_item['uri'], $localhost)) {
129                                 Logger::log('Followup ' . $target_item["guid"], Logger::DEBUG);
130                                 // local followup to remote post
131                                 $followup = true;
132                         }
133
134                         if (empty($parent['allow_cid'])
135                                 && empty($parent['allow_gid'])
136                                 && empty($parent['deny_cid'])
137                                 && empty($parent['deny_gid'])
138                                 && !$parent["private"]) {
139                                 $public_message = true;
140                         }
141                 }
142
143                 if (empty($items)) {
144                         Logger::log('No delivery data for  ' . $cmd . ' - Item ID: ' .$item_id . ' - Contact ID: ' . $contact_id);
145                 }
146
147                 $owner = User::getOwnerDataById($uid);
148                 if (!DBA::isResult($owner)) {
149                         return;
150                 }
151
152                 // We don't deliver our items to blocked or pending contacts, and not to ourselves either
153                 $contact = DBA::selectFirst('contact', [],
154                         ['id' => $contact_id, 'blocked' => false, 'pending' => false, 'self' => false]
155                 );
156                 if (!DBA::isResult($contact)) {
157                         return;
158                 }
159
160                 if (Network::isUrlBlocked($contact['url'])) {
161                         return;
162                 }
163
164                 // Transmit via Diaspora if the thread had started as Diaspora post
165                 // This is done since the uri wouldn't match (Diaspora doesn't transmit it)
166                 if (isset($parent) && ($parent['network'] == Protocol::DIASPORA) && ($contact['network'] == Protocol::DFRN)) {
167                         $contact['network'] = Protocol::DIASPORA;
168                 }
169
170                 Logger::log("Delivering " . $cmd . " followup=$followup - via network " . $contact['network']);
171
172                 switch ($contact['network']) {
173
174                         case Protocol::DFRN:
175                                 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
176                                 break;
177
178                         case Protocol::DIASPORA:
179                                 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
180                                 break;
181
182                         case Protocol::OSTATUS:
183                                 // Do not send to otatus if we are not configured to send to public networks
184                                 if ($owner['prvnets']) {
185                                         break;
186                                 }
187                                 if (Config::get('system','ostatus_disabled') || Config::get('system','dfrn_only')) {
188                                         break;
189                                 }
190
191                                 // There is currently no code here to distribute anything to OStatus.
192                                 // This is done in "notifier.php" (See "url_recipients" and "push_notify")
193                                 break;
194
195                         case Protocol::MAIL:
196                                 self::deliverMail($cmd, $contact, $owner, $target_item);
197                                 break;
198
199                         default:
200                                 break;
201                 }
202
203                 return;
204         }
205
206         /**
207          * @brief Deliver content via DFRN
208          *
209          * @param string  $cmd            Command
210          * @param array   $contact        Contact record of the receiver
211          * @param array   $owner          Owner record of the sender
212          * @param array   $items          Item record of the content and the parent
213          * @param array   $target_item    Item record of the content
214          * @param boolean $public_message Is the content public?
215          * @param boolean $top_level      Is it a thread starter?
216          * @param boolean $followup       Is it an answer to a remote post?
217          */
218         private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
219         {
220                 Logger::log('Deliver ' . defaults($target_item, 'guid', $target_item['id']) . ' via DFRN to ' . (empty($contact['addr']) ? $contact['url'] : $contact['addr']));
221
222                 if ($cmd == self::MAIL) {
223                         $item = $target_item;
224                         $item['body'] = Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
225                         $atom = DFRN::mail($item, $owner);
226                 } elseif ($cmd == self::SUGGESTION) {
227                         $item = $target_item;
228                         $atom = DFRN::fsuggest($item, $owner);
229                         DBA::delete('fsuggest', ['id' => $item['id']]);
230                 } elseif ($cmd == self::RELOCATION) {
231                         $atom = DFRN::relocate($owner, $owner['uid']);
232                 } elseif ($followup) {
233                         $msgitems = [$target_item];
234                         $atom = DFRN::entries($msgitems, $owner);
235                 } else {
236                         $msgitems = [];
237                         foreach ($items as $item) {
238                                 // Only add the parent when we don't delete other items.
239                                 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
240                                         $item["entry:comment-allow"] = true;
241                                         $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
242                                         $msgitems[] = $item;
243                                 }
244                         }
245                         $atom = DFRN::entries($msgitems, $owner);
246                 }
247
248                 Logger::log('Notifier entry: ' . $contact["url"] . ' ' . defaults($target_item, 'guid', $target_item['id']) . ' entry: ' . $atom, Logger::DATA);
249
250                 $basepath =  implode('/', array_slice(explode('/', $contact['url']), 0, 3));
251
252                 // perform local delivery if we are on the same site
253
254                 if (Strings::compareLink($basepath, System::baseUrl())) {
255                         $condition = ['nurl' => Strings::normaliseLink($contact['url']), 'self' => true];
256                         $target_self = DBA::selectFirst('contact', ['uid'], $condition);
257                         if (!DBA::isResult($target_self)) {
258                                 return;
259                         }
260                         $target_uid = $target_self['uid'];
261
262                         // Check if the user has got this contact
263                         $cid = Contact::getIdForURL($owner['url'], $target_uid);
264                         if (!$cid) {
265                                 // Otherwise there should be a public contact
266                                 $cid = Contact::getIdForURL($owner['url']);
267                                 if (!$cid) {
268                                         return;
269                                 }
270                         }
271
272                         $target_importer = DFRN::getImporter($cid, $target_uid);
273                         if (empty($target_importer)) {
274                                 // This should never happen
275                                 return;
276                         }
277
278                         DFRN::import($atom, $target_importer);
279                         return;
280                 }
281
282                 // We don't have a relationship with contacts on a public post.
283                 // Se we transmit with the new method and via Diaspora as a fallback
284                 if (!empty($items) && (($items[0]['uid'] == 0) || ($contact['uid'] == 0))) {
285                         // Transmit in public if it's a relay post
286                         $public_dfrn = ($contact['contact-type'] == Contact::ACCOUNT_TYPE_RELAY);
287
288                         $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
289
290                         // We never spool failed relay deliveries
291                         if ($public_dfrn) {
292                                 Logger::log('Relay delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
293                                 return;
294                         }
295
296                         if (($deliver_status < 200) || ($deliver_status > 299)) {
297                                 // Transmit via Diaspora if not possible via Friendica
298                                 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
299                                 return;
300                         }
301                 } elseif ($cmd != self::RELOCATION) {
302                         $deliver_status = DFRN::deliver($owner, $contact, $atom);
303                 } else {
304                         $deliver_status = DFRN::deliver($owner, $contact, $atom, false, true);
305                 }
306
307                 Logger::log('Delivery to ' . $contact['url'] . ' with guid ' . defaults($target_item, 'guid', $target_item['id']) . ' returns ' . $deliver_status);
308
309                 if ($deliver_status < 0) {
310                         Logger::log('Delivery failed: queuing message ' . defaults($target_item, 'guid', $target_item['id']));
311                         Queue::add($contact['id'], Protocol::DFRN, $atom, false, $target_item['guid']);
312                 }
313
314                 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
315                         // We successfully delivered a message, the contact is alive
316                         Contact::unmarkForArchival($contact);
317                 } else {
318                         // The message could not be delivered. We mark the contact as "dead"
319                         Contact::markForArchival($contact);
320
321                         // Transmit via Diaspora when all other methods (legacy DFRN and new one) are failing.
322                         // This is a fallback for systems that don't know the new methods.
323                         self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
324                 }
325         }
326
327         /**
328          * @brief Deliver content via Diaspora
329          *
330          * @param string  $cmd            Command
331          * @param array   $contact        Contact record of the receiver
332          * @param array   $owner          Owner record of the sender
333          * @param array   $items          Item record of the content and the parent
334          * @param array   $target_item    Item record of the content
335          * @param boolean $public_message Is the content public?
336          * @param boolean $top_level      Is it a thread starter?
337          * @param boolean $followup       Is it an answer to a remote post?
338          */
339         private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
340         {
341                 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
342                 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != Contact::ACCOUNT_TYPE_COMMUNITY);
343
344                 if ($public_message) {
345                         $loc = 'public batch ' . $contact['batch'];
346                 } else {
347                         $loc = $contact['addr'];
348                 }
349
350                 Logger::log('Deliver ' . defaults($target_item, 'guid', $target_item['id']) . ' via Diaspora to ' . $loc);
351
352                 if (Config::get('system', 'dfrn_only') || !Config::get('system', 'diaspora_enabled')) {
353                         return;
354                 }
355                 if ($cmd == self::MAIL) {
356                         Diaspora::sendMail($target_item, $owner, $contact);
357                         return;
358                 }
359
360                 if ($cmd == self::SUGGESTION) {
361                         return;
362                 }
363                 if (!$contact['pubkey'] && !$public_message) {
364                         return;
365                 }
366                 if ($cmd == self::RELOCATION) {
367                         Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
368                         return;
369                 } elseif ($target_item['deleted'] && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
370                         // top-level retraction
371                         Logger::log('diaspora retract: ' . $loc);
372                         Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
373                         return;
374                 } elseif ($followup) {
375                         // send comments and likes to owner to relay
376                         Logger::log('diaspora followup: ' . $loc);
377                         Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
378                         return;
379                 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
380                         // we are the relay - send comments, likes and relayable_retractions to our conversants
381                         Logger::log('diaspora relay: ' . $loc);
382                         Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
383                         return;
384                 } elseif ($top_level && !$walltowall) {
385                         // currently no workable solution for sending walltowall
386                         Logger::log('diaspora status: ' . $loc);
387                         Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
388                         return;
389                 }
390
391                 Logger::log('Unknown mode ' . $cmd . ' for ' . $loc);
392         }
393
394         /**
395          * @brief Deliver content via mail
396          *
397          * @param string $cmd         Command
398          * @param array  $contact     Contact record of the receiver
399          * @param array  $owner       Owner record of the sender
400          * @param array  $target_item Item record of the content
401          */
402         private static function deliverMail($cmd, $contact, $owner, $target_item)
403         {
404                 if (Config::get('system','dfrn_only')) {
405                         return;
406                 }
407                 // WARNING: does not currently convert to RFC2047 header encodings, etc.
408
409                 $addr = $contact['addr'];
410                 if (!strlen($addr)) {
411                         return;
412                 }
413
414                 if (!in_array($cmd, [self::POST, self::COMMENT])) {
415                         return;
416                 }
417
418                 $local_user = DBA::selectFirst('user', [], ['uid' => $owner['uid']]);
419                 if (!DBA::isResult($local_user)) {
420                         return;
421                 }
422
423                 Logger::log('Deliver ' . $target_item["guid"] . ' via mail to ' . $contact['addr']);
424
425                 $reply_to = '';
426                 $mailacct = DBA::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
427                 if (DBA::isResult($mailacct) && !empty($mailacct['reply_to'])) {
428                         $reply_to = $mailacct['reply_to'];
429                 }
430
431                 $subject  = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : L10n::t("\x28no subject\x29"));
432
433                 // only expose our real email address to true friends
434
435                 if (($contact['rel'] == Contact::FRIEND) && !$contact['blocked']) {
436                         if ($reply_to) {
437                                 $headers  = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to.'>' . "\n";
438                                 $headers .= 'Sender: ' . $local_user['email'] . "\n";
439                         } else {
440                                 $headers  = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8').' <' . $local_user['email'] . '>' . "\n";
441                         }
442                 } else {
443                         $headers  = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <noreply@' . self::getApp()->getHostName() . '>' . "\n";
444                 }
445
446                 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
447
448                 if ($target_item['uri'] !== $target_item['parent-uri']) {
449                         $headers .= "References: <" . Email::iri2msgid($target_item["parent-uri"]) . ">";
450
451                         // If Threading is enabled, write down the correct parent
452                         if (($target_item["thr-parent"] != "") && ($target_item["thr-parent"] != $target_item["parent-uri"])) {
453                                 $headers .= " <".Email::iri2msgid($target_item["thr-parent"]).">";
454                         }
455
456                         $headers .= "\n";
457
458                         if (empty($target_item['title'])) {
459                                 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
460                                 $title = Item::selectFirst(['title'], $condition);
461
462                                 if (DBA::isResult($title) && ($title['title'] != '')) {
463                                         $subject = $title['title'];
464                                 } else {
465                                         $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
466                                         $title = Item::selectFirst(['title'], $condition);
467
468                                         if (DBA::isResult($title) && ($title['title'] != '')) {
469                                                 $subject = $title['title'];
470                                         }
471                                 }
472                         }
473
474                         if (strncasecmp($subject, 'RE:', 3)) {
475                                 $subject = 'Re: ' . $subject;
476                         }
477                 }
478
479                 Email::send($addr, $subject, $headers, $target_item);
480         }
481 }