3 * @file src/Worker/Delivery.php
6 namespace Friendica\Worker;
9 use Friendica\Core\System;
10 use Friendica\Core\Config;
11 use Friendica\Database\DBM;
12 use Friendica\Protocol\Diaspora;
13 use Friendica\Protocol\DFRN;
15 require_once 'include/queue_fn.php';
16 require_once 'include/html2plain.php';
17 require_once 'include/datetime.php';
18 require_once 'include/items.php';
19 require_once 'include/bbcode.php';
20 require_once 'include/email.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('delivery: invoked: '.$cmd.': '.$item_id.' to '.$contact_id, LOGGER_DEBUG);
35 $recipients = array();
36 $url_recipients = array();
41 $recipients[] = $contact_id;
43 if ($cmd === 'mail') {
46 $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1",
49 if (!count($message)) {
52 $uid = $message[0]['uid'];
53 $recipients[] = $message[0]['contact-id'];
55 } elseif ($cmd === 'expire') {
58 $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1
59 AND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 30 MINUTE",
67 } elseif ($cmd === 'suggest') {
71 $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1",
74 if (!count($suggest)) {
77 $uid = $suggest[0]['uid'];
78 $recipients[] = $suggest[0]['cid'];
80 } elseif ($cmd === 'relocate') {
86 $r = q("SELECT * FROM `item` WHERE `id` = %d AND visible = 1 AND moderated = 0 LIMIT 1",
90 if (!DBM::is_result($r) || !intval($r[0]['parent'])) {
95 $parent_id = intval($r[0]['parent']);
97 $updated = $r[0]['edited'];
99 $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
100 FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d AND visible = 1 AND moderated = 0 ORDER BY `id` ASC",
104 if (!count($items)) {
109 $contacts_arr = array();
110 foreach ($items as $item) {
111 if (!in_array($item['contact-id'],$contacts_arr)) {
112 $contacts_arr[] = intval($item['contact-id']);
115 if (count($contacts_arr)) {
116 $str_contacts = implode(',',$contacts_arr);
117 $icontacts = q("SELECT * FROM `contact`
118 WHERE `id` IN ( $str_contacts ) "
121 if ( !($icontacts && count($icontacts))) {
125 // avoid race condition with deleting entries
127 if ($items[0]['deleted']) {
128 foreach ($items as $item) {
129 $item['deleted'] = 1;
133 // When commenting too fast after delivery, a post wasn't recognized as top level post.
134 // The count then showed more than one entry. The additional check should help.
135 // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
136 if ((($items[0]['id'] == $item_id) || (count($items) == 1)) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
137 logger('delivery: top level post');
142 $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`,
143 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
144 `user`.`page-flags`, `user`.`account-type`, `user`.`prvnets`
145 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
146 WHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
150 if (!DBM::is_result($r)) {
156 $walltowall = (($top_level && ($owner['id'] != $items[0]['contact-id'])) ? true : false);
158 $public_message = true;
160 if (!($mail || $fsuggest || $relocate)) {
161 require_once 'include/group.php';
165 // This is IMPORTANT!!!!
167 // We will only send a "notify owner to relay" or followup message if the referenced post
168 // originated on our system by virtue of having our hostname somewhere
169 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
170 // if $parent['wall'] == 1 we will already have the parent message in our array
171 // and we will relay the whole lot.
173 // expire sends an entire group of expire messages and cannot be forwarded.
174 // However the conversation owner will be a part of the conversation and will
175 // be notified during this run.
176 // Other DFRN conversation members will be alerted during polled updates.
178 // Diaspora members currently are not notified of expirations, and other networks have
179 // either limited or no ability to process deletions. We should at least fix Diaspora
180 // by stringing togther an array of retractions and sending them onward.
183 $localhost = $a->get_hostname();
184 if (strpos($localhost,':')) {
185 $localhost = substr($localhost,0,strpos($localhost,':'));
189 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
190 * have been known to cause runaway conditions which affected several servers, along with
191 * permissions issues.
195 $relay_to_owner = false;
197 if (!$top_level && ($parent['wall'] == 0) && !$expire && stristr($target_item['uri'],$localhost)) {
198 $relay_to_owner = true;
201 if ($relay_to_owner) {
202 logger('followup '.$target_item["guid"], LOGGER_DEBUG);
203 // local followup to remote post
207 if ((strlen($parent['allow_cid']))
208 || (strlen($parent['allow_gid']))
209 || (strlen($parent['deny_cid']))
210 || (strlen($parent['deny_gid']))
211 || $parent["private"]) {
212 $public_message = false; // private recipients, not public
217 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `blocked` = 0 AND `pending` = 0",
221 if (DBM::is_result($r)) {
224 if ($contact['self']) {
229 logger("main delivery by delivery: followup=$followup mail=$mail fsuggest=$fsuggest relocate=$relocate - network ".$contact['network']);
231 switch($contact['network']) {
234 logger('notifier: '.$target_item["guid"].' dfrndelivery: '.$contact['name']);
237 $item['body'] = fix_private_photos($item['body'],$owner['uid'],null,$message[0]['contact-id']);
238 $atom = DFRN::mail($item, $owner);
239 } elseif ($fsuggest) {
240 $atom = DFRN::fsuggest($item, $owner);
241 q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1", intval($item['id']));
242 } elseif ($relocate) {
243 $atom = DFRN::relocate($owner, $uid);
244 } elseif ($followup) {
246 foreach ($items as $item) { // there is only one item
247 if (!$item['parent']) {
250 if ($item['id'] == $item_id) {
251 logger('followup: item: '. print_r($item,true), LOGGER_DATA);
255 $atom = DFRN::entries($msgitems,$owner);
258 foreach ($items as $item) {
259 if (!$item['parent']) {
263 // private emails may be in included in public conversations. Filter them.
264 if ($public_message && $item['private']) {
268 $item_contact = get_item_contact($item,$icontacts);
269 if (!$item_contact) {
274 if ($item_id == $item['id'] || $item['id'] == $item['parent']) {
275 $item["entry:comment-allow"] = true;
276 $item["entry:cid"] = (($top_level) ? $contact['id'] : 0);
280 $item["entry:comment-allow"] = true;
284 $atom = DFRN::entries($msgitems,$owner);
287 logger('notifier entry: '.$contact["url"].' '.$target_item["guid"].' entry: '.$atom, LOGGER_DEBUG);
289 logger('notifier: '.$atom, LOGGER_DATA);
290 $basepath = implode('/', array_slice(explode('/',$contact['url']),0,3));
292 // perform local delivery if we are on the same site
294 if (link_compare($basepath,System::baseUrl())) {
296 $nickname = basename($contact['url']);
297 if ($contact['issued-id']) {
298 $sql_extra = sprintf(" AND `dfrn-id` = '%s' ", dbesc($contact['issued-id']));
300 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($contact['dfrn-id']));
303 $x = q("SELECT `contact`.*, `contact`.`uid` AS `importer_uid`,
304 `contact`.`pubkey` AS `cpubkey`,
305 `contact`.`prvkey` AS `cprvkey`,
306 `contact`.`thumb` AS `thumb`,
307 `contact`.`url` as `url`,
308 `contact`.`name` as `senderName`,
311 INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`
312 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
313 AND `contact`.`network` = '%s' AND `user`.`nickname` = '%s'
315 AND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 LIMIT 1",
320 if ($x && count($x)) {
321 $write_flag = ((($x[0]['rel']) && ($x[0]['rel'] != CONTACT_IS_SHARING)) ? true : false);
322 if ((($owner['page-flags'] == PAGE_COMMUNITY) || $write_flag) && !$x[0]['writable']) {
323 q("UPDATE `contact` SET `writable` = 1 WHERE `id` = %d",
326 $x[0]['writable'] = 1;
329 $ssl_policy = Config::get('system','ssl_policy');
330 fix_contact_ssl_policy($x[0],$ssl_policy);
332 // If we are setup as a soapbox we aren't accepting top level posts from this person
334 if (($x[0]['page-flags'] == PAGE_SOAPBOX) && $top_level) {
337 logger('mod-delivery: local delivery');
338 DFRN::import($atom, $x[0]);
343 if (!was_recently_delayed($contact['id'])) {
344 $deliver_status = DFRN::deliver($owner,$contact,$atom);
346 $deliver_status = (-1);
349 logger('notifier: dfrn_delivery to '.$contact["url"].' with guid '.$target_item["guid"].' returns '.$deliver_status);
351 if ($deliver_status < 0) {
352 logger('notifier: delivery failed: queuing message');
353 add_to_queue($contact['id'],NETWORK_DFRN,$atom);
355 // The message could not be delivered. We mark the contact as "dead"
356 mark_for_death($contact);
358 // We successfully delivered a message, the contact is alive
359 unmark_for_death($contact);
364 case NETWORK_OSTATUS:
365 // Do not send to otatus if we are not configured to send to public networks
366 if ($owner['prvnets']) {
369 if (Config::get('system','ostatus_disabled') || Config::get('system','dfrn_only')) {
373 // There is currently no code here to distribute anything to OStatus.
374 // This is done in "notifier.php" (See "url_recipients" and "push_notify")
380 if (Config::get('system','dfrn_only')) {
383 // WARNING: does not currently convert to RFC2047 header encodings, etc.
385 $addr = $contact['addr'];
386 if (!strlen($addr)) {
390 if ($cmd === 'wall-new' || $cmd === 'comment-new') {
393 if ($cmd === 'wall-new') {
396 $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
400 if (DBM::is_result($r))
407 $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
410 if (!count($local_user))
414 $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
417 if ($r1 && $r1[0]['reply_to'])
418 $reply_to = $r1[0]['reply_to'];
420 $subject = (($it['title']) ? email_header_encode($it['title'],'UTF-8') : t("\x28no subject\x29")) ;
422 // only expose our real email address to true friends
424 if (($contact['rel'] == CONTACT_IS_FRIEND) && !$contact['blocked']) {
426 $headers = 'From: '.email_header_encode($local_user[0]['username'],'UTF-8').' <'.$reply_to.'>'."\n";
427 $headers .= 'Sender: '.$local_user[0]['email']."\n";
429 $headers = 'From: '.email_header_encode($local_user[0]['username'],'UTF-8').' <'.$local_user[0]['email'].'>'."\n";
432 $headers = 'From: '. email_header_encode($local_user[0]['username'],'UTF-8') .' <'. t('noreply') .'@'.$a->get_hostname() .'>'. "\n";
436 // $headers .= 'Reply-to: '.$reply_to . "\n";
438 $headers .= 'Message-Id: <'. iri2msgid($it['uri']).'>'. "\n";
440 //logger("Mail: uri: ".$it['uri']." parent-uri ".$it['parent-uri'], LOGGER_DEBUG);
441 //logger("Mail: Data: ".print_r($it, true), LOGGER_DEBUG);
442 //logger("Mail: Data: ".print_r($it, true), LOGGER_DATA);
444 if ($it['uri'] !== $it['parent-uri']) {
445 $headers .= "References: <".iri2msgid($it["parent-uri"]).">";
447 // If Threading is enabled, write down the correct parent
448 if (($it["thr-parent"] != "") && ($it["thr-parent"] != $it["parent-uri"]))
449 $headers .= " <".iri2msgid($it["thr-parent"]).">";
453 $r = q("SELECT `title` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
454 dbesc($it['parent-uri']),
457 if (DBM::is_result($r) && ($r[0]['title'] != '')) {
458 $subject = $r[0]['title'];
460 $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d LIMIT 1",
461 dbesc($it['parent-uri']),
464 if (DBM::is_result($r) && ($r[0]['title'] != ''))
465 $subject = $r[0]['title'];
468 if (strncasecmp($subject,'RE:',3))
469 $subject = 'Re: '.$subject;
471 email_send($addr, $subject, $headers, $it);
475 case NETWORK_DIASPORA:
477 $loc = 'public batch '.$contact['batch'];
479 $loc = $contact['name'];
481 logger('delivery: diaspora batch deliver: '.$loc);
483 if (Config::get('system','dfrn_only') || !Config::get('system','diaspora_enabled'))
487 Diaspora::send_mail($item,$owner,$contact);
494 if (!$contact['pubkey'] && !$public_message)
497 if (($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
498 // top-level retraction
499 logger('diaspora retract: '.$loc);
500 Diaspora::send_retraction($target_item,$owner,$contact,$public_message);
502 } elseif ($relocate) {
503 Diaspora::sendAccountMigration($owner, $contact, $uid);
505 } elseif ($followup) {
506 // send comments and likes to owner to relay
507 logger('diaspora followup: '.$loc);
508 Diaspora::send_followup($target_item,$owner,$contact,$public_message);
510 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
511 // we are the relay - send comments, likes and relayable_retractions to our conversants
512 logger('diaspora relay: '.$loc);
513 Diaspora::send_relay($target_item,$owner,$contact,$public_message);
515 } elseif ($top_level && !$walltowall) {
516 // currently no workable solution for sending walltowall
517 logger('diaspora status: '.$loc);
518 Diaspora::send_status($target_item,$owner,$contact,$public_message);
522 logger('delivery: diaspora unknown mode: '.$contact['name']);