3 require_once("boot.php");
4 require_once('include/queue_fn.php');
5 require_once('include/html2plain.php');
8 * This file was at one time responsible for doing all deliveries, but this caused
9 * big problems on shared hosting systems, where the process might get killed by the
10 * hosting provider and nothing would get delivered.
11 * It now only delivers one message under certain cases, and invokes a queued
12 * delivery mechanism (include/deliver.php) to deliver individual contacts at
13 * controlled intervals.
14 * This has a much better chance of surviving random processes getting killed
15 * by the hosting provider.
16 * A lot of this code is duplicated in include/deliver.php until we have time to go back
17 * and re-structure the delivery procedure based on the obstacles that have been thrown at
18 * us by hosting providers.
21 function notifier_run($argv, $argc){
29 @include(".htconfig.php");
30 require_once("dba.php");
31 $db = new dba($db_host, $db_user, $db_pass, $db_data);
32 unset($db_host, $db_user, $db_pass, $db_data);
35 require_once("session.php");
36 require_once("datetime.php");
37 require_once('include/items.php');
38 require_once('include/bbcode.php');
39 require_once('include/email.php');
40 load_config('config');
41 load_config('system');
48 $a->set_baseurl(get_config('system','url'));
50 logger('notifier: invoked: ' . print_r($argv,true));
57 $item_id = intval($argv[2]);
68 $recipients = array();
69 $url_recipients = array();
76 $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1",
79 if(! count($message)){
82 $uid = $message[0]['uid'];
83 $recipients[] = $message[0]['contact-id'];
87 elseif($cmd === 'expire') {
90 $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1
91 AND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 10 MINUTE",
99 elseif($cmd === 'suggest') {
100 $normal_mode = false;
103 $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1",
106 if(! count($suggest))
108 $uid = $suggest[0]['uid'];
109 $recipients[] = $suggest[0]['cid'];
115 $r = q("SELECT * FROM `item` WHERE `id` = %d and visible = 1 and moderated = 0 LIMIT 1",
119 if((! count($r)) || (! intval($r[0]['parent']))) {
123 $target_item = $r[0];
124 $parent_id = intval($r[0]['parent']);
126 $updated = $r[0]['edited'];
131 $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
132 FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d and visible = 1 and moderated = 0 ORDER BY `id` ASC",
136 if(! count($items)) {
140 // avoid race condition with deleting entries
142 if($items[0]['deleted']) {
143 foreach($items as $item)
144 $item['deleted'] = 1;
147 if((count($items) == 1) && ($items[0]['id'] === $target_item['id']) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
148 logger('notifier: top level post');
154 $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`,
155 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
156 `user`.`page-flags`, `user`.`prvnets`
157 FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
158 WHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
167 $walltowall = ((($top_level) && ($owner['id'] != $items[0]['contact-id'])) ? true : false);
169 $hub = get_config('system','huburl');
171 // If this is a public conversation, notify the feed hub
172 $public_message = true;
174 // fill this in with a single salmon slap if applicable
177 if(! ($mail || $fsuggest)) {
179 require_once('include/group.php');
183 // This is IMPORTANT!!!!
185 // We will only send a "notify owner to relay" or followup message if the referenced post
186 // originated on our system by virtue of having our hostname somewhere
187 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
189 // if $parent['wall'] == 1 we will already have the parent message in our array
190 // and we will relay the whole lot.
192 // expire sends an entire group of expire messages and cannot be forwarded.
193 // However the conversation owner will be a part of the conversation and will
194 // be notified during this run.
195 // Other DFRN conversation members will be alerted during polled updates.
199 // Diaspora members currently are not notified of expirations, and other networks have
200 // either limited or no ability to process deletions. We should at least fix Diaspora
201 // by stringing togther an array of retractions and sending them onward.
204 $localhost = str_replace('www.','',$a->get_hostname());
205 if(strpos($localhost,':'))
206 $localhost = substr($localhost,0,strpos($localhost,':'));
210 * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes
211 * have been known to cause runaway conditions which affected several servers, along with
212 * permissions issues.
216 $relay_to_owner = false;
218 if((! $top_level) && ($parent['wall'] == 0) && (! $expire) && (stristr($target_item['uri'],$localhost))) {
219 $relay_to_owner = true;
223 if(($cmd === 'uplink') && (intval($parent['forum_mode'])) && (! $top_level)) {
224 $relay_to_owner = true;
227 // until the 'origin' flag has been in use for several months
228 // we will just use it as a fallback test
229 // later we will be able to use it as the primary test of whether or not to relay.
231 if(! $target_item['origin'])
232 $relay_to_owner = false;
234 if($parent['origin'])
235 $relay_to_owner = false;
239 if($relay_to_owner) {
240 logger('notifier: followup', LOGGER_DEBUG);
241 // local followup to remote post
243 $public_message = false; // not public
244 $conversant_str = dbesc($parent['contact-id']);
249 // don't send deletions onward for other people's stuff
251 if($target_item['deleted'] && (! intval($target_item['wall']))) {
252 logger('notifier: ignoring delete notification for non-wall item');
256 if((strlen($parent['allow_cid']))
257 || (strlen($parent['allow_gid']))
258 || (strlen($parent['deny_cid']))
259 || (strlen($parent['deny_gid']))) {
260 $public_message = false; // private recipients, not public
263 $allow_people = expand_acl($parent['allow_cid']);
264 $allow_groups = expand_groups(expand_acl($parent['allow_gid']));
265 $deny_people = expand_acl($parent['deny_cid']);
266 $deny_groups = expand_groups(expand_acl($parent['deny_gid']));
268 // if our parent is a forum, uplink to the origional author causing
271 if(intval($parent['forum_mode']) && (! $top_level) && ($cmd !== 'uplink')) {
272 proc_run('php','include/notifier','uplink',$item_id);
275 $conversants = array();
277 foreach($items as $item) {
278 $recipients[] = $item['contact-id'];
279 $conversants[] = $item['contact-id'];
280 // pull out additional tagged people to notify (if public message)
281 if($public_message && strlen($item['inform'])) {
282 $people = explode(',',$item['inform']);
283 foreach($people as $person) {
284 if(substr($person,0,4) === 'cid:') {
285 $recipients[] = intval(substr($person,4));
286 $conversants[] = intval(substr($person,4));
289 $url_recipients[] = substr($person,4);
295 logger('notifier: url_recipients' . print_r($url_recipients,true));
297 $conversants = array_unique($conversants);
300 $recipients = array_unique(array_merge($recipients,$allow_people,$allow_groups));
301 $deny = array_unique(array_merge($deny_people,$deny_groups));
302 $recipients = array_diff($recipients,$deny);
304 $conversant_str = dbesc(implode(', ',$conversants));
307 $r = q("SELECT * FROM `contact` WHERE `id` IN ( $conversant_str ) AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
313 $feed_template = get_markup_template('atom_feed.tpl');
314 $mail_template = get_markup_template('atom_mail.tpl');
319 $hubxml = feed_hublinks();
321 $birthday = feed_birthday($owner['uid'],$owner['timezone']);
323 if(strlen($birthday))
324 $birthday = '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>';
326 $atom .= replace_macros($feed_template, array(
327 '$version' => xmlify(FRIENDICA_VERSION),
328 '$feed_id' => xmlify($a->get_baseurl() . '/profile/' . $owner['nickname'] ),
329 '$feed_title' => xmlify($owner['name']),
330 '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', $updated . '+00:00' , ATOM_TIME)) ,
332 '$salmon' => '', // private feed, we don't use salmon here
333 '$name' => xmlify($owner['name']),
334 '$profile_page' => xmlify($owner['url']),
335 '$photo' => xmlify($owner['photo']),
336 '$thumb' => xmlify($owner['thumb']),
337 '$picdate' => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
338 '$uridate' => xmlify(datetime_convert('UTC','UTC',$owner['uri-date'] . '+00:00' , ATOM_TIME)) ,
339 '$namdate' => xmlify(datetime_convert('UTC','UTC',$owner['name-date'] . '+00:00' , ATOM_TIME)) ,
340 '$birthday' => $birthday,
341 '$community' => (($owner['page-flags'] == PAGE_COMMUNITY) ? '<dfrn:community>1</dfrn:community>' : '')
346 $public_message = false; // mail is not public
348 $body = fix_private_photos($item['body'],$owner['uid']);
350 $atom .= replace_macros($mail_template, array(
351 '$name' => xmlify($owner['name']),
352 '$profile_page' => xmlify($owner['url']),
353 '$thumb' => xmlify($owner['thumb']),
354 '$item_id' => xmlify($item['uri']),
355 '$subject' => xmlify($item['title']),
356 '$created' => xmlify(datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME)),
357 '$content' => xmlify($body),
358 '$parent_id' => xmlify($item['parent-uri'])
362 $public_message = false; // suggestions are not public
364 $sugg_template = get_markup_template('atom_suggest.tpl');
366 $atom .= replace_macros($sugg_template, array(
367 '$name' => xmlify($item['name']),
368 '$url' => xmlify($item['url']),
369 '$photo' => xmlify($item['photo']),
370 '$request' => xmlify($item['request']),
371 '$note' => xmlify($item['note'])
374 // We don't need this any more
376 q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1",
383 foreach($items as $item) { // there is only one item
384 if(! $item['parent'])
386 if($item['id'] == $item_id) {
387 logger('notifier: followup: item: ' . print_r($item,true), LOGGER_DATA);
388 $slap = atom_entry($item,'html',null,$owner,false);
389 $atom .= atom_entry($item,'text',null,$owner,false);
394 foreach($items as $item) {
396 if(! $item['parent'])
399 // private emails may be in included in public conversations. Filter them.
401 if(($public_message) && $item['private'])
405 $contact = get_item_contact($item,$contacts);
412 // we only need the current item, but include the parent because without it
413 // older sites without a corresponding dfrn_notify change may do the wrong thing.
415 if($item_id == $item['id'] || $item['id'] == $item['parent'])
416 $atom .= atom_entry($item,'text',null,$owner,true);
419 $atom .= atom_entry($item,'text',null,$owner,true);
421 if(($top_level) && ($public_message) && ($item['author-link'] === $item['owner-link']) && (! $expire))
422 $slaps[] = atom_entry($item,'html',null,$owner,true);
426 $atom .= '</feed>' . "\r\n";
428 logger('notifier: ' . $atom, LOGGER_DATA);
430 logger('notifier: slaps: ' . print_r($slaps,true), LOGGER_DATA);
432 // If this is a public message and pubmail is set on the parent, include all your email contacts
434 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
436 if(! $mail_disabled) {
437 if((! strlen($target_item['allow_cid'])) && (! strlen($target_item['allow_gid']))
438 && (! strlen($target_item['deny_cid'])) && (! strlen($target_item['deny_gid']))
439 && (intval($target_item['pubmail']))) {
440 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `network` = '%s'",
446 $recipients[] = $rr['id'];
452 $recip_str = $parent['contact-id'];
454 $recip_str = implode(', ', $recipients);
456 $r = q("SELECT * FROM `contact` WHERE `id` IN ( %s ) AND `blocked` = 0 AND `pending` = 0 ",
461 require_once('include/salmon.php');
463 $interval = ((get_config('system','delivery_interval') === false) ? 2 : intval(get_config('system','delivery_interval')));
469 foreach($r as $contact) {
470 if((! $mail) && (! $fsuggest) && (! $followup) && (! $contact['self'])) {
471 if(($contact['network'] === NETWORK_DIASPORA) && ($public_message))
473 q("insert into deliverq ( `cmd`,`item`,`contact` ) values ('%s', %d, %d )",
476 intval($contact['id'])
481 foreach($r as $contact) {
485 // potentially more than one recipient. Start a new process and space them out a bit.
486 // we will deliver single recipient types of message and email receipients here.
488 if((! $mail) && (! $fsuggest) && (! $followup)) {
489 proc_run('php','include/delivery.php',$cmd,$item_id,$contact['id']);
491 @time_sleep_until(microtime(true) + (float) $interval);
497 logger("main delivery by notifier: followup=$followup mail=$mail fsuggest=$fsuggest");
499 switch($contact['network']) {
502 // perform local delivery if we are on the same site
504 $basepath = implode('/', array_slice(explode('/',$contact['url']),0,3));
506 if(link_compare($basepath,$a->get_baseurl())) {
508 $nickname = basename($contact['url']);
509 if($contact['issued-id'])
510 $sql_extra = sprintf(" AND `dfrn-id` = '%s' ", dbesc($contact['issued-id']));
512 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($contact['dfrn-id']));
514 $x = q("SELECT `contact`.*, `contact`.`uid` AS `importer_uid`,
515 `contact`.`pubkey` AS `cpubkey`,
516 `contact`.`prvkey` AS `cprvkey`,
517 `contact`.`thumb` AS `thumb`,
518 `contact`.`url` as `url`,
519 `contact`.`name` as `senderName`,
522 LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
523 WHERE `contact`.`blocked` = 0 AND `contact`.`archive` = 0
524 AND `contact`.`pending` = 0
525 AND `contact`.`network` = '%s' AND `user`.`nickname` = '%s'
527 AND `user`.`account_expired` = 0 LIMIT 1",
534 if($owner['page-flags'] == PAGE_COMMUNITY && ! $x[0]['writable']) {
535 q("update contact set writable = 1 where id = %d limit 1",
538 $x[0]['writable'] = 1;
541 // if contact's ssl policy changed, which we just determined
542 // is on our own server, update our contact links
544 $ssl_policy = get_config('system','ssl_policy');
545 fix_contact_ssl_policy($x[0],$ssl_policy);
547 // If we are setup as a soapbox we aren't accepting input from this person
549 if($x[0]['page-flags'] == PAGE_SOAPBOX)
552 require_once('library/simplepie/simplepie.inc');
553 logger('mod-delivery: local delivery');
554 local_delivery($x[0],$atom);
561 logger('notifier: dfrndelivery: ' . $contact['name']);
562 $deliver_status = dfrn_deliver($owner,$contact,$atom);
564 logger('notifier: dfrn_delivery returns ' . $deliver_status);
566 if($deliver_status == (-1)) {
567 logger('notifier: delivery failed: queuing message');
568 // queue message for redelivery
569 add_to_queue($contact['id'],NETWORK_DFRN,$atom);
572 case NETWORK_OSTATUS:
574 // Do not send to otatus if we are not configured to send to public networks
575 if($owner['prvnets'])
577 if(get_config('system','ostatus_disabled') || get_config('system','dfrn_only'))
580 if($followup && $contact['notify']) {
581 logger('notifier: slapdelivery: ' . $contact['name']);
582 $deliver_status = slapper($owner,$contact['notify'],$slap);
584 if($deliver_status == (-1)) {
585 // queue message for redelivery
586 add_to_queue($contact['id'],NETWORK_OSTATUS,$slap);
591 // only send salmon if public - e.g. if it's ok to notify
592 // a public hub, it's ok to send a salmon
594 if((count($slaps)) && ($public_message) && (! $expire)) {
595 logger('notifier: slapdelivery: ' . $contact['name']);
596 foreach($slaps as $slappy) {
597 if($contact['notify']) {
598 $deliver_status = slapper($owner,$contact['notify'],$slappy);
599 if($deliver_status == (-1)) {
600 // queue message for redelivery
601 add_to_queue($contact['id'],NETWORK_OSTATUS,$slappy);
612 if(get_config('system','dfrn_only'))
615 // WARNING: does not currently convert to RFC2047 header encodings, etc.
617 $addr = $contact['addr'];
621 if($cmd === 'wall-new' || $cmd === 'comment-new') {
624 if($cmd === 'wall-new')
627 $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
639 $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
642 if(! count($local_user))
646 $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
649 if($r1 && $r1[0]['reply_to'])
650 $reply_to = $r1[0]['reply_to'];
652 $subject = (($it['title']) ? email_header_encode($it['title'],'UTF-8') : t("\x28no subject\x29")) ;
654 // only expose our real email address to true friends
656 if(($contact['rel'] == CONTACT_IS_FRIEND) && (! $contact['blocked']))
657 $headers = 'From: ' . email_header_encode($local_user[0]['username'],'UTF-8') . ' <' . $local_user[0]['email'] . '>' . "\n";
659 $headers = 'From: ' . email_header_encode($local_user[0]['username'],'UTF-8') . ' <' . t('noreply') . '@' . $a->get_hostname() . '>' . "\n";
662 $headers .= 'Reply-to: ' . $reply_to . "\n";
664 // for testing purposes: Collect exported mails
665 //$file = tempnam("/tmp/friendica/", "mail-out2-");
666 //file_put_contents($file, json_encode($it));
668 $headers .= 'Message-Id: <' . iri2msgid($it['uri']) . '>' . "\n";
670 if($it['uri'] !== $it['parent-uri']) {
671 $headers .= 'References: <' . iri2msgid($it['parent-uri']) . '>' . "\n";
672 if(!strlen($it['title'])) {
673 $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' LIMIT 1",
674 dbesc($it['parent-uri']));
676 if(count($r) AND ($r[0]['title'] != ''))
677 $subject = $r[0]['title'];
679 if(strncasecmp($subject,'RE:',3))
680 $subject = 'Re: '.$subject;
682 email_send($addr, $subject, $headers, $it);
685 case NETWORK_DIASPORA:
686 require_once('include/diaspora.php');
688 if(get_config('system','dfrn_only') || (! get_config('system','diaspora_enabled')))
692 diaspora_send_mail($item,$owner,$contact);
699 // special handling for followup to public post
700 // all other public posts processed as public batches further below
702 if($public_message) {
704 diaspora_send_followup($target_item,$owner,$contact, true);
708 if(! $contact['pubkey'])
711 if($target_item['verb'] === ACTIVITY_DISLIKE) {
715 elseif(($target_item['deleted']) && ($target_item['verb'] !== ACTIVITY_LIKE)) {
717 diaspora_send_retraction($target_item,$owner,$contact);
721 // send comments, likes and retractions of likes to owner to relay
722 diaspora_send_followup($target_item,$owner,$contact);
725 elseif($target_item['parent'] != $target_item['id']) {
726 // we are the relay - send comments, likes and unlikes to our conversants
727 diaspora_send_relay($target_item,$owner,$contact);
730 elseif(($top_level) && (! $walltowall)) {
731 // currently no workable solution for sending walltowall
732 diaspora_send_status($target_item,$owner,$contact);
739 case NETWORK_FACEBOOK:
740 if(get_config('system','dfrn_only'))
748 // send additional slaps to mentioned remote tags (@foo@example.com)
750 if($slap && count($url_recipients) && ($followup || $top_level) && $public_message && (! $expire)) {
751 if(! get_config('system','dfrn_only')) {
752 foreach($url_recipients as $url) {
754 logger('notifier: urldelivery: ' . $url);
755 $deliver_status = slapper($owner,$url,$slap);
756 // TODO: redeliver/queue these items on failure, though there is no contact record
763 if($public_message) {
765 $r1 = q("SELECT DISTINCT(`batch`), `id`, `name`,`network` FROM `contact` WHERE `network` = '%s'
766 AND `uid` = %d AND `rel` != %d group by `batch` ORDER BY rand() ",
767 dbesc(NETWORK_DIASPORA),
768 intval($owner['uid']),
769 intval(CONTACT_IS_SHARING)
772 $r2 = q("SELECT `id`, `name`,`network` FROM `contact`
773 WHERE `network` in ( '%s', '%s') AND `uid` = %d AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0
774 AND `rel` != %d order by rand() ",
776 dbesc(NETWORK_MAIL2),
777 intval($owner['uid']),
778 intval(CONTACT_IS_SHARING)
781 $r = array_merge($r2,$r1);
784 logger('pubdeliver: ' . print_r($r,true), LOGGER_DEBUG);
786 // throw everything into the queue in case we get killed
789 if((! $mail) && (! $fsuggest) && (! $followup)) {
790 q("insert into deliverq ( `cmd`,`item`,`contact` ) values ('%s', %d, %d )",
800 // except for Diaspora batch jobs
801 // Don't deliver to folks who have already been delivered to
803 if(($rr['network'] !== NETWORK_DIASPORA) && (in_array($rr['id'],$conversants))) {
804 logger('notifier: already delivered id=' . $rr['id']);
808 if((! $mail) && (! $fsuggest) && (! $followup)) {
809 logger('notifier: delivery agent: ' . $rr['name'] . ' ' . $rr['id']);
810 proc_run('php','include/delivery.php',$cmd,$item_id,$rr['id']);
812 @time_sleep_until(microtime(true) + (float) $interval);
819 $hubs = explode(',', $hub);
821 foreach($hubs as $h) {
825 $params = 'hub.mode=publish&hub.url=' . urlencode($a->get_baseurl() . '/dfrn_poll/' . $owner['nickname'] );
826 post_url($h,$params);
827 logger('pubsub: publish: ' . $h . ' ' . $params . ' returned ' . $a->get_curl_code());
829 sleep(7); // try and avoid multiple hubs responding at precisely the same time
837 call_hooks('notifier_normal',$target_item);
839 call_hooks('notifier_end',$target_item);
844 if (array_search(__file__,get_included_files())===0){
845 notifier_run($argv,$argc);