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;
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;
25 class Delivery extends BaseObject
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';
36 public static function execute($cmd, $target_id, $contact_id)
38 Logger::log('Invoked: ' . $cmd . ': ' . $target_id . ' to ' . $contact_id, Logger::DEBUG);
42 $public_message = false;
45 if ($cmd == self::MAIL) {
46 $target_item = DBA::selectFirst('mail', [], ['id' => $target_id]);
47 if (!DBA::isResult($target_item)) {
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)) {
56 $uid = $target_item['uid'];
57 } elseif ($cmd == self::RELOCATION) {
61 $item = Item::selectFirst(['parent'], ['id' => $target_id]);
62 if (!DBA::isResult($item) || empty($item['parent'])) {
65 $parent_id = intval($item['parent']);
67 $condition = ['id' => [$target_id, $parent_id], 'moderated' => false];
68 $params = ['order' => ['id']];
69 $itemdata = Item::select([], $condition, $params);
71 while ($item = Item::fetch($itemdata)) {
72 if ($item['id'] == $parent_id) {
75 if ($item['id'] == $target_id) {
80 DBA::close($itemdata);
82 if (empty($target_item)) {
83 Logger::log('Item ' . $target_id . "wasn't found. Quitting here.");
88 Logger::log('Parent ' . $parent_id . ' for item ' . $target_id . "wasn't found. Quitting here.");
92 if (!empty($target_item['contact-uid'])) {
93 $uid = $target_item['contact-uid'];
94 } elseif (!empty($target_item['uid'])) {
95 $uid = $target_item['uid'];
97 Logger::log('Only public users for item ' . $target_id, Logger::DEBUG);
101 // avoid race condition with deleting entries
102 if ($items[0]['deleted']) {
103 foreach ($items as $item) {
104 $item['deleted'] = 1;
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');
116 // This is IMPORTANT!!!!
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.
124 $localhost = self::getApp()->getHostName();
125 if (strpos($localhost, ':')) {
126 $localhost = substr($localhost, 0, strpos($localhost, ':'));
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.
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
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;
152 Logger::log('No delivery data for ' . $cmd . ' - Item ID: ' .$target_id . ' - Contact ID: ' . $contact_id);
155 $owner = User::getOwnerDataById($uid);
156 if (!DBA::isResult($owner)) {
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]
164 if (!DBA::isResult($contact)) {
168 if (Network::isUrlBlocked($contact['url'])) {
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;
178 Logger::log("Delivering " . $cmd . " followup=$followup - via network " . $contact['network']);
180 switch ($contact['network']) {
183 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
185 if (in_array($cmd, [Delivery::POST, Delivery::COMMENT])) {
186 ItemDeliveryData::incrementQueueDone($target_id);
190 case Protocol::DIASPORA:
191 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
193 if (in_array($cmd, [Delivery::POST, Delivery::COMMENT])) {
194 ItemDeliveryData::incrementQueueDone($target_id);
198 case Protocol::OSTATUS:
199 // Do not send to otatus if we are not configured to send to public networks
200 if ($owner['prvnets']) {
203 if (Config::get('system','ostatus_disabled') || Config::get('system','dfrn_only')) {
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")
212 self::deliverMail($cmd, $contact, $owner, $target_item);
223 * @brief Deliver content via DFRN
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 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
234 * @throws \ImagickException
236 private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
238 Logger::log('Deliver ' . defaults($target_item, 'guid', $target_item['id']) . ' via DFRN to ' . (empty($contact['addr']) ? $contact['url'] : $contact['addr']));
240 if ($cmd == self::MAIL) {
241 $item = $target_item;
242 $item['body'] = Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
243 $atom = DFRN::mail($item, $owner);
244 } elseif ($cmd == self::SUGGESTION) {
245 $item = $target_item;
246 $atom = DFRN::fsuggest($item, $owner);
247 DBA::delete('fsuggest', ['id' => $item['id']]);
248 } elseif ($cmd == self::RELOCATION) {
249 $atom = DFRN::relocate($owner, $owner['uid']);
250 } elseif ($followup) {
251 $msgitems = [$target_item];
252 $atom = DFRN::entries($msgitems, $owner);
255 foreach ($items as $item) {
256 // Only add the parent when we don't delete other items.
257 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
258 $item["entry:comment-allow"] = true;
259 $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
263 $atom = DFRN::entries($msgitems, $owner);
266 Logger::log('Notifier entry: ' . $contact["url"] . ' ' . defaults($target_item, 'guid', $target_item['id']) . ' entry: ' . $atom, Logger::DATA);
268 $basepath = implode('/', array_slice(explode('/', $contact['url']), 0, 3));
270 // perform local delivery if we are on the same site
272 if (Strings::compareLink($basepath, System::baseUrl())) {
273 $condition = ['nurl' => Strings::normaliseLink($contact['url']), 'self' => true];
274 $target_self = DBA::selectFirst('contact', ['uid'], $condition);
275 if (!DBA::isResult($target_self)) {
278 $target_uid = $target_self['uid'];
280 // Check if the user has got this contact
281 $cid = Contact::getIdForURL($owner['url'], $target_uid);
283 // Otherwise there should be a public contact
284 $cid = Contact::getIdForURL($owner['url']);
290 $target_importer = DFRN::getImporter($cid, $target_uid);
291 if (empty($target_importer)) {
292 // This should never happen
296 DFRN::import($atom, $target_importer);
300 // We don't have a relationship with contacts on a public post.
301 // Se we transmit with the new method and via Diaspora as a fallback
302 if (!empty($items) && (($items[0]['uid'] == 0) || ($contact['uid'] == 0))) {
303 // Transmit in public if it's a relay post
304 $public_dfrn = ($contact['contact-type'] == Contact::TYPE_RELAY);
306 $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
308 // We never spool failed relay deliveries
310 Logger::log('Relay delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
314 if (($deliver_status < 200) || ($deliver_status > 299)) {
315 // Transmit via Diaspora if not possible via Friendica
316 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
319 } elseif ($cmd != self::RELOCATION) {
320 $deliver_status = DFRN::deliver($owner, $contact, $atom);
322 $deliver_status = DFRN::deliver($owner, $contact, $atom, false, true);
325 Logger::log('Delivery to ' . $contact['url'] . ' with guid ' . defaults($target_item, 'guid', $target_item['id']) . ' returns ' . $deliver_status);
327 if ($deliver_status < 0) {
328 Logger::log('Delivery failed: queuing message ' . defaults($target_item, 'guid', $target_item['id']));
329 Queue::add($contact['id'], Protocol::DFRN, $atom, false, $target_item['guid']);
332 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
333 // We successfully delivered a message, the contact is alive
334 Contact::unmarkForArchival($contact);
336 // The message could not be delivered. We mark the contact as "dead"
337 Contact::markForArchival($contact);
339 // Transmit via Diaspora when all other methods (legacy DFRN and new one) are failing.
340 // This is a fallback for systems that don't know the new methods.
341 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
346 * @brief Deliver content via Diaspora
348 * @param string $cmd Command
349 * @param array $contact Contact record of the receiver
350 * @param array $owner Owner record of the sender
351 * @param array $items Item record of the content and the parent
352 * @param array $target_item Item record of the content
353 * @param boolean $public_message Is the content public?
354 * @param boolean $top_level Is it a thread starter?
355 * @param boolean $followup Is it an answer to a remote post?
356 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
357 * @throws \ImagickException
359 private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
361 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
362 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY);
364 if ($public_message) {
365 $loc = 'public batch ' . $contact['batch'];
367 $loc = $contact['addr'];
370 Logger::log('Deliver ' . defaults($target_item, 'guid', $target_item['id']) . ' via Diaspora to ' . $loc);
372 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) {
383 if (!$contact['pubkey'] && !$public_message) {
386 if ($cmd == self::RELOCATION) {
387 Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
389 } elseif ($target_item['deleted'] && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
390 // top-level retraction
391 Logger::log('diaspora retract: ' . $loc);
392 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 Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
399 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
400 // we are the relay - send comments, likes and relayable_retractions to our conversants
401 Logger::log('diaspora relay: ' . $loc);
402 Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
404 } elseif ($top_level && !$walltowall) {
405 // currently no workable solution for sending walltowall
406 Logger::log('diaspora status: ' . $loc);
407 Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
411 Logger::log('Unknown mode ' . $cmd . ' for ' . $loc);
415 * @brief Deliver content via mail
417 * @param string $cmd Command
418 * @param array $contact Contact record of the receiver
419 * @param array $owner Owner record of the sender
420 * @param array $target_item Item record of the content
421 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
422 * @throws \ImagickException
424 private static function deliverMail($cmd, $contact, $owner, $target_item)
426 if (Config::get('system','dfrn_only')) {
429 // WARNING: does not currently convert to RFC2047 header encodings, etc.
431 $addr = $contact['addr'];
432 if (!strlen($addr)) {
436 if (!in_array($cmd, [self::POST, self::COMMENT])) {
440 $local_user = DBA::selectFirst('user', [], ['uid' => $owner['uid']]);
441 if (!DBA::isResult($local_user)) {
445 Logger::log('Deliver ' . $target_item["guid"] . ' via mail to ' . $contact['addr']);
448 $mailacct = DBA::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
449 if (DBA::isResult($mailacct) && !empty($mailacct['reply_to'])) {
450 $reply_to = $mailacct['reply_to'];
453 $subject = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : L10n::t("\x28no subject\x29"));
455 // only expose our real email address to true friends
457 if (($contact['rel'] == Contact::FRIEND) && !$contact['blocked']) {
459 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to.'>' . "\n";
460 $headers .= 'Sender: ' . $local_user['email'] . "\n";
462 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8').' <' . $local_user['email'] . '>' . "\n";
465 $headers = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <noreply@' . self::getApp()->getHostName() . '>' . "\n";
468 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
470 if ($target_item['uri'] !== $target_item['parent-uri']) {
471 $headers .= "References: <" . Email::iri2msgid($target_item["parent-uri"]) . ">";
473 // If Threading is enabled, write down the correct parent
474 if (($target_item["thr-parent"] != "") && ($target_item["thr-parent"] != $target_item["parent-uri"])) {
475 $headers .= " <".Email::iri2msgid($target_item["thr-parent"]).">";
480 if (empty($target_item['title'])) {
481 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
482 $title = Item::selectFirst(['title'], $condition);
484 if (DBA::isResult($title) && ($title['title'] != '')) {
485 $subject = $title['title'];
487 $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
488 $title = Item::selectFirst(['title'], $condition);
490 if (DBA::isResult($title) && ($title['title'] != '')) {
491 $subject = $title['title'];
496 if (strncasecmp($subject, 'RE:', 3)) {
497 $subject = 'Re: ' . $subject;
501 Email::send($addr, $subject, $headers, $target_item);