3 use \Friendica\Core\Config;
5 require_once('include/queue_fn.php');
6 require_once('include/html2plain.php');
7 require_once('include/Scrape.php');
8 require_once('include/diaspora.php');
9 require_once('include/ostatus.php');
10 require_once('include/dfrn.php');
12 function delivery_run(&$argv, &$argc){
15 require_once('include/datetime.php');
16 require_once('include/items.php');
17 require_once('include/bbcode.php');
18 require_once('include/email.php');
24 logger('delivery: invoked: '. print_r($argv,true), LOGGER_DEBUG);
27 $item_id = intval($argv[2]);
29 for ($x = 3; $x < $argc; $x ++) {
31 $contact_id = intval($argv[$x]);
33 if (!$item_id || !$contact_id) {
42 $recipients = array();
43 $url_recipients = array();
48 $recipients[] = $contact_id;
50 if ($cmd === 'mail') {
53 $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1",
56 if (!count($message)) {
59 $uid = $message[0]['uid'];
60 $recipients[] = $message[0]['contact-id'];
62 } elseif ($cmd === 'expire') {
65 $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1
66 AND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 30 MINUTE",
74 } elseif ($cmd === 'suggest') {
78 $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1",
81 if (!count($suggest)) {
84 $uid = $suggest[0]['uid'];
85 $recipients[] = $suggest[0]['cid'];
87 } elseif ($cmd === 'relocate') {
93 $r = q("SELECT * FROM `item` WHERE `id` = %d and visible = 1 and moderated = 0 LIMIT 1",
97 if ((!dbm::is_result($r)) || (!intval($r[0]['parent']))) {
101 $target_item = $r[0];
102 $parent_id = intval($r[0]['parent']);
104 $updated = $r[0]['edited'];
106 $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
107 FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d and visible = 1 and moderated = 0 ORDER BY `id` ASC",
111 if (!count($items)) {
116 $contacts_arr = array();
117 foreach ($items as $item) {
118 if (!in_array($item['contact-id'],$contacts_arr)) {
119 $contacts_arr[] = intval($item['contact-id']);
122 if (count($contacts_arr)) {
123 $str_contacts = implode(',',$contacts_arr);
124 $icontacts = q("SELECT * FROM `contact`
125 WHERE `id` IN ( $str_contacts ) "
128 if ( !($icontacts && count($icontacts))) {
132 // avoid race condition with deleting entries
134 if ($items[0]['deleted']) {
135 foreach ($items as $item) {
136 $item['deleted'] = 1;
140 // When commenting too fast after delivery, a post wasn't recognized as top level post.
141 // The count then showed more than one entry. The additional check should help.
142 // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
143 if ((($items[0]['id'] == $item_id) || (count($items) == 1)) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
144 logger('delivery: top level post');
149 $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`,
150 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
151 `user`.`page-flags`, `user`.`account-type`, `user`.`prvnets`
152 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
153 WHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
157 if (!dbm::is_result($r)) {
163 $walltowall = ((($top_level) && ($owner['id'] != $items[0]['contact-id'])) ? true : false);
165 $public_message = true;
167 if (!($mail || $fsuggest || $relocate)) {
168 require_once('include/group.php');
172 // This is IMPORTANT!!!!
174 // We will only send a "notify owner to relay" or followup message if the referenced post
175 // originated on our system by virtue of having our hostname somewhere
176 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
177 // if $parent['wall'] == 1 we will already have the parent message in our array
178 // and we will relay the whole lot.
180 // expire sends an entire group of expire messages and cannot be forwarded.
181 // However the conversation owner will be a part of the conversation and will
182 // be notified during this run.
183 // Other DFRN conversation members will be alerted during polled updates.
185 // Diaspora members currently are not notified of expirations, and other networks have
186 // either limited or no ability to process deletions. We should at least fix Diaspora
187 // by stringing togther an array of retractions and sending them onward.
190 $localhost = $a->get_hostname();
191 if (strpos($localhost,':')) {
192 $localhost = substr($localhost,0,strpos($localhost,':'));
196 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
197 * have been known to cause runaway conditions which affected several servers, along with
198 * permissions issues.
202 $relay_to_owner = false;
204 if (!$top_level && ($parent['wall'] == 0) && !$expire && stristr($target_item['uri'],$localhost)) {
205 $relay_to_owner = true;
208 if ($relay_to_owner) {
209 logger('followup '.$target_item["guid"], LOGGER_DEBUG);
210 // local followup to remote post
214 if ((strlen($parent['allow_cid']))
215 || (strlen($parent['allow_gid']))
216 || (strlen($parent['deny_cid']))
217 || (strlen($parent['deny_gid']))
218 || $parent["private"]) {
219 $public_message = false; // private recipients, not public
224 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `blocked` = 0 AND `pending` = 0",
228 if (dbm::is_result($r)) {
231 if ($contact['self']) {
236 logger("main delivery by delivery: followup=$followup mail=$mail fsuggest=$fsuggest relocate=$relocate - network ".$contact['network']);
238 switch($contact['network']) {
241 logger('notifier: '.$target_item["guid"].' dfrndelivery: '.$contact['name']);
244 $item['body'] = fix_private_photos($item['body'],$owner['uid'],null,$message[0]['contact-id']);
245 $atom = dfrn::mail($item, $owner);
246 } elseif ($fsuggest) {
247 $atom = dfrn::fsuggest($item, $owner);
248 q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1", intval($item['id']));
249 } elseif ($relocate) {
250 $atom = dfrn::relocate($owner, $uid);
251 } elseif ($followup) {
253 foreach ($items as $item) { // there is only one item
254 if (!$item['parent']) {
257 if ($item['id'] == $item_id) {
258 logger('followup: item: '. print_r($item,true), LOGGER_DATA);
262 $atom = dfrn::entries($msgitems,$owner);
265 foreach ($items as $item) {
266 if (!$item['parent']) {
270 // private emails may be in included in public conversations. Filter them.
271 if ($public_message && $item['private']) {
275 $item_contact = get_item_contact($item,$icontacts);
276 if (!$item_contact) {
281 if ($item_id == $item['id'] || $item['id'] == $item['parent']) {
282 $item["entry:comment-allow"] = true;
283 $item["entry:cid"] = (($top_level) ? $contact['id'] : 0);
287 $item["entry:comment-allow"] = true;
291 $atom = dfrn::entries($msgitems,$owner);
294 logger('notifier entry: '.$contact["url"].' '.$target_item["guid"].' entry: '.$atom, LOGGER_DEBUG);
296 logger('notifier: '.$atom, LOGGER_DATA);
297 $basepath = implode('/', array_slice(explode('/',$contact['url']),0,3));
299 // perform local delivery if we are on the same site
301 if (link_compare($basepath,App::get_baseurl())) {
303 $nickname = basename($contact['url']);
304 if ($contact['issued-id']) {
305 $sql_extra = sprintf(" AND `dfrn-id` = '%s' ", dbesc($contact['issued-id']));
307 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($contact['dfrn-id']));
310 $x = q("SELECT `contact`.*, `contact`.`uid` AS `importer_uid`,
311 `contact`.`pubkey` AS `cpubkey`,
312 `contact`.`prvkey` AS `cprvkey`,
313 `contact`.`thumb` AS `thumb`,
314 `contact`.`url` as `url`,
315 `contact`.`name` as `senderName`,
318 INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`
319 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
320 AND `contact`.`network` = '%s' AND `user`.`nickname` = '%s'
322 AND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 LIMIT 1",
327 if ($x && count($x)) {
328 $write_flag = ((($x[0]['rel']) && ($x[0]['rel'] != CONTACT_IS_SHARING)) ? true : false);
329 if ((($owner['page-flags'] == PAGE_COMMUNITY) || $write_flag) && !$x[0]['writable']) {
330 q("UPDATE `contact` SET `writable` = 1 WHERE `id` = %d",
333 $x[0]['writable'] = 1;
336 $ssl_policy = get_config('system','ssl_policy');
337 fix_contact_ssl_policy($x[0],$ssl_policy);
339 // If we are setup as a soapbox we aren't accepting top level posts from this person
341 if (($x[0]['page-flags'] == PAGE_SOAPBOX) AND $top_level) {
344 logger('mod-delivery: local delivery');
345 dfrn::import($atom, $x[0]);
350 if (!was_recently_delayed($contact['id'])) {
351 $deliver_status = dfrn::deliver($owner,$contact,$atom);
353 $deliver_status = (-1);
356 logger('notifier: dfrn_delivery to '.$contact["url"].' with guid '.$target_item["guid"].' returns '.$deliver_status);
358 if ($deliver_status < 0) {
359 logger('notifier: delivery failed: queuing message');
360 add_to_queue($contact['id'],NETWORK_DFRN,$atom);
362 // The message could not be delivered. We mark the contact as "dead"
363 mark_for_death($contact);
365 // We successfully delivered a message, the contact is alive
366 unmark_for_death($contact);
371 case NETWORK_OSTATUS:
372 // Do not send to otatus if we are not configured to send to public networks
373 if ($owner['prvnets']) {
376 if (get_config('system','ostatus_disabled') || get_config('system','dfrn_only')) {
380 // There is currently no code here to distribute anything to OStatus.
381 // This is done in "notifier.php" (See "url_recipients" and "push_notify")
387 if (get_config('system','dfrn_only')) {
390 // WARNING: does not currently convert to RFC2047 header encodings, etc.
392 $addr = $contact['addr'];
393 if (!strlen($addr)) {
397 if ($cmd === 'wall-new' || $cmd === 'comment-new') {
400 if ($cmd === 'wall-new') {
403 $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
407 if (dbm::is_result($r))
414 $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
417 if (!count($local_user))
421 $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
424 if ($r1 && $r1[0]['reply_to'])
425 $reply_to = $r1[0]['reply_to'];
427 $subject = (($it['title']) ? email_header_encode($it['title'],'UTF-8') : t("\x28no subject\x29")) ;
429 // only expose our real email address to true friends
431 if (($contact['rel'] == CONTACT_IS_FRIEND) && !$contact['blocked']) {
433 $headers = 'From: '.email_header_encode($local_user[0]['username'],'UTF-8').' <'.$reply_to.'>'."\n";
434 $headers .= 'Sender: '.$local_user[0]['email']."\n";
436 $headers = 'From: '.email_header_encode($local_user[0]['username'],'UTF-8').' <'.$local_user[0]['email'].'>'."\n";
439 $headers = 'From: '. email_header_encode($local_user[0]['username'],'UTF-8') .' <'. t('noreply') .'@'.$a->get_hostname() .'>'. "\n";
443 // $headers .= 'Reply-to: '.$reply_to . "\n";
445 $headers .= 'Message-Id: <'. iri2msgid($it['uri']).'>'. "\n";
447 //logger("Mail: uri: ".$it['uri']." parent-uri ".$it['parent-uri'], LOGGER_DEBUG);
448 //logger("Mail: Data: ".print_r($it, true), LOGGER_DEBUG);
449 //logger("Mail: Data: ".print_r($it, true), LOGGER_DATA);
451 if ($it['uri'] !== $it['parent-uri']) {
452 $headers .= "References: <".iri2msgid($it["parent-uri"]).">";
454 // If Threading is enabled, write down the correct parent
455 if (($it["thr-parent"] != "") and ($it["thr-parent"] != $it["parent-uri"]))
456 $headers .= " <".iri2msgid($it["thr-parent"]).">";
460 $r = q("SELECT `title` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
461 dbesc($it['parent-uri']),
464 if (dbm::is_result($r) AND ($r[0]['title'] != '')) {
465 $subject = $r[0]['title'];
467 $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d LIMIT 1",
468 dbesc($it['parent-uri']),
471 if (dbm::is_result($r) AND ($r[0]['title'] != ''))
472 $subject = $r[0]['title'];
475 if (strncasecmp($subject,'RE:',3))
476 $subject = 'Re: '.$subject;
478 email_send($addr, $subject, $headers, $it);
482 case NETWORK_DIASPORA:
484 $loc = 'public batch '.$contact['batch'];
486 $loc = $contact['name'];
488 logger('delivery: diaspora batch deliver: '.$loc);
490 if (get_config('system','dfrn_only') || (!get_config('system','diaspora_enabled')))
494 Diaspora::send_mail($item,$owner,$contact);
501 if (!$contact['pubkey'] && !$public_message)
504 if (($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
505 // top-level retraction
506 logger('diaspora retract: '.$loc);
507 Diaspora::send_retraction($target_item,$owner,$contact,$public_message);
509 } elseif ($followup) {
510 // send comments and likes to owner to relay
511 logger('diaspora followup: '.$loc);
512 Diaspora::send_followup($target_item,$owner,$contact,$public_message);
514 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
515 // we are the relay - send comments, likes and relayable_retractions to our conversants
516 logger('diaspora relay: '.$loc);
517 Diaspora::send_relay($target_item,$owner,$contact,$public_message);
519 } elseif ($top_level && !$walltowall) {
520 // currently no workable solution for sending walltowall
521 logger('diaspora status: '.$loc);
522 Diaspora::send_status($target_item,$owner,$contact,$public_message);
526 logger('delivery: diaspora unknown mode: '.$contact['name']);