]> git.mxchange.org Git - friendica.git/blob - src/Worker/Delivery.php
d7d9ac504da9b44479fc256275faa06b8660c932
[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 ' . $item_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          */
234         private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
235         {
236                 Logger::log('Deliver ' . defaults($target_item, 'guid', $target_item['id']) . ' via DFRN to ' . (empty($contact['addr']) ? $contact['url'] : $contact['addr']));
237
238                 if ($cmd == self::MAIL) {
239                         $item = $target_item;
240                         $item['body'] = Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
241                         $atom = DFRN::mail($item, $owner);
242                 } elseif ($cmd == self::SUGGESTION) {
243                         $item = $target_item;
244                         $atom = DFRN::fsuggest($item, $owner);
245                         DBA::delete('fsuggest', ['id' => $item['id']]);
246                 } elseif ($cmd == self::RELOCATION) {
247                         $atom = DFRN::relocate($owner, $owner['uid']);
248                 } elseif ($followup) {
249                         $msgitems = [$target_item];
250                         $atom = DFRN::entries($msgitems, $owner);
251                 } else {
252                         $msgitems = [];
253                         foreach ($items as $item) {
254                                 // Only add the parent when we don't delete other items.
255                                 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
256                                         $item["entry:comment-allow"] = true;
257                                         $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
258                                         $msgitems[] = $item;
259                                 }
260                         }
261                         $atom = DFRN::entries($msgitems, $owner);
262                 }
263
264                 Logger::log('Notifier entry: ' . $contact["url"] . ' ' . defaults($target_item, 'guid', $target_item['id']) . ' entry: ' . $atom, Logger::DATA);
265
266                 $basepath =  implode('/', array_slice(explode('/', $contact['url']), 0, 3));
267
268                 // perform local delivery if we are on the same site
269
270                 if (Strings::compareLink($basepath, System::baseUrl())) {
271                         $condition = ['nurl' => Strings::normaliseLink($contact['url']), 'self' => true];
272                         $target_self = DBA::selectFirst('contact', ['uid'], $condition);
273                         if (!DBA::isResult($target_self)) {
274                                 return;
275                         }
276                         $target_uid = $target_self['uid'];
277
278                         // Check if the user has got this contact
279                         $cid = Contact::getIdForURL($owner['url'], $target_uid);
280                         if (!$cid) {
281                                 // Otherwise there should be a public contact
282                                 $cid = Contact::getIdForURL($owner['url']);
283                                 if (!$cid) {
284                                         return;
285                                 }
286                         }
287
288                         $target_importer = DFRN::getImporter($cid, $target_uid);
289                         if (empty($target_importer)) {
290                                 // This should never happen
291                                 return;
292                         }
293
294                         DFRN::import($atom, $target_importer);
295                         return;
296                 }
297
298                 // We don't have a relationship with contacts on a public post.
299                 // Se we transmit with the new method and via Diaspora as a fallback
300                 if (!empty($items) && (($items[0]['uid'] == 0) || ($contact['uid'] == 0))) {
301                         // Transmit in public if it's a relay post
302                         $public_dfrn = ($contact['contact-type'] == Contact::ACCOUNT_TYPE_RELAY);
303
304                         $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
305
306                         // We never spool failed relay deliveries
307                         if ($public_dfrn) {
308                                 Logger::log('Relay delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
309                                 return;
310                         }
311
312                         if (($deliver_status < 200) || ($deliver_status > 299)) {
313                                 // Transmit via Diaspora if not possible via Friendica
314                                 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
315                                 return;
316                         }
317                 } elseif ($cmd != self::RELOCATION) {
318                         $deliver_status = DFRN::deliver($owner, $contact, $atom);
319                 } else {
320                         $deliver_status = DFRN::deliver($owner, $contact, $atom, false, true);
321                 }
322
323                 Logger::log('Delivery to ' . $contact['url'] . ' with guid ' . defaults($target_item, 'guid', $target_item['id']) . ' returns ' . $deliver_status);
324
325                 if ($deliver_status < 0) {
326                         Logger::log('Delivery failed: queuing message ' . defaults($target_item, 'guid', $target_item['id']));
327                         Queue::add($contact['id'], Protocol::DFRN, $atom, false, $target_item['guid']);
328                 }
329
330                 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
331                         // We successfully delivered a message, the contact is alive
332                         Contact::unmarkForArchival($contact);
333                 } else {
334                         // The message could not be delivered. We mark the contact as "dead"
335                         Contact::markForArchival($contact);
336
337                         // Transmit via Diaspora when all other methods (legacy DFRN and new one) are failing.
338                         // This is a fallback for systems that don't know the new methods.
339                         self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
340                 }
341         }
342
343         /**
344          * @brief Deliver content via Diaspora
345          *
346          * @param string  $cmd            Command
347          * @param array   $contact        Contact record of the receiver
348          * @param array   $owner          Owner record of the sender
349          * @param array   $items          Item record of the content and the parent
350          * @param array   $target_item    Item record of the content
351          * @param boolean $public_message Is the content public?
352          * @param boolean $top_level      Is it a thread starter?
353          * @param boolean $followup       Is it an answer to a remote post?
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'] != Contact::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          */
418         private static function deliverMail($cmd, $contact, $owner, $target_item)
419         {
420                 if (Config::get('system','dfrn_only')) {
421                         return;
422                 }
423                 // WARNING: does not currently convert to RFC2047 header encodings, etc.
424
425                 $addr = $contact['addr'];
426                 if (!strlen($addr)) {
427                         return;
428                 }
429
430                 if (!in_array($cmd, [self::POST, self::COMMENT])) {
431                         return;
432                 }
433
434                 $local_user = DBA::selectFirst('user', [], ['uid' => $owner['uid']]);
435                 if (!DBA::isResult($local_user)) {
436                         return;
437                 }
438
439                 Logger::log('Deliver ' . $target_item["guid"] . ' via mail to ' . $contact['addr']);
440
441                 $reply_to = '';
442                 $mailacct = DBA::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
443                 if (DBA::isResult($mailacct) && !empty($mailacct['reply_to'])) {
444                         $reply_to = $mailacct['reply_to'];
445                 }
446
447                 $subject  = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : L10n::t("\x28no subject\x29"));
448
449                 // only expose our real email address to true friends
450
451                 if (($contact['rel'] == Contact::FRIEND) && !$contact['blocked']) {
452                         if ($reply_to) {
453                                 $headers  = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to.'>' . "\n";
454                                 $headers .= 'Sender: ' . $local_user['email'] . "\n";
455                         } else {
456                                 $headers  = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8').' <' . $local_user['email'] . '>' . "\n";
457                         }
458                 } else {
459                         $headers  = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <noreply@' . self::getApp()->getHostName() . '>' . "\n";
460                 }
461
462                 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
463
464                 if ($target_item['uri'] !== $target_item['parent-uri']) {
465                         $headers .= "References: <" . Email::iri2msgid($target_item["parent-uri"]) . ">";
466
467                         // If Threading is enabled, write down the correct parent
468                         if (($target_item["thr-parent"] != "") && ($target_item["thr-parent"] != $target_item["parent-uri"])) {
469                                 $headers .= " <".Email::iri2msgid($target_item["thr-parent"]).">";
470                         }
471
472                         $headers .= "\n";
473
474                         if (empty($target_item['title'])) {
475                                 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
476                                 $title = Item::selectFirst(['title'], $condition);
477
478                                 if (DBA::isResult($title) && ($title['title'] != '')) {
479                                         $subject = $title['title'];
480                                 } else {
481                                         $condition = ['parent-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                                         }
487                                 }
488                         }
489
490                         if (strncasecmp($subject, 'RE:', 3)) {
491                                 $subject = 'Re: ' . $subject;
492                         }
493                 }
494
495                 Email::send($addr, $subject, $headers, $target_item);
496         }
497 }