content_admin.inc 59.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
<?php
// $Id$

/**
 * @file
 * Administrative interface for content type creation.
 */


/**
 * Menu callback; presents a listing of content types.
 */
function _content_admin_type_overview() {
John Hwang's avatar
John Hwang committed
14
  $types = content_types();
15 16 17 18 19

  $header = array(t('Label'), t('Name'), t('Description'), array('data' => t('Operations'), 'colspan' => 3));
  $rows = array();
  foreach ($types as $type) {
    $row = array();
John Hwang's avatar
John Hwang committed
20 21 22
    $row[] = l(t($type['label']), 'admin/node/types/'. $type['type_name'] .'/fields');
    $row[] = $type['type_name'];
    $row[] = $type['description'];
23

John Hwang's avatar
John Hwang committed
24 25 26
    $row[] = l(t('edit'), 'admin/node/types/'. $type['type_name']);
    $row[] = l(t('duplicate'), 'admin/node/types/'. $type['type_name'] .'/duplicate');
    $row[] = l(t('delete'), 'admin/node/types/'. $type['type_name'] .'/delete');
27 28 29 30 31 32 33 34 35 36 37 38 39

    $rows[] = $row;
  }

  $output = theme('table', $header, $rows);

  return $output;
}

/**
 * Menu callback; lists all defined fields for quick reference.
 */
function _content_admin_type_fields() {
John Hwang's avatar
John Hwang committed
40
  $fields = content_fields();
41 42 43 44 45 46 47 48 49

  $header = array(t('Name'), t('Type'), t('Content types'));
  $rows = array();
  foreach ($fields as $field) {
    $row = array();
    $row[] = $field['field_name'];
    $row[] = $field['type'];

    $types = array();
50
    $result = db_query("SELECT nt.label FROM {node_field_instance} nfi LEFT JOIN {node_type_content} nt ON nt.type_name = nfi.type_name WHERE nfi.field_name = '%s' ORDER BY nt.label ASC", $field['field_name']);
John Hwang's avatar
John Hwang committed
51 52
    while ($type = db_fetch_array($result)) {
      $types[] = $type['label'];
53
    }
54
    $row[] = implode(', ', $types);
55 56 57 58 59 60 61 62 63 64 65 66 67

    $rows[] = $row;
  }

  $output = theme('table', $header, $rows);

  return $output;
}

/**
 * Menu callback; handles the editing of a content type.
 */
function _content_admin_type_edit($type_name = '', $original_type_name = '') {
John Hwang's avatar
John Hwang committed
68
  $types = content_types();
69 70 71 72 73 74 75 76
  if (isset($types[$type_name])) {
    $type = $types[$type_name];
  }
  else {
    if (isset($types[$original_type_name])) {
      $type = $types[$original_type_name];
    }
    else {
John Hwang's avatar
John Hwang committed
77 78 79 80 81
      $type = array();
      $type['label'] = '';
      $type['description'] = '';
      $type['help'] = '';
      $type['title_label'] = 'Title';
82 83 84 85 86 87 88
    }
  }

  $form = array();
  $form['label'] = array(
    '#title' => t('Label'),
    '#type' => 'textfield',
John Hwang's avatar
John Hwang committed
89
    '#default_value' => $type['label'],
90 91 92 93 94 95
    '#description' => t('The human-readable name of this content type.'),
    '#required' => TRUE,
  );
  $form['description'] = array(
    '#title' => t('Description'),
    '#type' => 'textarea',
John Hwang's avatar
John Hwang committed
96
    '#default_value' => $type['description'],
97 98 99 100 101 102 103
    '#rows' => 10,
    '#description' => t('A brief description of the content type.'),
    '#required' => FALSE,
  );
  $form['help'] = array(
    '#title' => t('Help text'),
    '#type' => 'textarea',
John Hwang's avatar
John Hwang committed
104
    '#default_value' => $type['help'],
105 106 107 108 109 110 111
    '#rows' => 10,
    '#description' => t('Instructions to present to the user when adding new content of this type.'),
    '#required' => FALSE,
  );
  $form['title_label'] = array(
    '#title' => t('Title field label'),
    '#type' => 'textfield',
John Hwang's avatar
John Hwang committed
112
    '#default_value' => $type['title_label'],
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
    '#description' => t('The label for the title field.'),
    '#required' => TRUE,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save content type'),
  );
  $form['type_name'] = array(
    '#type' => 'value',
    '#value' => $type_name,
  );
  $form['original_type_name'] = array(
    '#type' => 'value',
    '#value' => $original_type_name,
  );
  return drupal_get_form('_content_admin_type_edit', $form);
}

/**
 * Save a content type after editing.
 */
function _content_admin_type_edit_submit($form_id, $form_values) {
John Hwang's avatar
John Hwang committed
135
  $types = content_types();
136 137 138 139 140 141
  if (!isset($types[$form_values['type_name']])) {
    // Find a valid, computer-friendly type name.
    $form_values['type_name'] = trim($form_values['label']);
    $form_values['type_name'] = drupal_strtolower($form_values['type_name']);
    $form_values['type_name'] = str_replace(array(' ', '-'), '_', $form_values['type_name']);
    $form_values['type_name'] = preg_replace('/[^a-z0-9_]/', '', $form_values['type_name']);
142
    $form_values['type_name'] = 'content_'. $form_values['type_name'];
143 144 145 146 147 148 149 150 151
    $form_values['type_name'] = substr($form_values['type_name'], 0, 32);
    if (isset($types[$form_values['type_name']])) {
      $counter = 0;
      do {
        $new_name = substr($form_values['type_name'], 0, 30) .'_'. $counter++;
      } while (isset($types[$new_name]));
      $form_values['type_name'] = $new_name;
    }

152
    db_query("INSERT INTO {node_type_content} (type_name, label, description, help, title_label) VALUES ('%s', '%s', '%s', '%s', '%s')", $form_values['type_name'], $form_values['label'], $form_values['description'], $form_values['help'], $form_values['title_label']);
JonBob's avatar
JonBob committed
153 154 155 156

    switch ($GLOBALS['db_type']) {
      case 'mysql':
      case 'mysqli':
157
        db_query("CREATE TABLE {node_". $form_values['type_name'] ."} (
JonBob's avatar
JonBob committed
158 159 160
            vid int unsigned NOT NULL default '0',
            nid int unsigned NOT NULL default '0',
            PRIMARY KEY (vid)
161
          ) /*!40100 DEFAULT CHARACTER SET utf8 */");
JonBob's avatar
JonBob committed
162 163 164
        break;

      case 'pgsql':
165
        db_query("CREATE TABLE {node_". $form_values['type_name'] ."} (
166 167
            vid integer NOT NULL default '0' CHECK (vid >= 0),
            nid integer NOT NULL default '0' CHECK (nid >= 0),
JonBob's avatar
JonBob committed
168 169 170
            PRIMARY KEY (vid)
          )");
        break;
171
    }
172 173
  }
  else {
174
    db_query("UPDATE {node_type_content} SET label = '%s', description = '%s', help = '%s', title_label = '%s' WHERE type_name = '%s'", $form_values['label'], $form_values['description'], $form_values['help'], $form_values['title_label'], $form_values['type_name']);
175 176
  }

177
  if ($form_values['original_type_name'] > '') {
178

179
    // Duplicate the field structure from the old content type.
180 181 182 183
    $info   = _content_type_info();
    $fields = array_keys($info['content types'][$form_values['original_type_name']]['fields']);
    foreach ($fields as $field) {
      $field_values = array('field_name' => $field, 'type_name' => $form_values['type_name']);
184
      // using this function will both create new field instances
185 186 187
      // and move existing fields to separate shared table, if not already shared
      _content_admin_field_add_existing_submit('_content_admin_field_add_existing', $field_values);
    }
188 189 190
    if (module_exist('fieldgroup')) {
      fieldgroup_duplicate($form_values['original_type_name'], $form_values['type_name']);
    }
191 192 193 194 195 196 197
  }

  drupal_set_message(t('Saved content type %type.', array('%type' => theme('placeholder', $form_values['label']))));

  content_clear_type_cache();
  menu_rebuild();

198
  return 'admin/node/types/'. $form_values['type_name'];
199 200 201 202 203 204
}

/**
 * Menu callback; delete a content type.
 */
function _content_admin_type_delete($type_name = '') {
John Hwang's avatar
John Hwang committed
205
  $type = content_types($type_name);
206 207 208

  $form = array();
  $form['type_name'] = array('#type' => 'value', '#value' => $type_name);
John Hwang's avatar
John Hwang committed
209
  return confirm_form('_content_admin_type_delete', $form, t('Are you sure you want to delete the content type %type?', array('%type' => theme('placeholder', $type['label']))), 'admin/node/types', t('If you have any content left in this content type, it will be permanently deleted. This action cannot be undone.'), t('Delete'), t('Cancel'));
210 211 212 213 214 215
}

/**
 * Delete a content type.
 */
function _content_admin_type_delete_submit($form_id, $form_values) {
John Hwang's avatar
John Hwang committed
216
  $type = content_types($form_values['type_name']);
217 218

  if ($type && $form_values['confirm']) {
219
    include_once('./'. drupal_get_path('module', 'content') .'/content_crud.inc');
220
    content_type_delete($form_values);
John Hwang's avatar
John Hwang committed
221
    drupal_set_message(t('Deleted content type %type.', array('%type' => theme('placeholder', $type['label']))));
222
    return 'admin/node/types';
223 224 225 226 227
  }
}

/**
 * Menu callback; presents a listing of fields for a content type.
228
 *
229 230 231
 * Form includes form widgets to set weight and group for each item
 * and displays other form elements and their weights to make it
 * easier to place CCK fields in the form and see where they will appear.
232 233
 */
function _content_admin_field_overview($type_name) {
234 235 236 237 238 239
  return drupal_get_form('content_admin_field_overview_form', content_admin_field_overview_form($type_name));
}

function content_admin_field_overview_form($type_name) {
  $form = array();

John Hwang's avatar
John Hwang committed
240
  $type = content_types($type_name);
241
  $field_types = _content_field_types();
242

243 244
  // Create a dummy node and form and call hook_form_alter()
  // to produce an array of fields and weights added to the node by all modules.
245
  $dummy_node = new stdClass();
246 247 248 249 250 251 252
  $dummy_node->type = $type['type_name'];
  $dummy_form_id = $type['type_name'] .'_node_form';
  $dummy_form = node_form_array($dummy_node);
  foreach (module_implements('form_alter') as $module) {
    $function = $module .'_form_alter';
    $function($dummy_form_id, $dummy_form);
  }
253

254 255 256 257 258 259 260 261 262 263 264 265 266 267
  // Move group fields into a 'fields' subgroup to make them easier to identify.
  // Remove fields that are used in groups from the form, the group will handle them.
  if (module_exist('fieldgroup')) {
    $form['#groups']       = fieldgroup_groups($type['type_name']);
    $form['#group_labels'] = _fieldgroup_groups_label($type['type_name']);
    if (!$form['#groups']) {
      drupal_set_message(t('There are no groups configured for this content type.'));
    }
    foreach ($form['#groups'] as $group) {
      foreach ($group['fields'] as $field_name => $field) {
        unset($dummy_form[$field_name]);
      }
    }
  }
268

269 270 271
  if (!$type['fields']) {
    drupal_set_message(t('There are no fields configured for this content type.'));
  }
272

273 274 275
  if (!$type['fields'] && !$form['#groups']) {
    return $form;
  }
276

277
  $form['disabled']['#value'] = array();
278

279 280 281
  // Iterate through the dummy form and add top-level fields and weights to a table.
  // Construct the table values in an array '#table' that FAPI will ignore, keyed on the item's weight.
  // Create separate form elements for each weight and group value and put a placeholder for each in #table.
282

283
  foreach ($dummy_form as $key => $value) {
284

285 286 287 288
    // Limiting weight to < 10 will keep workflow and submit elements from being added to the overview table.
    // They're outside the weight range allowed for CCK fields, so won't interfere with field placement.

    if (is_array($value) && (isset($value['#weight']) || $key == 'body_filter') && $value['#weight'] <= 10) {
289

290
      // if this item is a group, insert group info into table, then add all the group fields below it
291
      if (substr($key, 0, 6) == 'group_' && isset($form['#groups'])) {
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
        $row = $group_form = array();
        $row['label']     = $form['#group_labels'][$form['#groups'][$key]['group_name']];
        $row['name']      = $form['#groups'][$key]['group_name'];
        $row['type']      = t('group');
        $row['weights']   = 'form-group-weights';
        $row['groups']    = '';
        $row['configure'] = l(t('configure'), 'admin/node/types/'. $type['type_name'] .'/groups/'. $form['#groups'][$key]['group_name'] .'/edit');
        $row['remove']    = l(t('remove'), 'admin/node/types/'. $type['type_name'] .'/groups/'. $form['#groups'][$key]['group_name'] .'/remove');
        $data = $row;

        $form['group-weights'][$key] = array('#type' => 'weight', '#default_value' => $value['#weight']);
        foreach ($form['#groups'][$key]['fields'] as $field_name => $field) {
          $row = array();
          $field = $type['fields'][$field_name];
          $row['label']     = $field['widget']['label'];
          $row['name']      = $field['field_name'];
          $row['type']      = $field_types[$field['type']]['label'];
          $row['weights']   = 'form-field-weights';
          $row['groups']    = 'form-field-groups';
          $row['configure'] = l(t('configure'), 'admin/node/types/'. $type['type_name'] .'/fields/'. $field_name);
          $row['remove']    = l(t('remove'), 'admin/node/types/'. $type['type_name'] .'/fields/'. $field_name .'/remove');
          $group_form[$field['widget']['weight']][] = array($field_name => $row);

          $form['field-weights'][$field_name] = array('#type' => 'weight', '#default_value' => $field['widget']['weight']);
          $form['field-groups'][$field_name]  = array('#type' => 'select', '#options' => $form['#group_labels'], '#default_value' => fieldgroup_get_group($type['type_name'], $field_name));
          $form['field-groups-defaults'][$field_name]  = array('#type' => 'hidden', '#value' => fieldgroup_get_group($type['type_name'], $field_name));
        }
        // sort the group fields by weight
        ksort($group_form);
        $group = (array) $data + array('fields' => $group_form);
        $form['#table'][$value['#weight']][] = array($key => $group);
      }
324

325 326 327 328 329 330 331 332 333 334 335 336 337 338
      // else if this item is a top-level field, insert field row into the table
      elseif (substr($key, 0, 6) == 'field_') {
        $row = array();
        $field = $type['fields'][$key];
        $row['label']     = $field['widget']['label'];
        $row['name']      = $field['field_name'];
        $row['type']      = $field_types[$field['type']]['label'];
        $row['weights']   = 'form-field-weights';
        if (isset($form['#groups'])) {
          $row['groups']  = 'form-field-groups';
        }
        $row['configure'] = l(t('configure'), 'admin/node/types/'. $type['type_name'] .'/fields/'. $key);
        $row['remove']    = l(t('remove'), 'admin/node/types/'. $type['type_name'] .'/fields/'. $key .'/remove');
        $form['#table'][$field['widget']['weight']][] = array($key => $row);
339

340 341 342 343 344
        $form['field-weights'][$key] = array('#type' => 'weight', '#default_value' => $field['widget']['weight']);
        if (isset($form['#groups'])) {
          $form['field-groups'][$key]  = array('#type' => 'select', '#options' => $form['#group_labels'], '#default_value' => fieldgroup_get_group($type['type_name'], $key));
        }
      }
345

346 347 348 349 350 351 352 353 354 355 356 357 358
      // otherwise this is some other form field or fieldset
      // if it has a weight display it as a disabled item
      else {
        $row = array();
        $row['label']     = $key == 'body_filter' ? t('body') : $key;
        $row['name']      = $key;
        $row['type']      = $key;
        $row['weights']   = 'form-field-weights';
        if (isset($form['#groups'])) {
          $row['groups']  = '';
        }
        $row['configure'] = '';
        $row['remove']    = '';
359
        $form['#table'][$value['#weight']][] = array($key => $row);
360
        $form['disabled']['#value'][] = $key;
361

362 363 364
        $form['field-weights'][$key] = array('#type' => 'weight', '#default_value' => $value['#weight'], '#attributes' => array('disabled' => 'disabled'));
      }
    }
365
  }
366

367 368
  // sort the table by weight
  ksort($form['#table']);
369

370 371 372 373 374 375 376 377 378 379
  // add submit buttons and hidden fields
  $form['submit']                         = array('#type' => 'submit', '#value' => t('Update'));
  $form['field-weights']['#tree']         = TRUE;
  $form['group-weights']['#tree']         = TRUE;
  $form['field-groups']['#tree']          = TRUE;
  $form['field-groups-defaults']['#tree'] = TRUE;
  $form['disabled']['#type']              = 'hidden';
  $form['disabled']['#value']             = serialize($form['disabled']['#value']);
  $form['type_name']['#type']             = 'hidden';
  $form['type_name']['#value']            = $type['type_name'];
380

381
  return $form;
382

383
}
384

385 386 387 388
/**
 *  Theme the field overview table by iterating through the form and rendering form elements in table cells
 */
function theme_content_admin_field_overview_form($form) {
389

390 391
  if (!$form['#table']) {
    return;
392 393
  }

394
  $disabled = unserialize($form['disabled']['#value']);
395

396 397 398 399 400 401 402 403
  if (module_exist('fieldgroup')) {
    $header = array(t('Label'), t('Name'), t('Type'), t('Weight'), t('Group'), array('data' => t('Operations'), 'colspan' => 2));
    $colspan = 7;
  }
  else {
    $header = array(t('Label'), t('Name'), t('Type'), t('Weight'), array('data' => t('Operations'), 'colspan' => 2));
    $colspan = 6;
  }
404

405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
  $rows = array();
  $i = 0;

  // The table was created in the form
  // iterate through it and render form elements when placeholders are encountered
  // then run the rows array through theme_table().
  foreach ($form['#table'] as $weight => $frow) {
    foreach ($frow as $delta => $item) {
      foreach ($item as $fname => $field) {
        $row = array();
        $class = 'content-field-overview-enabled';
        if (in_array($fname, $disabled)) {
          $class = 'content-field-overview-disabled';
        }
        foreach ($field as $col => $cell) {
          // display cols other than the group 'fields' col
          if ($col != 'fields') {
            switch ($cell) {
            case 'form-field-weights':
              $row[] = form_render($form['field-weights'][$fname]);
              break;
            case 'form-group-weights':
              $row[] = form_render($form['group-weights'][$fname]);
              break;
            case 'form-field-groups':
              $row[] = form_render($form['field-groups'][$fname]);
              break;
            default:
              $row[] = array('data' => $cell, 'class' => $class);
            }
          }
436

437 438 439 440
          elseif (isset($form['#groups'])) {
            // if this form contains groups info and this is a group 'fields' col, finish the previous row
            // then theme the 'fields' col with a fieldset containing a table and the group fields
            $grows = array();
441

442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
            if (!empty($cell)) {
              foreach ($cell as $gweight => $grow) {
                foreach ($grow as $gdelta => $gitem) {
                  foreach ($gitem as $gname => $gfield) {
                    $grow = array();
                    foreach ($gfield as $gcol => $gcell) {
                      switch ($gcell) {
                        case 'form-field-weights':
                          $grow[] = form_render($form['field-weights'][$gname]);
                          break;
                        case 'form-field-groups':
                          $grow[] = form_render($form['field-groups'][$gname]);
                          break;
                        default:
                          $grow[] = $gcell;
                      }
                    }
                    $grows[] = array('data' => $grow, 'class' => 'content-field-overview-enabled');
                  }
                }
              }
            }
            else {
              $grows[] = array(array('data' => t('No fields have been added to this group.'), 'colspan' => $colspan, 'class' => 'content-field-overview-empty'));
            }
467

468 469 470 471 472 473 474 475 476
            // add the group row in its own table above the group fields table, then reset $row().
            $fieldset = array(
              '#title' => t('!label (!name)', array('!label' => $form['#group_labels'][$fname], '!name' => $fname)),
              '#collapsible' => TRUE,
              '#collapsed' => FALSE,
              '#value' => theme('table', array(), array(array('data' => $row, 'class' => 'content-field-overview-group'))) . theme('table', $header, $grows),
              );
            $row = array();
            $row[] = array(
477 478
              'data' => theme('fieldset', $fieldset),
              'colspan' => $colspan,
479 480 481 482 483 484 485 486 487 488 489
              'class' => 'active',
              );
            $grows = array();
          }
        }
        $rows[] = $row;
      }
    }
  }
  $output  = theme('table', $header, $rows, array('class' => 'content-field-overview'));
  $output .= form_render($form);
490
  return $output;
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511

}

function content_admin_field_overview_form_submit($form_id, $form_values) {
  $msg = FALSE;
  foreach ((array) $form_values['field-groups'] as $key => $value) {
    if ($key && !in_array($key, unserialize($form_values['disabled']))) {
      $values  = array('field_name' => $key, 'group' => $value, 'type_name' => $form_values['type_name']);
      $default = $form_values['field-groups-defaults'][$key];
      fieldgroup_content_admin_form_submit('_content_admin_field', $values, $default);
      $msg = TRUE;
    }
  }
  if ($msg) {
    drupal_set_message(t('Updated field groups.'));
  }
  $msg = FALSE;
  foreach ((array) $form_values['group-weights'] as $key => $value) {
    if ($key && !in_array($key, unserialize($form_values['disabled']))) {
      db_query("UPDATE {node_group} SET weight = %d WHERE type_name = '%s' AND group_name = '%s'",
        $value, $form_values['type_name'], $key);
512
      $msg = TRUE;
513 514 515 516 517 518 519 520
    }
  }
  if ($msg) {
    drupal_set_message(t('Updated group weights.'));
  }
  $msg = FALSE;
  foreach ((array) $form_values['field-weights'] as $key => $value) {
    if ($key && !in_array($key, unserialize($form_values['disabled']))) {
521
      db_query("UPDATE {node_field_instance} SET weight = %d WHERE type_name = '%s' AND field_name = '%s'",
522 523 524 525 526 527 528 529 530 531
        $value, $form_values['type_name'], $key);
      $msg = TRUE;
    }
  }
  if ($msg) {
    drupal_set_message(t('Updated field weights.'));
  }
  content_clear_type_cache();
  cache_clear_all('fieldgroup_data');

532 533
}

534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
/**
 * Menu callback; presents a listing of fields display settings for a content type.
 *
 * Form includes form widgets to select which fields appear for teaser, full node...
 * and how the field labels should be rendered
 */
function content_admin_display_overview_form($type_name) {
  $type = content_types($type_name);
  $field_types = _content_field_types();

  $form = array();
  if (empty($type['fields'])) {
    drupal_set_message(t('There are no fields configured for this content type.'));
    return $form;
  }

  $form['#tree'] = TRUE;
  foreach ($type['fields'] as $field) {
    $form['fields'][$field['field_name']] = _content_admin_display_overview_row($field, $field_types[$field['type']]);
  }

  $form['type_name'] = array('#type' => 'hidden', '#value' => $type['type_name']);
  $form['submit'] = array('#type' => 'submit', '#value' => t('Submit'));

  return drupal_get_form('content_admin_display_overview_form', $form);
}

function theme_content_admin_display_overview_form($form) {
  $header = array(t('Field'), t('Type'), t('Label'));
  foreach (_content_admin_display_contexts() as $key => $title) {
    $header[] = $title;
  }
  $rows = array();

  foreach (element_children($form['fields']) as $field) {
    $row = array();
    foreach (element_children($form['fields'][$field]) as $key) {
      $row[] = form_render($form['fields'][$field][$key]);
    }
    $rows[] = $row;
  }

  $output  = theme('table', $header, $rows, array('class' => 'content-field-display-overview'));
  $output .= form_render($form);
  return $output;
}

function content_admin_display_overview_form_submit($form_id, $form_values) {
  $type = $form_values['type_name'];
  foreach ($form_values['fields'] as $fieldname => $fieldvalues) {
    $display_settings = array();
    foreach ($fieldvalues as $key => $value) {
      $display_settings[$key] = $value;
    }

    db_query("UPDATE {node_field_instance} SET display_settings = '%s' WHERE type_name = '%s' AND field_name = '%s'",
      serialize($display_settings), $form_values['type_name'], $fieldname);
  }
592
  drupal_set_message(t('Your settings have been saved.'));
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
  content_clear_type_cache();
}

function _content_admin_display_overview_row($field, $field_type) {
  $defaults = $field['display_settings'];

  $options = array();
  foreach ($field_type['formatters'] as $name => $formatter_info) {
    $options[$name] = $formatter_info['label'];
  }
  $options['hidden'] = t('<Hidden>');

  $label_options = array(
    'above' => t('Above'),
    'inline' => t('Inline'),
    'hidden' => t('<Hidden>'),
  );

  $row = array();
  $row['type_label']  = array('#value' => $field['widget']['label']);
  $row['type']        = array('#value' => $field_type['label']);

  $row['label']['format'] = array(
    '#type' => 'select',
    '#options' => $label_options,
    '#default_value' => isset($defaults['label']['format']) ? $defaults['label']['format'] : 'above',
  );

  foreach (_content_admin_display_contexts() as $key => $title) {
    $row[$key]['format'] = array(
      '#type' => 'select',
      '#options' => $options,
      '#default_value' => isset($defaults[$key]['format']) ? $defaults[$key]['format'] : 'default',
    );
  }
  return $row;
}

function _content_admin_display_contexts() {
  return array(
    'teaser' => t('Teaser'),
    'full' => t('Full'),
  );
}

638 639 640 641
/**
 * Menu callback; presents the form for adding a new field.
 */
function _content_admin_field_add($type_name) {
642 643 644 645 646
  // make sure the old field list gets cleared before creating the new one
  if (!isset($_POST['edit'])) {
    content_clear_type_cache();
  }

John Hwang's avatar
John Hwang committed
647
  $type = content_types($type_name);
648
  $field_types = _content_field_types();
John Hwang's avatar
John Hwang committed
649
  $fields = content_fields();
650 651 652 653 654
  $widget_types = _content_widget_types();
  $output = '';

  $options = array();
  foreach ($fields as $field) {
John Hwang's avatar
John Hwang committed
655
    if (!isset($type['fields'][$field['field_name']]))
656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
    $options[$field['field_name']] = t($field['widget']['label']) .' ('. $field['field_name'] .')';
  }
  if ($options) {
    $form = array();
    $form['existing'] = array(
      '#type' => 'fieldset',
      '#title' => t('Add existing field'),
    );
    $form['existing']['field_name'] = array(
      '#type' => 'select',
      '#required' => TRUE,
      '#options' => $options,
    );
    $form['existing']['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Add field'),
    );
    $form['existing']['type_name'] = array(
      '#type' => 'value',
      '#value' => $type_name,
    );
    $output .= drupal_get_form('_content_admin_field_add_existing', $form);
  }

  $field_type_options = array();
  foreach ($field_types as $field_name => $field_type) {
    foreach ($widget_types as $widget_name => $widget_type) {
      if (in_array($field_name, $widget_type['field types'])) {
        $field_type_options[$field_name .'-'. $widget_name] = $widget_type['label'];
      }
    }
  }
  if (count($field_type_options) > 0) {
    $form = array();
    $form['new'] = array(
      '#type' => 'fieldset',
      '#title' => t('Create new field'),
    );
    $form['new']['widget']['label'] = array(
695
      '#title' => t('Name'),
696 697
      '#type' => 'textfield',
      '#default_value' => '',
698
      '#description' => t('The machine-readable name of the field.<br/>Allowed characters : unaccentuated a-z, numbers and _. All other characters will be discarded.<br/>You\'ll be able to choose a human-readable label for the field on next page'),
699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
      '#required' => TRUE,
    );
    $form['new']['field_widget_type'] = array(
      '#type' => 'radios',
      '#title' => t('Field type'),
      '#required' => TRUE,
      '#options' => $field_type_options,
      '#theme' => 'content_admin_field_add_new_field_widget_type',
    );

    $form['new']['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Create field'),
    );
    $form['new']['type_name'] = array(
      '#type' => 'value',
      '#value' => $type_name,
    );
    $output .= drupal_get_form('_content_admin_field_add_new', $form);
  }
  else {
    drupal_set_message(t('No field modules are enabled. You need to <a href="%modules_url">enable one</a>, such as text.module, before you can add new fields.', array('%modules_url' => url('admin/modules'))), 'error');
  }

  return $output;
}

function theme_content_admin_field_add_new_field_widget_type($form) {
  $field_types = _content_field_types();
  $widget_types = _content_widget_types();
  $output = '';

  $output .= '<dl>';
  foreach ($field_types as $field_name => $field_type) {
    $output .= '<dt>'. $field_type['label'] .'</dt>';
    foreach ($widget_types as $widget_name => $widget_type) {
      if (in_array($field_name, $widget_type['field types'])) {
        $output .= '<dd>'. form_render($form[$field_name .'-'. $widget_name]) .'</dd>';
      }
    }
  }
  $output .= '</dl>';

  return $output;
}

/**
 * Add an existing field to a content type.
 */
function _content_admin_field_add_existing_submit($form_id, $form_values) {
John Hwang's avatar
John Hwang committed
749
  $field = content_fields($form_values['field_name']);
JonBob's avatar
JonBob committed
750 751 752 753 754 755 756 757 758 759 760 761 762
  $field_types = _content_field_types();
  $field_type = $field_types[$field['type']];
  $columns = module_invoke($field_type['module'], 'field_settings', 'database columns', $field);

  if (is_array($columns) && count($columns)) {
    if ($field['db_storage'] == CONTENT_DB_STORAGE_PER_CONTENT_TYPE) {
      $new_field = $field;
      $new_field['db_storage'] = CONTENT_DB_STORAGE_PER_FIELD;
      db_query("UPDATE {node_field} SET db_storage = %d WHERE field_name = '%s'", CONTENT_DB_STORAGE_PER_FIELD, $form_values['field_name']);
      content_alter_db_field($field, $columns, $new_field, $columns);
    }
  }

763
  $prior_instance = db_fetch_array(db_query("SELECT * FROM {node_field_instance} WHERE field_name = '%s'", $form_values['field_name']));
764
  if (!$prior_instance) {
John Hwang's avatar
John Hwang committed
765 766 767 768 769
    $prior_instance = array();
    $prior_instance['weight'] = 0;
    $prior_instance['label'] = $form_values['field_name'];
    $prior_instance['widget_type'] = '';
    $prior_instance['widget_settings'] = '';
770
    $prior_instance['display_settings'] = '';
John Hwang's avatar
John Hwang committed
771
    $prior_instance['description'] = '';
772
  }
773
  db_query("INSERT INTO {node_field_instance} (field_name, type_name, weight, label, widget_type, widget_settings, display_settings, description) VALUES ('%s', '%s', %d, '%s', '%s', '%s', '%s', '%s')", $form_values['field_name'], $form_values['type_name'], $prior_instance['weight'], $prior_instance['label'], $prior_instance['widget_type'], $prior_instance['widget_settings'], $prior_instance['display_settings'], $prior_instance['description']);
774

John Hwang's avatar
John Hwang committed
775
  drupal_set_message(t('Added field %label.', array('%label' => theme('placeholder', $prior_instance['label']))));
776
  content_clear_type_cache();
777
  return 'admin/node/types/'. $form_values['type_name'] .'/fields';
778 779 780 781 782 783 784 785
}

/**
 * Create a new field for a content type.
 */
function _content_admin_field_add_new_submit($form_id, $form_values) {
  // Find a valid, computer-friendly field name.

John Hwang's avatar
John Hwang committed
786
  $fields = content_fields();
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802

  $field_name = trim($form_values['label']);
  $field_name = drupal_strtolower($field_name);
  $field_name = str_replace(array(' ', '-'), '_', $field_name);
  $field_name = preg_replace('/[^a-z0-9_]/', '', $field_name);
  $field_name = 'field_'. $field_name;
  $field_name = substr($field_name, 0, 31);
  if (isset($fields[$field_name])) {
    $counter = 0;
    do {
      $new_name = substr($field_name, 0, 29) .'_'. $counter++;
    } while (isset($fields[$new_name]));
    $field_name = $new_name;
  }

  $field_widget_type = explode('-', $form_values['field_widget_type']);
JonBob's avatar
JonBob committed
803
  db_query("INSERT INTO {node_field} (field_name, type, global_settings, required, multiple, db_storage) VALUES ('%s', '%s', '%s', %d, %d, %d)", $field_name, $field_widget_type[0], serialize(array()), 0, 0, CONTENT_DB_STORAGE_PER_CONTENT_TYPE);
804
  db_query("INSERT INTO {node_field_instance} (field_name, type_name, weight, label, widget_type, widget_settings, display_settings, description) VALUES ('%s', '%s', %d, '%s', '%s', '%s', '%s', '%s')", $field_name, $form_values['type_name'], 0, $form_values['label'], $field_widget_type[1], serialize(array()), serialize(array()), '');
805 806

  content_clear_type_cache();
807 808 809 810

  // Create new database columns as necessary.
  $field_types = _content_field_types();
  $field_type = $field_types[$field_widget_type[0]];
John Hwang's avatar
John Hwang committed
811
  $field = content_fields($field_name);
JonBob's avatar
JonBob committed
812

813
  $columns = module_invoke($field_type['module'], 'field_settings', 'database columns', $field);
814 815 816
  if (is_array($columns) && count($columns)) {
    content_alter_db_field(array(), array(), $field, $columns);
  }
817 818

  drupal_set_message(t('Created field %label.', array('%label' => theme('placeholder', $form_values['label']))));
819
  return 'admin/node/types/'. $form_values['type_name'] .'/fields/'. $field_name;
820 821 822 823 824 825
}

/**
 * Menu callback; present a form for removing a field from a content type.
 */
function _content_admin_field_remove($type_name, $field_name) {
John Hwang's avatar
John Hwang committed
826 827
  $type = content_types($type_name);
  $field = $type['fields'][$field_name];
828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844

  $form = array();
  $form['type_name'] = array(
    '#type' => 'value',
    '#value' => $type_name,
  );
  $form['field_name'] = array(
    '#type' => 'value',
    '#value' => $field_name,
  );
  return confirm_form('_content_admin_field_remove', $form, t('Are you sure you want to remove the field %field?', array('%field' => theme('placeholder', $field['widget']['label']))), 'admin/node/types/'. $type_name .'/fields', t('If you have any content left in this field, it will be lost. This action cannot be undone.'), t('Remove'), t('Cancel'));
}

/**
 * Remove a field from a content type.
 */
function _content_admin_field_remove_submit($form_id, $form_values) {
John Hwang's avatar
John Hwang committed
845 846
  $type = content_types($form_values['type_name']);
  $field = $type['fields'][$form_values['field_name']];
847 848

  if ($type && $field && $form_values['confirm']) {
849
    include_once('./'. drupal_get_path('module', 'content') .'/content_crud.inc');
850
    content_field_instance_delete($form_values);
851

John Hwang's avatar
John Hwang committed
852
    drupal_set_message(t('Removed field %field from %type.', array('%field' => theme('placeholder', $field['widget']['label']), '%type' => theme('placeholder', $type['label']))));
853

854
    return 'admin/node/types/'. $form_values['type_name'] .'/fields';
855 856 857 858 859 860 861 862 863
  }
}


/**
 * Menu callback; presents the field editing page.
 */
function _content_admin_field($type_name, $field_name) {
  $output = '';
John Hwang's avatar
John Hwang committed
864 865 866

  $type = content_types($type_name);
  $field = $type['fields'][$field_name];
867 868 869 870 871 872 873 874 875
  $field_types = _content_field_types();
  $field_type = $field_types[$field['type']];
  $widget_types = _content_widget_types();
  $widget_type = $widget_types[$field['widget']['type']];

  $form = array();
  $form['widget'] = array(
    '#type' => 'fieldset',
    '#title' => t('Widget settings'),
John Hwang's avatar
John Hwang committed
876
    '#description' => t('These settings apply only to the %field field as it appears in the %type content type.', array('%field' => theme('placeholder', $field['widget']['label']), '%type' => theme('placeholder', $type['label']))),
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
  );
  $options = array();
  foreach ($widget_types as $possible_widget_name => $possible_widget_type) {
    if (in_array($field['type'], $possible_widget_type['field types'])) {
      $options[$possible_widget_name] = $possible_widget_type['label'];
    }
  }
  if (count($options) == 1) {
    $key = array_keys($options);
    $default_widget = array_pop($key);
  }
  $form['widget']['widget_type'] = array(
    '#type' => 'radios',
    '#title' => t('Widget'),
    '#options' => $options,
    '#default_value' => $field['widget']['type'] ? $field['widget']['type'] : $default_widget,
    '#required' => TRUE,
  );
  $form['widget']['label'] = array(
    '#type' => 'textfield',
    '#title' => t('Label'),
    '#default_value' => $field['widget']['label'],
    '#required' => TRUE,
  );
  $form['widget']['weight'] = array(
902 903
    '#type' => 'hidden',
    '#value' => $field['widget']['weight'],
904
  );
905 906
  $additions = module_invoke($widget_type['module'], 'widget_settings', 'form', $field['widget']);
  if (is_array($additions)) {
907 908
    $form['widget'] = array_merge($form['widget'], $additions);
  }
909

JonBob's avatar
JonBob committed
910 911 912 913 914 915 916 917
  $form['widget']['description'] = array(
    '#type' => 'textarea',
    '#title' => t('Help text'),
    '#default_value' => $field['widget']['description'],
    '#rows' => 5,
    '#description' => t('Instructions to present to the user below this field on the editing form.'),
    '#required' => FALSE,
  );
918

919
  // Add handling for default value if not provided by field.
920
  if (content_handle('widget', 'default value', $field) == CONTENT_CALLBACK_DEFAULT) {
921
    $form['#attributes'] = array("enctype" => "multipart/form-data");
922 923 924 925 926 927 928 929 930 931 932
    $form['widget']['default_value_fieldset'] = array(
      '#type' => 'fieldset',
      '#title' => t('Default value'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
    );
    $default_value = is_array($field['widget']['default_value']) ? $field['widget']['default_value'] : array();
    $module = $widget_types[$field['widget']['type']]['module'];
    $function = $module .'_widget';
    if (function_exists($function)) {
      $node = array(); // TODO are there things we need to add in here ?
933 934 935 936 937
      // Make sure the default value is not a required field.
      $widget_field = $field;
      $widget_field['required'] = FALSE;
      $function('prepare form values', $node, $widget_field, $default_value);
      $form_element = $function('form', $node, $widget_field, $default_value);
938 939 940 941 942 943 944 945 946 947 948 949
    }
    else {
      // TODO : generate a series of textfields ?
      // why would a widget not have a hook_widget implementation ?
    }
    $form['widget']['default_value_fieldset'] = array_merge($form['widget']['default_value_fieldset'], $form_element);
    $form['widget']['default_value_fieldset']['advanced_options'] = array(
      '#type' => 'fieldset',
      '#title' => t('Php code'),
      '#collapsible' => TRUE,
      '#collapsed' => !isset($field['widget']['default_value_php']),
    );
950 951 952 953 954 955
    $db_info = content_database_info($field);
    $columns = array_keys($db_info['columns']);
    foreach ($columns as $key => $column) {
      $columns[$key] = "'$column' => ...";
    }
    $sample = 'array( 0 => array('. implode(', ', $columns) .'), 1 => ...)';
956 957 958 959 960 961
    $form['widget']['default_value_fieldset']['advanced_options']['default_value_php'] = array(
      '#type' => 'textarea',
      '#title' => t('Code'),
      '#default_value' => $field['widget']['default_value_php'],
      '#rows' => 6,
      '#tree' => TRUE,
962
      '#description' => t('Advanced Usage Only: PHP code that returns a default value. Should not include &lt;?php ?&gt; delimiters.<br/>If this field is filled out, the value returned by this code will override any value in the textfield above.<br/>Expected format : @sample.', array('@sample' => $sample)),
963 964 965
    );
  }

966 967
  $form['field'] = array(
    '#type' => 'fieldset',
968
    '#title' => t('Data settings'),
969 970 971 972 973 974 975 976 977 978 979 980 981
    '#description' => t('These settings apply to the %field field in every content type in which it appears.', array('%field' => theme('placeholder', $field['widget']['label']))),
  );
  $form['field']['required'] = array(
    '#type' => 'checkbox',
    '#title' => t('Required'),
    '#default_value' => $field['required'],
  );
  $form['field']['multiple'] = array(
    '#type' => 'checkbox',
    '#title' => t('Multiple values'),
    '#default_value' => $field['multiple'],
  );

982
  $additions = module_invoke($field_type['module'], 'field_settings', 'form', $field);
983 984 985
  if (is_array($additions)) {
    $form['field'] = array_merge($form['field'], $additions);
  }
986 987 988 989 990 991 992 993 994 995 996 997 998

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save field settings'),
  );
  $form['type_name'] = array(
    '#type' => 'value',
    '#value' => $type_name,
  );
  $form['field_name'] = array(
    '#type' => 'value',
    '#value' => $field_name,
  );
999 1000 1001 1002 1003 1004 1005 1006
  $form['field_type'] = array(
    '#type' => 'value',
    '#value' => $field['type'],
    );
  $form['module'] = array(
    '#type' => 'value',
    '#value' => $field_type['module'],
    );
1007

1008
  $output .= drupal_get_form('_content_admin_field', $form);
1009

1010 1011 1012 1013 1014 1015 1016
  return $output;
}

/**
 * Validate a field's settings.
 */
function _content_admin_field_validate($form_id, $form_values) {
John Hwang's avatar
John Hwang committed
1017 1018
  $type = content_types($form_values['type_name']);
  $field = $type['fields'][$form_values['field_name']];
1019 1020 1021 1022
  $field_types = _content_field_types();
  $field_type = $field_types[$field['type']];
  $widget_types = _content_widget_types();
  $widget_type = $widget_types[$field['widget']['type']];
1023

1024 1025
  module_invoke($widget_type['module'], 'widget_settings', 'validate', array_merge($field, $form_values));
  module_invoke($field_type['module'], 'field_settings', 'validate', array_merge($field, $form_values));
1026 1027 1028

  // If the content module is handling the default value,
  // validate the result using the field validation.
1029
  if (content_handle('widget', 'default value', $field) == CONTENT_CALLBACK_DEFAULT) {
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
    if (isset($form_values['default_value_php']) && ($php = trim($form_values['default_value_php']))) {
      ob_start();
      $return = eval($php);
      ob_get_clean();
      if (!is_array($return)) {
        $error = TRUE;
      }
      else {
        foreach ($return as $item) {
          if (!is_array($item)) {
            $error = TRUE;
            break;
          }
        }
      }
      if ($error) {
1046 1047 1048 1049 1050 1051 1052
        $db_info = content_database_info($field);
        $columns = array_keys($db_info['columns']);
        foreach ($columns as $key => $column) {
          $columns[$key] = "'$column' => ...";
        }
        $sample = 'array( 0 => array('. implode(', ', $columns) .'), 1 => ...)';
        form_set_error('default_value_php', t('The default value php code returned an incorrect value<br/>Expected format : @sample<br/>Returned value : @value', array('@sample' => $sample, '@value' => print_r($return, true))));
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
        return;
      }
      else {
        $default_value = $return;
        $is_code = TRUE;
        form_set_value(array('#parents' => array('default_value_php')), $php);
        form_set_value(array('#parents' => array('default_value')), array());
      }
    }
    else {
      $default_value = $form_values[$field['field_name']];
      $is_code = FALSE;
      form_set_value(array('#parents' => array('default_value_php')), '');
      form_set_value(array('#parents' => array('default_value')), $default_value);
    }
    if (isset($default_value)) {
      $node = array();
      $node[$form_values['field_name']] = $default_value;
      $field['required'] = FALSE;
      $field_function = $field_type['module'] .'_field';
      $widget_function = $widget_type['module'] .'_widget';

      // If default_value is created from php code, don't run it through widget processing.
      // This way the default value code can directly create the correct array without being
      // mangled by widget processing which sometimes requires an input array in a completely different format.
      if (function_exists($widget_function) && !$is_code) {
        $widget_function('validate', $node, $field, $default_value);
        $widget_function('process form values', $node, $field, $default_value);
        // The widget processing may have altered the value, save it to be sure.
        form_set_value(array('#parents' => array('default_value')), $default_value);
      }
      if (function_exists($field_function)) {
        $field_function('validate', $node, $field, $default_value, NULL, NULL);
      }
      // The field validation routine won't set an error on the right field, so set it here.
      if (form_get_errors()) {
        if (trim($form_values['default_value_php'])) {
          form_set_error('default_value_php', t('The default value php code created @value which is invalid.', array('@value' => print_r($default_value, true))));
        }
        else {
          form_set_error('default_value', t('The default value is invalid.'));
        }
      }
    }
  }
1098 1099
}

1100

1101 1102 1103 1104
/**
 * Save a field's settings after editing.
 */
function _content_admin_field_submit($form_id, $form_values) {
John Hwang's avatar
John Hwang committed
1105 1106
  $type = content_types($form_values['type_name']);
  $field = $type['fields'][$form_values['field_name']];
1107 1108 1109 1110 1111
  $field_types = _content_field_types();
  $field_type = $field_types[$field['type']];
  $widget_types = _content_widget_types();
  $widget_type = $widget_types[$form_values['widget_type']];

1112 1113
  // If the content module is handling the default value,
  // Initialize $widget_settings with default values,
1114
  if (content_handle('widget', 'default value', $field) == CONTENT_CALLBACK_DEFAULT) {
1115 1116 1117 1118 1119 1120
    $widget_settings = array(
      'default_value' => $form_values['default_value'],
      'default_value_php' => $form_values['default_value_php'],
      );
  }

1121 1122
  $setting_names = module_invoke($widget_type['module'], 'widget_settings', 'save', $field);
  if (is_array($setting_names)) {
1123 1124 1125 1126
    foreach ($setting_names as $setting) {
      $widget_settings[$setting] = $form_values[$setting];
    }
  }
1127

1128
  $field_settings = array();
1129 1130
  $setting_names = module_invoke($field_type['module'], 'field_settings', 'save', $field);
  if (is_array($setting_names)) {
1131 1132 1133 1134
    foreach ($setting_names as $setting) {
      $field_settings[$setting] = $form_values[$setting];
    }
  }
1135

1136 1137
  $prev_field = $field;
  $prev_columns = module_invoke($field_type['module'], 'field_settings', 'database columns', $field);
1138

JonBob's avatar
JonBob committed
1139
  db_query("UPDATE {node_field_instance} SET weight = %d, label = '%s', widget_type = '%s', widget_settings = '%s', description = '%s' WHERE type_name = '%s' AND field_name = '%s'", $form_values['weight'], $form_values['label'], $form_values['widget_type'], serialize($widget_settings), $form_values['description'], $form_values['type_name'], $form_values['field_name']);
1140

1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
  if ($form_values['multiple']) {
    $field['db_storage'] = CONTENT_DB_STORAGE_PER_FIELD;
  }
  else {
    $instances = db_result(db_query("SELECT COUNT(*) FROM {node_field_instance} WHERE field_name = '%s'", $form_values['field_name']));
    if ($instances == 1) {
      $field['db_storage'] = CONTENT_DB_STORAGE_PER_CONTENT_TYPE;
    }
  }
  db_query("UPDATE {node_field} SET required = %d, multiple = %d, global_settings = '%s', db_storage = %d WHERE field_name = '%s'", $form_values['required'], $form_values['multiple'], serialize($field_settings), $field['db_storage'], $form_values['field_name']);
1151 1152 1153

  drupal_set_message(t('Saved field %field.', array('%field' => theme('placeholder', $form_values['label']))));
  content_clear_type_cache();
1154

John Hwang's avatar
John Hwang committed
1155
  $new_field = content_fields($form_values['field_name']);
JonBob's avatar
JonBob committed
1156
  $new_columns = module_invoke($field_type['module'], 'field_settings', 'database columns', $new_field);
1157

1158 1159 1160 1161 1162 1163
  if (!isset($prev_columns)) {
    $prev_columns = array();
  }
  if (!isset($new_columns)) {
    $new_columns = array();
  }
1164 1165
  content_alter_db_field($prev_field, $prev_columns, $new_field, $new_columns);

1166 1167 1168 1169 1170 1171 1172
  // regenerate views queries if 'multiple' status was changed
  if (module_exist('views')) {
    if ($new_field['multiple'] != $prev_field['multiple']) {
      _content_views_rebuild_views(array($new_field['field_name']));
    }
  }

1173
  return 'admin/node/types/'. $form_values['type_name'] .'/fields';
1174
}
1175 1176 1177 1178 1179 1180


/**
 * Perform adds, alters, and drops as needed to synchronize the database with
 * new field definitions.
 */
JonBob's avatar
JonBob committed
1181 1182 1183
function content_alter_db_field($previous_field, $previous_columns, $new_field, $new_columns) {
  // When adding and removing columns, we need to know what content type has an instance of the field.
  if (count($previous_columns)) {
1184 1185 1186
    if (!isset($previous_field['type_name'])) {
      $previous_field['type_name'] = db_result(db_query("SELECT type_name FROM {node_field_instance} WHERE field_name = '%s'", $previous_field['field_name']));
    }
JonBob's avatar
JonBob committed
1187 1188 1189 1190 1191
    $previous_db_info = content_database_info($previous_field);
  }
  if (count($new_columns)) {
    $new_field['type_name'] = db_result(db_query("SELECT type_name FROM {node_field_instance} WHERE field_name = '%s'", $new_field['field_name']));
    $new_db_info = content_database_info($new_field);
1192 1193
  }

JonBob's avatar
JonBob committed
1194 1195 1196 1197
  if (!count($new_columns)) {
    if (count($previous_columns)) {
      if ($previous_field['db_storage'] == CONTENT_DB_STORAGE_PER_FIELD) {
        db_query('DROP TABLE {'. $previous_db_info['table'] .'}');
1198
      }
JonBob's avatar
JonBob committed
1199 1200 1201 1202
      else {
        foreach ($previous_db_info['columns'] as $column => $attributes) {
          db_query('ALTER TABLE {'. $previous_db_info['table'] .'} DROP '. $attributes['column']);
        }
1203 1204
      }
    }
JonBob's avatar
JonBob committed
1205
    return;
1206
  }
JonBob's avatar
JonBob committed
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219

  if ($new_field['db_storage'] == CONTENT_DB_STORAGE_PER_FIELD) {
    if (!count($previous_columns) || $previous_field['db_storage'] == CONTENT_DB_STORAGE_PER_CONTENT_TYPE) {
      // New columns with per-field storage; need to add a table.
      if ($new_field['multiple']) {
        switch ($GLOBALS['db_type']) {
          case 'mysql':
          case 'mysqli':
            db_query("CREATE TABLE {". $new_db_info['table'] ."} (
                vid int unsigned NOT NULL default '0',
                delta int unsigned NOT NULL default '0',
                nid int unsigned NOT NULL default '0',
                PRIMARY KEY (vid,delta)
1220
              ) /*!40100 DEFAULT CHARACTER SET utf8 */");
JonBob's avatar
JonBob committed
1221 1222 1223 1224
            break;

          case 'pgsql':
            db_query("CREATE TABLE {". $new_db_info['table'] ."} (
1225 1226 1227
                vid integer NOT NULL default '0' CHECK(vid >= 0),
                delta integer NOT NULL default '0' CHECK(delta >= 0),
                nid integer NOT NULL default '0' CHECK(nid >= 0),
JonBob's avatar
JonBob committed
1228 1229 1230 1231
                PRIMARY KEY (vid,delta)
              )");
            break;
        }
1232
      }
JonBob's avatar
JonBob committed
1233 1234 1235 1236 1237 1238 1239 1240
      else {
        switch ($GLOBALS['db_type']) {
          case 'mysql':
          case 'mysqli':
            db_query("CREATE TABLE {". $new_db_info['table'] ."} (
                vid int unsigned NOT NULL default '0',
                nid int unsigned NOT NULL default '0',
                PRIMARY KEY (vid)
1241
              ) /*!40100 DEFAULT CHARACTER SET utf8 */");
JonBob's avatar
JonBob committed
1242 1243 1244 1245
            break;

          case 'pgsql':
            db_query("CREATE TABLE {". $new_db_info['table'] ."} (
1246 1247
                vid integer NOT NULL default '0' CHECK(vid >= 0),
                nid integer NOT NULL default '0' CHECK(nid >= 0),
JonBob's avatar
JonBob committed
1248 1249 1250 1251
                PRIMARY KEY (vid)
              )");
            break;
        }
1252 1253 1254
      }
    }

JonBob's avatar
JonBob committed
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
    if (count($previous_columns) && $previous_field['db_storage'] == CONTENT_DB_STORAGE_PER_FIELD) {
      // Already using per-field storage; change multiplicity if needed.
      if ($previous_field['multiple'] && !$new_field['multiple']) {
        db_query('DELETE FROM {'. $new_db_info['table'] .'} WHERE delta != 0');
        db_query('ALTER TABLE {'. $new_db_info['table'] .'} DROP delta');
        switch ($GLOBALS['db_type']) {
          case 'mysql':
          case 'mysqli':
            db_query('ALTER TABLE {'. $new_db_info['table'] .'} DROP PRIMARY KEY');
            db_query('ALTER TABLE {'. $new_db_info['table'] .'} ADD PRIMARY KEY (vid)');
            break;
          case 'pgsql':
            db_query('ALTER TABLE {'. $new_db_info['table'] .'} DROP CONSTRAINT {'. $new_db_info['table'] .'}_pkey');
            db_query('ALTER TABLE {'. $new_db_info['table'] .'} ADD PRIMARY KEY (vid)');
            break;
        }
      }
      else if (!$previous_field['multiple'] && $new_field['multiple']) {
        content_db_add_column($new_db_info['table'], 'delta', 'int', array('unsigned' => TRUE, 'not null' => TRUE, 'default' => 0));
        switch ($GLOBALS['db_type']) {
          case 'mysql':
          case 'mysqli':
            db_query('ALTER TABLE {'. $new_db_info['table'] .'} DROP PRIMARY KEY');
            db_query('ALTER TABLE {'. $new_db_info['table'] .'} ADD PRIMARY KEY (vid,delta)');
            break;
          case 'pgsql':
            db_query('ALTER TABLE {'. $new_db_info['table'] .'} DROP CONSTRAINT {'. $new_db_info['table'] .'}_pkey');
            db_query('ALTER TABLE {'. $new_db_info['table'] .'} ADD PRIMARY KEY (vid,delta)');
            break;
        }
      }
1286 1287
    }
  }
JonBob's avatar
JonBob committed
1288 1289

  // Add new columns and change modified columns.
1290 1291
  foreach ($new_columns as $column => $attributes) {
    $column_name = $new_field['field_name'] .'_'. $column;
JonBob's avatar
JonBob committed
1292 1293
    if (!isset($previous_columns[$column]) || $previous_field['db_storage'] != $new_field['db_storage']) {
      content_db_add_column($new_db_info['table'], $column_name, $attributes['type'], $attributes);
1294 1295 1296
    }
    else {
      if ($attributes != $previous_columns[$column]) {
JonBob's avatar
JonBob committed
1297
        content_db_change_column($new_db_info['table'], $column_name, $column_name, $attributes['type'], $attributes);
1298 1299 1300 1301
      }
    }
  }

JonBob's avatar
JonBob committed
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
  if (count($previous_columns) && count($new_columns)) {
    // Remove obsolete columns.
    foreach ($previous_columns as $column => $attributes) {
      $column_name = $previous_field['field_name'] .'_'. $column;
      if (!isset($new_columns[$column])) {
        db_query('ALTER TABLE {'. $new_db_info['table'] .'} DROP '. $column_name);
      }
    }

    // Migrate data from per-content-type storage.
    if ($previous_field['db_storage'] == CONTENT_DB_STORAGE_PER_CONTENT_TYPE && $new_field['db_storage'] == CONTENT_DB_STORAGE_PER_FIELD) {
      $columns = array();
      foreach ($previous_db_info['columns'] as $column => $attributes) {
        $columns[] = $attributes['column'];
      }
      if ($new_field['multiple']) {
        db_query('INSERT INTO {'. $new_db_info['table'] .'} (vid, nid, delta, '. implode(', ', $columns) .') SELECT vid, nid, 0, '. implode(', ', $columns) .' FROM {'. $previous_db_info['table'] .'}');
      }
      else {
        db_query('INSERT INTO {'. $new_db_info['table'] .'} (vid, nid, '. implode(', ', $columns) .') SELECT vid, nid, '. implode(', ', $columns) .' FROM {'. $previous_db_info['table'] .'}');
      }
JonBob's avatar
JonBob committed
1323 1324 1325
      foreach ($columns as $column_name) {
        db_query('ALTER TABLE {'. $previous_db_info['table'] .'} DROP '. $column_name);
      }
JonBob's avatar
JonBob committed
1326 1327 1328 1329 1330
    }

    // Migrate data from per-field storage.
    if ($previous_field['db_storage'] == CONTENT_DB_STORAGE_PER_FIELD && $new_field['db_storage'] == CONTENT_DB_STORAGE_PER_CONTENT_TYPE) {
      $column_names = array();
1331 1332
      $column_placeholders_default = array();
      $column_assignments_default = array();
JonBob's avatar
JonBob committed
1333 1334 1335
      foreach ($new_db_info['columns'] as $column => $attributes) {
        $column_names[] = $attributes['column'];
        if (in_array($attributes['type'], array('int', 'mediumint', 'tinyint', 'bigint', 'float'))) {
1336 1337
          $column_placeholders_default[] = '%d';
          $column_assignments_default[] = $attributes['column'] .' = %d';
JonBob's avatar
JonBob committed
1338 1339
        }
        else {
1340 1341
          $column_placeholders_default[] = "'%s'";
          $column_assignments_default[] = $attributes['column'] ." = '%s'";
JonBob's avatar
JonBob committed
1342 1343 1344 1345 1346 1347 1348 1349 1350
        }
      }
      if ($previous_field['multiple']) {
        $result = db_query('SELECT '. implode(', ', $column_names) .', vid, nid FROM {'. $previous_db_info['table'] .'} WHERE delta = 0');
      }
      else {
        $result = db_query('SELECT '. implode(', ', $column_names) .', vid, nid FROM {'. $previous_db_info['table'] .'}');
      }
      while ($data = db_fetch_array($result)) {
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
        $column_assignments = $column_assignments_default;
        $column_placeholders = $column_placeholders_default;
        // search for NULL values and replace assignments and placeholders accordingly
        foreach ($data as $key => $value) {
          if (is_null($value)) {
            $pos = array_search($key, $column_names);
            $column_assignments[$pos] = $key ."= %s";
            $column_placeholders[$pos] = "%s";
            $data[$key] = 'NULL';
          }
        }
JonBob's avatar
JonBob committed
1362 1363 1364 1365 1366 1367 1368 1369 1370 1371
        if (db_result(db_query('SELECT COUNT(*) FROM {'. $new_db_info['table'] .'} WHERE vid = %d AND nid = %d', $data['vid'], $data['nid']))) {
          db_query('UPDATE {'. $new_db_info['table'] .'} SET '. implode(', ', $column_assignments) .' WHERE vid = %d AND nid = %d', $data);
        }
        else {
          db_query('INSERT INTO {'. $new_db_info['table'] .'} ('. implode(', ', $column_names) .', vid, nid) VALUES ('. implode(', ', $column_placeholders) .', %d, %d)', $data);
        }
      }
      db_query('DROP TABLE {'. $previous_db_info['table'] .'}');
    }
  }
1372 1373 1374
}

/**
1375 1376 1377
 * Handle postgresql column type creation.
 * Translates int types.
 * Supports bigint types.
1378 1379 1380 1381 1382 1383 1384
 *
 * @param $column
 *   Name of the column
 * @param $type
 *   Type of column
 * @param $attributes
 *   Additional optional attributes. Recognized attributes:
1385 1386 1387 1388 1389
 *     length
 *     unsigned
 * @param &$not_null
 * @param &$default_val
 * @param &$default
1390
 */
1391 1392 1393 1394
function content_db_construct_column_type($column, $type, &$attributes, &$not_null, &$default_val, &$default) {

  $basetype = $type;
  $type = '';
1395 1396
  switch ($GLOBALS['db_type']) {
    case 'pgsql':
1397
      $mappings = array('int' => 'integer', 'mediumint' => 'integer', 'bigint' => 'bigint',
1398 1399 1400 1401
        'tinyint' => 'smallint',
        'float' => 'float',
        'varchar' => 'varchar',
        'text' => 'text', 'mediumtext' => 'text', 'longtext' => 'text');
1402 1403 1404

      if (isset($mappings[$basetype])) {
        $basetype = $mappings[$basetype];
1405 1406
      }
      else {
1407
        watchdog('database', t('No PostgreSQL mapping found for %type data type.', array('%type' => theme('placeholder', $basetype))), WATCHDOG_WARNING);
1408
      }
1409 1410

      if ($basetype != 'varchar') {
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
        unset($attributes['length']);
      }
      break;
  }

  if (array_key_exists('not null', $attributes) && $attributes['not null']) {
    $not_null = 'NOT NULL';
  }
  if (array_key_exists('default', $attributes)) {
    if (is_null($attributes['default'])) {
      $default_val = 'NULL';
      $default = 'default NULL';
    }
    elseif ($attributes['default'] === FALSE) {
      $default = '';
    }
    else {
      $default_val = "$attributes[default]";
      $default = "default $attributes[default]";
    }
  }
1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442

  // MySQL allows no DEFAULT value for text (and blob) columns
  if (in_array($basetype, array('text', 'mediumtext', 'longtext'))) {
    switch ($GLOBALS['db_type']) {
      case 'mysql':
      case 'mysqli':
        $default = '';
        break;
    }
  }

1443 1444 1445 1446
  if (array_key_exists('length', $attributes)) {
    $type .= '('. $attributes['length'] .')';
  }
  if (array_key_exists('unsigned', $attributes) && $attributes['unsigned']) {
1447 1448 1449 1450 1451 1452 1453 1454 1455
    switch ($GLOBALS['db_type']) {
      case 'pgsql':
        $basetype .= ' CHECK('.$column.' >= 0)';
        unset($attributes['unsigned']);
        break;
      default:
        $type .= ' unsigned';
        break;
    }
1456 1457
  }

1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
  $type = $basetype . $type;
  $basetype = '';

  return $type;
}


/**
 * Add a column to a database table.
 *
 * @param $table
 *   Name of the table, without {}
 * @param $column
 *   Name of the column
 * @param $type
 *   Type of column
 * @param $attributes
 *   Additional optional attributes. Recognized attributes:
 *     not null => TRUE|FALSE
 *     default  => NULL|FALSE|value (with or without '', it won't be added)
 */
function content_db_add_column($table, $column, $type, $attributes = array()) {
1480 1481 1482 1483
  $not_null = NULL;
  $default_val = NULL;
  $default = NULL;
  $type = content_db_construct_column_type($column, $type, $attributes, $not_null, $default_val, $default);
1484

1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500
  switch ($GLOBALS['db_type']) {
    case 'pgsql':
      db_query("ALTER TABLE {". $table ."} ADD $column $type");
      if ($default) {
        db_query("ALTER TABLE {". $table ."} ALTER $column SET $default");
      }
      if ($not_null) {
        if ($default) {
          db_query("UPDATE {". $table ."} SET $column = $default_val");
        }
        db_query("ALTER TABLE {". $table ."} ALTER $column SET NOT NULL");
      }
      break;

    case 'mysql':
    case 'mysqli':
1501 1502 1503 1504 1505 1506
       // MySQL allows no DEFAULT value for text (and blob) columns
      if (in_array($type, array('text', 'mediumtext', 'longtext'))) {
        $default = '';
        // We also allow NULL values to account for CCK's per field INSERTs
        $not_null = '';
      }
1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533
      db_query('ALTER TABLE {'. $table .'} ADD COLUMN '. $column .' '. $type .' '. $not_null .' '. $default);
      break;
  }
}

/**
 * Change a column definition.
 *
 * Remember that changing a column definition involves adding a new column
 * and dropping an old one. This means that any indices, primary keys and
 * sequences from serial-type columns are dropped and might need to be
 * recreated.
 *
 * @param $table
 *   Name of the table, without {}
 * @param $column
 *   Name of the column to change
 * @param $column_new
 *   New name for the column (set to the same as $column if you don't want to change the name)
 * @param $type
 *   Type of column
 * @param $attributes
 *   Additional optional attributes. Recognized attributes:
 *     not null => TRUE|FALSE
 *     default  => NULL|FALSE|value (with or without '', it won't be added)
 */
function content_db_change_column($table, $column, $column_new, $type, $attributes = array()) {
1534 1535 1536 1537
  $not_null = NULL;
  $default_val = NULL;
  $default = NULL;
  $type = content_db_construct_column_type($column_new, $type, $attributes, $not_null, $default_val, $default);
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554

  switch ($GLOBALS['db_type']) {
    case 'pgsql':
      db_query("ALTER TABLE {". $table ."} RENAME $column TO ". $column ."_old");
      db_query("ALTER TABLE {". $table ."} ADD $column_new $type");
      db_query("UPDATE {". $table ."} SET $column_new = ". $column ."_old");
      if ($default) {
        db_query("ALTER TABLE {". $table ."} ALTER $column_new SET $default");
      }
      if ($not_null) {
        db_query("ALTER TABLE {". $table ."} ALTER $column_new SET NOT NULL");
      }
      db_query("ALTER TABLE {". $table ."} DROP ". $column ."_old");
      break;

    case 'mysql':
    case 'mysqli':
1555 1556 1557 1558 1559 1560
       // MySQL allows no DEFAULT value for text (and blob) columns
      if (in_array($type, array('text', 'mediumtext', 'longtext'))) {
        $default = '';
        // We also allow NULL values to account for CCK's per field INSERTs
        $not_null = '';
      }
1561 1562 1563 1564
      db_query('ALTER TABLE {'. $table .'} CHANGE '. $column .' '. $column_new .' '. $type .' '. $not_null .' '. $default);
      break;
  }
}