<?php
/*
Plugin Name: Field Resetter
Description: Adds an advanced command to section list views to reset a field on all records
Version: 1.00
Requires at least: 2.03
*/

// Add the names of tables and fields, and the value to reset them to, to the following array.
// For example, to add a command to set the field 'available' to '0' on the table 'products'
// would look like this:
//   $GLOBALS['FIELD_RESET_FIELDS'] = array( 
//         array( 'tableName' => 'products', 'fieldName' => 'available', 'resetValue' => 0 )
//   );
$GLOBALS['FIELD_RESET_FIELDS'] = array( 
);



// DON'T UPDATE ANYTHING BELOW THIS LINE
addFilter( 'list_advancedCommands', '_fieldReset_addCommands', null, 1 );
addAction( 'section_unknownAction', '_fieldReset_handleReset', null, 2 );
addAction( 'init_complete', '_fieldReset_modal', null, null );

function _fieldReset_addCommands( $labelsToValues ) {
  global $CURRENT_USER;
  if ( !$CURRENT_USER['isAdmin'] ) return;

  $tableName = $_REQUEST['menu'];
  $i=0;
  foreach( $GLOBALS['FIELD_RESET_FIELDS'] as $field ) {
    if ( $field['tableName'] == $tableName ) {
      $label = "Set '{$field['fieldName']}' on all records to {$field['resetValue']}";
      $labelsToValues[ $label ] = "reset_" . $i;
    }
    $i++;
  }

  return $labelsToValues;
}

function _fieldReset_handleReset( $tableName, $action ) {
  if ( strpos( $action, 'reset' ) !== 0 ) return;

  $parts = preg_split( '!_!', $action );
  $field = $GLOBALS['FIELD_RESET_FIELDS'][ (int)$parts[1] ];

  global $TABLE_PREFIX;
  $query = "UPDATE {$TABLE_PREFIX}{$field['tableName']} SET {$field['fieldName']} = '" . mysql_escape( $field['resetValue'] ) . "'";
  mysql_query( $query ) or die( mysql_error()  );
  
  header( 'Location: admin.php?_fieldReset=' . $field['fieldName'] . '&menu=' . $tableName );
}

function _fieldReset_modal() {
  if ( @$_REQUEST['_fieldReset'] ) {
    global $APP;
    $APP['notices'] = 'All ' . $_REQUEST['_fieldReset'] . ' values reset';
  }
}
?>
