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)) {
46 self::setFailedQueue($cmd, $target_id);
49 $uid = $target_item['uid'];
50 } elseif ($cmd == self::SUGGESTION) {
51 $target_item = DBA::selectFirst('fsuggest', [], ['id' => $target_id]);
52 if (!DBA::isResult($target_item)) {
53 self::setFailedQueue($cmd, $target_id);
56 $uid = $target_item['uid'];
57 } elseif ($cmd == self::RELOCATION) {
61 $item = Model\Item::selectFirst(['parent'], ['id' => $target_id]);
62 if (!DBA::isResult($item) || empty($item['parent'])) {
63 self::setFailedQueue($cmd, $target_id);
66 $parent_id = intval($item['parent']);
68 $condition = ['id' => [$target_id, $parent_id], 'visible' => true, 'moderated' => false];
69 $params = ['order' => ['id']];
70 $itemdata = Model\Item::select([], $condition, $params);
72 while ($item = Model\Item::fetch($itemdata)) {
73 if ($item['id'] == $parent_id) {
76 if ($item['id'] == $target_id) {
81 DBA::close($itemdata);
83 if (empty($target_item)) {
84 Logger::log('Item ' . $target_id . "wasn't found. Quitting here.");
85 self::setFailedQueue($cmd, $target_id);
90 Logger::log('Parent ' . $parent_id . ' for item ' . $target_id . "wasn't found. Quitting here.");
91 self::setFailedQueue($cmd, $target_id);
95 if (!empty($target_item['contact-uid'])) {
96 $uid = $target_item['contact-uid'];
97 } elseif (!empty($target_item['uid'])) {
98 $uid = $target_item['uid'];
100 Logger::log('Only public users for item ' . $target_id, Logger::DEBUG);
101 self::setFailedQueue($cmd, $target_id);
105 if (!empty($contact_id) && Model\Contact::isArchived($contact_id)) {
106 Logger::info('Contact is archived', ['id' => $contact_id, 'cmd' => $cmd, 'item' => $target_item['id']]);
107 self::setFailedQueue($cmd, $target_id);
111 // avoid race condition with deleting entries
112 if ($items[0]['deleted']) {
113 foreach ($items as $item) {
114 $item['deleted'] = 1;
118 // When commenting too fast after delivery, a post wasn't recognized as top level post.
119 // The count then showed more than one entry. The additional check should help.
120 // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
121 if ((($parent['id'] == $target_id) || (count($items) == 1)) && ($parent['uri'] === $parent['parent-uri'])) {
122 Logger::log('Top level post');
126 // This is IMPORTANT!!!!
128 // We will only send a "notify owner to relay" or followup message if the referenced post
129 // originated on our system by virtue of having our hostname somewhere
130 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
131 // if $parent['wall'] == 1 we will already have the parent message in our array
132 // and we will relay the whole lot.
134 $localhost = self::getApp()->getHostName();
135 if (strpos($localhost, ':')) {
136 $localhost = substr($localhost, 0, strpos($localhost, ':'));
140 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
141 * have been known to cause runaway conditions which affected several servers, along with
142 * permissions issues.
146 if (!$top_level && ($parent['wall'] == 0) && stristr($target_item['uri'], $localhost)) {
147 Logger::log('Followup ' . $target_item["guid"], Logger::DEBUG);
148 // local followup to remote post
152 if (empty($parent['allow_cid'])
153 && empty($parent['allow_gid'])
154 && empty($parent['deny_cid'])
155 && empty($parent['deny_gid'])
156 && !$parent["private"]) {
157 $public_message = true;
162 Logger::log('No delivery data for ' . $cmd . ' - Item ID: ' .$target_id . ' - Contact ID: ' . $contact_id);
165 $owner = Model\User::getOwnerDataById($uid);
166 if (!DBA::isResult($owner)) {
167 self::setFailedQueue($cmd, $target_id);
171 // We don't deliver our items to blocked or pending contacts, and not to ourselves either
172 $contact = DBA::selectFirst('contact', [],
173 ['id' => $contact_id, 'blocked' => false, 'pending' => false, 'self' => false]
175 if (!DBA::isResult($contact)) {
176 self::setFailedQueue($cmd, $target_id);
180 if (Network::isUrlBlocked($contact['url'])) {
181 self::setFailedQueue($cmd, $target_id);
185 // Transmit via Diaspora if the thread had started as Diaspora post
186 // This is done since the uri wouldn't match (Diaspora doesn't transmit it)
187 if (isset($parent) && ($parent['network'] == Protocol::DIASPORA) && ($contact['network'] == Protocol::DFRN)) {
188 $contact['network'] = Protocol::DIASPORA;
191 Logger::log("Delivering " . $cmd . " followup=$followup - via network " . $contact['network']);
193 switch ($contact['network']) {
196 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
199 case Protocol::DIASPORA:
200 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
204 self::deliverMail($cmd, $contact, $owner, $target_item);
214 private static function setFailedQueue($cmd, $id)
216 if (!in_array($cmd, [Delivery::POST, Delivery::POKE])) {
220 Model\ItemDeliveryData::incrementQueueFailed($id);
224 * @brief Deliver content via DFRN
226 * @param string $cmd Command
227 * @param array $contact Contact record of the receiver
228 * @param array $owner Owner record of the sender
229 * @param array $items Item record of the content and the parent
230 * @param array $target_item Item record of the content
231 * @param boolean $public_message Is the content public?
232 * @param boolean $top_level Is it a thread starter?
233 * @param boolean $followup Is it an answer to a remote post?
234 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
235 * @throws \ImagickException
237 private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
239 Logger::log('Deliver ' . defaults($target_item, 'guid', $target_item['id']) . ' via DFRN to ' . (empty($contact['addr']) ? $contact['url'] : $contact['addr']));
241 if ($cmd == self::MAIL) {
242 $item = $target_item;
243 $item['body'] = Model\Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
244 $atom = DFRN::mail($item, $owner);
245 } elseif ($cmd == self::SUGGESTION) {
246 $item = $target_item;
247 $atom = DFRN::fsuggest($item, $owner);
248 DBA::delete('fsuggest', ['id' => $item['id']]);
249 } elseif ($cmd == self::RELOCATION) {
250 $atom = DFRN::relocate($owner, $owner['uid']);
251 } elseif ($followup) {
252 $msgitems = [$target_item];
253 $atom = DFRN::entries($msgitems, $owner);
256 foreach ($items as $item) {
257 // Only add the parent when we don't delete other items.
258 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
259 $item["entry:comment-allow"] = true;
260 $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
264 $atom = DFRN::entries($msgitems, $owner);
267 Logger::log('Notifier entry: ' . $contact["url"] . ' ' . defaults($target_item, 'guid', $target_item['id']) . ' entry: ' . $atom, Logger::DATA);
269 $basepath = implode('/', array_slice(explode('/', $contact['url']), 0, 3));
271 // perform local delivery if we are on the same site
273 if (Strings::compareLink($basepath, System::baseUrl())) {
274 $condition = ['nurl' => Strings::normaliseLink($contact['url']), 'self' => true];
275 $target_self = DBA::selectFirst('contact', ['uid'], $condition);
276 if (!DBA::isResult($target_self)) {
279 $target_uid = $target_self['uid'];
281 // Check if the user has got this contact
282 $cid = Model\Contact::getIdForURL($owner['url'], $target_uid);
284 // Otherwise there should be a public contact
285 $cid = Model\Contact::getIdForURL($owner['url']);
291 $target_importer = DFRN::getImporter($cid, $target_uid);
292 if (empty($target_importer)) {
293 // This should never happen
297 DFRN::import($atom, $target_importer);
299 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
300 Model\ItemDeliveryData::incrementQueueDone($target_item['id'], Model\ItemDeliveryData::DFRN);
306 $protocol = Model\ItemDeliveryData::DFRN;
308 // We don't have a relationship with contacts on a public post.
309 // Se we transmit with the new method and via Diaspora as a fallback
310 if (!empty($items) && (($items[0]['uid'] == 0) || ($contact['uid'] == 0))) {
311 // Transmit in public if it's a relay post
312 $public_dfrn = ($contact['contact-type'] == Model\Contact::TYPE_RELAY);
314 $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
316 // We never spool failed relay deliveries
318 Logger::log('Relay delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
320 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
321 Model\ItemDeliveryData::incrementQueueDone($target_item['id'], $protocol);
326 if (($deliver_status < 200) || ($deliver_status > 299)) {
327 // Transmit via Diaspora if not possible via Friendica
328 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
331 } elseif ($cmd != self::RELOCATION) {
332 // DFRN payload over Diaspora transport layer
333 $deliver_status = DFRN::transmit($owner, $contact, $atom);
334 if ($deliver_status < 200) {
336 $deliver_status = DFRN::deliver($owner, $contact, $atom);
337 $protocol = Model\ItemDeliveryData::LEGACY_DFRN;
340 $deliver_status = DFRN::deliver($owner, $contact, $atom);
341 $protocol = Model\ItemDeliveryData::LEGACY_DFRN;
344 Logger::info('DFRN Delivery', ['cmd' => $cmd, 'url' => $contact['url'], 'guid' => defaults($target_item, 'guid', $target_item['id']), 'return' => $deliver_status]);
346 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
347 // We successfully delivered a message, the contact is alive
348 Model\Contact::unmarkForArchival($contact);
350 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
351 Model\ItemDeliveryData::incrementQueueDone($target_item['id'], $protocol);
354 // The message could not be delivered. We mark the contact as "dead"
355 Model\Contact::markForArchival($contact);
357 Logger::info('Delivery failed: defer message', ['id' => defaults($target_item, 'guid', $target_item['id'])]);
358 if (!Worker::defer() && in_array($cmd, [Delivery::POST, Delivery::POKE])) {
359 Model\ItemDeliveryData::incrementQueueFailed($target_item['id']);
365 * @brief Deliver content via Diaspora
367 * @param string $cmd Command
368 * @param array $contact Contact record of the receiver
369 * @param array $owner Owner record of the sender
370 * @param array $items Item record of the content and the parent
371 * @param array $target_item Item record of the content
372 * @param boolean $public_message Is the content public?
373 * @param boolean $top_level Is it a thread starter?
374 * @param boolean $followup Is it an answer to a remote post?
375 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
376 * @throws \ImagickException
378 private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
380 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
381 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != Model\User::ACCOUNT_TYPE_COMMUNITY);
383 if ($public_message) {
384 $loc = 'public batch ' . $contact['batch'];
386 $loc = $contact['addr'];
389 Logger::log('Deliver ' . defaults($target_item, 'guid', $target_item['id']) . ' via Diaspora to ' . $loc);
391 if (Config::get('system', 'dfrn_only') || !Config::get('system', 'diaspora_enabled')) {
395 if ($cmd == self::MAIL) {
396 Diaspora::sendMail($target_item, $owner, $contact);
400 if ($cmd == self::SUGGESTION) {
404 if (!$contact['pubkey'] && !$public_message) {
408 if ($cmd == self::RELOCATION) {
409 $deliver_status = Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
410 } elseif ($target_item['deleted'] && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
411 // top-level retraction
412 Logger::log('diaspora retract: ' . $loc);
413 $deliver_status = Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
414 } elseif ($followup) {
415 // send comments and likes to owner to relay
416 Logger::log('diaspora followup: ' . $loc);
417 $deliver_status = Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
418 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
419 // we are the relay - send comments, likes and relayable_retractions to our conversants
420 Logger::log('diaspora relay: ' . $loc);
421 $deliver_status = Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
422 } elseif ($top_level && !$walltowall) {
423 // currently no workable solution for sending walltowall
424 Logger::log('diaspora status: ' . $loc);
425 $deliver_status = Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
427 Logger::log('Unknown mode ' . $cmd . ' for ' . $loc);
431 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
432 // We successfully delivered a message, the contact is alive
433 Model\Contact::unmarkForArchival($contact);
435 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
436 Model\ItemDeliveryData::incrementQueueDone($target_item['id'], Model\ItemDeliveryData::DIASPORA);
439 // The message could not be delivered. We mark the contact as "dead"
440 Model\Contact::markForArchival($contact);
442 // When it is delivered to the public endpoint, we do mark the relay contact for archival as well
443 if ($public_message) {
444 Diaspora::markRelayForArchival($contact);
447 if (empty($contact['contact-type']) || ($contact['contact-type'] != Model\Contact::TYPE_RELAY)) {
448 Logger::info('Delivery failed: defer message', ['id' => defaults($target_item, 'guid', $target_item['id'])]);
449 // defer message for redelivery
450 if (!Worker::defer() && in_array($cmd, [Delivery::POST, Delivery::POKE])) {
451 Model\ItemDeliveryData::incrementQueueFailed($target_item['id'], Model\ItemDeliveryData::DIASPORA);
453 } elseif (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
454 Model\ItemDeliveryData::incrementQueueDone($target_item['id'], Model\ItemDeliveryData::DIASPORA);
460 * @brief Deliver content via mail
462 * @param string $cmd Command
463 * @param array $contact Contact record of the receiver
464 * @param array $owner Owner record of the sender
465 * @param array $target_item Item record of the content
466 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
467 * @throws \ImagickException
469 private static function deliverMail($cmd, $contact, $owner, $target_item)
471 if (Config::get('system','dfrn_only')) {
474 // WARNING: does not currently convert to RFC2047 header encodings, etc.
476 $addr = $contact['addr'];
477 if (!strlen($addr)) {
481 if (!in_array($cmd, [self::POST, self::POKE])) {
485 $local_user = DBA::selectFirst('user', [], ['uid' => $owner['uid']]);
486 if (!DBA::isResult($local_user)) {
490 Logger::log('Deliver ' . $target_item["guid"] . ' via mail to ' . $contact['addr']);
493 $mailacct = DBA::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
494 if (DBA::isResult($mailacct) && !empty($mailacct['reply_to'])) {
495 $reply_to = $mailacct['reply_to'];
498 $subject = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : L10n::t("\x28no subject\x29"));
500 // only expose our real email address to true friends
502 if (($contact['rel'] == Model\Contact::FRIEND) && !$contact['blocked']) {
504 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to.'>' . "\n";
505 $headers .= 'Sender: ' . $local_user['email'] . "\n";
507 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8').' <' . $local_user['email'] . '>' . "\n";
510 $headers = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <noreply@' . self::getApp()->getHostName() . '>' . "\n";
513 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
515 if ($target_item['uri'] !== $target_item['parent-uri']) {
516 $headers .= "References: <" . Email::iri2msgid($target_item["parent-uri"]) . ">";
518 // If Threading is enabled, write down the correct parent
519 if (($target_item["thr-parent"] != "") && ($target_item["thr-parent"] != $target_item["parent-uri"])) {
520 $headers .= " <".Email::iri2msgid($target_item["thr-parent"]).">";
525 if (empty($target_item['title'])) {
526 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
527 $title = Model\Item::selectFirst(['title'], $condition);
529 if (DBA::isResult($title) && ($title['title'] != '')) {
530 $subject = $title['title'];
532 $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
533 $title = Model\Item::selectFirst(['title'], $condition);
535 if (DBA::isResult($title) && ($title['title'] != '')) {
536 $subject = $title['title'];
541 if (strncasecmp($subject, 'RE:', 3)) {
542 $subject = 'Re: ' . $subject;
546 Email::send($addr, $subject, $headers, $target_item);