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\System;
11 use Friendica\Database\DBM;
12 use Friendica\Model\Contact;
13 use Friendica\Model\Item;
14 use Friendica\Model\Queue;
15 use Friendica\Model\User;
16 use Friendica\Protocol\DFRN;
17 use Friendica\Protocol\Diaspora;
18 use Friendica\Protocol\Email;
21 require_once 'include/items.php';
23 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';
31 public static function execute($cmd, $item_id, $contact_id) {
32 logger('Invoked: ' . $cmd . ': ' . $item_id . ' to ' . $contact_id, LOGGER_DEBUG);
36 $public_message = false;
38 if ($cmd == self::MAIL) {
39 $target_item = dba::selectFirst('mail', [], ['id' => $item_id]);
40 if (!DBM::is_result($message)) {
43 $uid = $target_item['uid'];
44 } elseif ($cmd == self::SUGGESTION) {
45 $target_item = dba::selectFirst('fsuggest', [], ['id' => $item_id]);
46 if (!DBM::is_result($message)) {
49 $uid = $target_item['uid'];
50 } elseif ($cmd == self::RELOCATION) {
53 $item = dba::selectFirst('item', ['parent'], ['id' => $item_id]);
54 if (!DBM::is_result($item) || empty($item['parent'])) {
57 $parent_id = intval($item['parent']);
59 $itemdata = dba::p("SELECT `item`.*, `contact`.`uid` AS `cuid`,
60 `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
62 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
63 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
64 WHERE `item`.`id` IN (?, ?) AND `visible` AND NOT `moderated`
65 ORDER BY `item`.`id`",
66 $item_id, $parent_id);
68 while ($item = dba::fetch($itemdata)) {
69 if ($item['id'] == $parent_id) {
72 if ($item['id'] == $item_id) {
77 dba::close($itemdata);
79 $uid = $target_item['cuid'];
81 // avoid race condition with deleting entries
82 if ($items[0]['deleted']) {
83 foreach ($items as $item) {
88 // When commenting too fast after delivery, a post wasn't recognized as top level post.
89 // The count then showed more than one entry. The additional check should help.
90 // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
91 if ((($parent['id'] == $item_id) || (count($items) == 1)) && ($parent['uri'] === $parent['parent-uri'])) {
92 logger('Top level post');
96 // This is IMPORTANT!!!!
98 // We will only send a "notify owner to relay" or followup message if the referenced post
99 // originated on our system by virtue of having our hostname somewhere
100 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
101 // if $parent['wall'] == 1 we will already have the parent message in our array
102 // and we will relay the whole lot.
104 $localhost = self::getApp()->get_hostname();
105 if (strpos($localhost, ':')) {
106 $localhost = substr($localhost, 0, strpos($localhost, ':'));
110 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
111 * have been known to cause runaway conditions which affected several servers, along with
112 * permissions issues.
116 if (!$top_level && ($parent['wall'] == 0) && stristr($target_item['uri'], $localhost)) {
117 logger('Followup ' . $target_item["guid"], LOGGER_DEBUG);
118 // local followup to remote post
122 if (empty($parent['allow_cid'])
123 && empty($parent['allow_gid'])
124 && empty($parent['deny_cid'])
125 && empty($parent['deny_gid'])
126 && !$parent["private"]) {
127 $public_message = true;
131 $owner = User::getOwnerDataById($uid);
132 if (!DBM::is_result($owner)) {
136 // We don't deliver our items to blocked or pending contacts, and not to ourselves either
137 $contact = dba::selectFirst('contact', [],
138 ['id' => $contact_id, 'blocked' => false, 'pending' => false, 'self' => false]
140 if (!DBM::is_result($contact)) {
144 // Transmit via Diaspora if the thread had started as Diaspora post
145 // This is done since the uri wouldn't match (Diaspora doesn't transmit it)
146 if (isset($parent) && ($parent['network'] == NETWORK_DIASPORA) && ($contact['network'] == NETWORK_DFRN)) {
147 $contact['network'] = NETWORK_DIASPORA;
150 logger("Delivering " . $cmd . " followup=$followup - via network " . $contact['network']);
152 switch ($contact['network']) {
155 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
158 case NETWORK_DIASPORA:
159 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
162 case NETWORK_OSTATUS:
163 // Do not send to otatus if we are not configured to send to public networks
164 if ($owner['prvnets']) {
167 if (Config::get('system','ostatus_disabled') || Config::get('system','dfrn_only')) {
171 // There is currently no code here to distribute anything to OStatus.
172 // This is done in "notifier.php" (See "url_recipients" and "push_notify")
176 self::deliverMail($cmd, $contact, $owner, $target_item);
186 private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
188 logger('Deliver ' . $target_item["guid"] . ' via DFRN to ' . $contact['addr']);
190 if ($cmd == self::MAIL) {
191 $item = $target_item;
192 $item['body'] = Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
193 $atom = DFRN::mail($item, $owner);
194 } elseif ($cmd == self::SUGGESTION) {
195 $item = $target_item;
196 $atom = DFRN::fsuggest($item, $owner);
197 dba::delete('fsuggest', ['id' => $item['id']]);
198 } elseif ($cmd == self::RELOCATION) {
199 $atom = DFRN::relocate($owner, $owner['uid']);
200 } elseif ($followup) {
201 $msgitems = [$target_item];
202 $atom = DFRN::entries($msgitems, $owner);
205 foreach ($items as $item) {
206 // Only add the parent when we don't delete other items.
207 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
208 $item["entry:comment-allow"] = true;
209 $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
213 $atom = DFRN::entries($msgitems, $owner);
216 logger('Notifier entry: ' . $contact["url"] . ' ' . $target_item["guid"] . ' entry: ' . $atom, LOGGER_DATA);
218 $basepath = implode('/', array_slice(explode('/', $contact['url']), 0, 3));
220 // perform local delivery if we are on the same site
222 if (link_compare($basepath, System::baseUrl())) {
223 $condition = ['nurl' => normalise_link($contact['url']), 'self' => true];
224 $target_self = dba::selectFirst('contact', ['uid'], $condition);
225 if (!DBM::is_result($target_self)) {
228 $target_uid = $target_self['uid'];
230 // Check if the user has got this contact
231 $cid = Contact::getIdForURL($owner['url'], $target_uid);
233 // Otherwise there should be a public contact
234 $cid = Contact::getIdForURL($owner['url']);
240 // We now have some contact, so we fetch it
241 $target_importer = dba::fetch_first("SELECT *, `name` as `senderName`
243 WHERE NOT `blocked` AND `id` = ? LIMIT 1",
246 // This should never fail
247 if (!DBM::is_result($target_importer)) {
251 // Set the user id. This is important if this is a public contact
252 $target_importer['importer_uid'] = $target_uid;
253 DFRN::import($atom, $target_importer);
257 // We don't have a relationship with contacts on a public post.
258 // Se we transmit with the new method and via Diaspora as a fallback
259 if ($items[0]['uid'] == 0) {
260 $deliver_status = DFRN::transmit($owner, $contact, $atom);
261 if ($deliver_status < 200) {
262 // Transmit via Diaspora if not possible via Friendica
263 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
267 $deliver_status = DFRN::deliver($owner, $contact, $atom);
270 logger('Delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
272 if ($deliver_status < 0) {
273 logger('Delivery failed: queuing message ' . $target_item["guid"] );
274 Queue::add($contact['id'], NETWORK_DFRN, $atom, false, $target_item['guid']);
277 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
278 // We successfully delivered a message, the contact is alive
279 Contact::unmarkForArchival($contact);
281 // The message could not be delivered. We mark the contact as "dead"
282 Contact::markForArchival($contact);
286 private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
288 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
289 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != ACCOUNT_TYPE_COMMUNITY);
291 if ($public_message) {
292 $loc = 'public batch ' . $contact['batch'];
294 $loc = $contact['addr'];
297 logger('Deliver ' . $target_item["guid"] . ' via Diaspora to ' . $loc);
299 if (Config::get('system', 'dfrn_only') || !Config::get('system', 'diaspora_enabled')) {
302 if ($cmd == self::MAIL) {
303 Diaspora::sendMail($target_item, $owner, $contact);
307 if ($cmd == self::SUGGESTION) {
310 if (!$contact['pubkey'] && !$public_message) {
313 if (($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
314 // top-level retraction
315 logger('diaspora retract: ' . $loc);
316 Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
318 } elseif ($cmd == self::RELOCATION) {
319 Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
321 } elseif ($followup) {
322 // send comments and likes to owner to relay
323 logger('diaspora followup: ' . $loc);
324 Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
326 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
327 // we are the relay - send comments, likes and relayable_retractions to our conversants
328 logger('diaspora relay: ' . $loc);
329 Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
331 } elseif ($top_level && !$walltowall) {
332 // currently no workable solution for sending walltowall
333 logger('diaspora status: ' . $loc);
334 Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
338 logger('Unknown mode ' . $cmd . ' for ' . $loc);
341 private static function deliverMail($cmd, $contact, $owner, $target_item)
343 if (Config::get('system','dfrn_only')) {
346 // WARNING: does not currently convert to RFC2047 header encodings, etc.
348 $addr = $contact['addr'];
349 if (!strlen($addr)) {
353 if (!in_array($cmd, [self::POST, self::COMMENT])) {
357 $local_user = dba::selectFirst('user', [], ['uid' => $owner['uid']]);
358 if (!DBM::is_result($local_user)) {
362 logger('Deliver ' . $target_item["guid"] . ' via mail to ' . $contact['addr']);
365 $mailacct = dba::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
366 if (DBM::is_result($mailacct) && !empty($mailacct['reply_to'])) {
367 $reply_to = $mailacct['reply_to'];
370 $subject = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : L10n::t("\x28no subject\x29"));
372 // only expose our real email address to true friends
374 if (($contact['rel'] == CONTACT_IS_FRIEND) && !$contact['blocked']) {
376 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to.'>' . "\n";
377 $headers .= 'Sender: ' . $local_user['email'] . "\n";
379 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8').' <' . $local_user['email'] . '>' . "\n";
382 $headers = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <noreply@' . self::getApp()->get_hostname() . '>' . "\n";
385 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
387 if ($target_item['uri'] !== $target_item['parent-uri']) {
388 $headers .= "References: <" . Email::iri2msgid($target_item["parent-uri"]) . ">";
390 // If Threading is enabled, write down the correct parent
391 if (($target_item["thr-parent"] != "") && ($target_item["thr-parent"] != $target_item["parent-uri"])) {
392 $headers .= " <".Email::iri2msgid($target_item["thr-parent"]).">";
396 if (empty($target_item['title'])) {
397 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
398 $title = dba::selectFirst('item', ['title'], $condition);
399 if (DBM::is_result($title) && ($title['title'] != '')) {
400 $subject = $title['title'];
402 $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
403 $title = dba::selectFirst('item', ['title'], $condition);
404 if (DBM::is_result($title) && ($title['title'] != '')) {
405 $subject = $title['title'];
409 if (strncasecmp($subject, 'RE:', 3)) {
410 $subject = 'Re: ' . $subject;
413 Email::send($addr, $subject, $headers, $target_item);