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