4 use Friendica\Core\Config;
6 require_once 'include/queue_fn.php';
7 require_once 'include/html2plain.php';
8 require_once 'include/probe.php';
9 require_once 'include/diaspora.php';
10 require_once 'include/ostatus.php';
11 require_once 'include/dfrn.php';
13 function delivery_run(&$argv, &$argc){
16 require_once 'include/datetime.php';
17 require_once 'include/items.php';
18 require_once 'include/bbcode.php';
19 require_once 'include/email.php';
25 logger('delivery: invoked: '. print_r($argv,true), LOGGER_DEBUG);
28 $item_id = intval($argv[2]);
30 for ($x = 3; $x < $argc; $x ++) {
32 $contact_id = intval($argv[$x]);
34 if (!$item_id || !$contact_id) {
43 $recipients = array();
44 $url_recipients = array();
49 $recipients[] = $contact_id;
51 if ($cmd === 'mail') {
54 $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1",
57 if (!count($message)) {
60 $uid = $message[0]['uid'];
61 $recipients[] = $message[0]['contact-id'];
63 } elseif ($cmd === 'expire') {
66 $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1
67 AND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 30 MINUTE",
75 } elseif ($cmd === 'suggest') {
79 $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1",
82 if (!count($suggest)) {
85 $uid = $suggest[0]['uid'];
86 $recipients[] = $suggest[0]['cid'];
88 } elseif ($cmd === 'relocate') {
94 $r = q("SELECT * FROM `item` WHERE `id` = %d AND visible = 1 AND moderated = 0 LIMIT 1",
98 if ((!dbm::is_result($r)) || (!intval($r[0]['parent']))) {
102 $target_item = $r[0];
103 $parent_id = intval($r[0]['parent']);
105 $updated = $r[0]['edited'];
107 $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
108 FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d AND visible = 1 AND moderated = 0 ORDER BY `id` ASC",
112 if (!count($items)) {
117 $contacts_arr = array();
118 foreach ($items as $item) {
119 if (!in_array($item['contact-id'],$contacts_arr)) {
120 $contacts_arr[] = intval($item['contact-id']);
123 if (count($contacts_arr)) {
124 $str_contacts = implode(',',$contacts_arr);
125 $icontacts = q("SELECT * FROM `contact`
126 WHERE `id` IN ( $str_contacts ) "
129 if ( !($icontacts && count($icontacts))) {
133 // avoid race condition with deleting entries
135 if ($items[0]['deleted']) {
136 foreach ($items as $item) {
137 $item['deleted'] = 1;
141 // When commenting too fast after delivery, a post wasn't recognized as top level post.
142 // The count then showed more than one entry. The additional check should help.
143 // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
144 if ((($items[0]['id'] == $item_id) || (count($items) == 1)) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
145 logger('delivery: top level post');
150 $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`,
151 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
152 `user`.`page-flags`, `user`.`account-type`, `user`.`prvnets`
153 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
154 WHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
158 if (!dbm::is_result($r)) {
164 $walltowall = ((($top_level) && ($owner['id'] != $items[0]['contact-id'])) ? true : false);
166 $public_message = true;
168 if (!($mail || $fsuggest || $relocate)) {
169 require_once 'include/group.php';
173 // This is IMPORTANT!!!!
175 // We will only send a "notify owner to relay" or followup message if the referenced post
176 // originated on our system by virtue of having our hostname somewhere
177 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
178 // if $parent['wall'] == 1 we will already have the parent message in our array
179 // and we will relay the whole lot.
181 // expire sends an entire group of expire messages and cannot be forwarded.
182 // However the conversation owner will be a part of the conversation and will
183 // be notified during this run.
184 // Other DFRN conversation members will be alerted during polled updates.
186 // Diaspora members currently are not notified of expirations, and other networks have
187 // either limited or no ability to process deletions. We should at least fix Diaspora
188 // by stringing togther an array of retractions and sending them onward.
191 $localhost = $a->get_hostname();
192 if (strpos($localhost,':')) {
193 $localhost = substr($localhost,0,strpos($localhost,':'));
197 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
198 * have been known to cause runaway conditions which affected several servers, along with
199 * permissions issues.
203 $relay_to_owner = false;
205 if (!$top_level && ($parent['wall'] == 0) && !$expire && stristr($target_item['uri'],$localhost)) {
206 $relay_to_owner = true;
209 if ($relay_to_owner) {
210 logger('followup '.$target_item["guid"], LOGGER_DEBUG);
211 // local followup to remote post
215 if ((strlen($parent['allow_cid']))
216 || (strlen($parent['allow_gid']))
217 || (strlen($parent['deny_cid']))
218 || (strlen($parent['deny_gid']))
219 || $parent["private"]) {
220 $public_message = false; // private recipients, not public
225 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `blocked` = 0 AND `pending` = 0",
229 if (dbm::is_result($r)) {
232 if ($contact['self']) {
237 logger("main delivery by delivery: followup=$followup mail=$mail fsuggest=$fsuggest relocate=$relocate - network ".$contact['network']);
239 switch($contact['network']) {
242 logger('notifier: '.$target_item["guid"].' dfrndelivery: '.$contact['name']);
245 $item['body'] = fix_private_photos($item['body'],$owner['uid'],null,$message[0]['contact-id']);
246 $atom = dfrn::mail($item, $owner);
247 } elseif ($fsuggest) {
248 $atom = dfrn::fsuggest($item, $owner);
249 q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1", intval($item['id']));
250 } elseif ($relocate) {
251 $atom = dfrn::relocate($owner, $uid);
252 } elseif ($followup) {
254 foreach ($items as $item) { // there is only one item
255 if (!$item['parent']) {
258 if ($item['id'] == $item_id) {
259 logger('followup: item: '. print_r($item,true), LOGGER_DATA);
263 $atom = dfrn::entries($msgitems,$owner);
266 foreach ($items as $item) {
267 if (!$item['parent']) {
271 // private emails may be in included in public conversations. Filter them.
272 if ($public_message && $item['private']) {
276 $item_contact = get_item_contact($item,$icontacts);
277 if (!$item_contact) {
282 if ($item_id == $item['id'] || $item['id'] == $item['parent']) {
283 $item["entry:comment-allow"] = true;
284 $item["entry:cid"] = (($top_level) ? $contact['id'] : 0);
288 $item["entry:comment-allow"] = true;
292 $atom = dfrn::entries($msgitems,$owner);
295 logger('notifier entry: '.$contact["url"].' '.$target_item["guid"].' entry: '.$atom, LOGGER_DEBUG);
297 logger('notifier: '.$atom, LOGGER_DATA);
298 $basepath = implode('/', array_slice(explode('/',$contact['url']),0,3));
300 // perform local delivery if we are on the same site
302 if (link_compare($basepath,App::get_baseurl())) {
304 $nickname = basename($contact['url']);
305 if ($contact['issued-id']) {
306 $sql_extra = sprintf(" AND `dfrn-id` = '%s' ", dbesc($contact['issued-id']));
308 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($contact['dfrn-id']));
311 $x = q("SELECT `contact`.*, `contact`.`uid` AS `importer_uid`,
312 `contact`.`pubkey` AS `cpubkey`,
313 `contact`.`prvkey` AS `cprvkey`,
314 `contact`.`thumb` AS `thumb`,
315 `contact`.`url` as `url`,
316 `contact`.`name` as `senderName`,
319 INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`
320 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
321 AND `contact`.`network` = '%s' AND `user`.`nickname` = '%s'
323 AND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 LIMIT 1",
328 if ($x && count($x)) {
329 $write_flag = ((($x[0]['rel']) && ($x[0]['rel'] != CONTACT_IS_SHARING)) ? true : false);
330 if ((($owner['page-flags'] == PAGE_COMMUNITY) || $write_flag) && !$x[0]['writable']) {
331 q("UPDATE `contact` SET `writable` = 1 WHERE `id` = %d",
334 $x[0]['writable'] = 1;
337 $ssl_policy = get_config('system','ssl_policy');
338 fix_contact_ssl_policy($x[0],$ssl_policy);
340 // If we are setup as a soapbox we aren't accepting top level posts from this person
342 if (($x[0]['page-flags'] == PAGE_SOAPBOX) && $top_level) {
345 logger('mod-delivery: local delivery');
346 dfrn::import($atom, $x[0]);
351 if (!was_recently_delayed($contact['id'])) {
352 $deliver_status = dfrn::deliver($owner,$contact,$atom);
354 $deliver_status = (-1);
357 logger('notifier: dfrn_delivery to '.$contact["url"].' with guid '.$target_item["guid"].' returns '.$deliver_status);
359 if ($deliver_status < 0) {
360 logger('notifier: delivery failed: queuing message');
361 add_to_queue($contact['id'],NETWORK_DFRN,$atom);
363 // The message could not be delivered. We mark the contact as "dead"
364 mark_for_death($contact);
366 // We successfully delivered a message, the contact is alive
367 unmark_for_death($contact);
372 case NETWORK_OSTATUS:
373 // Do not send to otatus if we are not configured to send to public networks
374 if ($owner['prvnets']) {
377 if (get_config('system','ostatus_disabled') || get_config('system','dfrn_only')) {
381 // There is currently no code here to distribute anything to OStatus.
382 // This is done in "notifier.php" (See "url_recipients" and "push_notify")
388 if (get_config('system','dfrn_only')) {
391 // WARNING: does not currently convert to RFC2047 header encodings, etc.
393 $addr = $contact['addr'];
394 if (!strlen($addr)) {
398 if ($cmd === 'wall-new' || $cmd === 'comment-new') {
401 if ($cmd === 'wall-new') {
404 $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
408 if (dbm::is_result($r))
415 $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
418 if (!count($local_user))
422 $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
425 if ($r1 && $r1[0]['reply_to'])
426 $reply_to = $r1[0]['reply_to'];
428 $subject = (($it['title']) ? email_header_encode($it['title'],'UTF-8') : t("\x28no subject\x29")) ;
430 // only expose our real email address to true friends
432 if (($contact['rel'] == CONTACT_IS_FRIEND) && !$contact['blocked']) {
434 $headers = 'From: '.email_header_encode($local_user[0]['username'],'UTF-8').' <'.$reply_to.'>'."\n";
435 $headers .= 'Sender: '.$local_user[0]['email']."\n";
437 $headers = 'From: '.email_header_encode($local_user[0]['username'],'UTF-8').' <'.$local_user[0]['email'].'>'."\n";
440 $headers = 'From: '. email_header_encode($local_user[0]['username'],'UTF-8') .' <'. t('noreply') .'@'.$a->get_hostname() .'>'. "\n";
444 // $headers .= 'Reply-to: '.$reply_to . "\n";
446 $headers .= 'Message-Id: <'. iri2msgid($it['uri']).'>'. "\n";
448 //logger("Mail: uri: ".$it['uri']." parent-uri ".$it['parent-uri'], LOGGER_DEBUG);
449 //logger("Mail: Data: ".print_r($it, true), LOGGER_DEBUG);
450 //logger("Mail: Data: ".print_r($it, true), LOGGER_DATA);
452 if ($it['uri'] !== $it['parent-uri']) {
453 $headers .= "References: <".iri2msgid($it["parent-uri"]).">";
455 // If Threading is enabled, write down the correct parent
456 if (($it["thr-parent"] != "") && ($it["thr-parent"] != $it["parent-uri"]))
457 $headers .= " <".iri2msgid($it["thr-parent"]).">";
461 $r = q("SELECT `title` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
462 dbesc($it['parent-uri']),
465 if (dbm::is_result($r) && ($r[0]['title'] != '')) {
466 $subject = $r[0]['title'];
468 $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d LIMIT 1",
469 dbesc($it['parent-uri']),
472 if (dbm::is_result($r) && ($r[0]['title'] != ''))
473 $subject = $r[0]['title'];
476 if (strncasecmp($subject,'RE:',3))
477 $subject = 'Re: '.$subject;
479 email_send($addr, $subject, $headers, $it);
483 case NETWORK_DIASPORA:
485 $loc = 'public batch '.$contact['batch'];
487 $loc = $contact['name'];
489 logger('delivery: diaspora batch deliver: '.$loc);
491 if (get_config('system','dfrn_only') || (!get_config('system','diaspora_enabled')))
495 Diaspora::send_mail($item,$owner,$contact);
502 if (!$contact['pubkey'] && !$public_message)
505 if (($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
506 // top-level retraction
507 logger('diaspora retract: '.$loc);
508 Diaspora::send_retraction($target_item,$owner,$contact,$public_message);
510 } elseif ($followup) {
511 // send comments and likes to owner to relay
512 logger('diaspora followup: '.$loc);
513 Diaspora::send_followup($target_item,$owner,$contact,$public_message);
515 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
516 // we are the relay - send comments, likes and relayable_retractions to our conversants
517 logger('diaspora relay: '.$loc);
518 Diaspora::send_relay($target_item,$owner,$contact,$public_message);
520 } elseif ($top_level && !$walltowall) {
521 // currently no workable solution for sending walltowall
522 logger('diaspora status: '.$loc);
523 Diaspora::send_status($target_item,$owner,$contact,$public_message);
527 logger('delivery: diaspora unknown mode: '.$contact['name']);