<?php

/**
 * @file
 * I am the (taxonomy) child catcher. I do the dirty work that core Drupal
 * doesn't do (http://drupal.org/node/1281114#comment-5678238). Who likes
 * candy?
 */

/**
 * Implements hook_menu().
 */
function taxonomy_orphanage_menu() {
  $items = array();

  $items['admin/structure/taxonomy/orphanage'] = array(
    'title' => 'Orphanage',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('taxonomy_orphanage_settings'),
    'access arguments' => array('administer taxonomy'),
    'file' => 'taxonomy_orphanage.admin.inc',
    'type' => MENU_LOCAL_TASK,
  );

  return $items;
}

/**
 * Implements hook_cron().
 */
function taxonomy_orphanage_cron() {
  if (variable_get('taxonomy_orphanage_cron_roundup', TRUE)) {
    // It's probably best to keep the limit low in case cron is being executed
    // by the web server.
    taxonomy_orphanage_roundup(FALSE, variable_get('taxonomy_orphanage_cron_limit', 50), FALSE);
  }
}

/**
 * Looks for orphaned taxonomy references and removes them.
 *
 * @param $progressive
 *   TRUE if this is a progressive batch, else FALSE.
 * @param $limit
 *   Number of records per batch set to process. Useful for cron jobs.
 * @param $display_finished
 *   TRUE to send finished messages to the log, else FALSE.
 */
function taxonomy_orphanage_roundup($progressive = TRUE, $limit = -1, $display_finished = TRUE) {
  $batch = array(
    'title' => t('Collecting orphans'),
    'file' => drupal_get_path('module', 'taxonomy_orphanage') . '/taxonomy_orphanage.batch.inc',
    'finished' => 'taxonomy_orphanage_batch_finished',
    'operations' => array(),
  );

  // Find all the taxonomy reference fields.
  $fields = field_info_fields();
  foreach ($fields as $field) {
    if ($field['type'] != 'taxonomy_term_reference') {
      continue;
    }
    $batch['operations'][] = array(
      'taxonomy_orphanage_batch_roundup', array($field, $limit, $display_finished),
    );
  }

  batch_set($batch);

  if (!$progressive) {
    $batch =& batch_get();
    $batch['progressive'] = FALSE;
  }

  batch_process();
}

