3 * @file src/Worker/Delivery.php
5 namespace Friendica\Worker;
7 use Friendica\BaseObject;
8 use Friendica\Core\Config;
9 use Friendica\Core\L10n;
10 use Friendica\Core\Protocol;
11 use Friendica\Core\System;
12 use Friendica\Database\DBA;
13 use Friendica\Model\Contact;
14 use Friendica\Model\Item;
15 use Friendica\Model\Queue;
16 use Friendica\Model\User;
17 use Friendica\Protocol\DFRN;
18 use Friendica\Protocol\ActivityPub;
19 use Friendica\Protocol\Diaspora;
20 use Friendica\Protocol\Email;
22 require_once 'include/items.php';
24 class Delivery extends BaseObject
27 const SUGGESTION = 'suggest';
28 const RELOCATION = 'relocate';
29 const DELETION = 'drop';
30 const POST = 'wall-new';
31 const COMMENT = 'comment-new';
32 const REMOVAL = 'removeme';
34 public static function execute($cmd, $item_id, $contact_id)
36 logger('Invoked: ' . $cmd . ': ' . $item_id . ' to ' . $contact_id, LOGGER_DEBUG);
40 $public_message = false;
42 if ($cmd == self::MAIL) {
43 $target_item = DBA::selectFirst('mail', [], ['id' => $item_id]);
44 if (!DBA::isResult($target_item)) {
47 $uid = $target_item['uid'];
49 } elseif ($cmd == self::SUGGESTION) {
50 $target_item = DBA::selectFirst('fsuggest', [], ['id' => $item_id]);
51 if (!DBA::isResult($target_item)) {
54 $uid = $target_item['uid'];
55 } elseif ($cmd == self::RELOCATION) {
58 $item = Item::selectFirst(['parent'], ['id' => $item_id]);
59 if (!DBA::isResult($item) || empty($item['parent'])) {
62 $parent_id = intval($item['parent']);
64 $condition = ['id' => [$item_id, $parent_id], 'moderated' => false];
65 $params = ['order' => ['id']];
66 $itemdata = Item::select([], $condition, $params);
69 while ($item = Item::fetch($itemdata)) {
70 if ($item['id'] == $parent_id) {
73 if ($item['id'] == $item_id) {
78 DBA::close($itemdata);
80 if (empty($target_item)) {
81 logger('Item ' . $item_id . "wasn't found. Quitting here.");
86 logger('Parent ' . $parent_id . ' for item ' . $item_id . "wasn't found. Quitting here.");
90 $uid = $target_item['contact-uid'];
92 // avoid race condition with deleting entries
93 if ($items[0]['deleted']) {
94 foreach ($items as $item) {
99 // When commenting too fast after delivery, a post wasn't recognized as top level post.
100 // The count then showed more than one entry. The additional check should help.
101 // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
102 if ((($parent['id'] == $item_id) || (count($items) == 1)) && ($parent['uri'] === $parent['parent-uri'])) {
103 logger('Top level post');
107 // This is IMPORTANT!!!!
109 // We will only send a "notify owner to relay" or followup message if the referenced post
110 // originated on our system by virtue of having our hostname somewhere
111 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
112 // if $parent['wall'] == 1 we will already have the parent message in our array
113 // and we will relay the whole lot.
115 $localhost = self::getApp()->get_hostname();
116 if (strpos($localhost, ':')) {
117 $localhost = substr($localhost, 0, strpos($localhost, ':'));
121 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
122 * have been known to cause runaway conditions which affected several servers, along with
123 * permissions issues.
127 if (!$top_level && ($parent['wall'] == 0) && stristr($target_item['uri'], $localhost)) {
128 logger('Followup ' . $target_item["guid"], LOGGER_DEBUG);
129 // local followup to remote post
133 if (empty($parent['allow_cid'])
134 && empty($parent['allow_gid'])
135 && empty($parent['deny_cid'])
136 && empty($parent['deny_gid'])
137 && !$parent["private"]) {
138 $public_message = true;
143 logger('No delivery data for ' . $cmd . ' - Item ID: ' .$item_id . ' - Contact ID: ' . $contact_id);
146 $owner = User::getOwnerDataById($uid);
147 if (!DBA::isResult($owner)) {
151 // We don't deliver our items to blocked or pending contacts, and not to ourselves either
152 $contact = DBA::selectFirst('contact', [],
153 ['id' => $contact_id, 'blocked' => false, 'pending' => false, 'self' => false]
155 if (!DBA::isResult($contact)) {
159 // Transmit via Diaspora if the thread had started as Diaspora post
160 // This is done since the uri wouldn't match (Diaspora doesn't transmit it)
161 if (isset($parent) && ($parent['network'] == Protocol::DIASPORA) && ($contact['network'] == Protocol::DFRN)) {
162 $contact['network'] = Protocol::DIASPORA;
165 logger("Delivering " . $cmd . " followup=$followup - via network " . $contact['network']);
167 switch ($contact['network']) {
169 case Protocol::ACTIVITYPUB:
170 self::deliverActivityPub($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
174 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
177 case Protocol::DIASPORA:
178 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
181 case Protocol::OSTATUS:
182 // Do not send to otatus if we are not configured to send to public networks
183 if ($owner['prvnets']) {
186 if (Config::get('system','ostatus_disabled') || Config::get('system','dfrn_only')) {
190 // There is currently no code here to distribute anything to OStatus.
191 // This is done in "notifier.php" (See "url_recipients" and "push_notify")
195 self::deliverMail($cmd, $contact, $owner, $target_item);
206 * @brief Deliver content via DFRN
208 * @param string $cmd Command
209 * @param array $contact Contact record of the receiver
210 * @param array $owner Owner record of the sender
211 * @param array $items Item record of the content and the parent
212 * @param array $target_item Item record of the content
213 * @param boolean $public_message Is the content public?
214 * @param boolean $top_level Is it a thread starter?
215 * @param boolean $followup Is it an answer to a remote post?
217 private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
219 logger('Deliver ' . $target_item["guid"] . ' via DFRN to ' . (empty($contact['addr']) ? $contact['url'] : $contact['addr']));
221 if ($cmd == self::MAIL) {
222 $item = $target_item;
223 $item['body'] = Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
224 $atom = DFRN::mail($item, $owner);
225 } elseif ($cmd == self::SUGGESTION) {
226 $item = $target_item;
227 $atom = DFRN::fsuggest($item, $owner);
228 DBA::delete('fsuggest', ['id' => $item['id']]);
229 } elseif ($cmd == self::RELOCATION) {
230 $atom = DFRN::relocate($owner, $owner['uid']);
231 } elseif ($followup) {
232 $msgitems = [$target_item];
233 $atom = DFRN::entries($msgitems, $owner);
236 foreach ($items as $item) {
237 // Only add the parent when we don't delete other items.
238 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
239 $item["entry:comment-allow"] = true;
240 $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
244 $atom = DFRN::entries($msgitems, $owner);
247 logger('Notifier entry: ' . $contact["url"] . ' ' . $target_item["guid"] . ' entry: ' . $atom, LOGGER_DATA);
249 $basepath = implode('/', array_slice(explode('/', $contact['url']), 0, 3));
251 // perform local delivery if we are on the same site
253 if (link_compare($basepath, System::baseUrl())) {
254 $condition = ['nurl' => normalise_link($contact['url']), 'self' => true];
255 $target_self = DBA::selectFirst('contact', ['uid'], $condition);
256 if (!DBA::isResult($target_self)) {
259 $target_uid = $target_self['uid'];
261 // Check if the user has got this contact
262 $cid = Contact::getIdForURL($owner['url'], $target_uid);
264 // Otherwise there should be a public contact
265 $cid = Contact::getIdForURL($owner['url']);
271 $target_importer = DFRN::getImporter($cid, $target_uid);
272 if (empty($target_importer)) {
273 // This should never happen
277 DFRN::import($atom, $target_importer);
281 // We don't have a relationship with contacts on a public post.
282 // Se we transmit with the new method and via Diaspora as a fallback
283 if (!empty($items) && (($items[0]['uid'] == 0) || ($contact['uid'] == 0))) {
284 // Transmit in public if it's a relay post
285 $public_dfrn = ($contact['contact-type'] == Contact::ACCOUNT_TYPE_RELAY);
287 $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
289 // We never spool failed relay deliveries
291 logger('Relay delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
295 if (($deliver_status < 200) || ($deliver_status > 299)) {
296 // Transmit via Diaspora if not possible via Friendica
297 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
301 $deliver_status = DFRN::deliver($owner, $contact, $atom);
304 logger('Delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
306 if ($deliver_status < 0) {
307 logger('Delivery failed: queuing message ' . $target_item["guid"] );
308 Queue::add($contact['id'], Protocol::DFRN, $atom, false, $target_item['guid']);
311 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
312 // We successfully delivered a message, the contact is alive
313 Contact::unmarkForArchival($contact);
315 // The message could not be delivered. We mark the contact as "dead"
316 Contact::markForArchival($contact);
318 // Transmit via Diaspora when all other methods (legacy DFRN and new one) are failing.
319 // This is a fallback for systems that don't know the new methods.
320 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
325 * @brief Deliver content via Diaspora
327 * @param string $cmd Command
328 * @param array $contact Contact record of the receiver
329 * @param array $owner Owner record of the sender
330 * @param array $items Item record of the content and the parent
331 * @param array $target_item Item record of the content
332 * @param boolean $public_message Is the content public?
333 * @param boolean $top_level Is it a thread starter?
334 * @param boolean $followup Is it an answer to a remote post?
336 private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
338 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
339 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != Contact::ACCOUNT_TYPE_COMMUNITY);
341 if ($public_message) {
342 $loc = 'public batch ' . $contact['batch'];
344 $loc = $contact['addr'];
347 logger('Deliver ' . $target_item["guid"] . ' via Diaspora to ' . $loc);
349 if (Config::get('system', 'dfrn_only') || !Config::get('system', 'diaspora_enabled')) {
352 if ($cmd == self::MAIL) {
353 Diaspora::sendMail($target_item, $owner, $contact);
357 if ($cmd == self::SUGGESTION) {
360 if (!$contact['pubkey'] && !$public_message) {
363 if (($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
364 // top-level retraction
365 logger('diaspora retract: ' . $loc);
366 Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
368 } elseif ($cmd == self::RELOCATION) {
369 Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
371 } elseif ($followup) {
372 // send comments and likes to owner to relay
373 logger('diaspora followup: ' . $loc);
374 Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
376 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
377 // we are the relay - send comments, likes and relayable_retractions to our conversants
378 logger('diaspora relay: ' . $loc);
379 Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
381 } elseif ($top_level && !$walltowall) {
382 // currently no workable solution for sending walltowall
383 logger('diaspora status: ' . $loc);
384 Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
388 logger('Unknown mode ' . $cmd . ' for ' . $loc);
392 * @brief Deliver content via ActivityPub
394 * @param string $cmd Command
395 * @param array $contact Contact record of the receiver
396 * @param array $owner Owner record of the sender
397 * @param array $items Item record of the content and the parent
398 * @param array $target_item Item record of the content
399 * @param boolean $public_message Is the content public?
400 * @param boolean $top_level Is it a thread starter?
401 * @param boolean $followup Is it an answer to a remote post?
403 private static function deliverActivityPub($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
405 // We don't treat Forum posts as "wall-to-wall" to be able to post them via ActivityPub
406 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != Contact::ACCOUNT_TYPE_COMMUNITY);
408 if ($public_message) {
409 $loc = 'public batch ' . $contact['batch'];
411 $loc = $contact['addr'];
414 logger('Deliver ' . $target_item["guid"] . ' via ActivityPub to ' . $loc);
416 // if (Config::get('system', 'dfrn_only') || !Config::get('system', 'diaspora_enabled')) {
419 if ($cmd == self::MAIL) {
420 // ActivityPub::sendMail($target_item, $owner, $contact);
424 if ($cmd == self::SUGGESTION) {
427 // if (!$contact['pubkey'] && !$public_message) {
428 // logger('No public key, no delivery.');
431 if (($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
432 // top-level retraction
433 logger('ActivityPub retract: ' . $loc);
434 // ActivityPub::sendRetraction($target_item, $owner, $contact, $public_message);
436 } elseif ($cmd == self::RELOCATION) {
437 // ActivityPub::sendAccountMigration($owner, $contact, $owner['uid']);
439 } elseif ($followup) {
440 // send comments and likes to owner to relay
441 logger('ActivityPub followup: ' . $loc);
442 $data = ActivityPub::createActivityFromItem($target_item['id']);
443 $content = json_encode($data);
444 ActivityPub::transmit($content, $contact['notify'], $owner['uid']);
445 // ActivityPub::sendFollowup($target_item, $owner, $contact, $public_message);
447 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
448 // we are the relay - send comments, likes and relayable_retractions to our conversants
449 logger('ActivityPub relay: ' . $loc);
450 $data = ActivityPub::createActivityFromItem($target_item['id']);
451 $content = json_encode($data);
452 ActivityPub::transmit($content, $contact['notify'], $owner['uid']);
453 // ActivityPub::sendRelay($target_item, $owner, $contact, $public_message);
455 } elseif ($top_level && !$walltowall) {
456 // currently no workable solution for sending walltowall
457 logger('ActivityPub status: ' . $loc);
458 $data = ActivityPub::createActivityFromItem($target_item['id']);
459 $content = json_encode($data);
460 ActivityPub::transmit($content, $contact['notify'], $owner['uid']);
461 // ActivityPub::sendStatus($target_item, $owner, $contact, $public_message);
465 logger('Unknown mode ' . $cmd . ' for ' . $loc);
469 * @brief Deliver content via mail
471 * @param string $cmd Command
472 * @param array $contact Contact record of the receiver
473 * @param array $owner Owner record of the sender
474 * @param array $target_item Item record of the content
476 private static function deliverMail($cmd, $contact, $owner, $target_item)
478 if (Config::get('system','dfrn_only')) {
481 // WARNING: does not currently convert to RFC2047 header encodings, etc.
483 $addr = $contact['addr'];
484 if (!strlen($addr)) {
488 if (!in_array($cmd, [self::POST, self::COMMENT])) {
492 $local_user = DBA::selectFirst('user', [], ['uid' => $owner['uid']]);
493 if (!DBA::isResult($local_user)) {
497 logger('Deliver ' . $target_item["guid"] . ' via mail to ' . $contact['addr']);
500 $mailacct = DBA::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
501 if (DBA::isResult($mailacct) && !empty($mailacct['reply_to'])) {
502 $reply_to = $mailacct['reply_to'];
505 $subject = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : L10n::t("\x28no subject\x29"));
507 // only expose our real email address to true friends
509 if (($contact['rel'] == Contact::FRIEND) && !$contact['blocked']) {
511 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to.'>' . "\n";
512 $headers .= 'Sender: ' . $local_user['email'] . "\n";
514 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8').' <' . $local_user['email'] . '>' . "\n";
517 $headers = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <noreply@' . self::getApp()->get_hostname() . '>' . "\n";
520 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
522 if ($target_item['uri'] !== $target_item['parent-uri']) {
523 $headers .= "References: <" . Email::iri2msgid($target_item["parent-uri"]) . ">";
525 // If Threading is enabled, write down the correct parent
526 if (($target_item["thr-parent"] != "") && ($target_item["thr-parent"] != $target_item["parent-uri"])) {
527 $headers .= " <".Email::iri2msgid($target_item["thr-parent"]).">";
532 if (empty($target_item['title'])) {
533 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
534 $title = Item::selectFirst(['title'], $condition);
536 if (DBA::isResult($title) && ($title['title'] != '')) {
537 $subject = $title['title'];
539 $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
540 $title = Item::selectFirst(['title'], $condition);
542 if (DBA::isResult($title) && ($title['title'] != '')) {
543 $subject = $title['title'];
548 if (strncasecmp($subject, 'RE:', 3)) {
549 $subject = 'Re: ' . $subject;
553 Email::send($addr, $subject, $headers, $target_item);