3 * @file src/Worker/Delivery.php
5 namespace Friendica\Worker;
7 use Friendica\Core\Config;
8 use Friendica\Core\L10n;
9 use Friendica\Core\System;
10 use Friendica\Database\DBM;
11 use Friendica\Model\Contact;
12 use Friendica\Model\Item;
13 use Friendica\Model\Queue;
14 use Friendica\Model\User;
15 use Friendica\Protocol\DFRN;
16 use Friendica\Protocol\Diaspora;
17 use Friendica\Protocol\Email;
20 require_once 'include/items.php';
22 /// @todo This is some ugly code that needs to be split into several methods
25 public static function execute($cmd, $item_id, $contact_id) {
28 logger('Invoked: ' . $cmd . ': ' . $item_id . ' to ' . $contact_id, LOGGER_DEBUG);
32 $public_message = false;
34 if ($cmd == DELIVER_MAIL) {
35 $target_item = dba::selectFirst('mail', [], ['id' => $item_id]);
36 if (!DBM::is_result($message)) {
39 $uid = $target_item['uid'];
40 } elseif ($cmd == DELIVER_SUGGESTION) {
41 $target_item = dba::selectFirst('fsuggest', [], ['id' => $item_id]);
42 if (!DBM::is_result($message)) {
45 $uid = $target_item['uid'];
46 } elseif ($cmd == DELIVER_RELOCATION) {
50 $target_item = dba::fetch_first("SELECT `item`.*, `contact`.`uid` AS `cuid`,
51 `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
53 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
54 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
55 WHERE `item`.`id` = ? AND `visible` AND NOT `moderated`", $item_id);
57 if (!DBM::is_result($target_item) || !intval($target_item['parent'])) {
61 $parent_id = intval($target_item['parent']);
62 $uid = $target_item['cuid'];
64 if ($parent_id != $item_id) {
65 $parent = dba::fetch_first("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
67 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
68 WHERE `item`.`id` = ? AND `visible` AND NOT `moderated`", $parent_id);
69 if (!DBM::is_result($parent)) {
72 $items = [$parent, $target_item];
74 $parent = $target_item;
75 $items = [$target_item];
78 // avoid race condition with deleting entries
79 if ($items[0]['deleted']) {
80 foreach ($items as $item) {
85 // When commenting too fast after delivery, a post wasn't recognized as top level post.
86 // The count then showed more than one entry. The additional check should help.
87 // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
88 if ((($parent['id'] == $item_id) || (count($items) == 1)) && ($parent['uri'] === $parent['parent-uri'])) {
89 logger('Top level post');
93 // This is IMPORTANT!!!!
95 // We will only send a "notify owner to relay" or followup message if the referenced post
96 // originated on our system by virtue of having our hostname somewhere
97 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
98 // if $parent['wall'] == 1 we will already have the parent message in our array
99 // and we will relay the whole lot.
101 $localhost = $a->get_hostname();
102 if (strpos($localhost, ':')) {
103 $localhost = substr($localhost, 0, strpos($localhost, ':'));
107 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
108 * have been known to cause runaway conditions which affected several servers, along with
109 * permissions issues.
113 if (!$top_level && ($parent['wall'] == 0) && stristr($target_item['uri'], $localhost)) {
114 logger('Followup ' . $target_item["guid"], LOGGER_DEBUG);
115 // local followup to remote post
119 if (empty($parent['allow_cid'])
120 && empty($parent['allow_gid'])
121 && empty($parent['deny_cid'])
122 && empty($parent['deny_gid'])
123 && !$parent["private"]) {
124 $public_message = true;
128 $owner = User::getOwnerDataById($uid);
129 if (!DBM::is_result($owner)) {
133 // We don't deliver our items to blocked or pending contacts, and not to ourselves either
134 $contact = dba::selectFirst('contact', [],
135 ['id' => $contact_id, 'blocked' => false, 'pending' => false, 'self' => false]
137 if (!DBM::is_result($contact)) {
141 // Transmit via Diaspora if the thread had started as Diaspora post
142 // This is done since the uri wouldn't match (Diaspora doesn't transmit it)
143 if (isset($parent) && ($parent['network'] == NETWORK_DIASPORA) && ($contact['network'] == NETWORK_DFRN)) {
144 $contact['network'] = NETWORK_DIASPORA;
147 logger("Delivering " . $cmd . " followup=$followup - via network " . $contact['network']);
149 switch ($contact['network']) {
152 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
155 case NETWORK_DIASPORA:
156 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
159 case NETWORK_OSTATUS:
160 // Do not send to otatus if we are not configured to send to public networks
161 if ($owner['prvnets']) {
164 if (Config::get('system','ostatus_disabled') || Config::get('system','dfrn_only')) {
168 // There is currently no code here to distribute anything to OStatus.
169 // This is done in "notifier.php" (See "url_recipients" and "push_notify")
173 self::deliverMail($cmd, $contact, $owner, $target_item);
183 private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
185 logger('Deliver ' . $target_item["guid"] . ' via DFRN to ' . $contact['addr']);
187 if ($cmd == DELIVER_MAIL) {
188 $item = $target_item;
189 $item['body'] = Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
190 $atom = DFRN::mail($item, $owner);
191 } elseif ($cmd == DELIVER_SUGGESTION) {
192 $item = $target_item;
193 $atom = DFRN::fsuggest($item, $owner);
194 dba::delete('fsuggest', ['id' => $item['id']]);
195 } elseif ($cmd == DELIVER_RELOCATION) {
196 $atom = DFRN::relocate($owner, $owner['uid']);
197 } elseif ($followup) {
198 $msgitems = [$target_item];
199 $atom = DFRN::entries($msgitems, $owner);
202 foreach ($items as $item) {
203 // Only add the parent when we don't delete other items.
204 if (($target_item['id'] == $item['id']) || ($cmd != DELIVER_DELETION)) {
205 $item["entry:comment-allow"] = true;
206 $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
210 $atom = DFRN::entries($msgitems,$owner);
213 logger('Notifier entry: ' . $contact["url"] . ' ' . $target_item["guid"] . ' entry: ' . $atom, LOGGER_DATA);
215 $basepath = implode('/', array_slice(explode('/',$contact['url']),0,3));
217 // perform local delivery if we are on the same site
219 if (link_compare($basepath, System::baseUrl())) {
220 $condition = ['nurl' => normalise_link($contact['url']), 'self' => true];
221 $target_self = dba::selectFirst('contact', ['uid'], $condition);
222 if (!DBM::is_result($target_self)) {
225 $target_uid = $target_self['uid'];
227 // Check if the user has got this contact
228 $cid = Contact::getIdForURL($owner['url'], $target_uid);
230 // Otherwise there should be a public contact
231 $cid = Contact::getIdForURL($owner['url']);
237 // We now have some contact, so we fetch it
238 $target_importer = dba::fetch_first("SELECT *, `name` as `senderName`
240 WHERE NOT `blocked` AND `id` = ? LIMIT 1",
243 // This should never fail
244 if (!DBM::is_result($target_importer)) {
248 // Set the user id. This is important if this is a public contact
249 $target_importer['importer_uid'] = $target_uid;
250 DFRN::import($atom, $target_importer);
254 if ($items[0]['uid'] == 0) {
255 $deliver_status = DFRN::transmit($owner, $contact, $atom);
256 if ($deliver_status < 200) {
257 // Transmit via Diaspora if not possible via Friendica
258 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
262 $deliver_status = DFRN::deliver($owner, $contact, $atom);
265 logger('Delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
267 if ($deliver_status < 0) {
268 logger('Delivery failed: queuing message ' . $target_item["guid"] );
269 Queue::add($contact['id'], NETWORK_DFRN, $atom, false, $target_item['guid']);
272 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
273 // We successfully delivered a message, the contact is alive
274 Contact::unmarkForArchival($contact);
276 // The message could not be delivered. We mark the contact as "dead"
277 Contact::markForArchival($contact);
281 private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
283 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
284 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != ACCOUNT_TYPE_COMMUNITY);
286 if ($public_message) {
287 $loc = 'public batch ' . $contact['batch'];
289 $loc = $contact['addr'];
292 logger('Deliver ' . $target_item["guid"] . ' via Diaspora to ' . $loc);
294 if (Config::get('system', 'dfrn_only') || !Config::get('system', 'diaspora_enabled')) {
297 if ($cmd == DELIVER_MAIL) {
298 Diaspora::sendMail($target_item, $owner, $contact);
302 if ($cmd == DELIVER_SUGGESTION) {
305 if (!$contact['pubkey'] && !$public_message) {
308 if (($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
309 // top-level retraction
310 logger('diaspora retract: ' . $loc);
311 Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
313 } elseif ($cmd == DELIVER_RELOCATION) {
314 Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
316 } elseif ($followup) {
317 // send comments and likes to owner to relay
318 logger('diaspora followup: ' . $loc);
319 Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
321 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
322 // we are the relay - send comments, likes and relayable_retractions to our conversants
323 logger('diaspora relay: ' . $loc);
324 Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
326 } elseif ($top_level && !$walltowall) {
327 // currently no workable solution for sending walltowall
328 logger('diaspora status: ' . $loc);
329 Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
333 logger('Unknown mode ' . $cmd . ' for ' . $loc);
336 private static function deliverMail($cmd, $contact, $owner, $target_item)
340 if (Config::get('system','dfrn_only')) {
343 // WARNING: does not currently convert to RFC2047 header encodings, etc.
345 $addr = $contact['addr'];
346 if (!strlen($addr)) {
350 if (!in_array($cmd, [DELIVER_POST, DELIVER_COMMENT])) {
354 $local_user = dba::selectFirst('user', [], ['uid' => $owner['uid']]);
355 if (!DBM::is_result($local_user)) {
359 logger('Deliver ' . $target_item["guid"] . ' via mail to ' . $contact['addr']);
362 $mailacct = dba::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
363 if (DBM::is_result($mailacct) && !empty($mailacct['reply_to'])) {
364 $reply_to = $mailacct['reply_to'];
367 $subject = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : L10n::t("\x28no subject\x29"));
369 // only expose our real email address to true friends
371 if (($contact['rel'] == CONTACT_IS_FRIEND) && !$contact['blocked']) {
373 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to.'>' . "\n";
374 $headers .= 'Sender: ' . $local_user['email'] . "\n";
376 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8').' <' . $local_user['email'] . '>' . "\n";
379 $headers = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <noreply@' . $a->get_hostname() . '>' . "\n";
382 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
384 if ($target_item['uri'] !== $target_item['parent-uri']) {
385 $headers .= "References: <" . Email::iri2msgid($target_item["parent-uri"]) . ">";
387 // If Threading is enabled, write down the correct parent
388 if (($target_item["thr-parent"] != "") && ($target_item["thr-parent"] != $target_item["parent-uri"])) {
389 $headers .= " <".Email::iri2msgid($target_item["thr-parent"]).">";
393 if (empty($target_item['title'])) {
394 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
395 $title = dba::selectFirst('item', ['title'], $condition);
396 if (DBM::is_result($title) && ($title['title'] != '')) {
397 $subject = $title['title'];
399 $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
400 $title = dba::selectFirst('item', ['title'], $condition);
401 if (DBM::is_result($title) && ($title['title'] != '')) {
402 $subject = $title['title'];
406 if (strncasecmp($subject, 'RE:', 3)) {
407 $subject = 'Re: ' . $subject;
410 Email::send($addr, $subject, $headers, $target_item);