<?php

/**
 * Implementation of hook_apachesolr_modify_query()
 */
function search_restrict_apache_solr_apachesolr_modify_query(&$query, &$params, $caller) {
  global $user;
  // User 1 can search everything.
  if ($user->uid == 1) {
    return;
  }

  $excluded_types = search_restrict_apache_solr_excluded($user->roles);
	
  if (!empty($excluded_types)) {

    foreach ($excluded_types as $excluded_type) {
      $query->add_filter('type', $excluded_type, TRUE);
    }
  }

}

/**
 * Get list of content types to exclude.
 */
function search_restrict_apache_solr_excluded($user_roles) {

  $excluded_types = array();
  $types = node_get_types();

  foreach ($types as $type => $type_info) {
    $roles = variable_get('search_restrict_type_'. $type, array());
    $access = FALSE;
    $access_false = array();
    $access_true = array();

    // list included and excluded roles
    foreach ($roles as $role_id => $selected) {
      if (empty($selected)) { 
        $access_false[] = $role_id;
      }
      else {
        $access_true[] = $role_id;  
      } 
    }

    // If no roles or all roles have been selected then everyone has access
    // skip this content type.
    if (!empty($access_true) && !empty($access_false)) {
      // If user has role in include list skip this content type.
      foreach ($access_true as $role_selected) {
        if (!empty($user_roles[$role_selected])) $access = TRUE;
      } 
    
      // User doesn't have any roles that are allowed to search this content type.
      if (empty($access)) $excluded_types[] =  $type; 
    }
	}
	
	return $excluded_types;	
}