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';
29 const COMMENT = 'comment-new';
30 const REMOVAL = 'removeme';
31 const PROFILEUPDATE = 'profileupdate';
33 public static function execute($cmd, $target_id, $contact_id)
35 Logger::log('Invoked: ' . $cmd . ': ' . $target_id . ' to ' . $contact_id, Logger::DEBUG);
39 $public_message = false;
42 if ($cmd == self::MAIL) {
43 $target_item = DBA::selectFirst('mail', [], ['id' => $target_id]);
44 if (!DBA::isResult($target_item)) {
47 $uid = $target_item['uid'];
48 } elseif ($cmd == self::SUGGESTION) {
49 $target_item = DBA::selectFirst('fsuggest', [], ['id' => $target_id]);
50 if (!DBA::isResult($target_item)) {
53 $uid = $target_item['uid'];
54 } elseif ($cmd == self::RELOCATION) {
58 $item = Model\Item::selectFirst(['parent'], ['id' => $target_id]);
59 if (!DBA::isResult($item) || empty($item['parent'])) {
62 $parent_id = intval($item['parent']);
64 $condition = ['id' => [$target_id, $parent_id], 'visible' => true, 'moderated' => false];
65 $params = ['order' => ['id']];
66 $itemdata = Model\Item::select([], $condition, $params);
68 while ($item = Model\Item::fetch($itemdata)) {
69 if ($item['id'] == $parent_id) {
72 if ($item['id'] == $target_id) {
77 DBA::close($itemdata);
79 if (empty($target_item)) {
80 Logger::log('Item ' . $target_id . "wasn't found. Quitting here.");
85 Logger::log('Parent ' . $parent_id . ' for item ' . $target_id . "wasn't found. Quitting here.");
89 if (!empty($target_item['contact-uid'])) {
90 $uid = $target_item['contact-uid'];
91 } elseif (!empty($target_item['uid'])) {
92 $uid = $target_item['uid'];
94 Logger::log('Only public users for item ' . $target_id, Logger::DEBUG);
98 // avoid race condition with deleting entries
99 if ($items[0]['deleted']) {
100 foreach ($items as $item) {
101 $item['deleted'] = 1;
105 // When commenting too fast after delivery, a post wasn't recognized as top level post.
106 // The count then showed more than one entry. The additional check should help.
107 // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
108 if ((($parent['id'] == $target_id) || (count($items) == 1)) && ($parent['uri'] === $parent['parent-uri'])) {
109 Logger::log('Top level post');
113 // This is IMPORTANT!!!!
115 // We will only send a "notify owner to relay" or followup message if the referenced post
116 // originated on our system by virtue of having our hostname somewhere
117 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
118 // if $parent['wall'] == 1 we will already have the parent message in our array
119 // and we will relay the whole lot.
121 $localhost = self::getApp()->getHostName();
122 if (strpos($localhost, ':')) {
123 $localhost = substr($localhost, 0, strpos($localhost, ':'));
127 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
128 * have been known to cause runaway conditions which affected several servers, along with
129 * permissions issues.
133 if (!$top_level && ($parent['wall'] == 0) && stristr($target_item['uri'], $localhost)) {
134 Logger::log('Followup ' . $target_item["guid"], Logger::DEBUG);
135 // local followup to remote post
139 if (empty($parent['allow_cid'])
140 && empty($parent['allow_gid'])
141 && empty($parent['deny_cid'])
142 && empty($parent['deny_gid'])
143 && !$parent["private"]) {
144 $public_message = true;
149 Logger::log('No delivery data for ' . $cmd . ' - Item ID: ' .$target_id . ' - Contact ID: ' . $contact_id);
152 $owner = Model\User::getOwnerDataById($uid);
153 if (!DBA::isResult($owner)) {
157 // We don't deliver our items to blocked or pending contacts, and not to ourselves either
158 $contact = DBA::selectFirst('contact', [],
159 ['id' => $contact_id, 'blocked' => false, 'pending' => false, 'self' => false]
161 if (!DBA::isResult($contact)) {
165 if (Network::isUrlBlocked($contact['url'])) {
169 // Transmit via Diaspora if the thread had started as Diaspora post
170 // This is done since the uri wouldn't match (Diaspora doesn't transmit it)
171 if (isset($parent) && ($parent['network'] == Protocol::DIASPORA) && ($contact['network'] == Protocol::DFRN)) {
172 $contact['network'] = Protocol::DIASPORA;
175 Logger::log("Delivering " . $cmd . " followup=$followup - via network " . $contact['network']);
177 switch ($contact['network']) {
180 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
182 if (in_array($cmd, [Delivery::POST, Delivery::COMMENT])) {
183 Model\ItemDeliveryData::incrementQueueDone($target_id);
187 case Protocol::DIASPORA:
188 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
190 if (in_array($cmd, [Delivery::POST, Delivery::COMMENT])) {
191 Model\ItemDeliveryData::incrementQueueDone($target_id);
195 case Protocol::OSTATUS:
196 // Do not send to otatus if we are not configured to send to public networks
197 if ($owner['prvnets']) {
200 if (Config::get('system','ostatus_disabled') || Config::get('system','dfrn_only')) {
204 // There is currently no code here to distribute anything to OStatus.
205 // This is done in "notifier.php" (See "url_recipients" and "push_notify")
209 self::deliverMail($cmd, $contact, $owner, $target_item);
220 * @brief Deliver content via DFRN
222 * @param string $cmd Command
223 * @param array $contact Contact record of the receiver
224 * @param array $owner Owner record of the sender
225 * @param array $items Item record of the content and the parent
226 * @param array $target_item Item record of the content
227 * @param boolean $public_message Is the content public?
228 * @param boolean $top_level Is it a thread starter?
229 * @param boolean $followup Is it an answer to a remote post?
230 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
231 * @throws \ImagickException
233 private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
235 Logger::log('Deliver ' . defaults($target_item, 'guid', $target_item['id']) . ' via DFRN to ' . (empty($contact['addr']) ? $contact['url'] : $contact['addr']));
237 if ($cmd == self::MAIL) {
238 $item = $target_item;
239 $item['body'] = Model\Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
240 $atom = DFRN::mail($item, $owner);
241 } elseif ($cmd == self::SUGGESTION) {
242 $item = $target_item;
243 $atom = DFRN::fsuggest($item, $owner);
244 DBA::delete('fsuggest', ['id' => $item['id']]);
245 } elseif ($cmd == self::RELOCATION) {
246 $atom = DFRN::relocate($owner, $owner['uid']);
247 } elseif ($followup) {
248 $msgitems = [$target_item];
249 $atom = DFRN::entries($msgitems, $owner);
252 foreach ($items as $item) {
253 // Only add the parent when we don't delete other items.
254 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
255 $item["entry:comment-allow"] = true;
256 $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
260 $atom = DFRN::entries($msgitems, $owner);
263 Logger::log('Notifier entry: ' . $contact["url"] . ' ' . defaults($target_item, 'guid', $target_item['id']) . ' entry: ' . $atom, Logger::DATA);
265 $basepath = implode('/', array_slice(explode('/', $contact['url']), 0, 3));
267 // perform local delivery if we are on the same site
269 if (Strings::compareLink($basepath, System::baseUrl())) {
270 $condition = ['nurl' => Strings::normaliseLink($contact['url']), 'self' => true];
271 $target_self = DBA::selectFirst('contact', ['uid'], $condition);
272 if (!DBA::isResult($target_self)) {
275 $target_uid = $target_self['uid'];
277 // Check if the user has got this contact
278 $cid = Model\Contact::getIdForURL($owner['url'], $target_uid);
280 // Otherwise there should be a public contact
281 $cid = Model\Contact::getIdForURL($owner['url']);
287 $target_importer = DFRN::getImporter($cid, $target_uid);
288 if (empty($target_importer)) {
289 // This should never happen
293 DFRN::import($atom, $target_importer);
297 // We don't have a relationship with contacts on a public post.
298 // Se we transmit with the new method and via Diaspora as a fallback
299 if (!empty($items) && (($items[0]['uid'] == 0) || ($contact['uid'] == 0))) {
300 // Transmit in public if it's a relay post
301 $public_dfrn = ($contact['contact-type'] == Model\Contact::TYPE_RELAY);
303 $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
305 // We never spool failed relay deliveries
307 Logger::log('Relay delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
311 if (($deliver_status < 200) || ($deliver_status > 299)) {
312 // Transmit via Diaspora if not possible via Friendica
313 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
316 } elseif ($cmd != self::RELOCATION) {
317 $deliver_status = DFRN::deliver($owner, $contact, $atom);
319 $deliver_status = DFRN::deliver($owner, $contact, $atom, false, true);
322 Logger::log('Delivery to ' . $contact['url'] . ' with guid ' . defaults($target_item, 'guid', $target_item['id']) . ' returns ' . $deliver_status);
324 if ($deliver_status < 0) {
325 Logger::info('Delivery failed: defer message', ['id' => defaults($target_item, 'guid', $target_item['id'])]);
329 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
330 // We successfully delivered a message, the contact is alive
331 Model\Contact::unmarkForArchival($contact);
333 // The message could not be delivered. We mark the contact as "dead"
334 Model\Contact::markForArchival($contact);
336 // Transmit via Diaspora when all other methods (legacy DFRN and new one) are failing.
337 // This is a fallback for systems that don't know the new methods.
338 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
343 * @brief Deliver content via Diaspora
345 * @param string $cmd Command
346 * @param array $contact Contact record of the receiver
347 * @param array $owner Owner record of the sender
348 * @param array $items Item record of the content and the parent
349 * @param array $target_item Item record of the content
350 * @param boolean $public_message Is the content public?
351 * @param boolean $top_level Is it a thread starter?
352 * @param boolean $followup Is it an answer to a remote post?
353 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
354 * @throws \ImagickException
356 private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
358 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
359 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != Model\User::ACCOUNT_TYPE_COMMUNITY);
361 if ($public_message) {
362 $loc = 'public batch ' . $contact['batch'];
364 $loc = $contact['addr'];
367 Logger::log('Deliver ' . defaults($target_item, 'guid', $target_item['id']) . ' via Diaspora to ' . $loc);
369 if (Config::get('system', 'dfrn_only') || !Config::get('system', 'diaspora_enabled')) {
372 if ($cmd == self::MAIL) {
373 Diaspora::sendMail($target_item, $owner, $contact);
377 if ($cmd == self::SUGGESTION) {
380 if (!$contact['pubkey'] && !$public_message) {
383 if ($cmd == self::RELOCATION) {
384 Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
386 } elseif ($target_item['deleted'] && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
387 // top-level retraction
388 Logger::log('diaspora retract: ' . $loc);
389 Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
391 } elseif ($followup) {
392 // send comments and likes to owner to relay
393 Logger::log('diaspora followup: ' . $loc);
394 Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
396 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
397 // we are the relay - send comments, likes and relayable_retractions to our conversants
398 Logger::log('diaspora relay: ' . $loc);
399 Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
401 } elseif ($top_level && !$walltowall) {
402 // currently no workable solution for sending walltowall
403 Logger::log('diaspora status: ' . $loc);
404 Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
408 Logger::log('Unknown mode ' . $cmd . ' for ' . $loc);
412 * @brief Deliver content via mail
414 * @param string $cmd Command
415 * @param array $contact Contact record of the receiver
416 * @param array $owner Owner record of the sender
417 * @param array $target_item Item record of the content
418 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
419 * @throws \ImagickException
421 private static function deliverMail($cmd, $contact, $owner, $target_item)
423 if (Config::get('system','dfrn_only')) {
426 // WARNING: does not currently convert to RFC2047 header encodings, etc.
428 $addr = $contact['addr'];
429 if (!strlen($addr)) {
433 if (!in_array($cmd, [self::POST, self::COMMENT])) {
437 $local_user = DBA::selectFirst('user', [], ['uid' => $owner['uid']]);
438 if (!DBA::isResult($local_user)) {
442 Logger::log('Deliver ' . $target_item["guid"] . ' via mail to ' . $contact['addr']);
445 $mailacct = DBA::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
446 if (DBA::isResult($mailacct) && !empty($mailacct['reply_to'])) {
447 $reply_to = $mailacct['reply_to'];
450 $subject = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : L10n::t("\x28no subject\x29"));
452 // only expose our real email address to true friends
454 if (($contact['rel'] == Model\Contact::FRIEND) && !$contact['blocked']) {
456 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to.'>' . "\n";
457 $headers .= 'Sender: ' . $local_user['email'] . "\n";
459 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8').' <' . $local_user['email'] . '>' . "\n";
462 $headers = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <noreply@' . self::getApp()->getHostName() . '>' . "\n";
465 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
467 if ($target_item['uri'] !== $target_item['parent-uri']) {
468 $headers .= "References: <" . Email::iri2msgid($target_item["parent-uri"]) . ">";
470 // If Threading is enabled, write down the correct parent
471 if (($target_item["thr-parent"] != "") && ($target_item["thr-parent"] != $target_item["parent-uri"])) {
472 $headers .= " <".Email::iri2msgid($target_item["thr-parent"]).">";
477 if (empty($target_item['title'])) {
478 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
479 $title = Model\Item::selectFirst(['title'], $condition);
481 if (DBA::isResult($title) && ($title['title'] != '')) {
482 $subject = $title['title'];
484 $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
485 $title = Model\Item::selectFirst(['title'], $condition);
487 if (DBA::isResult($title) && ($title['title'] != '')) {
488 $subject = $title['title'];
493 if (strncasecmp($subject, 'RE:', 3)) {
494 $subject = 'Re: ' . $subject;
498 Email::send($addr, $subject, $headers, $target_item);