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");
9 function delivery_run(&$argv, &$argc){
17 @include(".htconfig.php");
18 require_once("include/dba.php");
19 $db = new dba($db_host, $db_user, $db_pass, $db_data);
20 unset($db_host, $db_user, $db_pass, $db_data);
23 require_once("include/session.php");
24 require_once("include/datetime.php");
25 require_once('include/items.php');
26 require_once('include/bbcode.php');
27 require_once('include/email.php');
29 load_config('config');
30 load_config('system');
37 $a->set_baseurl(get_config('system','url'));
39 logger('delivery: invoked: ' . print_r($argv,true), LOGGER_DEBUG);
42 $item_id = intval($argv[2]);
44 for($x = 3; $x < $argc; $x ++) {
46 $contact_id = intval($argv[$x]);
48 // Some other process may have delivered this item already.
50 $r = q("SELECT * FROM `deliverq` WHERE `cmd` = '%s' AND `item` = %d AND `contact` = %d LIMIT 1",
59 $maxsysload = intval(get_config('system','maxloadavg'));
63 $load = current_load();
65 if(intval($load) > $maxsysload) {
66 logger('system: load ' . $load . ' too high. Delivery deferred to next queue run.');
71 // It's ours to deliver. Remove it from the queue.
73 q("DELETE FROM `deliverq` WHERE `cmd` = '%s' AND `item` = %d AND `contact` = %d",
79 if((! $item_id) || (! $contact_id))
87 $recipients = array();
88 $url_recipients = array();
93 $recipients[] = $contact_id;
98 $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1",
101 if(! count($message)){
104 $uid = $message[0]['uid'];
105 $recipients[] = $message[0]['contact-id'];
108 elseif($cmd === 'expire') {
109 $normal_mode = false;
111 $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1
112 AND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 30 MINUTE",
120 elseif($cmd === 'suggest') {
121 $normal_mode = false;
124 $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1",
127 if(! count($suggest))
129 $uid = $suggest[0]['uid'];
130 $recipients[] = $suggest[0]['cid'];
132 } elseif($cmd === 'relocate') {
133 $normal_mode = false;
138 $r = q("SELECT * FROM `item` WHERE `id` = %d and visible = 1 and moderated = 0 LIMIT 1",
142 if((! count($r)) || (! intval($r[0]['parent']))) {
146 $target_item = $r[0];
147 $parent_id = intval($r[0]['parent']);
149 $updated = $r[0]['edited'];
151 $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
152 FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d and visible = 1 and moderated = 0 ORDER BY `id` ASC",
156 if(! count($items)) {
161 $contacts_arr = array();
162 foreach($items as $item)
163 if(! in_array($item['contact-id'],$contacts_arr))
164 $contacts_arr[] = intval($item['contact-id']);
165 if(count($contacts_arr)) {
166 $str_contacts = implode(',',$contacts_arr);
167 $icontacts = q("SELECT * FROM `contact`
168 WHERE `id` IN ( $str_contacts ) "
171 if( ! ($icontacts && count($icontacts)))
174 // avoid race condition with deleting entries
176 if($items[0]['deleted']) {
177 foreach($items as $item)
178 $item['deleted'] = 1;
181 if((count($items) == 1) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
182 logger('delivery: top level post');
187 $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`,
188 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
189 `user`.`page-flags`, `user`.`prvnets`
190 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
191 WHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
200 $walltowall = ((($top_level) && ($owner['id'] != $items[0]['contact-id'])) ? true : false);
202 $public_message = true;
204 if(! ($mail || $fsuggest || $relocate)) {
205 require_once('include/group.php');
209 // This is IMPORTANT!!!!
211 // We will only send a "notify owner to relay" or followup message if the referenced post
212 // originated on our system by virtue of having our hostname somewhere
213 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
214 // if $parent['wall'] == 1 we will already have the parent message in our array
215 // and we will relay the whole lot.
217 // expire sends an entire group of expire messages and cannot be forwarded.
218 // However the conversation owner will be a part of the conversation and will
219 // be notified during this run.
220 // Other DFRN conversation members will be alerted during polled updates.
222 // Diaspora members currently are not notified of expirations, and other networks have
223 // either limited or no ability to process deletions. We should at least fix Diaspora
224 // by stringing togther an array of retractions and sending them onward.
227 $localhost = $a->get_hostname();
228 if(strpos($localhost,':'))
229 $localhost = substr($localhost,0,strpos($localhost,':'));
233 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
234 * have been known to cause runaway conditions which affected several servers, along with
235 * permissions issues.
239 $relay_to_owner = false;
241 if((! $top_level) && ($parent['wall'] == 0) && (! $expire) && (stristr($target_item['uri'],$localhost))) {
242 $relay_to_owner = true;
245 if($relay_to_owner) {
246 logger('followup '.$target_item["guid"], LOGGER_DEBUG);
247 // local followup to remote post
251 if((strlen($parent['allow_cid']))
252 || (strlen($parent['allow_gid']))
253 || (strlen($parent['deny_cid']))
254 || (strlen($parent['deny_gid']))) {
255 $public_message = false; // private recipients, not public
260 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `blocked` = 0 AND `pending` = 0",
267 $hubxml = feed_hublinks();
274 logger("main delivery by delivery: followup=$followup mail=$mail fsuggest=$fsuggest relocate=$relocate - network ".$contact['network']);
276 switch($contact['network']) {
279 logger('notifier: '.$target_item["guid"].' dfrndelivery: ' . $contact['name']);
281 $feed_template = get_markup_template('atom_feed.tpl');
282 $mail_template = get_markup_template('atom_mail.tpl');
287 $birthday = feed_birthday($owner['uid'],$owner['timezone']);
289 if(strlen($birthday))
290 $birthday = '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>';
292 $atom .= replace_macros($feed_template, array(
293 '$version' => xmlify(FRIENDICA_VERSION),
294 '$feed_id' => xmlify($a->get_baseurl() . '/profile/' . $owner['nickname'] ),
295 '$feed_title' => xmlify($owner['name']),
296 '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', $updated . '+00:00' , ATOM_TIME)) ,
298 '$salmon' => '', // private feed, we don't use salmon here
299 '$name' => xmlify($owner['name']),
300 '$profile_page' => xmlify($owner['url']),
301 '$photo' => xmlify($owner['photo']),
302 '$thumb' => xmlify($owner['thumb']),
303 '$picdate' => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
304 '$uridate' => xmlify(datetime_convert('UTC','UTC',$owner['uri-date'] . '+00:00' , ATOM_TIME)) ,
305 '$namdate' => xmlify(datetime_convert('UTC','UTC',$owner['name-date'] . '+00:00' , ATOM_TIME)) ,
306 '$birthday' => $birthday,
307 '$community' => (($owner['page-flags'] == PAGE_COMMUNITY) ? '<dfrn:community>1</dfrn:community>' : '')
311 $public_message = false; // mail is not public
313 $body = fix_private_photos($item['body'],$owner['uid'],null,$message[0]['contact-id']);
315 $atom .= replace_macros($mail_template, array(
316 '$name' => xmlify($owner['name']),
317 '$profile_page' => xmlify($owner['url']),
318 '$thumb' => xmlify($owner['thumb']),
319 '$item_id' => xmlify($item['uri']),
320 '$subject' => xmlify($item['title']),
321 '$created' => xmlify(datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME)),
322 '$content' => xmlify($body),
323 '$parent_id' => xmlify($item['parent-uri'])
325 } elseif($fsuggest) {
326 $public_message = false; // suggestions are not public
328 $sugg_template = get_markup_template('atom_suggest.tpl');
330 $atom .= replace_macros($sugg_template, array(
331 '$name' => xmlify($item['name']),
332 '$url' => xmlify($item['url']),
333 '$photo' => xmlify($item['photo']),
334 '$request' => xmlify($item['request']),
335 '$note' => xmlify($item['note'])
338 // We don't need this any more
340 q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1",
343 } elseif($relocate) {
344 $public_message = false; // suggestions are not public
346 $sugg_template = get_markup_template('atom_relocate.tpl');
348 /* get site pubkey. this could be a new installation with no site keys*/
349 $pubkey = get_config('system','site_pubkey');
351 $res = new_keypair(1024);
352 set_config('system','site_prvkey', $res['prvkey']);
353 set_config('system','site_pubkey', $res['pubkey']);
356 $rp = q("SELECT `resource-id` , `scale`, type FROM `photo`
357 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;", $uid);
359 $ext = Photo::supportedTypes();
361 $photos[$p['scale']] = $a->get_baseurl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
365 $atom .= replace_macros($sugg_template, array(
366 '$name' => xmlify($owner['name']),
367 '$photo' => xmlify($photos[4]),
368 '$thumb' => xmlify($photos[5]),
369 '$micro' => xmlify($photos[6]),
370 '$url' => xmlify($owner['url']),
371 '$request' => xmlify($owner['request']),
372 '$confirm' => xmlify($owner['confirm']),
373 '$notify' => xmlify($owner['notify']),
374 '$poll' => xmlify($owner['poll']),
375 '$sitepubkey' => xmlify(get_config('system','site_pubkey')),
376 //'$pubkey' => xmlify($owner['pubkey']),
377 //'$prvkey' => xmlify($owner['prvkey']),
380 } elseif($followup) {
381 foreach($items as $item) { // there is only one item
382 if(! $item['parent'])
384 if($item['id'] == $item_id) {
385 logger('followup: item: ' . print_r($item,true), LOGGER_DATA);
386 $atom .= atom_entry($item,'text',null,$owner,false);
390 foreach($items as $item) {
391 if(! $item['parent'])
394 // private emails may be in included in public conversations. Filter them.
395 if(($public_message) && $item['private'] == 1)
398 $item_contact = get_item_contact($item,$icontacts);
403 if($item_id == $item['id'] || $item['id'] == $item['parent'])
404 $atom .= atom_entry($item,'text',null,$owner,true,(($top_level) ? $contact['id'] : 0));
406 $atom .= atom_entry($item,'text',null,$owner,true);
410 $atom .= '</feed>' . "\r\n";
412 logger('notifier: '.$contact["url"].' '.$target_item["guid"].' entry: '.$atom, LOGGER_DEBUG);
414 logger('notifier: ' . $atom, LOGGER_DATA);
415 $basepath = implode('/', array_slice(explode('/',$contact['url']),0,3));
417 // perform local delivery if we are on the same site
419 if(link_compare($basepath,$a->get_baseurl())) {
421 $nickname = basename($contact['url']);
422 if($contact['issued-id'])
423 $sql_extra = sprintf(" AND `dfrn-id` = '%s' ", dbesc($contact['issued-id']));
425 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($contact['dfrn-id']));
427 $x = q("SELECT `contact`.*, `contact`.`uid` AS `importer_uid`,
428 `contact`.`pubkey` AS `cpubkey`,
429 `contact`.`prvkey` AS `cprvkey`,
430 `contact`.`thumb` AS `thumb`,
431 `contact`.`url` as `url`,
432 `contact`.`name` as `senderName`,
435 INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`
436 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
437 AND `contact`.`network` = '%s' AND `user`.`nickname` = '%s'
439 AND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 LIMIT 1",
444 if($x && count($x)) {
445 $write_flag = ((($x[0]['rel']) && ($x[0]['rel'] != CONTACT_IS_SHARING)) ? true : false);
446 if((($owner['page-flags'] == PAGE_COMMUNITY) || ($write_flag)) && (! $x[0]['writable'])) {
447 q("update contact set writable = 1 where id = %d",
450 $x[0]['writable'] = 1;
453 $ssl_policy = get_config('system','ssl_policy');
454 fix_contact_ssl_policy($x[0],$ssl_policy);
456 // If we are setup as a soapbox we aren't accepting top level posts from this person
458 if (($x[0]['page-flags'] == PAGE_SOAPBOX) AND $top_level)
461 require_once('library/simplepie/simplepie.inc');
462 logger('mod-delivery: local delivery');
463 local_delivery($x[0],$atom);
468 if(! was_recently_delayed($contact['id']))
469 $deliver_status = dfrn_deliver($owner,$contact,$atom);
471 $deliver_status = (-1);
473 logger('notifier: dfrn_delivery to '.$contact["url"].' with guid '.$target_item["guid"].' returns '.$deliver_status);
475 if($deliver_status == (-1)) {
476 logger('notifier: delivery failed: queuing message');
477 add_to_queue($contact['id'],NETWORK_DFRN,$atom);
481 case NETWORK_OSTATUS:
482 // Do not send to otatus if we are not configured to send to public networks
483 if($owner['prvnets'])
485 if(get_config('system','ostatus_disabled') || get_config('system','dfrn_only'))
488 // There is currently no code here to distribute anything to OStatus.
489 // This is done in "notifier.php" (See "url_recipients" and "push_notify")
495 if(get_config('system','dfrn_only'))
497 // WARNING: does not currently convert to RFC2047 header encodings, etc.
499 $addr = $contact['addr'];
503 if($cmd === 'wall-new' || $cmd === 'comment-new') {
506 if($cmd === 'wall-new')
509 $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
520 $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
523 if(! count($local_user))
527 $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
530 if($r1 && $r1[0]['reply_to'])
531 $reply_to = $r1[0]['reply_to'];
533 $subject = (($it['title']) ? email_header_encode($it['title'],'UTF-8') : t("\x28no subject\x29")) ;
535 // only expose our real email address to true friends
537 if(($contact['rel'] == CONTACT_IS_FRIEND) && (! $contact['blocked'])) {
539 $headers = 'From: '.email_header_encode($local_user[0]['username'],'UTF-8').' <'.$reply_to.'>'."\n";
540 $headers .= 'Sender: '.$local_user[0]['email']."\n";
542 $headers = 'From: '.email_header_encode($local_user[0]['username'],'UTF-8').' <'.$local_user[0]['email'].'>'."\n";
544 $headers = 'From: ' . email_header_encode($local_user[0]['username'],'UTF-8') . ' <' . t('noreply') . '@' . $a->get_hostname() . '>' . "\n";
547 // $headers .= 'Reply-to: ' . $reply_to . "\n";
549 $headers .= 'Message-Id: <' . iri2msgid($it['uri']). '>' . "\n";
551 //logger("Mail: uri: ".$it['uri']." parent-uri ".$it['parent-uri'], LOGGER_DEBUG);
552 //logger("Mail: Data: ".print_r($it, true), LOGGER_DEBUG);
553 //logger("Mail: Data: ".print_r($it, true), LOGGER_DATA);
555 if($it['uri'] !== $it['parent-uri']) {
556 $headers .= "References: <".iri2msgid($it["parent-uri"]).">";
558 // If Threading is enabled, write down the correct parent
559 if (($it["thr-parent"] != "") and ($it["thr-parent"] != $it["parent-uri"]))
560 $headers .= " <".iri2msgid($it["thr-parent"]).">";
564 $r = q("SELECT `title` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
565 dbesc($it['parent-uri']),
568 if(count($r) AND ($r[0]['title'] != ''))
569 $subject = $r[0]['title'];
571 $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d LIMIT 1",
572 dbesc($it['parent-uri']),
575 if(count($r) AND ($r[0]['title'] != ''))
576 $subject = $r[0]['title'];
579 if(strncasecmp($subject,'RE:',3))
580 $subject = 'Re: '.$subject;
582 email_send($addr, $subject, $headers, $it);
586 case NETWORK_DIASPORA:
588 $loc = 'public batch ' . $contact['batch'];
590 $loc = $contact['name'];
592 logger('delivery: diaspora batch deliver: ' . $loc);
594 if(get_config('system','dfrn_only') || (!get_config('system','diaspora_enabled')))
598 diaspora_send_mail($item,$owner,$contact);
605 if((! $contact['pubkey']) && (! $public_message))
608 $unsupported_activities = array(ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE);
610 //don't transmit activities which are not supported by diaspora
611 foreach($unsupported_activities as $act) {
612 if(activity_match($target_item['verb'],$act)) {
617 if(($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
618 // top-level retraction
619 logger('delivery: diaspora retract: ' . $loc);
621 diaspora_send_retraction($target_item,$owner,$contact,$public_message);
623 } elseif($followup) {
624 // send comments and likes to owner to relay
625 diaspora_send_followup($target_item,$owner,$contact,$public_message);
627 } elseif($target_item['uri'] !== $target_item['parent-uri']) {
628 // we are the relay - send comments, likes and relayable_retractions to our conversants
629 logger('delivery: diaspora relay: ' . $loc);
631 diaspora_send_relay($target_item,$owner,$contact,$public_message);
633 } elseif(($top_level) && (! $walltowall)) {
634 // currently no workable solution for sending walltowall
635 logger('delivery: diaspora status: ' . $loc);
636 diaspora_send_status($target_item,$owner,$contact,$public_message);
640 logger('delivery: diaspora unknown mode: ' . $contact['name']);
652 if (array_search(__file__,get_included_files())===0){
653 delivery_run($_SERVER["argv"],$_SERVER["argc"]);