3 * @file src/Worker/Delivery.php
5 namespace Friendica\Worker;
8 use Friendica\Core\System;
9 use Friendica\Core\Config;
10 use Friendica\Core\L10n;
11 use Friendica\Database\DBM;
12 use Friendica\Model\Contact;
13 use Friendica\Model\Queue;
14 use Friendica\Model\User;
15 use Friendica\Protocol\Diaspora;
16 use Friendica\Protocol\DFRN;
17 use Friendica\Protocol\Email;
20 require_once 'include/html2plain.php';
21 require_once 'include/datetime.php';
22 require_once 'include/items.php';
23 require_once 'include/bbcode.php';
25 /// @todo This is some ugly code that needs to be split into several methods
28 public static function execute($cmd, $item_id, $contact_id) {
31 logger('delivery: invoked: '.$cmd.': '.$item_id.' to '.$contact_id, LOGGER_DEBUG);
43 $recipients[] = $contact_id;
45 if ($cmd === 'mail') {
48 $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1",
51 if (!count($message)) {
54 $uid = $message[0]['uid'];
55 $recipients[] = $message[0]['contact-id'];
57 } elseif ($cmd === 'suggest') {
61 $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1",
64 if (!count($suggest)) {
67 $uid = $suggest[0]['uid'];
68 $recipients[] = $suggest[0]['cid'];
70 } elseif ($cmd === 'relocate') {
76 $target_item = dba::fetch_first("SELECT `item`.*, `contact`.`uid` AS `cuid` FROM `item`
77 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
78 WHERE `item`.`id` = ? AND `visible` AND NOT `moderated`", $item_id);
80 if (!DBM::is_result($target_item) || !intval($target_item['parent'])) {
84 $parent_id = intval($target_item['parent']);
85 $uid = $target_item['cuid'];
86 $updated = $target_item['edited'];
88 $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
89 FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d AND visible = 1 AND moderated = 0 ORDER BY `id` ASC",
99 foreach ($items as $item) {
100 if (!in_array($item['contact-id'],$contacts_arr)) {
101 $contacts_arr[] = intval($item['contact-id']);
104 if (count($contacts_arr)) {
105 $str_contacts = implode(',',$contacts_arr);
106 $icontacts = q("SELECT * FROM `contact`
107 WHERE `id` IN ( $str_contacts ) "
110 if ( !($icontacts && count($icontacts))) {
114 // avoid race condition with deleting entries
116 if ($items[0]['deleted']) {
117 foreach ($items as $item) {
118 $item['deleted'] = 1;
122 // When commenting too fast after delivery, a post wasn't recognized as top level post.
123 // The count then showed more than one entry. The additional check should help.
124 // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
125 if ((($items[0]['id'] == $item_id) || (count($items) == 1)) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
126 logger('delivery: top level post');
131 $owner = User::getOwnerDataById($uid);
136 $walltowall = (($top_level && ($owner['id'] != $items[0]['contact-id'])) ? true : false);
138 $public_message = true;
140 if (!$mail && !$fsuggest && !$relocate) {
143 // This is IMPORTANT!!!!
145 // We will only send a "notify owner to relay" or followup message if the referenced post
146 // originated on our system by virtue of having our hostname somewhere
147 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
148 // if $parent['wall'] == 1 we will already have the parent message in our array
149 // and we will relay the whole lot.
151 $localhost = $a->get_hostname();
152 if (strpos($localhost,':')) {
153 $localhost = substr($localhost,0,strpos($localhost,':'));
157 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
158 * have been known to cause runaway conditions which affected several servers, along with
159 * permissions issues.
163 $relay_to_owner = false;
165 if (!$top_level && ($parent['wall'] == 0) && stristr($target_item['uri'], $localhost)) {
166 $relay_to_owner = true;
169 if ($relay_to_owner) {
170 logger('followup '.$target_item["guid"], LOGGER_DEBUG);
171 // local followup to remote post
175 if (strlen($parent['allow_cid'])
176 || strlen($parent['allow_gid'])
177 || strlen($parent['deny_cid'])
178 || strlen($parent['deny_gid'])
179 || $parent["private"]) {
180 $public_message = false; // private recipients, not public
185 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `blocked` = 0 AND `pending` = 0",
189 if (DBM::is_result($r)) {
192 if ($contact['self']) {
197 // Transmit via Diaspora if not possible via Friendica
198 if (($item['uid'] == 0) && ($contact['network'] == NETWORK_DFRN)) {
199 $contact['network'] = NETWORK_DIASPORA;
202 logger("main delivery by delivery: followup=$followup mail=$mail fsuggest=$fsuggest relocate=$relocate - network ".$contact['network']);
204 switch ($contact['network']) {
207 logger('notifier: '.$target_item["guid"].' dfrndelivery: '.$contact['name']);
210 $item['body'] = fix_private_photos($item['body'],$owner['uid'],null,$message[0]['contact-id']);
211 $atom = DFRN::mail($item, $owner);
212 } elseif ($fsuggest) {
213 $atom = DFRN::fsuggest($item, $owner);
214 q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1", intval($item['id']));
215 } elseif ($relocate) {
216 $atom = DFRN::relocate($owner, $uid);
217 } elseif ($followup) {
219 foreach ($items as $item) { // there is only one item
220 if (!$item['parent']) {
223 if ($item['id'] == $item_id) {
224 logger('followup: item: '. print_r($item,true), LOGGER_DATA);
228 $atom = DFRN::entries($msgitems,$owner);
231 foreach ($items as $item) {
232 if (!$item['parent']) {
236 // private emails may be in included in public conversations. Filter them.
237 if ($public_message && $item['private']) {
241 $item_contact = get_item_contact($item,$icontacts);
242 if (!$item_contact) {
247 if ($item_id == $item['id'] || $item['id'] == $item['parent']) {
248 $item["entry:comment-allow"] = true;
249 $item["entry:cid"] = (($top_level) ? $contact['id'] : 0);
253 $item["entry:comment-allow"] = true;
257 $atom = DFRN::entries($msgitems,$owner);
260 logger('notifier entry: '.$contact["url"].' '.$target_item["guid"].' entry: '.$atom, LOGGER_DEBUG);
262 logger('notifier: '.$atom, LOGGER_DATA);
263 $basepath = implode('/', array_slice(explode('/',$contact['url']),0,3));
265 // perform local delivery if we are on the same site
267 if (link_compare($basepath,System::baseUrl())) {
268 $nickname = basename($contact['url']);
269 if ($contact['issued-id']) {
270 $sql_extra = sprintf(" AND `dfrn-id` = '%s' ", dbesc($contact['issued-id']));
272 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($contact['dfrn-id']));
275 $x = q("SELECT `contact`.*, `contact`.`uid` AS `importer_uid`,
276 `contact`.`pubkey` AS `cpubkey`,
277 `contact`.`prvkey` AS `cprvkey`,
278 `contact`.`thumb` AS `thumb`,
279 `contact`.`url` as `url`,
280 `contact`.`name` as `senderName`,
283 INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`
284 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
285 AND `contact`.`network` = '%s' AND `user`.`nickname` = '%s'
287 AND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 LIMIT 1",
292 if ($x && count($x)) {
293 $write_flag = ((($x[0]['rel']) && ($x[0]['rel'] != CONTACT_IS_SHARING)) ? true : false);
294 if ((($owner['page-flags'] == PAGE_COMMUNITY) || $write_flag) && !$x[0]['writable']) {
295 q("UPDATE `contact` SET `writable` = 1 WHERE `id` = %d",
298 $x[0]['writable'] = 1;
301 $ssl_policy = Config::get('system','ssl_policy');
302 fix_contact_ssl_policy($x[0],$ssl_policy);
304 // If we are setup as a soapbox we aren't accepting top level posts from this person
306 if (($x[0]['page-flags'] == PAGE_SOAPBOX) && $top_level) {
309 logger('mod-delivery: local delivery');
310 DFRN::import($atom, $x[0]);
315 if (!Queue::wasDelayed($contact['id'])) {
316 $deliver_status = DFRN::deliver($owner, $contact, $atom);
318 $deliver_status = (-1);
321 logger('notifier: dfrn_delivery to '.$contact["url"].' with guid '.$target_item["guid"].' returns '.$deliver_status);
323 if ($deliver_status < 0) {
324 logger('notifier: delivery failed: queuing message');
325 Queue::add($contact['id'], NETWORK_DFRN, $atom);
327 // The message could not be delivered. We mark the contact as "dead"
328 Contact::markForArchival($contact);
330 // We successfully delivered a message, the contact is alive
331 Contact::unmarkForArchival($contact);
336 case NETWORK_OSTATUS:
337 // Do not send to otatus if we are not configured to send to public networks
338 if ($owner['prvnets']) {
341 if (Config::get('system','ostatus_disabled') || Config::get('system','dfrn_only')) {
345 // There is currently no code here to distribute anything to OStatus.
346 // This is done in "notifier.php" (See "url_recipients" and "push_notify")
351 if (Config::get('system','dfrn_only')) {
354 // WARNING: does not currently convert to RFC2047 header encodings, etc.
356 $addr = $contact['addr'];
357 if (!strlen($addr)) {
361 if ($cmd === 'wall-new' || $cmd === 'comment-new') {
363 if ($cmd === 'wall-new') {
366 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
369 if (DBM::is_result($r)) {
377 $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
380 if (!count($local_user)) {
385 $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
388 if ($r1 && $r1[0]['reply_to']) {
389 $reply_to = $r1[0]['reply_to'];
392 $subject = (($it['title']) ? Email::encodeHeader($it['title'],'UTF-8') : L10n::t("\x28no subject\x29")) ;
394 // only expose our real email address to true friends
396 if (($contact['rel'] == CONTACT_IS_FRIEND) && !$contact['blocked']) {
398 $headers = 'From: '.Email::encodeHeader($local_user[0]['username'],'UTF-8').' <'.$reply_to.'>'."\n";
399 $headers .= 'Sender: '.$local_user[0]['email']."\n";
401 $headers = 'From: '.Email::encodeHeader($local_user[0]['username'],'UTF-8').' <'.$local_user[0]['email'].'>'."\n";
404 $headers = 'From: '. Email::encodeHeader($local_user[0]['username'],'UTF-8') .' <'. L10n::t('noreply') .'@'.$a->get_hostname() .'>'. "\n";
408 // $headers .= 'Reply-to: '.$reply_to . "\n";
410 $headers .= 'Message-Id: <'. Email::iri2msgid($it['uri']).'>'. "\n";
412 //logger("Mail: uri: ".$it['uri']." parent-uri ".$it['parent-uri'], LOGGER_DEBUG);
413 //logger("Mail: Data: ".print_r($it, true), LOGGER_DEBUG);
414 //logger("Mail: Data: ".print_r($it, true), LOGGER_DATA);
416 if ($it['uri'] !== $it['parent-uri']) {
417 $headers .= "References: <".Email::iri2msgid($it["parent-uri"]).">";
419 // If Threading is enabled, write down the correct parent
420 if (($it["thr-parent"] != "") && ($it["thr-parent"] != $it["parent-uri"])) {
421 $headers .= " <".Email::iri2msgid($it["thr-parent"]).">";
426 $r = q("SELECT `title` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
427 dbesc($it['parent-uri']),
430 if (DBM::is_result($r) && ($r[0]['title'] != '')) {
431 $subject = $r[0]['title'];
433 $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d LIMIT 1",
434 dbesc($it['parent-uri']),
437 if (DBM::is_result($r) && ($r[0]['title'] != '')) {
438 $subject = $r[0]['title'];
442 if (strncasecmp($subject,'RE:',3)) {
443 $subject = 'Re: '.$subject;
446 Email::send($addr, $subject, $headers, $it);
450 case NETWORK_DIASPORA:
451 if ($public_message) {
452 $loc = 'public batch '.$contact['batch'];
454 $loc = $contact['name'];
457 logger('delivery: diaspora batch deliver: '.$loc);
459 if (Config::get('system','dfrn_only') || !Config::get('system','diaspora_enabled')) {
463 Diaspora::sendMail($item,$owner,$contact);
470 if (!$contact['pubkey'] && !$public_message) {
473 if (($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
474 // top-level retraction
475 logger('diaspora retract: '.$loc);
476 Diaspora::sendRetraction($target_item,$owner,$contact,$public_message);
478 } elseif ($relocate) {
479 Diaspora::sendAccountMigration($owner, $contact, $uid);
481 } elseif ($followup) {
482 // send comments and likes to owner to relay
483 logger('diaspora followup: '.$loc);
484 Diaspora::sendFollowup($target_item,$owner,$contact,$public_message);
486 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
487 // we are the relay - send comments, likes and relayable_retractions to our conversants
488 logger('diaspora relay: '.$loc);
489 Diaspora::sendRelay($target_item,$owner,$contact,$public_message);
491 } elseif ($top_level && !$walltowall) {
492 // currently no workable solution for sending walltowall
493 logger('diaspora status: '.$loc);
494 Diaspora::sendStatus($target_item,$owner,$contact,$public_message);
498 logger('delivery: diaspora unknown mode: '.$contact['name']);