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