3 * @file include/delivery.php
6 use Friendica\Core\System;
7 use Friendica\Core\Config;
8 use Friendica\Database\DBM;
9 use Friendica\Protocol\Diaspora;
10 use Friendica\Protocol\DFRN;
12 require_once 'include/queue_fn.php';
13 require_once 'include/html2plain.php';
15 function delivery_run(&$argv, &$argc){
18 require_once 'include/datetime.php';
19 require_once 'include/items.php';
20 require_once 'include/bbcode.php';
21 require_once 'include/email.php';
27 logger('delivery: invoked: '. print_r($argv,true), LOGGER_DEBUG);
30 $item_id = intval($argv[2]);
32 for ($x = 3; $x < $argc; $x ++) {
34 $contact_id = intval($argv[$x]);
36 if (!$item_id || !$contact_id) {
45 $recipients = array();
46 $url_recipients = array();
51 $recipients[] = $contact_id;
53 if ($cmd === 'mail') {
56 $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1",
59 if (!count($message)) {
62 $uid = $message[0]['uid'];
63 $recipients[] = $message[0]['contact-id'];
65 } elseif ($cmd === 'expire') {
68 $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1
69 AND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 30 MINUTE",
77 } elseif ($cmd === 'suggest') {
81 $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1",
84 if (!count($suggest)) {
87 $uid = $suggest[0]['uid'];
88 $recipients[] = $suggest[0]['cid'];
90 } elseif ($cmd === 'relocate') {
96 $r = q("SELECT * FROM `item` WHERE `id` = %d AND visible = 1 AND moderated = 0 LIMIT 1",
100 if ((!DBM::is_result($r)) || (!intval($r[0]['parent']))) {
104 $target_item = $r[0];
105 $parent_id = intval($r[0]['parent']);
107 $updated = $r[0]['edited'];
109 $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
110 FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d AND visible = 1 AND moderated = 0 ORDER BY `id` ASC",
114 if (!count($items)) {
119 $contacts_arr = array();
120 foreach ($items as $item) {
121 if (!in_array($item['contact-id'],$contacts_arr)) {
122 $contacts_arr[] = intval($item['contact-id']);
125 if (count($contacts_arr)) {
126 $str_contacts = implode(',',$contacts_arr);
127 $icontacts = q("SELECT * FROM `contact`
128 WHERE `id` IN ( $str_contacts ) "
131 if ( !($icontacts && count($icontacts))) {
135 // avoid race condition with deleting entries
137 if ($items[0]['deleted']) {
138 foreach ($items as $item) {
139 $item['deleted'] = 1;
143 // When commenting too fast after delivery, a post wasn't recognized as top level post.
144 // The count then showed more than one entry. The additional check should help.
145 // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
146 if ((($items[0]['id'] == $item_id) || (count($items) == 1)) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
147 logger('delivery: top level post');
152 $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`,
153 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
154 `user`.`page-flags`, `user`.`account-type`, `user`.`prvnets`
155 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
156 WHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
160 if (!DBM::is_result($r)) {
166 $walltowall = ((($top_level) && ($owner['id'] != $items[0]['contact-id'])) ? true : false);
168 $public_message = true;
170 if (!($mail || $fsuggest || $relocate)) {
171 require_once 'include/group.php';
175 // This is IMPORTANT!!!!
177 // We will only send a "notify owner to relay" or followup message if the referenced post
178 // originated on our system by virtue of having our hostname somewhere
179 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
180 // if $parent['wall'] == 1 we will already have the parent message in our array
181 // and we will relay the whole lot.
183 // expire sends an entire group of expire messages and cannot be forwarded.
184 // However the conversation owner will be a part of the conversation and will
185 // be notified during this run.
186 // Other DFRN conversation members will be alerted during polled updates.
188 // Diaspora members currently are not notified of expirations, and other networks have
189 // either limited or no ability to process deletions. We should at least fix Diaspora
190 // by stringing togther an array of retractions and sending them onward.
193 $localhost = $a->get_hostname();
194 if (strpos($localhost,':')) {
195 $localhost = substr($localhost,0,strpos($localhost,':'));
199 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
200 * have been known to cause runaway conditions which affected several servers, along with
201 * permissions issues.
205 $relay_to_owner = false;
207 if (!$top_level && ($parent['wall'] == 0) && !$expire && stristr($target_item['uri'],$localhost)) {
208 $relay_to_owner = true;
211 if ($relay_to_owner) {
212 logger('followup '.$target_item["guid"], LOGGER_DEBUG);
213 // local followup to remote post
217 if ((strlen($parent['allow_cid']))
218 || (strlen($parent['allow_gid']))
219 || (strlen($parent['deny_cid']))
220 || (strlen($parent['deny_gid']))
221 || $parent["private"]) {
222 $public_message = false; // private recipients, not public
227 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `blocked` = 0 AND `pending` = 0",
231 if (DBM::is_result($r)) {
234 if ($contact['self']) {
239 logger("main delivery by delivery: followup=$followup mail=$mail fsuggest=$fsuggest relocate=$relocate - network ".$contact['network']);
241 switch($contact['network']) {
244 logger('notifier: '.$target_item["guid"].' dfrndelivery: '.$contact['name']);
247 $item['body'] = fix_private_photos($item['body'],$owner['uid'],null,$message[0]['contact-id']);
248 $atom = DFRN::mail($item, $owner);
249 } elseif ($fsuggest) {
250 $atom = DFRN::fsuggest($item, $owner);
251 q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1", intval($item['id']));
252 } elseif ($relocate) {
253 $atom = DFRN::relocate($owner, $uid);
254 } elseif ($followup) {
256 foreach ($items as $item) { // there is only one item
257 if (!$item['parent']) {
260 if ($item['id'] == $item_id) {
261 logger('followup: item: '. print_r($item,true), LOGGER_DATA);
265 $atom = DFRN::entries($msgitems,$owner);
268 foreach ($items as $item) {
269 if (!$item['parent']) {
273 // private emails may be in included in public conversations. Filter them.
274 if ($public_message && $item['private']) {
278 $item_contact = get_item_contact($item,$icontacts);
279 if (!$item_contact) {
284 if ($item_id == $item['id'] || $item['id'] == $item['parent']) {
285 $item["entry:comment-allow"] = true;
286 $item["entry:cid"] = (($top_level) ? $contact['id'] : 0);
290 $item["entry:comment-allow"] = true;
294 $atom = DFRN::entries($msgitems,$owner);
297 logger('notifier entry: '.$contact["url"].' '.$target_item["guid"].' entry: '.$atom, LOGGER_DEBUG);
299 logger('notifier: '.$atom, LOGGER_DATA);
300 $basepath = implode('/', array_slice(explode('/',$contact['url']),0,3));
302 // perform local delivery if we are on the same site
304 if (link_compare($basepath,System::baseUrl())) {
306 $nickname = basename($contact['url']);
307 if ($contact['issued-id']) {
308 $sql_extra = sprintf(" AND `dfrn-id` = '%s' ", dbesc($contact['issued-id']));
310 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($contact['dfrn-id']));
313 $x = q("SELECT `contact`.*, `contact`.`uid` AS `importer_uid`,
314 `contact`.`pubkey` AS `cpubkey`,
315 `contact`.`prvkey` AS `cprvkey`,
316 `contact`.`thumb` AS `thumb`,
317 `contact`.`url` as `url`,
318 `contact`.`name` as `senderName`,
321 INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`
322 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
323 AND `contact`.`network` = '%s' AND `user`.`nickname` = '%s'
325 AND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 LIMIT 1",
330 if ($x && count($x)) {
331 $write_flag = ((($x[0]['rel']) && ($x[0]['rel'] != CONTACT_IS_SHARING)) ? true : false);
332 if ((($owner['page-flags'] == PAGE_COMMUNITY) || $write_flag) && !$x[0]['writable']) {
333 q("UPDATE `contact` SET `writable` = 1 WHERE `id` = %d",
336 $x[0]['writable'] = 1;
339 $ssl_policy = Config::get('system','ssl_policy');
340 fix_contact_ssl_policy($x[0],$ssl_policy);
342 // If we are setup as a soapbox we aren't accepting top level posts from this person
344 if (($x[0]['page-flags'] == PAGE_SOAPBOX) && $top_level) {
347 logger('mod-delivery: local delivery');
348 DFRN::import($atom, $x[0]);
353 if (!was_recently_delayed($contact['id'])) {
354 $deliver_status = DFRN::deliver($owner,$contact,$atom);
356 $deliver_status = (-1);
359 logger('notifier: dfrn_delivery to '.$contact["url"].' with guid '.$target_item["guid"].' returns '.$deliver_status);
361 if ($deliver_status < 0) {
362 logger('notifier: delivery failed: queuing message');
363 add_to_queue($contact['id'],NETWORK_DFRN,$atom);
365 // The message could not be delivered. We mark the contact as "dead"
366 mark_for_death($contact);
368 // We successfully delivered a message, the contact is alive
369 unmark_for_death($contact);
374 case NETWORK_OSTATUS:
375 // Do not send to otatus if we are not configured to send to public networks
376 if ($owner['prvnets']) {
379 if (Config::get('system','ostatus_disabled') || Config::get('system','dfrn_only')) {
383 // There is currently no code here to distribute anything to OStatus.
384 // This is done in "notifier.php" (See "url_recipients" and "push_notify")
390 if (Config::get('system','dfrn_only')) {
393 // WARNING: does not currently convert to RFC2047 header encodings, etc.
395 $addr = $contact['addr'];
396 if (!strlen($addr)) {
400 if ($cmd === 'wall-new' || $cmd === 'comment-new') {
403 if ($cmd === 'wall-new') {
406 $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
410 if (DBM::is_result($r))
417 $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
420 if (!count($local_user))
424 $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
427 if ($r1 && $r1[0]['reply_to'])
428 $reply_to = $r1[0]['reply_to'];
430 $subject = (($it['title']) ? email_header_encode($it['title'],'UTF-8') : t("\x28no subject\x29")) ;
432 // only expose our real email address to true friends
434 if (($contact['rel'] == CONTACT_IS_FRIEND) && !$contact['blocked']) {
436 $headers = 'From: '.email_header_encode($local_user[0]['username'],'UTF-8').' <'.$reply_to.'>'."\n";
437 $headers .= 'Sender: '.$local_user[0]['email']."\n";
439 $headers = 'From: '.email_header_encode($local_user[0]['username'],'UTF-8').' <'.$local_user[0]['email'].'>'."\n";
442 $headers = 'From: '. email_header_encode($local_user[0]['username'],'UTF-8') .' <'. t('noreply') .'@'.$a->get_hostname() .'>'. "\n";
446 // $headers .= 'Reply-to: '.$reply_to . "\n";
448 $headers .= 'Message-Id: <'. iri2msgid($it['uri']).'>'. "\n";
450 //logger("Mail: uri: ".$it['uri']." parent-uri ".$it['parent-uri'], LOGGER_DEBUG);
451 //logger("Mail: Data: ".print_r($it, true), LOGGER_DEBUG);
452 //logger("Mail: Data: ".print_r($it, true), LOGGER_DATA);
454 if ($it['uri'] !== $it['parent-uri']) {
455 $headers .= "References: <".iri2msgid($it["parent-uri"]).">";
457 // If Threading is enabled, write down the correct parent
458 if (($it["thr-parent"] != "") && ($it["thr-parent"] != $it["parent-uri"]))
459 $headers .= " <".iri2msgid($it["thr-parent"]).">";
463 $r = q("SELECT `title` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
464 dbesc($it['parent-uri']),
467 if (DBM::is_result($r) && ($r[0]['title'] != '')) {
468 $subject = $r[0]['title'];
470 $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d LIMIT 1",
471 dbesc($it['parent-uri']),
474 if (DBM::is_result($r) && ($r[0]['title'] != ''))
475 $subject = $r[0]['title'];
478 if (strncasecmp($subject,'RE:',3))
479 $subject = 'Re: '.$subject;
481 email_send($addr, $subject, $headers, $it);
485 case NETWORK_DIASPORA:
487 $loc = 'public batch '.$contact['batch'];
489 $loc = $contact['name'];
491 logger('delivery: diaspora batch deliver: '.$loc);
493 if (Config::get('system','dfrn_only') || (!Config::get('system','diaspora_enabled')))
497 Diaspora::send_mail($item,$owner,$contact);
504 if (!$contact['pubkey'] && !$public_message)
507 if (($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
508 // top-level retraction
509 logger('diaspora retract: '.$loc);
510 Diaspora::send_retraction($target_item,$owner,$contact,$public_message);
512 } elseif ($relocate) {
513 Diaspora::sendAccountMigration($owner, $contact, $uid);
515 } elseif ($followup) {
516 // send comments and likes to owner to relay
517 logger('diaspora followup: '.$loc);
518 Diaspora::send_followup($target_item,$owner,$contact,$public_message);
520 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
521 // we are the relay - send comments, likes and relayable_retractions to our conversants
522 logger('diaspora relay: '.$loc);
523 Diaspora::send_relay($target_item,$owner,$contact,$public_message);
525 } elseif ($top_level && !$walltowall) {
526 // currently no workable solution for sending walltowall
527 logger('diaspora status: '.$loc);
528 Diaspora::send_status($target_item,$owner,$contact,$public_message);
532 logger('delivery: diaspora unknown mode: '.$contact['name']);