array(
      'title' => t('Access default users list'),
      'description' => t('Access default users list.'),
    ),
    'access default UC roles expiration list' => array(
      'title' => t('access default UC roles expiration list'),
      'description' => t('access default UC roles expiration list.'),
    ),
    'access duplicate mails list' => array(
      'title' => t('access duplicate mails list'),
      'description' => t('access duplicate mails list.'),
    ),
    'materio admin fix term reference field' => array(
      'title' => t('Materio admin fix term reference field'),
      'description' => t('Materio admin fix term reference field.'),
    ),
  );
}
/**
 * Implements hook_menu().
 */
function materio_admin_menu() {
  $items['admin/people/duplicatemails'] = array(
    'title' => "Duplicate mails",
    'page callback' => 'materio_duplicatemails',
    'access callback' => 'user_access',
    'access arguments' => array('access duplicate mails list'),
    'type' => MENU_LOCAL_TASK
  );
  if(module_exists('simplenews')){
    $cats = simplenews_category_list();
    // dsm($cats, 'cats');
    foreach ($cats as $tid => $name) {
      $items['node/add/simplenews/'.$tid] = array(
        'title' => $name,
        'title callback' => 'check_plain',
        'page callback' => 'node_add',
        'page arguments' => array('simplenews'),
        'access callback' => 'node_access',
        'access arguments' => array('create', 'simplenews'),
        'file path' => drupal_get_path('module', 'node'),
        'file' => 'node.pages.inc',
      );
    }
  }
  // fix term ref field lost with taxonomy
  $items['admin/config/content/materio'] = array(
    'title' => 'Materio',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('materio_admin_fix_termref_fields_form'),
    'access arguments' => array('materio admin fix term reference field'),
    'type' => MENU_NORMAL_ITEM,
  );
  $items['admin/config/content/materio/fix_termref_fields'] = array(
    'title' => 'Fix term reference field from taxonomy',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
  return $items;
}
function materio_duplicatemails(){
  $mails = db_query('SELECT mail FROM {users} GROUP BY mail HAVING count(mail) > 1')->fetchCol();
  // Bail out early if there are no duplicates.
  if (!$mails) {
    return t('All accounts have unique email addresses.');
  }
  // Grab all the user data for accounts with addresses identified as
  // duplicates. This is a little convoluted, but it lets us grab all the user
  // data in one shot.
  $uids = db_select('users', 'u')
    ->fields('u', array('uid'))
    ->condition('mail', $mails, 'IN')
    ->orderBy('access', 'DESC')
    ->execute()
    ->fetchCol();
  $duplicate_users = user_load_multiple($uids);
  $duplicate_mails = array();
  foreach ($duplicate_users as $duplicate_user) {
    $duplicate_mails[$duplicate_user->mail][] = $duplicate_user;
  }
  // Turn the data we've got into markup.
  $output = t('Accounts with duplicate email address:') . '
';
  $output = "
";
  foreach ($duplicate_mails as $mail => $users) {
    $output .= "-  $mail : 
 ";
    $accounts = array();
    foreach ($users as $duplicate_user) {
       $accounts[] =  l($duplicate_user->name, "user/{$duplicate_user->uid}") . ' ('. date('Y-m-d', $duplicate_user->access) .')';
    }
    $output .= implode(', ', $accounts);
      $output .= '
';
  }
  $output .= "
";
  return $output;
}
function materio_admin_fix_termref_fields_form(){
  drupal_set_title('Fix term reference fields', PASS_THROUGH);
  $types = node_type_get_types();
  // dsm($types, 'types');
  $nt_options = array();
  foreach ($types as $mn => $type) {
    $nt_options[$mn] = $type->name;
  }
  $node_type = variable_get('materio_admin_fix_termref_node_type', null);
  // source field (must be a text field)
  $form['node_type'] = array(
    '#type'=>'select',
    '#options'=>$nt_options,
    '#default_value' => $node_type,
    '#title' => t('Content type'),
    '#multiple' => false,
  );
  if($node_type){
    $fieldsmap = field_info_field_map();
    $target_options = array();
    foreach ($fieldsmap as $field_name => $field) {
      // dsm($field, $field_name);
      if ($field['type'] == 'taxonomy_term_reference'
          && isset($field['bundles']['node'])
          && in_array($node_type, $field['bundles']['node'])) {
        $target_options[$field_name] = $field_name;
      }
    }
    $target_field = variable_get('materio_admin_fix_termref_target_field', null);
    // target field (must be a entity_reference field)
    $form['target_field'] = array(
      '#type'=>'select',
      '#options'=>$target_options,
      '#default_value' => $target_field,
      '#title' => t('target field (must be a term_reference field)'),
      '#multiple' => false,
    );
    if($target_field){
      // retrive various field infos
      $field_info = field_info_field($target_field);
      // dsm($field_info, 'field_info');
      // $field_instance = field_info_instance('node', $target_field, $node_type);
      // dsm($field_instance, 'field_instance');
      $voc_name = $field_info['settings']['allowed_values'][0]['vocabulary'];
      $vid = taxonomy_vocabulary_machine_name_load($voc_name)->vid;
      $voc = taxonomy_vocabulary_load($vid);
      $tree = taxonomy_get_tree($vid);
      // dsm($tree, 'tree');
      foreach ($tree as $key => $term) {
        $terms[$term->tid] = $term->name;
      }
      $src_term = variable_get('materio_admin_fix_termref_src_term', null);
      // src term
      $form['src_term'] = array(
        '#type'=>'select',
        '#options'=>$terms,
        '#default_value' => $src_term,
        '#title' => t('source term'),
        '#multiple' => false,
      );
      if($src_term){
        $form['txt_nids'] = array(
          '#type'=>'textarea',
          '#title' => t('nids to fix'),
          '#description' => t('comma separated nids list'),
        );
        $form['fixterms'] = array(
          '#type' => 'submit',
          '#value' => 'Fixterms',
        );
        // $nodes = taxonomy_select_nodes($src_term, false);
        // dsm($nodes, 'nodes');
        // $src_items = field_get_items('node', node_load(11858), $target_field);
        // dsm($src_items);
      }
    }
  }
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Save',
    // '#submit' => array('materio_showroom_migrate_location_fields_migrate'),
  );
  return $form;
}
function materio_admin_fix_termref_fields_form_submit($form, &$form_state){
  // dsm($form_state, 'form_state');
  $node_type = $form_state['values']['node_type'];  $context['results']['field_migrated']++;
  $target_field = $form_state['values']['target_field'];
  $src_term = $form_state['values']['src_term'];
  variable_set('materio_admin_fix_termref_node_type', $node_type);
  variable_set('materio_admin_fix_termref_target_field', $target_field);
  variable_set('materio_admin_fix_termref_src_term', $src_term);
  $nids = explode(',', $form_state['values']['txt_nids']);
  if ($form_state['values']['op'] == 'Fixterms' && !empty($nids)){
    _materio_admin_batch_fixterm_ref($node_type, $target_field, $src_term, $nids);
  }
}
function _materio_admin_batch_fixterm_ref($node_type, $target_field, $src_tid, $nids){
  // Reset counter for debug information.
  $_SESSION['http_request_count'] = 0;
  $batch = array(
    'title' => t('Fixing ref terms ...'),
    'operations' => array(),
    'init_message' => t('Commencing'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('An error occurred during processing'),
    'finished' => '_materio_admin_batch_fixterm_ref_finished',
  );
  foreach ($nids as $nid) {
    $nid = trim($nid);
    $batch['operations'][] = array(
      '_materio_admin_batch_fixterm_ref_op',
      array(
        $nid,
        $src_tid, $target_field,
        $node_type,
      )
    );
  }
  batch_set($batch);
}
function _materio_admin_batch_fixterm_ref_op($nid, $src_tid, $target_field, $node_type){
  $context['results']['field_migrated']++;
  $node = node_load($nid);
  if($node->type == $node_type){
    $items = field_get_items('node', $node, $target_field);
    foreach ($items as $key => $item) {
      $flat_items[] = $item['tid'];
    }
    if(!in_array($src_tid, $flat_items)){
      // $items[] = array('tid'=>$src_tid);
      $node->{$target_field}[LANGUAGE_NONE][] = array('tid'=>$src_tid);
    }
    node_save($node);
  }
  //Simply show the import row count.
  $context['message'] = t('Migrating node !c : %title (%nid)', array(
    '!c' => $context['results']['field_migrated'],
    '%title'=>$node->title,
    '%nid'=>$nid ));
  // In order to slow importing and debug better,
  // we can uncomment this line to make each import slightly slower.
  // usleep(2500);
  if ( false ) {
    $context['results']['failed_nodes'][] = $nid ;
  }
  _materio_admin_update_http_requests();
}
function _materio_admin_batch_fixterm_ref_finished($success, $results, $operations){
  // dsm($success, 'success');
  // dsm($results, 'results');
  // dsm($operations, 'operations');
  if ($success) {
    // Here we could do something meaningful with the results.
    // We just display the number of nodes we processed...
    drupal_set_message(t('@count results processed in @requests HTTP requests.', array('@count' => count($results), '@requests' => _materio_admin_get_http_requests())));
    drupal_set_message(t('The final result was "%final"', array('%final' => end($results))));
  }
  else {
    // An error occurred.
    // $operations contains the operations that remained unprocessed.
    drupal_set_message(
      t('operations : @args',
        array(
          '@args' => print_r(current($operations), TRUE),
        )
      ),
      'error'
    );
    $error_operation = reset($operations);
    drupal_set_message(
      t('An error occurred while processing @operation with arguments : @args',
        array(
          '@operation' => $error_operation[0],
          '@args' => print_r($error_operation[0], TRUE),
        )
      ),
      'error'
    );
  }
}
/**
 * Utility function to increment HTTP requests in a session variable.
 */
function _materio_admin_update_http_requests() {
  $_SESSION['http_request_count']++;
}
/**
 * Utility function to count the HTTP requests in a session variable.
 *
 * @return int
 *   Number of requests.
 */
function _materio_admin_get_http_requests() {
  return !empty($_SESSION['http_request_count']) ? $_SESSION['http_request_count'] : 0;
}
/**
 * Implements hook_menu_alter().
 */
function materio_admin_menu_alter(&$items){
  // dsm($items, 'menu alter items');
  if(isset($items['admin/people'])){
    $items['admin/people']['access arguments'] = array('access default users list');
    // dsm($items['admin/people']);
  }
  if(isset($items['admin/people/expiration'])){
    $items['admin/people/expiration']['access arguments'] = array('access default UC roles expiration list');
    // dsm($items['admin/people/expiration']);
  }
  # deactivate default home page
  $items['node']['access callback'] = FALSE;
  // if(isset($items['admin/content/add/simplenews'])){
    // delete($items['admin/content/add/simplenews']);
  //   $cats = simplenews_category_list();
  //   dsm($cats, 'cats');
  //   foreach ($cats as $tid => $name) {
  //     $items['admin/content/add/simplenews/'.$tid]
  //   }
  // }
}
/**
 * Implements hook_menu_local_tasks_alter().
 */
function materio_admin_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  if ($root_path == 'admin/people/simplenews') {
    $item = menu_get_item('admin/content/simplenews');
    if ($item['access']) {
      $item['title'] = 'Go to '.$item['title'];
      $data['actions']['output'][] = array(
        '#theme' => 'menu_local_task',
        '#link' => $item,
      );
    }
  }
  if ($root_path == 'admin/content/simplenews') {
    $cats = simplenews_category_list();
    foreach ($cats as $tid => $name) {
      $item = menu_get_item('node/add/simplenews/'.$tid);
      $item['title'] = 'Add new '.$name;
      if ($item['access']) {
        $data['actions']['output'][] = array(
          '#theme' => 'menu_local_task',
          '#link' => $item,
        );
      }
    }
    $item = menu_get_item('admin/people/simplenews');
    if ($item['access']) {
      $item['title'] = 'Go to '.$item['title'];
      $data['actions']['output'][] = array(
        '#theme' => 'menu_local_task',
        '#link' => $item,
      );
    }
  }
}
/**
  * Implements hook_form_alter().
  */
function materio_admin_form_simplenews_node_form_alter(&$form, &$form_state, $form_id) {
  // dsm($form_id, '$form_id');
  // dsm($form_state, '$form_state');
  // dsm($form, '$form');
  // dsm($_GET, 'GET');
  if(!$form['nid']['#value']){
    $cats = simplenews_category_list();
    $cats_tids = array_keys($cats);
    $q = parse_url($_GET['q']);
    $cat = array_pop(explode('/', $q['path']));
    // dsm($cat, 'cat');
    if(in_array($cat, $cats_tids)){
      // prepopulate type of news
      $form['field_simplenews_term']['und']['#default_value'] = $cat;
      $form['field_simplenews_term']['und']['#disabled'] = true;
      // change default template regarding type of news
      $form['body']['und'][0]['#default_value'] = materio_admin_getSimplenewsNodeBodyTemplate($cat);
    }
  }else{
    $form['field_simplenews_term']['und']['#disabled'] = true;
  }
  $form['body']['und'][0]['#rows'] = 50;
}
function materio_admin_getSimplenewsNodeBodyTemplate($cat){
  return file_get_contents(drupal_get_path('module', 'materio_admin').'/templates/simplenews_'.$cat.'_node.html');
}
// http://stackoverflow.com/questions/19202449/change-drupal-7-compiled-css-and-js-includes-to-use-https-as-opposed-to-http
function materio_admin_process_html(&$vars){
  foreach (array('head', 'styles', 'scripts') as $replace) {
    if (!isset($vars[$replace])) {
      continue;
    }
    $vars[$replace] = preg_replace('/(src|href|@import )(url\(|=)(")http(s?):/', '$1$2$3', $vars[$replace]);
  }
}