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\Queue;
17 use Friendica\Model\User;
18 use Friendica\Protocol\DFRN;
19 use Friendica\Protocol\Diaspora;
20 use Friendica\Protocol\Email;
22 require_once 'include/items.php';
24 class Delivery extends BaseObject
27 const SUGGESTION = 'suggest';
28 const RELOCATION = 'relocate';
29 const DELETION = 'drop';
30 const POST = 'wall-new';
31 const COMMENT = 'comment-new';
32 const REMOVAL = 'removeme';
33 const PROFILEUPDATE = 'profileupdate';
35 public static function execute($cmd, $item_id, $contact_id)
37 Logger::log('Invoked: ' . $cmd . ': ' . $item_id . ' to ' . $contact_id, Logger::DEBUG);
41 $public_message = false;
44 if ($cmd == self::MAIL) {
45 $target_item = DBA::selectFirst('mail', [], ['id' => $item_id]);
46 if (!DBA::isResult($target_item)) {
49 $uid = $target_item['uid'];
50 } elseif ($cmd == self::SUGGESTION) {
51 $target_item = DBA::selectFirst('fsuggest', [], ['id' => $item_id]);
52 if (!DBA::isResult($target_item)) {
55 $uid = $target_item['uid'];
56 } elseif ($cmd == self::RELOCATION) {
60 $item = Item::selectFirst(['parent'], ['id' => $item_id]);
61 if (!DBA::isResult($item) || empty($item['parent'])) {
64 $parent_id = intval($item['parent']);
66 $condition = ['id' => [$item_id, $parent_id], 'moderated' => false];
67 $params = ['order' => ['id']];
68 $itemdata = Item::select([], $condition, $params);
70 while ($item = Item::fetch($itemdata)) {
71 if ($item['id'] == $parent_id) {
74 if ($item['id'] == $item_id) {
79 DBA::close($itemdata);
81 if (empty($target_item)) {
82 Logger::log('Item ' . $item_id . "wasn't found. Quitting here.");
87 Logger::log('Parent ' . $parent_id . ' for item ' . $item_id . "wasn't found. Quitting here.");
91 $uid = $target_item['contact-uid'];
93 // avoid race condition with deleting entries
94 if ($items[0]['deleted']) {
95 foreach ($items as $item) {
100 // When commenting too fast after delivery, a post wasn't recognized as top level post.
101 // The count then showed more than one entry. The additional check should help.
102 // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
103 if ((($parent['id'] == $item_id) || (count($items) == 1)) && ($parent['uri'] === $parent['parent-uri'])) {
104 Logger::log('Top level post');
108 // This is IMPORTANT!!!!
110 // We will only send a "notify owner to relay" or followup message if the referenced post
111 // originated on our system by virtue of having our hostname somewhere
112 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
113 // if $parent['wall'] == 1 we will already have the parent message in our array
114 // and we will relay the whole lot.
116 $localhost = self::getApp()->getHostName();
117 if (strpos($localhost, ':')) {
118 $localhost = substr($localhost, 0, strpos($localhost, ':'));
122 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
123 * have been known to cause runaway conditions which affected several servers, along with
124 * permissions issues.
128 if (!$top_level && ($parent['wall'] == 0) && stristr($target_item['uri'], $localhost)) {
129 Logger::log('Followup ' . $target_item["guid"], Logger::DEBUG);
130 // local followup to remote post
134 if (empty($parent['allow_cid'])
135 && empty($parent['allow_gid'])
136 && empty($parent['deny_cid'])
137 && empty($parent['deny_gid'])
138 && !$parent["private"]) {
139 $public_message = true;
144 Logger::log('No delivery data for ' . $cmd . ' - Item ID: ' .$item_id . ' - Contact ID: ' . $contact_id);
147 $owner = User::getOwnerDataById($uid);
148 if (!DBA::isResult($owner)) {
152 // We don't deliver our items to blocked or pending contacts, and not to ourselves either
153 $contact = DBA::selectFirst('contact', [],
154 ['id' => $contact_id, 'blocked' => false, 'pending' => false, 'self' => false]
156 if (!DBA::isResult($contact)) {
160 // Transmit via Diaspora if the thread had started as Diaspora post
161 // This is done since the uri wouldn't match (Diaspora doesn't transmit it)
162 if (isset($parent) && ($parent['network'] == Protocol::DIASPORA) && ($contact['network'] == Protocol::DFRN)) {
163 $contact['network'] = Protocol::DIASPORA;
166 Logger::log("Delivering " . $cmd . " followup=$followup - via network " . $contact['network']);
168 switch ($contact['network']) {
171 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
174 case Protocol::DIASPORA:
175 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
178 case Protocol::OSTATUS:
179 // Do not send to otatus if we are not configured to send to public networks
180 if ($owner['prvnets']) {
183 if (Config::get('system','ostatus_disabled') || Config::get('system','dfrn_only')) {
187 // There is currently no code here to distribute anything to OStatus.
188 // This is done in "notifier.php" (See "url_recipients" and "push_notify")
192 self::deliverMail($cmd, $contact, $owner, $target_item);
203 * @brief Deliver content via DFRN
205 * @param string $cmd Command
206 * @param array $contact Contact record of the receiver
207 * @param array $owner Owner record of the sender
208 * @param array $items Item record of the content and the parent
209 * @param array $target_item Item record of the content
210 * @param boolean $public_message Is the content public?
211 * @param boolean $top_level Is it a thread starter?
212 * @param boolean $followup Is it an answer to a remote post?
214 private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
216 Logger::log('Deliver ' . $target_item["guid"] . ' via DFRN to ' . (empty($contact['addr']) ? $contact['url'] : $contact['addr']));
218 if ($cmd == self::MAIL) {
219 $item = $target_item;
220 $item['body'] = Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
221 $atom = DFRN::mail($item, $owner);
222 } elseif ($cmd == self::SUGGESTION) {
223 $item = $target_item;
224 $atom = DFRN::fsuggest($item, $owner);
225 DBA::delete('fsuggest', ['id' => $item['id']]);
226 } elseif ($cmd == self::RELOCATION) {
227 $atom = DFRN::relocate($owner, $owner['uid']);
228 } elseif ($followup) {
229 $msgitems = [$target_item];
230 $atom = DFRN::entries($msgitems, $owner);
233 foreach ($items as $item) {
234 // Only add the parent when we don't delete other items.
235 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
236 $item["entry:comment-allow"] = true;
237 $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
241 $atom = DFRN::entries($msgitems, $owner);
244 Logger::log('Notifier entry: ' . $contact["url"] . ' ' . $target_item["guid"] . ' entry: ' . $atom, Logger::DATA);
246 $basepath = implode('/', array_slice(explode('/', $contact['url']), 0, 3));
248 // perform local delivery if we are on the same site
250 if (link_compare($basepath, System::baseUrl())) {
251 $condition = ['nurl' => normalise_link($contact['url']), 'self' => true];
252 $target_self = DBA::selectFirst('contact', ['uid'], $condition);
253 if (!DBA::isResult($target_self)) {
256 $target_uid = $target_self['uid'];
258 // Check if the user has got this contact
259 $cid = Contact::getIdForURL($owner['url'], $target_uid);
261 // Otherwise there should be a public contact
262 $cid = Contact::getIdForURL($owner['url']);
268 $target_importer = DFRN::getImporter($cid, $target_uid);
269 if (empty($target_importer)) {
270 // This should never happen
274 DFRN::import($atom, $target_importer);
278 // We don't have a relationship with contacts on a public post.
279 // Se we transmit with the new method and via Diaspora as a fallback
280 if (!empty($items) && (($items[0]['uid'] == 0) || ($contact['uid'] == 0))) {
281 // Transmit in public if it's a relay post
282 $public_dfrn = ($contact['contact-type'] == Contact::ACCOUNT_TYPE_RELAY);
284 $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
286 // We never spool failed relay deliveries
288 Logger::log('Relay delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
292 if (($deliver_status < 200) || ($deliver_status > 299)) {
293 // Transmit via Diaspora if not possible via Friendica
294 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
297 } elseif ($cmd != self::RELOCATION) {
298 $deliver_status = DFRN::deliver($owner, $contact, $atom);
300 $deliver_status = DFRN::deliver($owner, $contact, $atom, false, true);
303 Logger::log('Delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
305 if ($deliver_status < 0) {
306 Logger::log('Delivery failed: queuing message ' . $target_item["guid"] );
307 Queue::add($contact['id'], Protocol::DFRN, $atom, false, $target_item['guid']);
310 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
311 // We successfully delivered a message, the contact is alive
312 Contact::unmarkForArchival($contact);
314 // The message could not be delivered. We mark the contact as "dead"
315 Contact::markForArchival($contact);
317 // Transmit via Diaspora when all other methods (legacy DFRN and new one) are failing.
318 // This is a fallback for systems that don't know the new methods.
319 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
324 * @brief Deliver content via Diaspora
326 * @param string $cmd Command
327 * @param array $contact Contact record of the receiver
328 * @param array $owner Owner record of the sender
329 * @param array $items Item record of the content and the parent
330 * @param array $target_item Item record of the content
331 * @param boolean $public_message Is the content public?
332 * @param boolean $top_level Is it a thread starter?
333 * @param boolean $followup Is it an answer to a remote post?
335 private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
337 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
338 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != Contact::ACCOUNT_TYPE_COMMUNITY);
340 if ($public_message) {
341 $loc = 'public batch ' . $contact['batch'];
343 $loc = $contact['addr'];
346 Logger::log('Deliver ' . $target_item["guid"] . ' via Diaspora to ' . $loc);
348 if (Config::get('system', 'dfrn_only') || !Config::get('system', 'diaspora_enabled')) {
351 if ($cmd == self::MAIL) {
352 Diaspora::sendMail($target_item, $owner, $contact);
356 if ($cmd == self::SUGGESTION) {
359 if (!$contact['pubkey'] && !$public_message) {
362 if (($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
363 // top-level retraction
364 Logger::log('diaspora retract: ' . $loc);
365 Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
367 } elseif ($cmd == self::RELOCATION) {
368 Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
370 } elseif ($followup) {
371 // send comments and likes to owner to relay
372 Logger::log('diaspora followup: ' . $loc);
373 Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
375 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
376 // we are the relay - send comments, likes and relayable_retractions to our conversants
377 Logger::log('diaspora relay: ' . $loc);
378 Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
380 } elseif ($top_level && !$walltowall) {
381 // currently no workable solution for sending walltowall
382 Logger::log('diaspora status: ' . $loc);
383 Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
387 Logger::log('Unknown mode ' . $cmd . ' for ' . $loc);
391 * @brief Deliver content via mail
393 * @param string $cmd Command
394 * @param array $contact Contact record of the receiver
395 * @param array $owner Owner record of the sender
396 * @param array $target_item Item record of the content
398 private static function deliverMail($cmd, $contact, $owner, $target_item)
400 if (Config::get('system','dfrn_only')) {
403 // WARNING: does not currently convert to RFC2047 header encodings, etc.
405 $addr = $contact['addr'];
406 if (!strlen($addr)) {
410 if (!in_array($cmd, [self::POST, self::COMMENT])) {
414 $local_user = DBA::selectFirst('user', [], ['uid' => $owner['uid']]);
415 if (!DBA::isResult($local_user)) {
419 Logger::log('Deliver ' . $target_item["guid"] . ' via mail to ' . $contact['addr']);
422 $mailacct = DBA::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
423 if (DBA::isResult($mailacct) && !empty($mailacct['reply_to'])) {
424 $reply_to = $mailacct['reply_to'];
427 $subject = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : L10n::t("\x28no subject\x29"));
429 // only expose our real email address to true friends
431 if (($contact['rel'] == Contact::FRIEND) && !$contact['blocked']) {
433 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to.'>' . "\n";
434 $headers .= 'Sender: ' . $local_user['email'] . "\n";
436 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8').' <' . $local_user['email'] . '>' . "\n";
439 $headers = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <noreply@' . self::getApp()->getHostName() . '>' . "\n";
442 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
444 if ($target_item['uri'] !== $target_item['parent-uri']) {
445 $headers .= "References: <" . Email::iri2msgid($target_item["parent-uri"]) . ">";
447 // If Threading is enabled, write down the correct parent
448 if (($target_item["thr-parent"] != "") && ($target_item["thr-parent"] != $target_item["parent-uri"])) {
449 $headers .= " <".Email::iri2msgid($target_item["thr-parent"]).">";
454 if (empty($target_item['title'])) {
455 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
456 $title = Item::selectFirst(['title'], $condition);
458 if (DBA::isResult($title) && ($title['title'] != '')) {
459 $subject = $title['title'];
461 $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
462 $title = Item::selectFirst(['title'], $condition);
464 if (DBA::isResult($title) && ($title['title'] != '')) {
465 $subject = $title['title'];
470 if (strncasecmp($subject, 'RE:', 3)) {
471 $subject = 'Re: ' . $subject;
475 Email::send($addr, $subject, $headers, $target_item);