You are here

certificate.module in Certificate 6.2

Certificate module.

File

certificate.module
View source
<?php

/**
 * Certificate module.
 * @file
 */

/**
 * Implementation of hook_node_info().
 */
function certificate_node_info() {
  $items = array(
    'certificate' => array(
      'name' => t('Certificate'),
      'module' => 'certificate',
      'description' => t('A tokenized certificate template that will be converted to a PDF and displayed to users who complete accredited activities.'),
      'has_title' => TRUE,
      'title_label' => t('Title'),
      'has_body' => TRUE,
      'body_label' => t('Certificate Body'),
      'min_word_count' => '0',
      'help' => '',
      'locked' => TRUE,
    ),
  );
  return $items;
}

/**
 * Implementation of hook_access().
 */
function certificate_access($op, $node, $account) {
  if ($op == 'create') {
    return user_access('create certificate content', $account);
  }
  if ($op == 'update') {
    if (user_access('edit any certificate content', $account) || user_access('edit own certificate content', $account) && $account->uid == $node->uid) {
      return TRUE;
    }
  }
  if ($op == 'delete') {
    if (user_access('delete any certificate content', $account) || user_access('delete own certificate content', $account) && $account->uid == $node->uid) {
      return TRUE;
    }
  }
}
function certificate_form(&$node, $form_state) {

  // The site admin can decide if this node type has a title and body, and how
  // the fields should be labeled. We need to load these settings so we can
  // build the node form correctly.
  $type = node_get_types('type', $node);
  if ($type->has_title) {
    $form['title'] = array(
      '#type' => 'textfield',
      '#title' => check_plain($type->title_label),
      '#required' => TRUE,
      '#default_value' => $node->title,
      '#weight' => -5,
    );
  }
  if ($type->has_body) {

    // In Drupal 6, we use node_body_field() to get the body and filter
    // elements. This replaces the old textarea + filter_form() method of
    // setting this up. It will also ensure the teaser splitter gets set up
    // properly.
    $form['body_field'] = node_body_field($node, $type->body_label, $type->min_word_count);
  }

  // Now we define the form elements specific to our node type.
  $form['certificate']['#tree'] = TRUE;
  $form['certificate']['orientation'] = array(
    '#type' => 'radios',
    '#title' => t('Orientation'),
    '#default_value' => isset($node->certificate['orientation']) ? $node->certificate['orientation'] : '',
    '#options' => array(
      'portrait' => t('Portrait'),
      'landscape' => t('Landscape'),
    ),
    '#required' => TRUE,
    '#description' => 'The orientation of the generated certificate.',
  );
  $form['options']['status']['#default_value'] = 0;
  $form['options']['promote']['#default_value'] = 0;
  return $form;
}

/**
 * Implementation of hook_menu().
 */
function certificate_menu() {
  $items = array();
  $items['admin/build/certificates'] = array(
    'title' => 'Certificates',
    'access arguments' => array(
      'administer certificates',
    ),
    'file' => 'certificate.admin.inc',
    'page callback' => 'certificate_templates_list',
  );
  $items['admin/build/certificates/templates'] = array(
    'title' => 'List',
    'access arguments' => array(
      'administer certificates',
    ),
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'file' => 'certificate.admin.inc',
    'page callback' => 'certificate_templates_list',
    'weight' => -5,
  );
  $items['admin/build/certificates/mapping'] = array(
    'title' => 'Mapping',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'certificate_settings_form',
    ),
    'access arguments' => array(
      'administer certificates',
    ),
    'file' => 'certificate.admin.inc',
    'type' => MENU_LOCAL_TASK,
    'weight' => -4,
  );
  $items['admin/build/certificates/mapping/list'] = array(
    'title' => 'Global',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -5,
  );
  $items['admin/build/certificates/mapping/groups'] = array(
    'title' => 'Field groups',
    'description' => 'Set up certificate field groups',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'certificate_field_grouping_form',
    ),
    'access arguments' => array(
      'administer certificates',
    ),
    'file' => 'certificate.admin.inc',
    'type' => MENU_LOCAL_TASK,
  );
  $items['admin/build/certificates/mapping/groups/add'] = array(
    'title' => 'Add field group',
    'description' => 'Add a field group',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'certificate_field_grouping_add_form',
    ),
    'access arguments' => array(
      'administer certificates',
    ),
    'file' => 'certificate.admin.inc',
    'type' => MENU_LOCAL_TASK,
  );

  /*
   $items['admin/build/certificates/mapping/groups/delete/%'] = array(
   'title' => 'Delete field group',
   'description' => 'Delete a field group',
   'page callback' => 'drupal_get_form',
   'page arguments' => array('certificate_field_grouping_delete_form'),
   'page arguments' => array(6),
   'access arguments' => array('administer certificates'),
   'file' => 'certificate.admin.inc',
   'type' => MENU_LOCAL_TASK,
   );
  */
  $items['admin/build/certificates/settings'] = array(
    'title' => 'Settings',
    'description' => 'Certificate settings.',
    'access arguments' => array(
      'administer certificates',
    ),
    'file' => 'certificate.admin.inc',
    'type' => MENU_LOCAL_TASK,
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'certificate_admin_settings_form',
    ),
  );
  $items['admin/build/certificates/clear'] = array(
    'title' => 'Clear',
    'access arguments' => array(
      'administer certificates',
    ),
    'file' => 'certificate.admin.inc',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'certificate_admin_clear_form',
    ),
    'type' => MENU_LOCAL_TASK,
    'weight' => 99,
  );
  $items['admin/build/certificates/templates/preview/%'] = array(
    'title' => 'Certificate Preview',
    'description' => 'Display earned certificate for this node',
    'page callback' => 'certificate_preview',
    'page arguments' => array(
      5,
    ),
    'access arguments' => array(
      'administer certificates',
    ),
    'file' => 'certificate.pages.inc',
    'type' => MENU_CALLBACK,
  );

  // Certificate tab on nodes.
  $items['node/%node/certificate'] = array(
    'title' => 'Certificate',
    'description' => 'Display earned certificate for this node',
    'page callback' => 'certificate_node_certificate',
    'page arguments' => array(
      1,
    ),
    'access callback' => 'certificate_can_access_certificate',
    'access arguments' => array(
      1,
    ),
    'file' => 'certificate.pages.inc',
    'type' => MENU_LOCAL_TASK,
  );
  return $items;
}

/**
 * Implementation of hook_perm().
 */
function certificate_perm() {
  return array(
    'access all certificates',
    'administer certificates',
    'create certificate content',
    'delete own certificate content',
    'delete any certificate content',
    'edit own certificate content',
    'edit any certificate content',
    'view all user certificates',
  );
}

/**
 * Implementation of hook_theme().
 *
 * Returns information about every themable function defined by the module.
 */
function certificate_theme() {
  $items = array();
  $items['certificate_certificate'] = array(
    'arguments' => array(
      'certificate' => array(),
    ),
    'file' => 'certificate.pages.inc',
  );
  $items['certificate_admin_clear_form'] = array(
    'arguments' => array(
      'form' => NULL,
    ),
    'file' => 'certificate.admin.inc',
  );
  return $items;
}

/**
 * Public loader function for the full collection of certificates.
 *
 * @todo cache?
 *
 * @return
 *   An array of all certificates, keyed by node (certificate) ID.
 */
function certificate_certificate_load_all() {
  $sql = "SELECT *, nid AS cid FROM {node} n WHERE type = 'certificate'";
  $result = db_query($sql);
  $certificates = array();
  while ($certificate = db_fetch_array($result)) {
    $certificates[$certificate['cid']] = $certificate;
  }
  drupal_alter('certificate_template_options', $certificates);
  return $certificates;
}

/**
 * Quick get per-node template settings.
 */
function certificate_course_node_template_settings($nid) {
  $sql = "SELECT * FROM {certificate_node} WHERE nid = %d";
  $result = db_query($sql, $nid);
  $node_template_settings = array();
  while ($node_template_setting = db_fetch_array($result)) {
    $node_template_settings[$node_template_setting['mapper']][$node_template_setting['type']] = $node_template_setting['template'];
  }
  return $node_template_settings;
}

/**
 * Implements hook_form_alter for course nodes.
 */
function certificate_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form['#node'])) {
    if (certificate_node_is_certifiable($form['#node']) && strpos($form_id, '_node_form') !== FALSE) {

      // Add per-node certificate settings.
      module_load_include('inc', 'certificate', 'certificate.admin');
      certificate_alter_node_form($form, $form_state);
    }
  }
  if ($form_id == 'node_type_form') {
    $form['certificate'] = array(
      '#type' => 'fieldset',
      '#title' => 'Certificate settings',
      '#collapsed' => TRUE,
      '#collapsible' => TRUE,
    );
    $form['certificate']['certificate_certifiable'] = array(
      '#type' => 'checkbox',
      '#title' => 'Award certificate',
      '#description' => t('Make this content type certificate-enabled. Certificate mapping selections will show on the node form.'),
      '#default_value' => variable_get("certificate_certifiable_{$form['#node_type']->type}", 0),
    );
  }
}
function certificate_form_certificate_node_form_alter(&$form, &$form_state) {
  if (module_exists('token')) {

    // Embed token help.
    $form['certificate_tokens'] = array(
      '#title' => 'Certificate tokens',
      '#type' => 'fieldset',
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
      '#value' => theme('token_tree', array(
        'global',
        'node',
        'user',
        'certificate',
      ), FALSE),
    );
  }

  // No preview - we want users to see it in PDF for accuracy.
  $form['buttons']['preview'] = NULL;
}

/**
 * Submit handler to update mappings.
 */
function certificate_update_node_mappings($nid, array $node_settings = NULL) {
  if (is_array($node_settings)) {
    db_query("DELETE FROM {certificate_node} WHERE nid = %d", $nid);
    foreach ($node_settings as $mapper => $values) {
      foreach (array_filter($values) as $match => $cert_nid) {
        $record = array(
          'nid' => $nid,
          'mapper' => $mapper,
          'type' => $match,
          'template' => $cert_nid,
        );
        drupal_write_record('certificate_node', $record);
      }
    }
  }
}

/**
 * Implements hook_nodeapi.
 */
function certificate_nodeapi(&$node, $op, $teaser = NULL, $page = NULL) {
  if (certificate_node_is_certifiable($node)) {
    switch ($op) {
      case 'insert':
      case 'update':
        if (isset($node->certificate)) {
          if (certificate_node_is_certifiable($node)) {

            // Update node mappings from a certifiable activity.
            certificate_update_node_mappings($node->nid, $node->certificate['map']);
          }
        }
        break;
      case 'delete':

        // Clean up the certificate template tables for the deleted node.
        db_query("DELETE FROM {certificate_node} WHERE nid = %d", $node->nid);
        db_query("DELETE FROM {certificate_snapshots} WHERE nid = %d", $node->nid);
        break;
      case 'load':
        return array(
          'certificate' => array(
            'node_settings' => certificate_course_node_template_settings($node->nid),
          ),
        );
      case 'view':
        if (certificate_can_access_certificate($node)) {

          // Add a download certificate link to the node content.
          $node->content['certificate']['#value'] = '<span class="certificate-link">' . l(t('Download certificate'), "node/{$node->nid}/certificate") . '</span>';
        }
        break;
    }
  }
  if ($node->type == 'certificate') {
    switch ($op) {
      case 'insert':
      case 'update':

        // Save the certificate settings.
        if (isset($node->certificate)) {
          $record = $node->certificate;
          $record['nid'] = $node->nid;
          if (db_result(db_query("select 1 from {certificate_node_settings} where nid = %d", $node->nid))) {
            $keys = array(
              'nid',
            );
          }
          drupal_write_record('certificate_node_settings', $record, $keys);
        }
        break;
      case 'load':
        return array(
          'certificate' => db_fetch_array(db_query("select * from {certificate_node_settings} where nid = %d", $node->nid)),
        );
    }
  }
}

/**
 * Implementation of hook_content_extra_fields().
 *
 * Allow the certificate download link to be sorted in the node edit forms.
 */
function certificate_content_extra_fields($type_name) {
  $extras = array();
  $node = new stdClass();
  $node->type = $type_name;
  if (certificate_node_is_certifiable($node)) {
    $extras['certificate'] = array(
      'label' => t('Certificate'),
      'description' => t('Certificate link.'),
      'weight' => 10,
    );
  }
  if ($type_name == 'certificate') {
    $extras['certificate_tokens'] = array(
      'label' => t('Certificate tokens'),
      'description' => t('Tokens to insert into the certificate.'),
    );
  }
  return $extras;
}

/**
 * Check if node is certifiable.
 *
 * @return bool
 */
function certificate_node_is_certifiable($node) {
  return variable_get("certificate_certifiable_{$node->type}", 0);
}

/**
 * Quick certificates snapshot check.
 *
 * @param $account
 * @param $node
 *
 * @return
 *   A single certificate snapshot in array format, or FALSE if none matched the incoming ID.
 */
function certificate_snapshot_load($account, $node) {
  $sql = "SELECT * FROM {certificate_snapshots} WHERE uid = %d AND nid = %d";
  $result = db_query($sql, $account->uid, $node->nid);
  return db_fetch_array($result);
}

/**
 * Inserts a new snapshot, or updates an existing one.
 *
 * @param $certificate
 *   A certificate to be saved. If $certificate['cid'] is set, the certificate will be updated.
 *   Otherwise, a new certificate will be inserted into the database.
 * @return
 *   The saved certificate, with its ID set.
 *
 * @see certificate_single()
 */
function certificate_snapshot_save($snapshot) {
  if (isset($snapshot['csid'])) {
    drupal_write_record('certificate_snapshots', $snapshot, 'csid');
  }
  else {
    drupal_write_record('certificate_snapshots', $snapshot);
  }
  return $snapshot;
}

/**
 * Remove snapshot.
 *
 * @param stdClass $account
 * @param stdClass $node
 *
 * @return bool
 */
function certificate_snapshot_delete($account, $node) {
  $sql = "DELETE FROM {certificate_snapshots} WHERE uid = %d AND nid = %d";
  db_query($sql, $account->uid, $node->nid);
  return TRUE;
}

/**
 * Delete all snapshots on a node.
 *
 * @param stdClass $node
 *
 * @return bool
 */
function certificate_snapshot_delete_by_node($node) {
  $sql = "DELETE FROM {certificate_snapshots} WHERE nid = %d";
  db_query($sql, $node->nid);
  return TRUE;
}

/**
 * Implementation of hook_action_info().
 */
function certificate_action_info() {
  $info = array();
  $info['certificate_reset_certificates_action'] = array(
    'type' => 'node',
    'description' => t('Reset certificate snapshots for this node.'),
    'configurable' => FALSE,
    'hooks' => array(
      'nodeapi' => array(
        'insert',
        'update',
      ),
    ),
  );
  return $info;
}

/**
 * Expose certificate awarding as an action.
 */
function certificate_rules_action_info() {
  $info = array();
  $info['certificate_rules_award_certificate'] = array(
    'label' => t('Award certificate'),
    'configurable' => FALSE,
    'module' => 'Certificate',
  );
  return $info;
}

/**
 * Set the awarded certificate.
 *
 * @todo in Drupal 7 and Rules 2, we can use return values. Rules 1 does not
 * have return values.
 */
function certificate_rules_award_certificate($node, $user) {
  global $_certificate_award;
  $_certificate_award = TRUE;
}

/**
 * Action to delete certificate snapshots on a node.
 */
function certificate_reset_certificates_action($object, $context) {
  $node = $object;
  if ($node->nid && is_numeric($node->nid)) {
    certificate_snapshot_delete_by_node($node);
    watchdog('action', 'Reset certificate snapshots for: %node.', array(
      '%node' => $node->title,
    ));
  }
  else {

    //print_r("No Node");
  }
}

/**
 * Check if a user can access a certificate for this node.
 *
 * This function:
 *  @return TRUE if certificate tab should show and be accessible.
 *  @return string (eval to true for Drupal's menu) if certificate tab should
 *    show but be denied with a message.
 *  @return FALSE if certificate tab should be hidden.
 */
function certificate_can_access_certificate($node, $account = NULL, $flush = FALSE) {
  static $cert_access = array();
  $found_true = NULL;
  $found_false = NULL;
  $admin = user_access('administer certificates');
  $view_all = user_access('view all user certificates');

  // Use account of a different user if allowed.
  if (($admin || $view_all) && arg(3) > 0) {
    $account = user_load(arg(3));
  }
  if (!$account) {
    global $user;
    $account = $user;
  }
  if (!$account->uid) {
    return FALSE;
  }
  if (!certificate_node_is_certifiable($node)) {
    return FALSE;
  }
  if ($flush || !isset($cert_access[$node->nid])) {
    $access = module_invoke_all('access_certificate', $node, $account);
    $cert_access[$node->nid] = $access;
  }
  else {
    $access = $cert_access[$node->nid];
  }
  foreach ($access as $item) {
    if ($item === TRUE) {

      // Something said the leaner should access the certificate.
      $found_true = TRUE;
    }
    if (is_string($item)) {

      // Something returned a string, return it (will show the menu, but error)
      return $item;
    }
    if ($item === FALSE) {
      $found_false = TRUE;
    }
  }
  if ($found_true) {
    if ($found_false) {

      // Found TRUE and FALSEs.
      return FALSE;
    }

    // Only found TRUE.
    return TRUE;
  }

  // All were false.
  return FALSE;
}

/**
 * Implements hook_user().
 *
 * Clean up after user deletion.
 */
function certificate_user($op, &$edit, &$account, $category = NULL) {
  if ($op == 'delete') {
    $sql = "delete from {certificate_snapshots} where uid = %d";
    db_query($sql, $account->uid);
  }
}

/**
 * Return an array of certificate templates suitable for use in an options
 * form element.
 */
function certificate_get_template_options() {

  // Get existing templates.
  $templates = certificate_certificate_load_all();
  foreach ($templates as $key => $template) {
    $template_options[$key] = $template['title'];
  }
  return $template_options;
}

/**
 * Implementation of hook_certificate_map_options().
 *
 * Provide a list of options to the user that can be mapped to certificate
 * templates.
 *
 * @return Array of mapping sets.
 */
function certificate_certificate_map_options() {
  $options = array();
  if (module_exists('rules')) {
    $rules = array();
    foreach (rules_get_configured_items('rule_sets') as $key => $ruleset) {
      if (in_array('certificate', $ruleset['categories'])) {
        $rules[$key] = $ruleset['label'];
      }
    }
    $options['rules'] = array(
      'title' => "Ruleset",
      'options' => $rules,
      'description' => 'When a ruleset ends with "Award certificate", the selected certificate will be awarded.',
    );
  }
  if (module_exists('content_profile')) {
    $fieldgroups = variable_get('certificate_field_groups', array());
    $options['content_profile'] = array(
      'title' => "Content profile",
      'options' => $fieldgroups,
      'description' => t('If a user matches a value in a field group, the selected certificate will be awarded.'),
    );
  }
  $options['manual'] = array(
    'title' => 'Manual',
    'description' => t('Select a single certificate to award to the user.'),
    'options' => array(
      'manual' => 'Manual',
    ),
  );
  return $options;
}

/**
 * Implementation of hook_certificate_map().
 *
 * Return the key of the mapping to use.
 *
 * @return string
 *   Key of matched mapping.
 */
function certificate_certificate_map($node, $user, $map_type, $options) {
  if ($map_type == 'rules') {
    foreach ($options as $key) {
      global $_certificate_award;
      $_certificate_award = FALSE;
      rules_invoke_rule_set($key, array(
        'node' => $node,
        'user' => $user,
      ));
      if ($_certificate_award) {
        return $key;
      }
    }
  }
  if ($map_type == 'content_profile') {
    $content_profile = content_profile_load('profile', $user->uid);
    $groupings = variable_get('certificate_field_grouping', array());
    foreach ($options as $key) {
      if (!empty($groupings[$key])) {
        foreach ($groupings[$key] as $field_name => $accepted_values) {
          foreach ($content_profile->{$field_name} as $item) {
            if (in_array($item['value'], $accepted_values)) {
              return $key;
            }
          }
        }
      }
    }
  }
  if ($map_type == 'manual') {
    if (isset($options[0]) && $options[0] == 'manual') {
      return 'manual';
    }
  }
}

/**
 * Implements hook_coder_ignore().
 */
function certificate_coder_ignore() {
  return array(
    'path' => drupal_get_path('module', 'certificate'),
    'line prefix' => drupal_get_path('module', 'certificate'),
  );
}

Functions

Namesort descending Description
certificate_access Implementation of hook_access().
certificate_action_info Implementation of hook_action_info().
certificate_can_access_certificate Check if a user can access a certificate for this node.
certificate_certificate_load_all Public loader function for the full collection of certificates.
certificate_certificate_map Implementation of hook_certificate_map().
certificate_certificate_map_options Implementation of hook_certificate_map_options().
certificate_coder_ignore Implements hook_coder_ignore().
certificate_content_extra_fields Implementation of hook_content_extra_fields().
certificate_course_node_template_settings Quick get per-node template settings.
certificate_form
certificate_form_alter Implements hook_form_alter for course nodes.
certificate_form_certificate_node_form_alter
certificate_get_template_options Return an array of certificate templates suitable for use in an options form element.
certificate_menu Implementation of hook_menu().
certificate_nodeapi Implements hook_nodeapi.
certificate_node_info Implementation of hook_node_info().
certificate_node_is_certifiable Check if node is certifiable.
certificate_perm Implementation of hook_perm().
certificate_reset_certificates_action Action to delete certificate snapshots on a node.
certificate_rules_action_info Expose certificate awarding as an action.
certificate_rules_award_certificate Set the awarded certificate.
certificate_snapshot_delete Remove snapshot.
certificate_snapshot_delete_by_node Delete all snapshots on a node.
certificate_snapshot_load Quick certificates snapshot check.
certificate_snapshot_save Inserts a new snapshot, or updates an existing one.
certificate_theme Implementation of hook_theme().
certificate_update_node_mappings Submit handler to update mappings.
certificate_user Implements hook_user().