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::log('Invoked: ' . $cmd . ': ' . $target_id . ' to ' . $contact_id, Logger::DEBUG);
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 // avoid race condition with deleting entries
100 if ($items[0]['deleted']) {
101 foreach ($items as $item) {
102 $item['deleted'] = 1;
106 // When commenting too fast after delivery, a post wasn't recognized as top level post.
107 // The count then showed more than one entry. The additional check should help.
108 // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
109 if ((($parent['id'] == $target_id) || (count($items) == 1)) && ($parent['uri'] === $parent['parent-uri'])) {
110 Logger::log('Top level post');
114 // This is IMPORTANT!!!!
116 // We will only send a "notify owner to relay" or followup message if the referenced post
117 // originated on our system by virtue of having our hostname somewhere
118 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
119 // if $parent['wall'] == 1 we will already have the parent message in our array
120 // and we will relay the whole lot.
122 $localhost = self::getApp()->getHostName();
123 if (strpos($localhost, ':')) {
124 $localhost = substr($localhost, 0, strpos($localhost, ':'));
128 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
129 * have been known to cause runaway conditions which affected several servers, along with
130 * permissions issues.
134 if (!$top_level && ($parent['wall'] == 0) && stristr($target_item['uri'], $localhost)) {
135 Logger::log('Followup ' . $target_item["guid"], Logger::DEBUG);
136 // local followup to remote post
140 if (empty($parent['allow_cid'])
141 && empty($parent['allow_gid'])
142 && empty($parent['deny_cid'])
143 && empty($parent['deny_gid'])
144 && !$parent["private"]) {
145 $public_message = true;
150 Logger::log('No delivery data for ' . $cmd . ' - Item ID: ' .$target_id . ' - Contact ID: ' . $contact_id);
153 $owner = Model\User::getOwnerDataById($uid);
154 if (!DBA::isResult($owner)) {
158 // We don't deliver our items to blocked or pending contacts, and not to ourselves either
159 $contact = DBA::selectFirst('contact', [],
160 ['id' => $contact_id, 'blocked' => false, 'pending' => false, 'self' => false]
162 if (!DBA::isResult($contact)) {
166 if (Network::isUrlBlocked($contact['url'])) {
170 // Transmit via Diaspora if the thread had started as Diaspora post
171 // This is done since the uri wouldn't match (Diaspora doesn't transmit it)
172 if (isset($parent) && ($parent['network'] == Protocol::DIASPORA) && ($contact['network'] == Protocol::DFRN)) {
173 $contact['network'] = Protocol::DIASPORA;
176 Logger::log("Delivering " . $cmd . " followup=$followup - via network " . $contact['network']);
178 switch ($contact['network']) {
181 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
184 case Protocol::DIASPORA:
185 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
189 self::deliverMail($cmd, $contact, $owner, $target_item);
200 * @brief Deliver content via DFRN
202 * @param string $cmd Command
203 * @param array $contact Contact record of the receiver
204 * @param array $owner Owner record of the sender
205 * @param array $items Item record of the content and the parent
206 * @param array $target_item Item record of the content
207 * @param boolean $public_message Is the content public?
208 * @param boolean $top_level Is it a thread starter?
209 * @param boolean $followup Is it an answer to a remote post?
210 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
211 * @throws \ImagickException
213 private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
215 Logger::log('Deliver ' . defaults($target_item, 'guid', $target_item['id']) . ' via DFRN to ' . (empty($contact['addr']) ? $contact['url'] : $contact['addr']));
217 if ($cmd == self::MAIL) {
218 $item = $target_item;
219 $item['body'] = Model\Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
220 $atom = DFRN::mail($item, $owner);
221 } elseif ($cmd == self::SUGGESTION) {
222 $item = $target_item;
223 $atom = DFRN::fsuggest($item, $owner);
224 DBA::delete('fsuggest', ['id' => $item['id']]);
225 } elseif ($cmd == self::RELOCATION) {
226 $atom = DFRN::relocate($owner, $owner['uid']);
227 } elseif ($followup) {
228 $msgitems = [$target_item];
229 $atom = DFRN::entries($msgitems, $owner);
232 foreach ($items as $item) {
233 // Only add the parent when we don't delete other items.
234 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
235 $item["entry:comment-allow"] = true;
236 $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
240 $atom = DFRN::entries($msgitems, $owner);
243 Logger::log('Notifier entry: ' . $contact["url"] . ' ' . defaults($target_item, 'guid', $target_item['id']) . ' entry: ' . $atom, Logger::DATA);
245 $basepath = implode('/', array_slice(explode('/', $contact['url']), 0, 3));
247 // perform local delivery if we are on the same site
249 if (Strings::compareLink($basepath, System::baseUrl())) {
250 $condition = ['nurl' => Strings::normaliseLink($contact['url']), 'self' => true];
251 $target_self = DBA::selectFirst('contact', ['uid'], $condition);
252 if (!DBA::isResult($target_self)) {
255 $target_uid = $target_self['uid'];
257 // Check if the user has got this contact
258 $cid = Model\Contact::getIdForURL($owner['url'], $target_uid);
260 // Otherwise there should be a public contact
261 $cid = Model\Contact::getIdForURL($owner['url']);
267 $target_importer = DFRN::getImporter($cid, $target_uid);
268 if (empty($target_importer)) {
269 // This should never happen
273 DFRN::import($atom, $target_importer);
275 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
276 Model\ItemDeliveryData::incrementQueueDone($target_item['id'], Model\ItemDeliveryData::DFRN);
282 $protocol = Model\ItemDeliveryData::DFRN;
284 // We don't have a relationship with contacts on a public post.
285 // Se we transmit with the new method and via Diaspora as a fallback
286 if (!empty($items) && (($items[0]['uid'] == 0) || ($contact['uid'] == 0))) {
287 // Transmit in public if it's a relay post
288 $public_dfrn = ($contact['contact-type'] == Model\Contact::TYPE_RELAY);
290 $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
292 // We never spool failed relay deliveries
294 Logger::log('Relay delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
298 if (($deliver_status < 200) || ($deliver_status > 299)) {
299 // Transmit via Diaspora if not possible via Friendica
300 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
303 } elseif ($cmd != self::RELOCATION) {
304 // DFRN payload over Diaspora transport layer
305 $deliver_status = DFRN::transmit($owner, $contact, $atom);
306 if ($deliver_status < 200) {
308 $deliver_status = DFRN::deliver($owner, $contact, $atom);
309 $protocol = Model\ItemDeliveryData::LEGACY_DFRN;
312 $deliver_status = DFRN::deliver($owner, $contact, $atom);
313 $protocol = Model\ItemDeliveryData::LEGACY_DFRN;
316 Logger::info('DFRN Delivery', ['cmd' => $cmd, 'url' => $contact['url'], 'guid' => defaults($target_item, 'guid', $target_item['id']), 'return' => $deliver_status]);
318 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
319 // We successfully delivered a message, the contact is alive
320 Model\Contact::unmarkForArchival($contact);
322 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
323 Model\ItemDeliveryData::incrementQueueDone($target_item['id'], $protocol);
326 // The message could not be delivered. We mark the contact as "dead"
327 Model\Contact::markForArchival($contact);
329 Logger::info('Delivery failed: defer message', ['id' => defaults($target_item, 'guid', $target_item['id'])]);
335 * @brief Deliver content via Diaspora
337 * @param string $cmd Command
338 * @param array $contact Contact record of the receiver
339 * @param array $owner Owner record of the sender
340 * @param array $items Item record of the content and the parent
341 * @param array $target_item Item record of the content
342 * @param boolean $public_message Is the content public?
343 * @param boolean $top_level Is it a thread starter?
344 * @param boolean $followup Is it an answer to a remote post?
345 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
346 * @throws \ImagickException
348 private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
350 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
351 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != Model\User::ACCOUNT_TYPE_COMMUNITY);
353 if ($public_message) {
354 $loc = 'public batch ' . $contact['batch'];
356 $loc = $contact['addr'];
359 Logger::log('Deliver ' . defaults($target_item, 'guid', $target_item['id']) . ' via Diaspora to ' . $loc);
361 if (Config::get('system', 'dfrn_only') || !Config::get('system', 'diaspora_enabled')) {
365 if ($cmd == self::MAIL) {
366 Diaspora::sendMail($target_item, $owner, $contact);
370 if ($cmd == self::SUGGESTION) {
374 if (!$contact['pubkey'] && !$public_message) {
378 if ($cmd == self::RELOCATION) {
379 $deliver_status = Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
380 } elseif ($target_item['deleted'] && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
381 // top-level retraction
382 Logger::log('diaspora retract: ' . $loc);
383 $deliver_status = Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
384 } elseif ($followup) {
385 // send comments and likes to owner to relay
386 Logger::log('diaspora followup: ' . $loc);
387 $deliver_status = Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
388 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
389 // we are the relay - send comments, likes and relayable_retractions to our conversants
390 Logger::log('diaspora relay: ' . $loc);
391 $deliver_status = Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
392 } elseif ($top_level && !$walltowall) {
393 // currently no workable solution for sending walltowall
394 Logger::log('diaspora status: ' . $loc);
395 $deliver_status = Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
397 Logger::log('Unknown mode ' . $cmd . ' for ' . $loc);
401 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
402 // We successfully delivered a message, the contact is alive
403 Model\Contact::unmarkForArchival($contact);
405 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
406 Model\ItemDeliveryData::incrementQueueDone($target_item['id'], Model\ItemDeliveryData::DIASPORA);
409 // The message could not be delivered. We mark the contact as "dead"
410 Model\Contact::markForArchival($contact);
412 if (empty($contact['contact-type']) || ($contact['contact-type'] != Model\Contact::TYPE_RELAY)) {
413 Logger::info('Delivery failed: defer message', ['id' => defaults($target_item, 'guid', $target_item['id'])]);
414 // defer message for redelivery
416 } elseif (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
417 Model\ItemDeliveryData::incrementQueueDone($target_item['id'], Model\ItemDeliveryData::DIASPORA);
423 * @brief Deliver content via mail
425 * @param string $cmd Command
426 * @param array $contact Contact record of the receiver
427 * @param array $owner Owner record of the sender
428 * @param array $target_item Item record of the content
429 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
430 * @throws \ImagickException
432 private static function deliverMail($cmd, $contact, $owner, $target_item)
434 if (Config::get('system','dfrn_only')) {
437 // WARNING: does not currently convert to RFC2047 header encodings, etc.
439 $addr = $contact['addr'];
440 if (!strlen($addr)) {
444 if (!in_array($cmd, [self::POST, self::POKE])) {
448 $local_user = DBA::selectFirst('user', [], ['uid' => $owner['uid']]);
449 if (!DBA::isResult($local_user)) {
453 Logger::log('Deliver ' . $target_item["guid"] . ' via mail to ' . $contact['addr']);
456 $mailacct = DBA::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
457 if (DBA::isResult($mailacct) && !empty($mailacct['reply_to'])) {
458 $reply_to = $mailacct['reply_to'];
461 $subject = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : L10n::t("\x28no subject\x29"));
463 // only expose our real email address to true friends
465 if (($contact['rel'] == Model\Contact::FRIEND) && !$contact['blocked']) {
467 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to.'>' . "\n";
468 $headers .= 'Sender: ' . $local_user['email'] . "\n";
470 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8').' <' . $local_user['email'] . '>' . "\n";
473 $headers = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <noreply@' . self::getApp()->getHostName() . '>' . "\n";
476 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
478 if ($target_item['uri'] !== $target_item['parent-uri']) {
479 $headers .= "References: <" . Email::iri2msgid($target_item["parent-uri"]) . ">";
481 // If Threading is enabled, write down the correct parent
482 if (($target_item["thr-parent"] != "") && ($target_item["thr-parent"] != $target_item["parent-uri"])) {
483 $headers .= " <".Email::iri2msgid($target_item["thr-parent"]).">";
488 if (empty($target_item['title'])) {
489 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
490 $title = Model\Item::selectFirst(['title'], $condition);
492 if (DBA::isResult($title) && ($title['title'] != '')) {
493 $subject = $title['title'];
495 $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
496 $title = Model\Item::selectFirst(['title'], $condition);
498 if (DBA::isResult($title) && ($title['title'] != '')) {
499 $subject = $title['title'];
504 if (strncasecmp($subject, 'RE:', 3)) {
505 $subject = 'Re: ' . $subject;
509 Email::send($addr, $subject, $headers, $target_item);