<?php
// $Id$

/**
 * @file
 * This module enables you to make Menu Settings required on specific content types
 *
 * It forces a node from one or more content types to be included in the menu system 
 * before the content will be saved successfully. This can be useful in a number of 
 * situations, e.g. when using [menupath-raw] in the pathauto settings, which expects
 * a node to live in the menu system. This module makes sure it does.
 * 
 * Based on the PHP snippet of @Keyz (http://drupal.org/node/466620)
 */

/**
* Implementation of hook_form_alter().
*/
function menu_force_form_alter(&$form, &$form_state, $form_id) {
  
  if ($form_id == 'node_type_form') {
    // If we already use the Menu Settings per Content Type module, we 
    // re-use their fieldset. If not, make the fieldset mandatory
    if (!module_exists('ctm')) {
      $form['menu_settings'] = array(
        '#type' => 'fieldset',
        '#title' => t('Menu Settings'),
        '#collapsible' => TRUE,
        '#collapsed' => !variable_get('menu_force_' . $form['#node_type']->type, FALSE),
      );
    }
    else {
      $form['menu_settings']['#description'] = t('Menu Settings for this content type.');
    }
    $form['menu_settings']['menu_force'] = array(
      '#type' => 'checkbox',
      '#title' => t('Make the Menu Settings mandatory for this content type.'),
      '#description' => t('Enabling this will force the user to add the node to the menu system.'),
      '#default_value' => variable_get('menu_force_' . $form['#node_type']->type, FALSE),
    );
    $form['#submit'][] = 'menu_force_node_type_form_submit';
  }
  
  // If the menu settings have been forced, alter the form add/edit form
  $node_types = node_get_types();
  foreach ($node_types as $type) {
    if ($form_id == $type->type . '_node_form') {
      if (variable_get('menu_force_' . $type->type, FALSE)) {
        // Make the menu fieldset expanded by default so it won't need to be opened.
        $form['menu']['#collapsed'] = FALSE;

        // Make the entry required
        $form['menu']['link_title']['#required'] = TRUE;
        $form['menu']['link_title']['#description'] = t('The link text corresponding to this item that should appear in the menu.');
      }
    }
  }
}

/**
 *  Saves the menu_force settings when a content type form has been submitted
 */
function menu_force_node_type_form_submit(&$form, $form_state) {
  $force_menu = $form_state['values']['menu_force'];
  if ($force_menu) {
    variable_set('menu_force_' . $form_state['values']['type'], TRUE);
  }
  else {
    variable_del('menu_force_' . $form_state['values']['type']);
  }
}

/**
 *  Delete the menu_force setting when a content type is deleted
 */
function menu_force_type_delete_confirm(&$form, $form_state) {
  variable_del('menu_force_' . $form_state['values']['type']);
}