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');
39 $a->set_baseurl(get_config('system','url'));
41 logger('delivery: invoked: '. print_r($argv,true), LOGGER_DEBUG);
44 $item_id = intval($argv[2]);
46 for ($x = 3; $x < $argc; $x ++) {
48 $contact_id = intval($argv[$x]);
50 /// @todo When switching completely to the worker we won't need this anymore
51 // Some other process may have delivered this item already.
53 $r = q("SELECT * FROM `deliverq` WHERE `cmd` = '%s' AND `item` = %d AND `contact` = %d LIMIT 1",
58 if (!dbm::is_result($r)) {
62 if ($a->maxload_reached()) {
66 // It's ours to deliver. Remove it from the queue.
68 q("DELETE FROM `deliverq` WHERE `cmd` = '%s' AND `item` = %d AND `contact` = %d",
74 if (!$item_id || !$contact_id) {
83 $recipients = array();
84 $url_recipients = array();
89 $recipients[] = $contact_id;
91 if ($cmd === 'mail') {
94 $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1",
97 if (!count($message)) {
100 $uid = $message[0]['uid'];
101 $recipients[] = $message[0]['contact-id'];
103 } elseif ($cmd === 'expire') {
104 $normal_mode = false;
106 $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1
107 AND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 30 MINUTE",
112 if (!count($items)) {
115 } elseif ($cmd === 'suggest') {
116 $normal_mode = false;
119 $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1",
122 if (!count($suggest)) {
125 $uid = $suggest[0]['uid'];
126 $recipients[] = $suggest[0]['cid'];
128 } elseif ($cmd === 'relocate') {
129 $normal_mode = false;
134 $r = q("SELECT * FROM `item` WHERE `id` = %d and visible = 1 and moderated = 0 LIMIT 1",
138 if ((!dbm::is_result($r)) || (!intval($r[0]['parent']))) {
142 $target_item = $r[0];
143 $parent_id = intval($r[0]['parent']);
145 $updated = $r[0]['edited'];
147 $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
148 FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d and visible = 1 and moderated = 0 ORDER BY `id` ASC",
152 if (!count($items)) {
157 $contacts_arr = array();
158 foreach ($items as $item) {
159 if (!in_array($item['contact-id'],$contacts_arr)) {
160 $contacts_arr[] = intval($item['contact-id']);
163 if (count($contacts_arr)) {
164 $str_contacts = implode(',',$contacts_arr);
165 $icontacts = q("SELECT * FROM `contact`
166 WHERE `id` IN ( $str_contacts ) "
169 if ( !($icontacts && count($icontacts))) {
173 // avoid race condition with deleting entries
175 if ($items[0]['deleted']) {
176 foreach ($items as $item) {
177 $item['deleted'] = 1;
181 // When commenting too fast after delivery, a post wasn't recognized as top level post.
182 // The count then showed more than one entry. The additional check should help.
183 // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
184 if ((($items[0]['id'] == $item_id) || (count($items) == 1)) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
185 logger('delivery: top level post');
190 $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`,
191 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
192 `user`.`page-flags`, `user`.`account-type`, `user`.`prvnets`
193 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
194 WHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
198 if (!dbm::is_result($r)) {
204 $walltowall = ((($top_level) && ($owner['id'] != $items[0]['contact-id'])) ? true : false);
206 $public_message = true;
208 if (!($mail || $fsuggest || $relocate)) {
209 require_once('include/group.php');
213 // This is IMPORTANT!!!!
215 // We will only send a "notify owner to relay" or followup message if the referenced post
216 // originated on our system by virtue of having our hostname somewhere
217 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
218 // if $parent['wall'] == 1 we will already have the parent message in our array
219 // and we will relay the whole lot.
221 // expire sends an entire group of expire messages and cannot be forwarded.
222 // However the conversation owner will be a part of the conversation and will
223 // be notified during this run.
224 // Other DFRN conversation members will be alerted during polled updates.
226 // Diaspora members currently are not notified of expirations, and other networks have
227 // either limited or no ability to process deletions. We should at least fix Diaspora
228 // by stringing togther an array of retractions and sending them onward.
231 $localhost = $a->get_hostname();
232 if (strpos($localhost,':')) {
233 $localhost = substr($localhost,0,strpos($localhost,':'));
237 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
238 * have been known to cause runaway conditions which affected several servers, along with
239 * permissions issues.
243 $relay_to_owner = false;
245 if (!$top_level && ($parent['wall'] == 0) && !$expire && stristr($target_item['uri'],$localhost)) {
246 $relay_to_owner = true;
249 if ($relay_to_owner) {
250 logger('followup '.$target_item["guid"], LOGGER_DEBUG);
251 // local followup to remote post
255 if ((strlen($parent['allow_cid']))
256 || (strlen($parent['allow_gid']))
257 || (strlen($parent['deny_cid']))
258 || (strlen($parent['deny_gid']))
259 || $parent["private"]) {
260 $public_message = false; // private recipients, not public
265 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `blocked` = 0 AND `pending` = 0",
269 if (dbm::is_result($r)) {
272 if ($contact['self']) {
277 logger("main delivery by delivery: followup=$followup mail=$mail fsuggest=$fsuggest relocate=$relocate - network ".$contact['network']);
279 switch($contact['network']) {
282 logger('notifier: '.$target_item["guid"].' dfrndelivery: '.$contact['name']);
285 $item['body'] = fix_private_photos($item['body'],$owner['uid'],null,$message[0]['contact-id']);
286 $atom = dfrn::mail($item, $owner);
287 } elseif ($fsuggest) {
288 $atom = dfrn::fsuggest($item, $owner);
289 q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1", intval($item['id']));
290 } elseif ($relocate) {
291 $atom = dfrn::relocate($owner, $uid);
292 } elseif ($followup) {
294 foreach ($items as $item) { // there is only one item
295 if (!$item['parent']) {
298 if ($item['id'] == $item_id) {
299 logger('followup: item: '. print_r($item,true), LOGGER_DATA);
303 $atom = dfrn::entries($msgitems,$owner);
306 foreach ($items as $item) {
307 if (!$item['parent']) {
311 // private emails may be in included in public conversations. Filter them.
312 if ($public_message && $item['private']) {
316 $item_contact = get_item_contact($item,$icontacts);
317 if (!$item_contact) {
322 if ($item_id == $item['id'] || $item['id'] == $item['parent']) {
323 $item["entry:comment-allow"] = true;
324 $item["entry:cid"] = (($top_level) ? $contact['id'] : 0);
328 $item["entry:comment-allow"] = true;
332 $atom = dfrn::entries($msgitems,$owner);
335 logger('notifier entry: '.$contact["url"].' '.$target_item["guid"].' entry: '.$atom, LOGGER_DEBUG);
337 logger('notifier: '.$atom, LOGGER_DATA);
338 $basepath = implode('/', array_slice(explode('/',$contact['url']),0,3));
340 // perform local delivery if we are on the same site
342 if (link_compare($basepath,App::get_baseurl())) {
344 $nickname = basename($contact['url']);
345 if ($contact['issued-id']) {
346 $sql_extra = sprintf(" AND `dfrn-id` = '%s' ", dbesc($contact['issued-id']));
348 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($contact['dfrn-id']));
351 $x = q("SELECT `contact`.*, `contact`.`uid` AS `importer_uid`,
352 `contact`.`pubkey` AS `cpubkey`,
353 `contact`.`prvkey` AS `cprvkey`,
354 `contact`.`thumb` AS `thumb`,
355 `contact`.`url` as `url`,
356 `contact`.`name` as `senderName`,
359 INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`
360 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
361 AND `contact`.`network` = '%s' AND `user`.`nickname` = '%s'
363 AND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 LIMIT 1",
368 if ($x && count($x)) {
369 $write_flag = ((($x[0]['rel']) && ($x[0]['rel'] != CONTACT_IS_SHARING)) ? true : false);
370 if ((($owner['page-flags'] == PAGE_COMMUNITY) || $write_flag) && !$x[0]['writable']) {
371 q("UPDATE `contact` SET `writable` = 1 WHERE `id` = %d",
374 $x[0]['writable'] = 1;
377 $ssl_policy = get_config('system','ssl_policy');
378 fix_contact_ssl_policy($x[0],$ssl_policy);
380 // If we are setup as a soapbox we aren't accepting top level posts from this person
382 if (($x[0]['page-flags'] == PAGE_SOAPBOX) AND $top_level) {
385 logger('mod-delivery: local delivery');
386 dfrn::import($atom, $x[0]);
391 if (!was_recently_delayed($contact['id'])) {
392 $deliver_status = dfrn::deliver($owner,$contact,$atom);
394 $deliver_status = (-1);
397 logger('notifier: dfrn_delivery to '.$contact["url"].' with guid '.$target_item["guid"].' returns '.$deliver_status);
399 if ($deliver_status == (-1)) {
400 logger('notifier: delivery failed: queuing message');
401 add_to_queue($contact['id'],NETWORK_DFRN,$atom);
403 // The message could not be delivered. We mark the contact as "dead"
404 mark_for_death($contact);
406 // We successfully delivered a message, the contact is alive
407 unmark_for_death($contact);
412 case NETWORK_OSTATUS:
413 // Do not send to otatus if we are not configured to send to public networks
414 if ($owner['prvnets']) {
417 if (get_config('system','ostatus_disabled') || get_config('system','dfrn_only')) {
421 // There is currently no code here to distribute anything to OStatus.
422 // This is done in "notifier.php" (See "url_recipients" and "push_notify")
428 if (get_config('system','dfrn_only')) {
431 // WARNING: does not currently convert to RFC2047 header encodings, etc.
433 $addr = $contact['addr'];
434 if (!strlen($addr)) {
438 if ($cmd === 'wall-new' || $cmd === 'comment-new') {
441 if ($cmd === 'wall-new') {
444 $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
448 if (dbm::is_result($r))
455 $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
458 if (!count($local_user))
462 $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
465 if ($r1 && $r1[0]['reply_to'])
466 $reply_to = $r1[0]['reply_to'];
468 $subject = (($it['title']) ? email_header_encode($it['title'],'UTF-8') : t("\x28no subject\x29")) ;
470 // only expose our real email address to true friends
472 if (($contact['rel'] == CONTACT_IS_FRIEND) && !$contact['blocked']) {
474 $headers = 'From: '.email_header_encode($local_user[0]['username'],'UTF-8').' <'.$reply_to.'>'."\n";
475 $headers .= 'Sender: '.$local_user[0]['email']."\n";
477 $headers = 'From: '.email_header_encode($local_user[0]['username'],'UTF-8').' <'.$local_user[0]['email'].'>'."\n";
480 $headers = 'From: '. email_header_encode($local_user[0]['username'],'UTF-8') .' <'. t('noreply') .'@'.$a->get_hostname() .'>'. "\n";
484 // $headers .= 'Reply-to: '.$reply_to . "\n";
486 $headers .= 'Message-Id: <'. iri2msgid($it['uri']).'>'. "\n";
488 //logger("Mail: uri: ".$it['uri']." parent-uri ".$it['parent-uri'], LOGGER_DEBUG);
489 //logger("Mail: Data: ".print_r($it, true), LOGGER_DEBUG);
490 //logger("Mail: Data: ".print_r($it, true), LOGGER_DATA);
492 if ($it['uri'] !== $it['parent-uri']) {
493 $headers .= "References: <".iri2msgid($it["parent-uri"]).">";
495 // If Threading is enabled, write down the correct parent
496 if (($it["thr-parent"] != "") and ($it["thr-parent"] != $it["parent-uri"]))
497 $headers .= " <".iri2msgid($it["thr-parent"]).">";
501 $r = q("SELECT `title` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
502 dbesc($it['parent-uri']),
505 if (dbm::is_result($r) AND ($r[0]['title'] != '')) {
506 $subject = $r[0]['title'];
508 $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d LIMIT 1",
509 dbesc($it['parent-uri']),
512 if (dbm::is_result($r) AND ($r[0]['title'] != ''))
513 $subject = $r[0]['title'];
516 if (strncasecmp($subject,'RE:',3))
517 $subject = 'Re: '.$subject;
519 email_send($addr, $subject, $headers, $it);
523 case NETWORK_DIASPORA:
525 $loc = 'public batch '.$contact['batch'];
527 $loc = $contact['name'];
529 logger('delivery: diaspora batch deliver: '.$loc);
531 if (get_config('system','dfrn_only') || (!get_config('system','diaspora_enabled')))
535 Diaspora::send_mail($item,$owner,$contact);
542 if (!$contact['pubkey'] && !$public_message)
545 if (($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
546 // top-level retraction
547 logger('diaspora retract: '.$loc);
548 Diaspora::send_retraction($target_item,$owner,$contact,$public_message);
550 } elseif ($followup) {
551 // send comments and likes to owner to relay
552 logger('diaspora followup: '.$loc);
553 Diaspora::send_followup($target_item,$owner,$contact,$public_message);
555 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
556 // we are the relay - send comments, likes and relayable_retractions to our conversants
557 logger('diaspora relay: '.$loc);
558 Diaspora::send_relay($target_item,$owner,$contact,$public_message);
560 } elseif ($top_level && !$walltowall) {
561 // currently no workable solution for sending walltowall
562 logger('diaspora status: '.$loc);
563 Diaspora::send_status($target_item,$owner,$contact,$public_message);
567 logger('delivery: diaspora unknown mode: '.$contact['name']);
579 if (array_search(__file__,get_included_files())===0){
580 delivery_run($_SERVER["argv"],$_SERVER["argc"]);