4 use Friendica\Core\System;
5 use Friendica\Core\Config;
6 use Friendica\Database\DBM;
7 use Friendica\Protocol\Diaspora;
8 use Friendica\Protocol\DFRN;
10 require_once 'include/queue_fn.php';
11 require_once 'include/html2plain.php';
12 require_once 'include/ostatus.php';
14 function delivery_run(&$argv, &$argc){
17 require_once 'include/datetime.php';
18 require_once 'include/items.php';
19 require_once 'include/bbcode.php';
20 require_once 'include/email.php';
26 logger('delivery: invoked: '. print_r($argv,true), LOGGER_DEBUG);
29 $item_id = intval($argv[2]);
31 for ($x = 3; $x < $argc; $x ++) {
33 $contact_id = intval($argv[$x]);
35 if (!$item_id || !$contact_id) {
44 $recipients = array();
45 $url_recipients = array();
50 $recipients[] = $contact_id;
52 if ($cmd === 'mail') {
55 $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1",
58 if (!count($message)) {
61 $uid = $message[0]['uid'];
62 $recipients[] = $message[0]['contact-id'];
64 } elseif ($cmd === 'expire') {
67 $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1
68 AND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 30 MINUTE",
76 } elseif ($cmd === 'suggest') {
80 $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1",
83 if (!count($suggest)) {
86 $uid = $suggest[0]['uid'];
87 $recipients[] = $suggest[0]['cid'];
89 } elseif ($cmd === 'relocate') {
95 $r = q("SELECT * FROM `item` WHERE `id` = %d AND visible = 1 AND moderated = 0 LIMIT 1",
99 if ((!DBM::is_result($r)) || (!intval($r[0]['parent']))) {
103 $target_item = $r[0];
104 $parent_id = intval($r[0]['parent']);
106 $updated = $r[0]['edited'];
108 $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
109 FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d AND visible = 1 AND moderated = 0 ORDER BY `id` ASC",
113 if (!count($items)) {
118 $contacts_arr = array();
119 foreach ($items as $item) {
120 if (!in_array($item['contact-id'],$contacts_arr)) {
121 $contacts_arr[] = intval($item['contact-id']);
124 if (count($contacts_arr)) {
125 $str_contacts = implode(',',$contacts_arr);
126 $icontacts = q("SELECT * FROM `contact`
127 WHERE `id` IN ( $str_contacts ) "
130 if ( !($icontacts && count($icontacts))) {
134 // avoid race condition with deleting entries
136 if ($items[0]['deleted']) {
137 foreach ($items as $item) {
138 $item['deleted'] = 1;
142 // When commenting too fast after delivery, a post wasn't recognized as top level post.
143 // The count then showed more than one entry. The additional check should help.
144 // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
145 if ((($items[0]['id'] == $item_id) || (count($items) == 1)) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
146 logger('delivery: top level post');
151 $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`,
152 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
153 `user`.`page-flags`, `user`.`account-type`, `user`.`prvnets`
154 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
155 WHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
159 if (!DBM::is_result($r)) {
165 $walltowall = ((($top_level) && ($owner['id'] != $items[0]['contact-id'])) ? true : false);
167 $public_message = true;
169 if (!($mail || $fsuggest || $relocate)) {
170 require_once 'include/group.php';
174 // This is IMPORTANT!!!!
176 // We will only send a "notify owner to relay" or followup message if the referenced post
177 // originated on our system by virtue of having our hostname somewhere
178 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
179 // if $parent['wall'] == 1 we will already have the parent message in our array
180 // and we will relay the whole lot.
182 // expire sends an entire group of expire messages and cannot be forwarded.
183 // However the conversation owner will be a part of the conversation and will
184 // be notified during this run.
185 // Other DFRN conversation members will be alerted during polled updates.
187 // Diaspora members currently are not notified of expirations, and other networks have
188 // either limited or no ability to process deletions. We should at least fix Diaspora
189 // by stringing togther an array of retractions and sending them onward.
192 $localhost = $a->get_hostname();
193 if (strpos($localhost,':')) {
194 $localhost = substr($localhost,0,strpos($localhost,':'));
198 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
199 * have been known to cause runaway conditions which affected several servers, along with
200 * permissions issues.
204 $relay_to_owner = false;
206 if (!$top_level && ($parent['wall'] == 0) && !$expire && stristr($target_item['uri'],$localhost)) {
207 $relay_to_owner = true;
210 if ($relay_to_owner) {
211 logger('followup '.$target_item["guid"], LOGGER_DEBUG);
212 // local followup to remote post
216 if ((strlen($parent['allow_cid']))
217 || (strlen($parent['allow_gid']))
218 || (strlen($parent['deny_cid']))
219 || (strlen($parent['deny_gid']))
220 || $parent["private"]) {
221 $public_message = false; // private recipients, not public
226 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `blocked` = 0 AND `pending` = 0",
230 if (DBM::is_result($r)) {
233 if ($contact['self']) {
238 logger("main delivery by delivery: followup=$followup mail=$mail fsuggest=$fsuggest relocate=$relocate - network ".$contact['network']);
240 switch($contact['network']) {
243 logger('notifier: '.$target_item["guid"].' dfrndelivery: '.$contact['name']);
246 $item['body'] = fix_private_photos($item['body'],$owner['uid'],null,$message[0]['contact-id']);
247 $atom = DFRN::mail($item, $owner);
248 } elseif ($fsuggest) {
249 $atom = DFRN::fsuggest($item, $owner);
250 q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1", intval($item['id']));
251 } elseif ($relocate) {
252 $atom = DFRN::relocate($owner, $uid);
253 } elseif ($followup) {
255 foreach ($items as $item) { // there is only one item
256 if (!$item['parent']) {
259 if ($item['id'] == $item_id) {
260 logger('followup: item: '. print_r($item,true), LOGGER_DATA);
264 $atom = DFRN::entries($msgitems,$owner);
267 foreach ($items as $item) {
268 if (!$item['parent']) {
272 // private emails may be in included in public conversations. Filter them.
273 if ($public_message && $item['private']) {
277 $item_contact = get_item_contact($item,$icontacts);
278 if (!$item_contact) {
283 if ($item_id == $item['id'] || $item['id'] == $item['parent']) {
284 $item["entry:comment-allow"] = true;
285 $item["entry:cid"] = (($top_level) ? $contact['id'] : 0);
289 $item["entry:comment-allow"] = true;
293 $atom = DFRN::entries($msgitems,$owner);
296 logger('notifier entry: '.$contact["url"].' '.$target_item["guid"].' entry: '.$atom, LOGGER_DEBUG);
298 logger('notifier: '.$atom, LOGGER_DATA);
299 $basepath = implode('/', array_slice(explode('/',$contact['url']),0,3));
301 // perform local delivery if we are on the same site
303 if (link_compare($basepath,System::baseUrl())) {
305 $nickname = basename($contact['url']);
306 if ($contact['issued-id']) {
307 $sql_extra = sprintf(" AND `dfrn-id` = '%s' ", dbesc($contact['issued-id']));
309 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($contact['dfrn-id']));
312 $x = q("SELECT `contact`.*, `contact`.`uid` AS `importer_uid`,
313 `contact`.`pubkey` AS `cpubkey`,
314 `contact`.`prvkey` AS `cprvkey`,
315 `contact`.`thumb` AS `thumb`,
316 `contact`.`url` as `url`,
317 `contact`.`name` as `senderName`,
320 INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`
321 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
322 AND `contact`.`network` = '%s' AND `user`.`nickname` = '%s'
324 AND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 LIMIT 1",
329 if ($x && count($x)) {
330 $write_flag = ((($x[0]['rel']) && ($x[0]['rel'] != CONTACT_IS_SHARING)) ? true : false);
331 if ((($owner['page-flags'] == PAGE_COMMUNITY) || $write_flag) && !$x[0]['writable']) {
332 q("UPDATE `contact` SET `writable` = 1 WHERE `id` = %d",
335 $x[0]['writable'] = 1;
338 $ssl_policy = Config::get('system','ssl_policy');
339 fix_contact_ssl_policy($x[0],$ssl_policy);
341 // If we are setup as a soapbox we aren't accepting top level posts from this person
343 if (($x[0]['page-flags'] == PAGE_SOAPBOX) && $top_level) {
346 logger('mod-delivery: local delivery');
347 DFRN::import($atom, $x[0]);
352 if (!was_recently_delayed($contact['id'])) {
353 $deliver_status = DFRN::deliver($owner,$contact,$atom);
355 $deliver_status = (-1);
358 logger('notifier: dfrn_delivery to '.$contact["url"].' with guid '.$target_item["guid"].' returns '.$deliver_status);
360 if ($deliver_status < 0) {
361 logger('notifier: delivery failed: queuing message');
362 add_to_queue($contact['id'],NETWORK_DFRN,$atom);
364 // The message could not be delivered. We mark the contact as "dead"
365 mark_for_death($contact);
367 // We successfully delivered a message, the contact is alive
368 unmark_for_death($contact);
373 case NETWORK_OSTATUS:
374 // Do not send to otatus if we are not configured to send to public networks
375 if ($owner['prvnets']) {
378 if (Config::get('system','ostatus_disabled') || Config::get('system','dfrn_only')) {
382 // There is currently no code here to distribute anything to OStatus.
383 // This is done in "notifier.php" (See "url_recipients" and "push_notify")
389 if (Config::get('system','dfrn_only')) {
392 // WARNING: does not currently convert to RFC2047 header encodings, etc.
394 $addr = $contact['addr'];
395 if (!strlen($addr)) {
399 if ($cmd === 'wall-new' || $cmd === 'comment-new') {
402 if ($cmd === 'wall-new') {
405 $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
409 if (DBM::is_result($r))
416 $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
419 if (!count($local_user))
423 $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
426 if ($r1 && $r1[0]['reply_to'])
427 $reply_to = $r1[0]['reply_to'];
429 $subject = (($it['title']) ? email_header_encode($it['title'],'UTF-8') : t("\x28no subject\x29")) ;
431 // only expose our real email address to true friends
433 if (($contact['rel'] == CONTACT_IS_FRIEND) && !$contact['blocked']) {
435 $headers = 'From: '.email_header_encode($local_user[0]['username'],'UTF-8').' <'.$reply_to.'>'."\n";
436 $headers .= 'Sender: '.$local_user[0]['email']."\n";
438 $headers = 'From: '.email_header_encode($local_user[0]['username'],'UTF-8').' <'.$local_user[0]['email'].'>'."\n";
441 $headers = 'From: '. email_header_encode($local_user[0]['username'],'UTF-8') .' <'. t('noreply') .'@'.$a->get_hostname() .'>'. "\n";
445 // $headers .= 'Reply-to: '.$reply_to . "\n";
447 $headers .= 'Message-Id: <'. iri2msgid($it['uri']).'>'. "\n";
449 //logger("Mail: uri: ".$it['uri']." parent-uri ".$it['parent-uri'], LOGGER_DEBUG);
450 //logger("Mail: Data: ".print_r($it, true), LOGGER_DEBUG);
451 //logger("Mail: Data: ".print_r($it, true), LOGGER_DATA);
453 if ($it['uri'] !== $it['parent-uri']) {
454 $headers .= "References: <".iri2msgid($it["parent-uri"]).">";
456 // If Threading is enabled, write down the correct parent
457 if (($it["thr-parent"] != "") && ($it["thr-parent"] != $it["parent-uri"]))
458 $headers .= " <".iri2msgid($it["thr-parent"]).">";
462 $r = q("SELECT `title` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
463 dbesc($it['parent-uri']),
466 if (DBM::is_result($r) && ($r[0]['title'] != '')) {
467 $subject = $r[0]['title'];
469 $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d LIMIT 1",
470 dbesc($it['parent-uri']),
473 if (DBM::is_result($r) && ($r[0]['title'] != ''))
474 $subject = $r[0]['title'];
477 if (strncasecmp($subject,'RE:',3))
478 $subject = 'Re: '.$subject;
480 email_send($addr, $subject, $headers, $it);
484 case NETWORK_DIASPORA:
486 $loc = 'public batch '.$contact['batch'];
488 $loc = $contact['name'];
490 logger('delivery: diaspora batch deliver: '.$loc);
492 if (Config::get('system','dfrn_only') || (!Config::get('system','diaspora_enabled')))
496 Diaspora::send_mail($item,$owner,$contact);
503 if (!$contact['pubkey'] && !$public_message)
506 if (($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
507 // top-level retraction
508 logger('diaspora retract: '.$loc);
509 Diaspora::send_retraction($target_item,$owner,$contact,$public_message);
511 } elseif ($relocate) {
512 Diaspora::sendAccountMigration($owner, $contact, $uid);
514 } elseif ($followup) {
515 // send comments and likes to owner to relay
516 logger('diaspora followup: '.$loc);
517 Diaspora::send_followup($target_item,$owner,$contact,$public_message);
519 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
520 // we are the relay - send comments, likes and relayable_retractions to our conversants
521 logger('diaspora relay: '.$loc);
522 Diaspora::send_relay($target_item,$owner,$contact,$public_message);
524 } elseif ($top_level && !$walltowall) {
525 // currently no workable solution for sending walltowall
526 logger('diaspora status: '.$loc);
527 Diaspora::send_status($target_item,$owner,$contact,$public_message);
531 logger('delivery: diaspora unknown mode: '.$contact['name']);