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';
23 public static function execute($cmd, $item_id, $contact_id) {
26 logger('Invoked: ' . $cmd . ': ' . $item_id . ' to ' . $contact_id, LOGGER_DEBUG);
30 $public_message = false;
32 if ($cmd == DELIVER_MAIL) {
33 $target_item = dba::selectFirst('mail', [], ['id' => $item_id]);
34 if (!DBM::is_result($message)) {
37 $uid = $target_item['uid'];
38 } elseif ($cmd == DELIVER_SUGGESTION) {
39 $target_item = dba::selectFirst('fsuggest', [], ['id' => $item_id]);
40 if (!DBM::is_result($message)) {
43 $uid = $target_item['uid'];
44 } elseif ($cmd == DELIVER_RELOCATION) {
47 $item = dba::selectFirst('item', ['parent'], ['id' => $item_id]);
48 if (!DBM::is_result($item) || empty($item['parent'])) {
51 $parent_id = intval($item['parent']);
53 $itemdata = dba::p("SELECT `item`.*, `contact`.`uid` AS `cuid`,
54 `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
56 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
57 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
58 WHERE `item`.`id` IN (?, ?) AND `visible` AND NOT `moderated`
59 ORDER BY `item`.`id`",
60 $item_id, $parent_id);
62 while ($item = dba::fetch($itemdata)) {
63 if ($item['id'] == $parent_id) {
66 if ($item['id'] == $item_id) {
71 dba::close($itemdata);
73 $uid = $target_item['cuid'];
75 // avoid race condition with deleting entries
76 if ($items[0]['deleted']) {
77 foreach ($items as $item) {
82 // When commenting too fast after delivery, a post wasn't recognized as top level post.
83 // The count then showed more than one entry. The additional check should help.
84 // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
85 if ((($parent['id'] == $item_id) || (count($items) == 1)) && ($parent['uri'] === $parent['parent-uri'])) {
86 logger('Top level post');
90 // This is IMPORTANT!!!!
92 // We will only send a "notify owner to relay" or followup message if the referenced post
93 // originated on our system by virtue of having our hostname somewhere
94 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
95 // if $parent['wall'] == 1 we will already have the parent message in our array
96 // and we will relay the whole lot.
98 $localhost = $a->get_hostname();
99 if (strpos($localhost, ':')) {
100 $localhost = substr($localhost, 0, strpos($localhost, ':'));
104 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
105 * have been known to cause runaway conditions which affected several servers, along with
106 * permissions issues.
110 if (!$top_level && ($parent['wall'] == 0) && stristr($target_item['uri'], $localhost)) {
111 logger('Followup ' . $target_item["guid"], LOGGER_DEBUG);
112 // local followup to remote post
116 if (empty($parent['allow_cid'])
117 && empty($parent['allow_gid'])
118 && empty($parent['deny_cid'])
119 && empty($parent['deny_gid'])
120 && !$parent["private"]) {
121 $public_message = true;
125 $owner = User::getOwnerDataById($uid);
126 if (!DBM::is_result($owner)) {
130 // We don't deliver our items to blocked or pending contacts, and not to ourselves either
131 $contact = dba::selectFirst('contact', [],
132 ['id' => $contact_id, 'blocked' => false, 'pending' => false, 'self' => false]
134 if (!DBM::is_result($contact)) {
138 // Transmit via Diaspora if the thread had started as Diaspora post
139 // This is done since the uri wouldn't match (Diaspora doesn't transmit it)
140 if (isset($parent) && ($parent['network'] == NETWORK_DIASPORA) && ($contact['network'] == NETWORK_DFRN)) {
141 $contact['network'] = NETWORK_DIASPORA;
144 logger("Delivering " . $cmd . " followup=$followup - via network " . $contact['network']);
146 switch ($contact['network']) {
149 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
152 case NETWORK_DIASPORA:
153 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
156 case NETWORK_OSTATUS:
157 // Do not send to otatus if we are not configured to send to public networks
158 if ($owner['prvnets']) {
161 if (Config::get('system','ostatus_disabled') || Config::get('system','dfrn_only')) {
165 // There is currently no code here to distribute anything to OStatus.
166 // This is done in "notifier.php" (See "url_recipients" and "push_notify")
170 self::deliverMail($cmd, $contact, $owner, $target_item);
180 private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
182 logger('Deliver ' . $target_item["guid"] . ' via DFRN to ' . $contact['addr']);
184 if ($cmd == DELIVER_MAIL) {
185 $item = $target_item;
186 $item['body'] = Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
187 $atom = DFRN::mail($item, $owner);
188 } elseif ($cmd == DELIVER_SUGGESTION) {
189 $item = $target_item;
190 $atom = DFRN::fsuggest($item, $owner);
191 dba::delete('fsuggest', ['id' => $item['id']]);
192 } elseif ($cmd == DELIVER_RELOCATION) {
193 $atom = DFRN::relocate($owner, $owner['uid']);
194 } elseif ($followup) {
195 $msgitems = [$target_item];
196 $atom = DFRN::entries($msgitems, $owner);
199 foreach ($items as $item) {
200 // Only add the parent when we don't delete other items.
201 if (($target_item['id'] == $item['id']) || ($cmd != DELIVER_DELETION)) {
202 $item["entry:comment-allow"] = true;
203 $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
207 $atom = DFRN::entries($msgitems,$owner);
210 logger('Notifier entry: ' . $contact["url"] . ' ' . $target_item["guid"] . ' entry: ' . $atom, LOGGER_DATA);
212 $basepath = implode('/', array_slice(explode('/',$contact['url']),0,3));
214 // perform local delivery if we are on the same site
216 if (link_compare($basepath, System::baseUrl())) {
217 $condition = ['nurl' => normalise_link($contact['url']), 'self' => true];
218 $target_self = dba::selectFirst('contact', ['uid'], $condition);
219 if (!DBM::is_result($target_self)) {
222 $target_uid = $target_self['uid'];
224 // Check if the user has got this contact
225 $cid = Contact::getIdForURL($owner['url'], $target_uid);
227 // Otherwise there should be a public contact
228 $cid = Contact::getIdForURL($owner['url']);
234 // We now have some contact, so we fetch it
235 $target_importer = dba::fetch_first("SELECT *, `name` as `senderName`
237 WHERE NOT `blocked` AND `id` = ? LIMIT 1",
240 // This should never fail
241 if (!DBM::is_result($target_importer)) {
245 // Set the user id. This is important if this is a public contact
246 $target_importer['importer_uid'] = $target_uid;
247 DFRN::import($atom, $target_importer);
251 if ($items[0]['uid'] == 0) {
252 $deliver_status = DFRN::transmit($owner, $contact, $atom);
253 if ($deliver_status < 200) {
254 // Transmit via Diaspora if not possible via Friendica
255 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
259 $deliver_status = DFRN::deliver($owner, $contact, $atom);
262 logger('Delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
264 if ($deliver_status < 0) {
265 logger('Delivery failed: queuing message ' . $target_item["guid"] );
266 Queue::add($contact['id'], NETWORK_DFRN, $atom, false, $target_item['guid']);
269 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
270 // We successfully delivered a message, the contact is alive
271 Contact::unmarkForArchival($contact);
273 // The message could not be delivered. We mark the contact as "dead"
274 Contact::markForArchival($contact);
278 private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
280 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
281 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != ACCOUNT_TYPE_COMMUNITY);
283 if ($public_message) {
284 $loc = 'public batch ' . $contact['batch'];
286 $loc = $contact['addr'];
289 logger('Deliver ' . $target_item["guid"] . ' via Diaspora to ' . $loc);
291 if (Config::get('system', 'dfrn_only') || !Config::get('system', 'diaspora_enabled')) {
294 if ($cmd == DELIVER_MAIL) {
295 Diaspora::sendMail($target_item, $owner, $contact);
299 if ($cmd == DELIVER_SUGGESTION) {
302 if (!$contact['pubkey'] && !$public_message) {
305 if (($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
306 // top-level retraction
307 logger('diaspora retract: ' . $loc);
308 Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
310 } elseif ($cmd == DELIVER_RELOCATION) {
311 Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
313 } elseif ($followup) {
314 // send comments and likes to owner to relay
315 logger('diaspora followup: ' . $loc);
316 Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
318 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
319 // we are the relay - send comments, likes and relayable_retractions to our conversants
320 logger('diaspora relay: ' . $loc);
321 Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
323 } elseif ($top_level && !$walltowall) {
324 // currently no workable solution for sending walltowall
325 logger('diaspora status: ' . $loc);
326 Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
330 logger('Unknown mode ' . $cmd . ' for ' . $loc);
333 private static function deliverMail($cmd, $contact, $owner, $target_item)
337 if (Config::get('system','dfrn_only')) {
340 // WARNING: does not currently convert to RFC2047 header encodings, etc.
342 $addr = $contact['addr'];
343 if (!strlen($addr)) {
347 if (!in_array($cmd, [DELIVER_POST, DELIVER_COMMENT])) {
351 $local_user = dba::selectFirst('user', [], ['uid' => $owner['uid']]);
352 if (!DBM::is_result($local_user)) {
356 logger('Deliver ' . $target_item["guid"] . ' via mail to ' . $contact['addr']);
359 $mailacct = dba::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
360 if (DBM::is_result($mailacct) && !empty($mailacct['reply_to'])) {
361 $reply_to = $mailacct['reply_to'];
364 $subject = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : L10n::t("\x28no subject\x29"));
366 // only expose our real email address to true friends
368 if (($contact['rel'] == CONTACT_IS_FRIEND) && !$contact['blocked']) {
370 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to.'>' . "\n";
371 $headers .= 'Sender: ' . $local_user['email'] . "\n";
373 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8').' <' . $local_user['email'] . '>' . "\n";
376 $headers = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <noreply@' . $a->get_hostname() . '>' . "\n";
379 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
381 if ($target_item['uri'] !== $target_item['parent-uri']) {
382 $headers .= "References: <" . Email::iri2msgid($target_item["parent-uri"]) . ">";
384 // If Threading is enabled, write down the correct parent
385 if (($target_item["thr-parent"] != "") && ($target_item["thr-parent"] != $target_item["parent-uri"])) {
386 $headers .= " <".Email::iri2msgid($target_item["thr-parent"]).">";
390 if (empty($target_item['title'])) {
391 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
392 $title = dba::selectFirst('item', ['title'], $condition);
393 if (DBM::is_result($title) && ($title['title'] != '')) {
394 $subject = $title['title'];
396 $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
397 $title = dba::selectFirst('item', ['title'], $condition);
398 if (DBM::is_result($title) && ($title['title'] != '')) {
399 $subject = $title['title'];
403 if (strncasecmp($subject, 'RE:', 3)) {
404 $subject = 'Re: ' . $subject;
407 Email::send($addr, $subject, $headers, $target_item);