You are here

function regcode_save in Registration codes 7.2

Same name and namespace in other branches
  1. 8 regcode.module \regcode_save()
  2. 6.2 regcode.module \regcode_save()
  3. 7 regcode.module \regcode_save()

Save given code to a record in the db and calls the regcode_presave hook.

@todo Remove the $terms parameter and put it in the object.

Parameters

object $code: A code object (required fields are code, begins, expires, is_active, and maxuses.

array $terms: An array of terms to associate this tag with.

int $action: Action to perform when saving the code.

Return value

bool TRUE if the code was saved.

2 calls to regcode_save()
regcode_admin_create_submit in ./regcode.admin.inc
Process creation form.
regcode_ie_admin_import_submit in regcode_ie/regcode_ie.module
Process import form.

File

./regcode.module, line 545
Main functionality and hooks of regcode module.

Code

function regcode_save($code, $terms = array(), $action = REGCODE_MODE_REPLACE) {
  $rid = FALSE;

  // Sanity check.
  if (empty($code) || empty($code->code)) {
    return FALSE;
  }

  // Trigger the regcode_save hook.
  foreach (module_implements('regcode_presave') as $module) {
    $hook = $module . '_regcode_presave';
    $hook($code, $terms);
  }

  // Insert mode.
  if ($action == REGCODE_MODE_REPLACE) {
    db_delete('regcode')
      ->condition('code', $code->code)
      ->execute();
  }

  // Build the query and fetch result.
  $isExist = db_select('regcode')
    ->fields('regcode', array(
    'rid',
  ))
    ->condition('code', $code->code)
    ->execute()
    ->fetchObject();

  // Check if already exists.
  if (empty($isExist) || $isExist->rid == FALSE) {

    // Insert.
    $rid = db_insert('regcode')
      ->fields(array(
      'created' => REQUEST_TIME,
      'begins' => empty($code->begins) ? NULL : (int) $code->begins,
      'expires' => empty($code->expires) ? NULL : (int) $code->expires,
      'code' => check_plain($code->code),
      'is_active' => isset($code->is_active) ? $code->is_active : 1,
      'maxuses' => isset($code->maxuses) ? (int) $code->maxuses : 1,
    ))
      ->execute();

    // Add tags.
    if (count($terms)) {
      foreach (array_filter($terms) as $tid => $enabled) {
        db_insert('regcode_term')
          ->fields(array(
          'rid' => $rid,
          'tid' => $tid,
        ))
          ->execute();
      }
    }
  }
  return $rid;
}