2 require_once("boot.php");
3 require_once('include/queue_fn.php');
4 require_once('include/html2plain.php');
5 require_once("include/Scrape.php");
6 require_once('include/diaspora.php');
7 require_once("include/ostatus.php");
8 require_once("include/dfrn.php");
10 function delivery_run(&$argv, &$argc){
18 @include(".htconfig.php");
19 require_once("include/dba.php");
20 $db = new dba($db_host, $db_user, $db_pass, $db_data);
21 unset($db_host, $db_user, $db_pass, $db_data);
24 require_once("include/session.php");
25 require_once("include/datetime.php");
26 require_once('include/items.php');
27 require_once('include/bbcode.php');
28 require_once('include/email.php');
30 load_config('config');
31 load_config('system');
38 $a->set_baseurl(get_config('system','url'));
40 logger('delivery: invoked: '. print_r($argv,true), LOGGER_DEBUG);
43 $item_id = intval($argv[2]);
45 for($x = 3; $x < $argc; $x ++) {
47 $contact_id = intval($argv[$x]);
49 /// @todo When switching completely to the worker we won't need this anymore
50 // Some other process may have delivered this item already.
52 $r = q("SELECT * FROM `deliverq` WHERE `cmd` = '%s' AND `item` = %d AND `contact` = %d LIMIT 1",
57 if (!dbm::is_result($r)) {
61 if ($a->maxload_reached())
64 // It's ours to deliver. Remove it from the queue.
66 q("DELETE FROM `deliverq` WHERE `cmd` = '%s' AND `item` = %d AND `contact` = %d",
72 if (!$item_id || !$contact_id)
80 $recipients = array();
81 $url_recipients = array();
86 $recipients[] = $contact_id;
88 if ($cmd === 'mail') {
91 $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1",
94 if (!count($message)){
97 $uid = $message[0]['uid'];
98 $recipients[] = $message[0]['contact-id'];
101 elseif ($cmd === 'expire') {
102 $normal_mode = false;
104 $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1
105 AND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 30 MINUTE",
113 elseif ($cmd === 'suggest') {
114 $normal_mode = false;
117 $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1",
120 if (!count($suggest))
122 $uid = $suggest[0]['uid'];
123 $recipients[] = $suggest[0]['cid'];
125 } elseif ($cmd === 'relocate') {
126 $normal_mode = false;
131 $r = q("SELECT * FROM `item` WHERE `id` = %d and visible = 1 and moderated = 0 LIMIT 1",
135 if ((!dbm::is_result($r)) || (!intval($r[0]['parent']))) {
139 $target_item = $r[0];
140 $parent_id = intval($r[0]['parent']);
142 $updated = $r[0]['edited'];
144 $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
145 FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d and visible = 1 and moderated = 0 ORDER BY `id` ASC",
149 if (!count($items)) {
154 $contacts_arr = array();
155 foreach($items as $item)
156 if (!in_array($item['contact-id'],$contacts_arr))
157 $contacts_arr[] = intval($item['contact-id']);
158 if (count($contacts_arr)) {
159 $str_contacts = implode(',',$contacts_arr);
160 $icontacts = q("SELECT * FROM `contact`
161 WHERE `id` IN ( $str_contacts ) "
164 if ( !($icontacts && count($icontacts)))
167 // avoid race condition with deleting entries
169 if ($items[0]['deleted']) {
170 foreach($items as $item)
171 $item['deleted'] = 1;
174 // When commenting too fast after delivery, a post wasn't recognized as top level post.
175 // The count then showed more than one entry. The additional check should help.
176 // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
177 if ((($items[0]['id'] = $item_id) OR (count($items) == 1)) AND ($items[0]['uri'] === $items[0]['parent-uri'])) {
178 logger('delivery: top level post');
183 $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`,
184 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
185 `user`.`page-flags`, `user`.`account-type`, `user`.`prvnets`
186 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
187 WHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
191 if (!dbm::is_result($r))
196 $walltowall = ((($top_level) && ($owner['id'] != $items[0]['contact-id'])) ? true : false);
198 $public_message = true;
200 if (!($mail || $fsuggest || $relocate)) {
201 require_once('include/group.php');
205 // This is IMPORTANT!!!!
207 // We will only send a "notify owner to relay" or followup message if the referenced post
208 // originated on our system by virtue of having our hostname somewhere
209 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
210 // if $parent['wall'] == 1 we will already have the parent message in our array
211 // and we will relay the whole lot.
213 // expire sends an entire group of expire messages and cannot be forwarded.
214 // However the conversation owner will be a part of the conversation and will
215 // be notified during this run.
216 // Other DFRN conversation members will be alerted during polled updates.
218 // Diaspora members currently are not notified of expirations, and other networks have
219 // either limited or no ability to process deletions. We should at least fix Diaspora
220 // by stringing togther an array of retractions and sending them onward.
223 $localhost = $a->get_hostname();
224 if (strpos($localhost,':'))
225 $localhost = substr($localhost,0,strpos($localhost,':'));
229 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
230 * have been known to cause runaway conditions which affected several servers, along with
231 * permissions issues.
235 $relay_to_owner = false;
237 if (!$top_level && ($parent['wall'] == 0) && !$expire && stristr($target_item['uri'],$localhost)) {
238 $relay_to_owner = true;
241 if ($relay_to_owner) {
242 logger('followup '.$target_item["guid"], LOGGER_DEBUG);
243 // local followup to remote post
247 if ((strlen($parent['allow_cid']))
248 || (strlen($parent['allow_gid']))
249 || (strlen($parent['deny_cid']))
250 || (strlen($parent['deny_gid']))
251 || $parent["private"]) {
252 $public_message = false; // private recipients, not public
257 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `blocked` = 0 AND `pending` = 0",
261 if (dbm::is_result($r))
264 if ($contact['self'])
269 logger("main delivery by delivery: followup=$followup mail=$mail fsuggest=$fsuggest relocate=$relocate - network ".$contact['network']);
271 switch($contact['network']) {
274 logger('notifier: '.$target_item["guid"].' dfrndelivery: '.$contact['name']);
277 $item['body'] = fix_private_photos($item['body'],$owner['uid'],null,$message[0]['contact-id']);
278 $atom = dfrn::mail($item, $owner);
279 } elseif ($fsuggest) {
280 $atom = dfrn::fsuggest($item, $owner);
281 q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1", intval($item['id']));
283 $atom = dfrn::relocate($owner, $uid);
286 foreach($items as $item) { // there is only one item
287 if (!$item['parent'])
289 if ($item['id'] == $item_id) {
290 logger('followup: item: '. print_r($item,true), LOGGER_DATA);
294 $atom = dfrn::entries($msgitems,$owner);
297 foreach($items as $item) {
298 if (!$item['parent'])
301 // private emails may be in included in public conversations. Filter them.
302 if ($public_message && $item['private'])
305 $item_contact = get_item_contact($item,$icontacts);
310 if ($item_id == $item['id'] || $item['id'] == $item['parent']) {
311 $item["entry:comment-allow"] = true;
312 $item["entry:cid"] = (($top_level) ? $contact['id'] : 0);
316 $item["entry:comment-allow"] = true;
320 $atom = dfrn::entries($msgitems,$owner);
323 logger('notifier entry: '.$contact["url"].' '.$target_item["guid"].' entry: '.$atom, LOGGER_DEBUG);
325 logger('notifier: '.$atom, LOGGER_DATA);
326 $basepath = implode('/', array_slice(explode('/',$contact['url']),0,3));
328 // perform local delivery if we are on the same site
330 if (link_compare($basepath,App::get_baseurl())) {
332 $nickname = basename($contact['url']);
333 if ($contact['issued-id'])
334 $sql_extra = sprintf(" AND `dfrn-id` = '%s' ", dbesc($contact['issued-id']));
336 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($contact['dfrn-id']));
338 $x = q("SELECT `contact`.*, `contact`.`uid` AS `importer_uid`,
339 `contact`.`pubkey` AS `cpubkey`,
340 `contact`.`prvkey` AS `cprvkey`,
341 `contact`.`thumb` AS `thumb`,
342 `contact`.`url` as `url`,
343 `contact`.`name` as `senderName`,
346 INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`
347 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
348 AND `contact`.`network` = '%s' AND `user`.`nickname` = '%s'
350 AND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 LIMIT 1",
355 if ($x && count($x)) {
356 $write_flag = ((($x[0]['rel']) && ($x[0]['rel'] != CONTACT_IS_SHARING)) ? true : false);
357 if ((($owner['page-flags'] == PAGE_COMMUNITY) || $write_flag) && !$x[0]['writable']) {
358 q("UPDATE `contact` SET `writable` = 1 WHERE `id` = %d",
361 $x[0]['writable'] = 1;
364 $ssl_policy = get_config('system','ssl_policy');
365 fix_contact_ssl_policy($x[0],$ssl_policy);
367 // If we are setup as a soapbox we aren't accepting top level posts from this person
369 if (($x[0]['page-flags'] == PAGE_SOAPBOX) AND $top_level)
372 logger('mod-delivery: local delivery');
373 dfrn::import($atom, $x[0]);
378 if (!was_recently_delayed($contact['id']))
379 $deliver_status = dfrn::deliver($owner,$contact,$atom);
381 $deliver_status = (-1);
383 logger('notifier: dfrn_delivery to '.$contact["url"].' with guid '.$target_item["guid"].' returns '.$deliver_status);
385 if ($deliver_status == (-1)) {
386 logger('notifier: delivery failed: queuing message');
387 add_to_queue($contact['id'],NETWORK_DFRN,$atom);
389 // The message could not be delivered. We mark the contact as "dead"
390 mark_for_death($contact);
392 // We successfully delivered a message, the contact is alive
393 unmark_for_death($contact);
398 case NETWORK_OSTATUS:
399 // Do not send to otatus if we are not configured to send to public networks
400 if ($owner['prvnets'])
402 if (get_config('system','ostatus_disabled') || get_config('system','dfrn_only'))
405 // There is currently no code here to distribute anything to OStatus.
406 // This is done in "notifier.php" (See "url_recipients" and "push_notify")
412 if (get_config('system','dfrn_only'))
414 // WARNING: does not currently convert to RFC2047 header encodings, etc.
416 $addr = $contact['addr'];
420 if ($cmd === 'wall-new' || $cmd === 'comment-new') {
423 if ($cmd === 'wall-new')
426 $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
430 if (dbm::is_result($r))
437 $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
440 if (!count($local_user))
444 $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
447 if ($r1 && $r1[0]['reply_to'])
448 $reply_to = $r1[0]['reply_to'];
450 $subject = (($it['title']) ? email_header_encode($it['title'],'UTF-8') : t("\x28no subject\x29")) ;
452 // only expose our real email address to true friends
454 if (($contact['rel'] == CONTACT_IS_FRIEND) && !$contact['blocked']) {
456 $headers = 'From: '.email_header_encode($local_user[0]['username'],'UTF-8').' <'.$reply_to.'>'."\n";
457 $headers .= 'Sender: '.$local_user[0]['email']."\n";
459 $headers = 'From: '.email_header_encode($local_user[0]['username'],'UTF-8').' <'.$local_user[0]['email'].'>'."\n";
461 $headers = 'From: '. email_header_encode($local_user[0]['username'],'UTF-8') .' <'. t('noreply') .'@'.$a->get_hostname() .'>'. "\n";
464 // $headers .= 'Reply-to: '.$reply_to . "\n";
466 $headers .= 'Message-Id: <'. iri2msgid($it['uri']).'>'. "\n";
468 //logger("Mail: uri: ".$it['uri']." parent-uri ".$it['parent-uri'], LOGGER_DEBUG);
469 //logger("Mail: Data: ".print_r($it, true), LOGGER_DEBUG);
470 //logger("Mail: Data: ".print_r($it, true), LOGGER_DATA);
472 if ($it['uri'] !== $it['parent-uri']) {
473 $headers .= "References: <".iri2msgid($it["parent-uri"]).">";
475 // If Threading is enabled, write down the correct parent
476 if (($it["thr-parent"] != "") and ($it["thr-parent"] != $it["parent-uri"]))
477 $headers .= " <".iri2msgid($it["thr-parent"]).">";
481 $r = q("SELECT `title` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
482 dbesc($it['parent-uri']),
485 if (dbm::is_result($r) AND ($r[0]['title'] != ''))
486 $subject = $r[0]['title'];
488 $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d LIMIT 1",
489 dbesc($it['parent-uri']),
492 if (dbm::is_result($r) AND ($r[0]['title'] != ''))
493 $subject = $r[0]['title'];
496 if (strncasecmp($subject,'RE:',3))
497 $subject = 'Re: '.$subject;
499 email_send($addr, $subject, $headers, $it);
503 case NETWORK_DIASPORA:
505 $loc = 'public batch '.$contact['batch'];
507 $loc = $contact['name'];
509 logger('delivery: diaspora batch deliver: '.$loc);
511 if (get_config('system','dfrn_only') || (!get_config('system','diaspora_enabled')))
515 Diaspora::send_mail($item,$owner,$contact);
522 if (!$contact['pubkey'] && !$public_message)
525 if (($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
526 // top-level retraction
527 logger('diaspora retract: '.$loc);
528 Diaspora::send_retraction($target_item,$owner,$contact,$public_message);
530 } elseif ($followup) {
531 // send comments and likes to owner to relay
532 logger('diaspora followup: '.$loc);
533 Diaspora::send_followup($target_item,$owner,$contact,$public_message);
535 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
536 // we are the relay - send comments, likes and relayable_retractions to our conversants
537 logger('diaspora relay: '.$loc);
538 Diaspora::send_relay($target_item,$owner,$contact,$public_message);
540 } elseif ($top_level && !$walltowall) {
541 // currently no workable solution for sending walltowall
542 logger('diaspora status: '.$loc);
543 Diaspora::send_status($target_item,$owner,$contact,$public_message);
547 logger('delivery: diaspora unknown mode: '.$contact['name']);
559 if (array_search(__file__,get_included_files())===0){
560 delivery_run($_SERVER["argv"],$_SERVER["argc"]);