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\Logger;
11 use Friendica\Core\Protocol;
12 use Friendica\Core\System;
13 use Friendica\Database\DBA;
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;
22 class Delivery extends BaseObject
25 const SUGGESTION = 'suggest';
26 const RELOCATION = 'relocate';
27 const DELETION = 'drop';
28 const POST = 'wall-new';
30 const UPLINK = 'uplink';
31 const REMOVAL = 'removeme';
32 const PROFILEUPDATE = 'profileupdate';
34 public static function execute($cmd, $target_id, $contact_id)
36 Logger::info('Invoked', ['cmd' => $cmd, 'target' => $target_id, 'contact' => $contact_id]);
40 $public_message = false;
43 if ($cmd == self::MAIL) {
44 $target_item = DBA::selectFirst('mail', [], ['id' => $target_id]);
45 if (!DBA::isResult($target_item)) {
48 $uid = $target_item['uid'];
49 } elseif ($cmd == self::SUGGESTION) {
50 $target_item = DBA::selectFirst('fsuggest', [], ['id' => $target_id]);
51 if (!DBA::isResult($target_item)) {
54 $uid = $target_item['uid'];
55 } elseif ($cmd == self::RELOCATION) {
59 $item = Model\Item::selectFirst(['parent'], ['id' => $target_id]);
60 if (!DBA::isResult($item) || empty($item['parent'])) {
63 $parent_id = intval($item['parent']);
65 $condition = ['id' => [$target_id, $parent_id], 'visible' => true, 'moderated' => false];
66 $params = ['order' => ['id']];
67 $itemdata = Model\Item::select([], $condition, $params);
69 while ($item = Model\Item::fetch($itemdata)) {
70 if ($item['id'] == $parent_id) {
73 if ($item['id'] == $target_id) {
78 DBA::close($itemdata);
80 if (empty($target_item)) {
81 Logger::log('Item ' . $target_id . "wasn't found. Quitting here.");
86 Logger::log('Parent ' . $parent_id . ' for item ' . $target_id . "wasn't found. Quitting here.");
90 if (!empty($target_item['contact-uid'])) {
91 $uid = $target_item['contact-uid'];
92 } elseif (!empty($target_item['uid'])) {
93 $uid = $target_item['uid'];
95 Logger::log('Only public users for item ' . $target_id, Logger::DEBUG);
99 if (!empty($contact_id) && Model\Contact::isArchived($contact_id)) {
100 Logger::info('Contact is archived', ['id' => $contact_id, 'cmd' => $cmd, 'item' => $target_item['id']]);
101 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
102 Model\ItemDeliveryData::incrementQueueFailed($target_item['id']);
107 // avoid race condition with deleting entries
108 if ($items[0]['deleted']) {
109 foreach ($items as $item) {
110 $item['deleted'] = 1;
114 // When commenting too fast after delivery, a post wasn't recognized as top level post.
115 // The count then showed more than one entry. The additional check should help.
116 // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
117 if ((($parent['id'] == $target_id) || (count($items) == 1)) && ($parent['uri'] === $parent['parent-uri'])) {
118 Logger::log('Top level post');
122 // This is IMPORTANT!!!!
124 // We will only send a "notify owner to relay" or followup message if the referenced post
125 // originated on our system by virtue of having our hostname somewhere
126 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
127 // if $parent['wall'] == 1 we will already have the parent message in our array
128 // and we will relay the whole lot.
130 $localhost = self::getApp()->getHostName();
131 if (strpos($localhost, ':')) {
132 $localhost = substr($localhost, 0, strpos($localhost, ':'));
136 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
137 * have been known to cause runaway conditions which affected several servers, along with
138 * permissions issues.
142 if (!$top_level && ($parent['wall'] == 0) && stristr($target_item['uri'], $localhost)) {
143 Logger::log('Followup ' . $target_item["guid"], Logger::DEBUG);
144 // local followup to remote post
148 if (empty($parent['allow_cid'])
149 && empty($parent['allow_gid'])
150 && empty($parent['deny_cid'])
151 && empty($parent['deny_gid'])
152 && !$parent["private"]) {
153 $public_message = true;
158 Logger::log('No delivery data for ' . $cmd . ' - Item ID: ' .$target_id . ' - Contact ID: ' . $contact_id);
161 $owner = Model\User::getOwnerDataById($uid);
162 if (!DBA::isResult($owner)) {
166 // We don't deliver our items to blocked or pending contacts, and not to ourselves either
167 $contact = DBA::selectFirst('contact', [],
168 ['id' => $contact_id, 'blocked' => false, 'pending' => false, 'self' => false]
170 if (!DBA::isResult($contact)) {
174 if (Network::isUrlBlocked($contact['url'])) {
178 // Transmit via Diaspora if the thread had started as Diaspora post
179 // This is done since the uri wouldn't match (Diaspora doesn't transmit it)
180 if (isset($parent) && ($parent['network'] == Protocol::DIASPORA) && ($contact['network'] == Protocol::DFRN)) {
181 $contact['network'] = Protocol::DIASPORA;
184 Logger::log("Delivering " . $cmd . " followup=$followup - via network " . $contact['network']);
186 switch ($contact['network']) {
189 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
192 case Protocol::DIASPORA:
193 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
197 self::deliverMail($cmd, $contact, $owner, $target_item);
208 * @brief Deliver content via DFRN
210 * @param string $cmd Command
211 * @param array $contact Contact record of the receiver
212 * @param array $owner Owner record of the sender
213 * @param array $items Item record of the content and the parent
214 * @param array $target_item Item record of the content
215 * @param boolean $public_message Is the content public?
216 * @param boolean $top_level Is it a thread starter?
217 * @param boolean $followup Is it an answer to a remote post?
218 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
219 * @throws \ImagickException
221 private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
223 Logger::log('Deliver ' . defaults($target_item, 'guid', $target_item['id']) . ' via DFRN to ' . (empty($contact['addr']) ? $contact['url'] : $contact['addr']));
225 if ($cmd == self::MAIL) {
226 $item = $target_item;
227 $item['body'] = Model\Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
228 $atom = DFRN::mail($item, $owner);
229 } elseif ($cmd == self::SUGGESTION) {
230 $item = $target_item;
231 $atom = DFRN::fsuggest($item, $owner);
232 DBA::delete('fsuggest', ['id' => $item['id']]);
233 } elseif ($cmd == self::RELOCATION) {
234 $atom = DFRN::relocate($owner, $owner['uid']);
235 } elseif ($followup) {
236 $msgitems = [$target_item];
237 $atom = DFRN::entries($msgitems, $owner);
240 foreach ($items as $item) {
241 // Only add the parent when we don't delete other items.
242 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
243 $item["entry:comment-allow"] = true;
244 $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
248 $atom = DFRN::entries($msgitems, $owner);
251 Logger::log('Notifier entry: ' . $contact["url"] . ' ' . defaults($target_item, 'guid', $target_item['id']) . ' entry: ' . $atom, Logger::DATA);
253 $basepath = implode('/', array_slice(explode('/', $contact['url']), 0, 3));
255 // perform local delivery if we are on the same site
257 if (Strings::compareLink($basepath, System::baseUrl())) {
258 $condition = ['nurl' => Strings::normaliseLink($contact['url']), 'self' => true];
259 $target_self = DBA::selectFirst('contact', ['uid'], $condition);
260 if (!DBA::isResult($target_self)) {
263 $target_uid = $target_self['uid'];
265 // Check if the user has got this contact
266 $cid = Model\Contact::getIdForURL($owner['url'], $target_uid);
268 // Otherwise there should be a public contact
269 $cid = Model\Contact::getIdForURL($owner['url']);
275 $target_importer = DFRN::getImporter($cid, $target_uid);
276 if (empty($target_importer)) {
277 // This should never happen
281 DFRN::import($atom, $target_importer);
283 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
284 Model\ItemDeliveryData::incrementQueueDone($target_item['id'], Model\ItemDeliveryData::DFRN);
290 $protocol = Model\ItemDeliveryData::DFRN;
292 // We don't have a relationship with contacts on a public post.
293 // Se we transmit with the new method and via Diaspora as a fallback
294 if (!empty($items) && (($items[0]['uid'] == 0) || ($contact['uid'] == 0))) {
295 // Transmit in public if it's a relay post
296 $public_dfrn = ($contact['contact-type'] == Model\Contact::TYPE_RELAY);
298 $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
300 // We never spool failed relay deliveries
302 Logger::log('Relay delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
306 if (($deliver_status < 200) || ($deliver_status > 299)) {
307 // Transmit via Diaspora if not possible via Friendica
308 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
311 } elseif ($cmd != self::RELOCATION) {
312 // DFRN payload over Diaspora transport layer
313 $deliver_status = DFRN::transmit($owner, $contact, $atom);
314 if ($deliver_status < 200) {
316 $deliver_status = DFRN::deliver($owner, $contact, $atom);
317 $protocol = Model\ItemDeliveryData::LEGACY_DFRN;
320 $deliver_status = DFRN::deliver($owner, $contact, $atom);
321 $protocol = Model\ItemDeliveryData::LEGACY_DFRN;
324 Logger::info('DFRN Delivery', ['cmd' => $cmd, 'url' => $contact['url'], 'guid' => defaults($target_item, 'guid', $target_item['id']), 'return' => $deliver_status]);
326 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
327 // We successfully delivered a message, the contact is alive
328 Model\Contact::unmarkForArchival($contact);
330 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
331 Model\ItemDeliveryData::incrementQueueDone($target_item['id'], $protocol);
334 // The message could not be delivered. We mark the contact as "dead"
335 Model\Contact::markForArchival($contact);
337 Logger::info('Delivery failed: defer message', ['id' => defaults($target_item, 'guid', $target_item['id'])]);
338 if (!Worker::defer() && in_array($cmd, [Delivery::POST, Delivery::POKE])) {
339 Model\ItemDeliveryData::incrementQueueFailed($target_item['id']);
345 * @brief Deliver content via Diaspora
347 * @param string $cmd Command
348 * @param array $contact Contact record of the receiver
349 * @param array $owner Owner record of the sender
350 * @param array $items Item record of the content and the parent
351 * @param array $target_item Item record of the content
352 * @param boolean $public_message Is the content public?
353 * @param boolean $top_level Is it a thread starter?
354 * @param boolean $followup Is it an answer to a remote post?
355 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
356 * @throws \ImagickException
358 private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
360 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
361 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != Model\User::ACCOUNT_TYPE_COMMUNITY);
363 if ($public_message) {
364 $loc = 'public batch ' . $contact['batch'];
366 $loc = $contact['addr'];
369 Logger::log('Deliver ' . defaults($target_item, 'guid', $target_item['id']) . ' via Diaspora to ' . $loc);
371 if (Config::get('system', 'dfrn_only') || !Config::get('system', 'diaspora_enabled')) {
375 if ($cmd == self::MAIL) {
376 Diaspora::sendMail($target_item, $owner, $contact);
380 if ($cmd == self::SUGGESTION) {
384 if (!$contact['pubkey'] && !$public_message) {
388 if ($cmd == self::RELOCATION) {
389 $deliver_status = Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
390 } elseif ($target_item['deleted'] && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
391 // top-level retraction
392 Logger::log('diaspora retract: ' . $loc);
393 $deliver_status = Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
394 } elseif ($followup) {
395 // send comments and likes to owner to relay
396 Logger::log('diaspora followup: ' . $loc);
397 $deliver_status = Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
398 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
399 // we are the relay - send comments, likes and relayable_retractions to our conversants
400 Logger::log('diaspora relay: ' . $loc);
401 $deliver_status = Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
402 } elseif ($top_level && !$walltowall) {
403 // currently no workable solution for sending walltowall
404 Logger::log('diaspora status: ' . $loc);
405 $deliver_status = Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
407 Logger::log('Unknown mode ' . $cmd . ' for ' . $loc);
411 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
412 // We successfully delivered a message, the contact is alive
413 Model\Contact::unmarkForArchival($contact);
415 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
416 Model\ItemDeliveryData::incrementQueueDone($target_item['id'], Model\ItemDeliveryData::DIASPORA);
419 // The message could not be delivered. We mark the contact as "dead"
420 Model\Contact::markForArchival($contact);
422 if (empty($contact['contact-type']) || ($contact['contact-type'] != Model\Contact::TYPE_RELAY)) {
423 Logger::info('Delivery failed: defer message', ['id' => defaults($target_item, 'guid', $target_item['id'])]);
424 // defer message for redelivery
425 if (!Worker::defer() && in_array($cmd, [Delivery::POST, Delivery::POKE])) {
426 Model\ItemDeliveryData::incrementQueueFailed($target_item['id'], Model\ItemDeliveryData::DIASPORA);
428 } elseif (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
429 Model\ItemDeliveryData::incrementQueueDone($target_item['id'], Model\ItemDeliveryData::DIASPORA);
435 * @brief Deliver content via mail
437 * @param string $cmd Command
438 * @param array $contact Contact record of the receiver
439 * @param array $owner Owner record of the sender
440 * @param array $target_item Item record of the content
441 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
442 * @throws \ImagickException
444 private static function deliverMail($cmd, $contact, $owner, $target_item)
446 if (Config::get('system','dfrn_only')) {
449 // WARNING: does not currently convert to RFC2047 header encodings, etc.
451 $addr = $contact['addr'];
452 if (!strlen($addr)) {
456 if (!in_array($cmd, [self::POST, self::POKE])) {
460 $local_user = DBA::selectFirst('user', [], ['uid' => $owner['uid']]);
461 if (!DBA::isResult($local_user)) {
465 Logger::log('Deliver ' . $target_item["guid"] . ' via mail to ' . $contact['addr']);
468 $mailacct = DBA::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
469 if (DBA::isResult($mailacct) && !empty($mailacct['reply_to'])) {
470 $reply_to = $mailacct['reply_to'];
473 $subject = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : L10n::t("\x28no subject\x29"));
475 // only expose our real email address to true friends
477 if (($contact['rel'] == Model\Contact::FRIEND) && !$contact['blocked']) {
479 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to.'>' . "\n";
480 $headers .= 'Sender: ' . $local_user['email'] . "\n";
482 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8').' <' . $local_user['email'] . '>' . "\n";
485 $headers = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <noreply@' . self::getApp()->getHostName() . '>' . "\n";
488 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
490 if ($target_item['uri'] !== $target_item['parent-uri']) {
491 $headers .= "References: <" . Email::iri2msgid($target_item["parent-uri"]) . ">";
493 // If Threading is enabled, write down the correct parent
494 if (($target_item["thr-parent"] != "") && ($target_item["thr-parent"] != $target_item["parent-uri"])) {
495 $headers .= " <".Email::iri2msgid($target_item["thr-parent"]).">";
500 if (empty($target_item['title'])) {
501 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
502 $title = Model\Item::selectFirst(['title'], $condition);
504 if (DBA::isResult($title) && ($title['title'] != '')) {
505 $subject = $title['title'];
507 $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
508 $title = Model\Item::selectFirst(['title'], $condition);
510 if (DBA::isResult($title) && ($title['title'] != '')) {
511 $subject = $title['title'];
516 if (strncasecmp($subject, 'RE:', 3)) {
517 $subject = 'Re: ' . $subject;
521 Email::send($addr, $subject, $headers, $target_item);