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