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\Model\Contact;
13 use Friendica\Model\User;
14 use Friendica\Protocol\Diaspora;
15 use Friendica\Protocol\DFRN;
16 use Friendica\Protocol\Email;
19 require_once 'include/queue_fn.php';
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);
38 $recipients = array();
39 $url_recipients = array();
44 $recipients[] = $contact_id;
46 if ($cmd === 'mail') {
49 $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1",
52 if (!count($message)) {
55 $uid = $message[0]['uid'];
56 $recipients[] = $message[0]['contact-id'];
58 } elseif ($cmd === 'expire') {
61 $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1
62 AND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 30 MINUTE",
70 } elseif ($cmd === 'suggest') {
74 $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1",
77 if (!count($suggest)) {
80 $uid = $suggest[0]['uid'];
81 $recipients[] = $suggest[0]['cid'];
83 } elseif ($cmd === 'relocate') {
89 $target_item = dba::fetch_first("SELECT `item`.*, `contact`.`uid` AS `cuid` FROM `item`
90 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
91 WHERE `item`.`id` = ? AND `visible` AND NOT `moderated`", $item_id);
93 if (!DBM::is_result($target_item) || !intval($target_item['parent'])) {
97 $parent_id = intval($target_item['parent']);
98 $uid = $target_item['cuid'];
99 $updated = $target_item['edited'];
101 $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
102 FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d AND visible = 1 AND moderated = 0 ORDER BY `id` ASC",
106 if (!count($items)) {
111 $contacts_arr = array();
112 foreach ($items as $item) {
113 if (!in_array($item['contact-id'],$contacts_arr)) {
114 $contacts_arr[] = intval($item['contact-id']);
117 if (count($contacts_arr)) {
118 $str_contacts = implode(',',$contacts_arr);
119 $icontacts = q("SELECT * FROM `contact`
120 WHERE `id` IN ( $str_contacts ) "
123 if ( !($icontacts && count($icontacts))) {
127 // avoid race condition with deleting entries
129 if ($items[0]['deleted']) {
130 foreach ($items as $item) {
131 $item['deleted'] = 1;
135 // When commenting too fast after delivery, a post wasn't recognized as top level post.
136 // The count then showed more than one entry. The additional check should help.
137 // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
138 if ((($items[0]['id'] == $item_id) || (count($items) == 1)) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
139 logger('delivery: top level post');
144 $owner = User::getOwnerDataById($uid);
149 $walltowall = (($top_level && ($owner['id'] != $items[0]['contact-id'])) ? true : false);
151 $public_message = true;
153 if (!$mail && !$fsuggest && !$relocate) {
156 // This is IMPORTANT!!!!
158 // We will only send a "notify owner to relay" or followup message if the referenced post
159 // originated on our system by virtue of having our hostname somewhere
160 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
161 // if $parent['wall'] == 1 we will already have the parent message in our array
162 // and we will relay the whole lot.
164 // expire sends an entire group of expire messages and cannot be forwarded.
165 // However the conversation owner will be a part of the conversation and will
166 // be notified during this run.
167 // Other DFRN conversation members will be alerted during polled updates.
169 // Diaspora members currently are not notified of expirations, and other networks have
170 // either limited or no ability to process deletions. We should at least fix Diaspora
171 // by stringing togther an array of retractions and sending them onward.
174 $localhost = $a->get_hostname();
175 if (strpos($localhost,':')) {
176 $localhost = substr($localhost,0,strpos($localhost,':'));
180 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
181 * have been known to cause runaway conditions which affected several servers, along with
182 * permissions issues.
186 $relay_to_owner = false;
188 if (!$top_level && ($parent['wall'] == 0) && !$expire && stristr($target_item['uri'],$localhost)) {
189 $relay_to_owner = true;
192 if ($relay_to_owner) {
193 logger('followup '.$target_item["guid"], LOGGER_DEBUG);
194 // local followup to remote post
198 if (strlen($parent['allow_cid'])
199 || strlen($parent['allow_gid'])
200 || strlen($parent['deny_cid'])
201 || strlen($parent['deny_gid'])
202 || $parent["private"]) {
203 $public_message = false; // private recipients, not public
208 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `blocked` = 0 AND `pending` = 0",
212 if (DBM::is_result($r)) {
215 if ($contact['self']) {
220 // Transmit via Diaspora if not possible via Friendica
221 if (($item['uid'] == 0) && ($contact['network'] == NETWORK_DFRN)) {
222 $contact['network'] = NETWORK_DIASPORA;
225 logger("main delivery by delivery: followup=$followup mail=$mail fsuggest=$fsuggest relocate=$relocate - network ".$contact['network']);
227 switch ($contact['network']) {
230 logger('notifier: '.$target_item["guid"].' dfrndelivery: '.$contact['name']);
233 $item['body'] = fix_private_photos($item['body'],$owner['uid'],null,$message[0]['contact-id']);
234 $atom = DFRN::mail($item, $owner);
235 } elseif ($fsuggest) {
236 $atom = DFRN::fsuggest($item, $owner);
237 q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1", intval($item['id']));
238 } elseif ($relocate) {
239 $atom = DFRN::relocate($owner, $uid);
240 } elseif ($followup) {
242 foreach ($items as $item) { // there is only one item
243 if (!$item['parent']) {
246 if ($item['id'] == $item_id) {
247 logger('followup: item: '. print_r($item,true), LOGGER_DATA);
251 $atom = DFRN::entries($msgitems,$owner);
254 foreach ($items as $item) {
255 if (!$item['parent']) {
259 // private emails may be in included in public conversations. Filter them.
260 if ($public_message && $item['private']) {
264 $item_contact = get_item_contact($item,$icontacts);
265 if (!$item_contact) {
270 if ($item_id == $item['id'] || $item['id'] == $item['parent']) {
271 $item["entry:comment-allow"] = true;
272 $item["entry:cid"] = (($top_level) ? $contact['id'] : 0);
276 $item["entry:comment-allow"] = true;
280 $atom = DFRN::entries($msgitems,$owner);
283 logger('notifier entry: '.$contact["url"].' '.$target_item["guid"].' entry: '.$atom, LOGGER_DEBUG);
285 logger('notifier: '.$atom, LOGGER_DATA);
286 $basepath = implode('/', array_slice(explode('/',$contact['url']),0,3));
288 // perform local delivery if we are on the same site
290 if (link_compare($basepath,System::baseUrl())) {
291 $nickname = basename($contact['url']);
292 if ($contact['issued-id']) {
293 $sql_extra = sprintf(" AND `dfrn-id` = '%s' ", dbesc($contact['issued-id']));
295 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($contact['dfrn-id']));
298 $x = q("SELECT `contact`.*, `contact`.`uid` AS `importer_uid`,
299 `contact`.`pubkey` AS `cpubkey`,
300 `contact`.`prvkey` AS `cprvkey`,
301 `contact`.`thumb` AS `thumb`,
302 `contact`.`url` as `url`,
303 `contact`.`name` as `senderName`,
306 INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`
307 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
308 AND `contact`.`network` = '%s' AND `user`.`nickname` = '%s'
310 AND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 LIMIT 1",
315 if ($x && count($x)) {
316 $write_flag = ((($x[0]['rel']) && ($x[0]['rel'] != CONTACT_IS_SHARING)) ? true : false);
317 if ((($owner['page-flags'] == PAGE_COMMUNITY) || $write_flag) && !$x[0]['writable']) {
318 q("UPDATE `contact` SET `writable` = 1 WHERE `id` = %d",
321 $x[0]['writable'] = 1;
324 $ssl_policy = Config::get('system','ssl_policy');
325 fix_contact_ssl_policy($x[0],$ssl_policy);
327 // If we are setup as a soapbox we aren't accepting top level posts from this person
329 if (($x[0]['page-flags'] == PAGE_SOAPBOX) && $top_level) {
332 logger('mod-delivery: local delivery');
333 DFRN::import($atom, $x[0]);
338 if (!was_recently_delayed($contact['id'])) {
339 $deliver_status = DFRN::deliver($owner,$contact,$atom);
341 $deliver_status = (-1);
344 logger('notifier: dfrn_delivery to '.$contact["url"].' with guid '.$target_item["guid"].' returns '.$deliver_status);
346 if ($deliver_status < 0) {
347 logger('notifier: delivery failed: queuing message');
348 add_to_queue($contact['id'],NETWORK_DFRN,$atom);
350 // The message could not be delivered. We mark the contact as "dead"
351 Contact::markForArchival($contact);
353 // We successfully delivered a message, the contact is alive
354 Contact::unmarkForArchival($contact);
359 case NETWORK_OSTATUS:
360 // Do not send to otatus if we are not configured to send to public networks
361 if ($owner['prvnets']) {
364 if (Config::get('system','ostatus_disabled') || Config::get('system','dfrn_only')) {
368 // There is currently no code here to distribute anything to OStatus.
369 // This is done in "notifier.php" (See "url_recipients" and "push_notify")
374 if (Config::get('system','dfrn_only')) {
377 // WARNING: does not currently convert to RFC2047 header encodings, etc.
379 $addr = $contact['addr'];
380 if (!strlen($addr)) {
384 if ($cmd === 'wall-new' || $cmd === 'comment-new') {
386 if ($cmd === 'wall-new') {
389 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
392 if (DBM::is_result($r)) {
400 $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
403 if (!count($local_user)) {
408 $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
411 if ($r1 && $r1[0]['reply_to']) {
412 $reply_to = $r1[0]['reply_to'];
415 $subject = (($it['title']) ? Email::encodeHeader($it['title'],'UTF-8') : t("\x28no subject\x29")) ;
417 // only expose our real email address to true friends
419 if (($contact['rel'] == CONTACT_IS_FRIEND) && !$contact['blocked']) {
421 $headers = 'From: '.Email::encodeHeader($local_user[0]['username'],'UTF-8').' <'.$reply_to.'>'."\n";
422 $headers .= 'Sender: '.$local_user[0]['email']."\n";
424 $headers = 'From: '.Email::encodeHeader($local_user[0]['username'],'UTF-8').' <'.$local_user[0]['email'].'>'."\n";
427 $headers = 'From: '. Email::encodeHeader($local_user[0]['username'],'UTF-8') .' <'. t('noreply') .'@'.$a->get_hostname() .'>'. "\n";
431 // $headers .= 'Reply-to: '.$reply_to . "\n";
433 $headers .= 'Message-Id: <'. Email::iri2msgid($it['uri']).'>'. "\n";
435 //logger("Mail: uri: ".$it['uri']." parent-uri ".$it['parent-uri'], LOGGER_DEBUG);
436 //logger("Mail: Data: ".print_r($it, true), LOGGER_DEBUG);
437 //logger("Mail: Data: ".print_r($it, true), LOGGER_DATA);
439 if ($it['uri'] !== $it['parent-uri']) {
440 $headers .= "References: <".Email::iri2msgid($it["parent-uri"]).">";
442 // If Threading is enabled, write down the correct parent
443 if (($it["thr-parent"] != "") && ($it["thr-parent"] != $it["parent-uri"])) {
444 $headers .= " <".Email::iri2msgid($it["thr-parent"]).">";
449 $r = q("SELECT `title` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
450 dbesc($it['parent-uri']),
453 if (DBM::is_result($r) && ($r[0]['title'] != '')) {
454 $subject = $r[0]['title'];
456 $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d LIMIT 1",
457 dbesc($it['parent-uri']),
460 if (DBM::is_result($r) && ($r[0]['title'] != '')) {
461 $subject = $r[0]['title'];
465 if (strncasecmp($subject,'RE:',3)) {
466 $subject = 'Re: '.$subject;
469 Email::send($addr, $subject, $headers, $it);
473 case NETWORK_DIASPORA:
474 if ($public_message) {
475 $loc = 'public batch '.$contact['batch'];
477 $loc = $contact['name'];
480 logger('delivery: diaspora batch deliver: '.$loc);
482 if (Config::get('system','dfrn_only') || !Config::get('system','diaspora_enabled')) {
486 Diaspora::sendMail($item,$owner,$contact);
493 if (!$contact['pubkey'] && !$public_message) {
496 if (($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
497 // top-level retraction
498 logger('diaspora retract: '.$loc);
499 Diaspora::sendRetraction($target_item,$owner,$contact,$public_message);
501 } elseif ($relocate) {
502 Diaspora::sendAccountMigration($owner, $contact, $uid);
504 } elseif ($followup) {
505 // send comments and likes to owner to relay
506 logger('diaspora followup: '.$loc);
507 Diaspora::sendFollowup($target_item,$owner,$contact,$public_message);
509 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
510 // we are the relay - send comments, likes and relayable_retractions to our conversants
511 logger('diaspora relay: '.$loc);
512 Diaspora::sendRelay($target_item,$owner,$contact,$public_message);
514 } elseif ($top_level && !$walltowall) {
515 // currently no workable solution for sending walltowall
516 logger('diaspora status: '.$loc);
517 Diaspora::sendStatus($target_item,$owner,$contact,$public_message);
521 logger('delivery: diaspora unknown mode: '.$contact['name']);