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