regcode.api.php in Registration codes 6
Same filename and directory in other branches
A generic set of functions for interacting with and creating regcodes
File
regcode.api.phpView source
<?php
/**
* @file
* A generic set of functions for interacting with and creating regcodes
*/
// Define validation error codes
define('REGCODE_VALIDITY_NOTEXISTING', 0);
define('REGCODE_VALIDITY_NOTAVAILABLE', -1);
define('REGCODE_VALIDITY_TAKEN', -3);
define('REGCODE_VALIDITY_EXPIRED', -2);
/**
* Return text message requested by given identifier/constant
*
* @param $code
* The message code
* @return
* The text of the message.
*/
function regcode_message($code) {
$messages[REGCODE_VALIDITY_NOTEXISTING] = t('Registration code does not exist');
$messages[REGCODE_VALIDITY_NOTAVAILABLE] = t('Registration code is not available');
$messages[REGCODE_VALIDITY_TAKEN] = t('Registration code has already been used');
$messages[REGCODE_VALIDITY_EXPIRED] = t('Registration code has expired');
return $messages[$code];
}
/**
* Retrieve a particular registration code identified by given code id,
* or assign it to a given user
*
* @param $code
* The code identifiert string
* @param $account_id
* Optional user id to assign the given code to
* @return
* The data array of the code to retrieve, or a boolean result (TRUE=successfully assigned to given uid) if assign_to_uid has been given.
*/
function regcode_get_code($code, $account_id = FALSE) {
// Look up and retrieve code record from DB
$code = db_fetch_array(db_query("SELECT * FROM {regcode} WHERE code = '%s'", $code));
// Check validity
if (!is_array($code)) {
return REGCODE_VALIDITY_NOTEXISTING;
}
if ($code['uses'] >= $code['maxuses'] && $code['maxuses'] !== '0') {
return REGCODE_VALIDITY_TAKEN;
}
if (!$code['is_active']) {
return REGCODE_VALIDITY_NOTAVAILABLE;
}
if (!empty($code['begins']) && strtotime($code['begins']) > time()) {
return REGCODE_VALIDITY_NOTAVAILABLE;
}
if (!empty($code['expires']) && strtotime($code['expires']) < time()) {
return REGCODE_VALIDITY_EXPIRED;
}
if ($account_id) {
// Mark the code inactive if it's used up
$active = 1;
if ($code['maxuses'] != 0 && $code['uses'] + 1 >= $code['maxuses']) {
$active = 0;
}
// Use the code
db_query("UPDATE {regcode} SET uses=uses+1, lastused=NOW(), uid=%d, is_active=%d WHERE code='%s'", $account_id, $active, $code['code']);
}
return $code;
}
/**
* Return a list of distinct categories
*/
function regcode_get_categories($match = '', $limit = 50) {
$result = db_query_range("SELECT DISTINCT category FROM {regcode} WHERE LOWER(category) LIKE LOWER('%s%%')", $match, 0, $limit);
$matches = array();
while ($regcode = db_fetch_object($result)) {
$matches[$regcode->category] = check_plain($regcode->category);
}
return $matches;
}
/**
* Load the regcode field definitions from the schema file
*
* @return array List of field definitions
*/
function regcode_get_fields() {
require_once 'regcode.install';
$schema = regcode_schema('regcode');
return $schema['regcode']['fields'];
}
/**
* Save given code array to a record in the db
*
* @param $code
* An array of code data fields (dates must be timestamps)
* @param $action
* Action to perform when saving the code:
* overwrite - overwrite any existing code with same code identifier
* skip - skip and do not save code if there is any existing code with same code identifier
* @return
* An array list of code data arrays
*/
function regcode_save_code($code, $action = 'overwrite') {
// Sanity check
if (empty($code) || empty($code['code'])) {
return FALSE;
}
if ($action == 'overwrite') {
db_query("DELETE FROM {regcode} WHERE code = '%s'", $code['code']);
}
// Format data
$format = 'Y-m-d h:j:s';
$begins = empty($code['begins']) ? 'NULL' : '"' . date($format, $code['begins']) . '"';
$expires = empty($code['expires']) ? 'NULL' : '"' . date($format, $code['expires']) . '"';
$maxuses = empty($code['maxuses']) ? 'NULL' : intval($code['maxuses']);
// Insert
$sql = "INSERT INTO {regcode} (created,begins,expires,category,code,is_active,maxuses)\n VALUES (NOW(), {$begins}, {$expires}, '%s', '%s', %d, %d)";
$result = db_query($sql, empty($code['category']) ? 'default' : check_plain($code['category']), check_plain($code['code']), $code['is_active'], $maxuses);
return $result;
}
/**
* Count codes
*/
function regcode_count($where = '') {
return db_result(db_query('SELECT COUNT(rid) AS count FROM {regcode}' . $where));
}
/**
* Categories
*/
function regcode_categories() {
$res = db_query('SELECT DISTINCT category FROM {regcode}');
$categories = array();
while ($category = db_fetch_array($res)) {
$categories[] = $category['category'];
}
return $categories;
}
/**
* Clean up codes
*
* @param $op
* Action to perform when cleaning the code:
* truncate - truncate all codes from db
* expired - remove expired codes
* used - remove one-time codes that have been used
*/
function regcode_clean_codes($op = 'truncate') {
switch ($op) {
case 'truncate':
db_query('TRUNCATE {regcode}');
break;
case 'expired':
db_query('DELETE FROM {regcode} WHERE expire < NOW()');
break;
case 'used':
db_query('DELETE FROM {regcode} WHERE uses >= maxuses');
break;
}
}
/**
* Generate a code
*/
function regcode_generate_code($length, $output, $case) {
static $seeded = FALSE;
// Possible seeds
$outputs['alpha'] = 'abcdefghijklmnopqrstuvwqyz';
$outputs['numeric'] = '0123456789';
$outputs['alphanum'] = 'abcdefghijklmnopqrstuvwqyz0123456789';
$outputs['hexadec'] = '0123456789abcdef';
// Choose seed
if (isset($outputs[$output])) {
$output = $outputs[$output];
}
// Seed generator (only do this once per invocation)
if (!$seeded) {
list($usec, $sec) = explode(' ', microtime());
$seed = (double) $sec + (double) $usec * 100000;
mt_srand($seed);
$seeded = TRUE;
}
// Generate
$str = '';
$output_count = strlen($output);
for ($i = 0; $length > $i; $i++) {
$str .= $output[mt_rand(0, $output_count - 1)];
}
if ($case) {
$str = strtoupper($str);
}
return $str;
}
Functions
Name | Description |
---|---|
regcode_categories | Categories |
regcode_clean_codes | Clean up codes |
regcode_count | Count codes |
regcode_generate_code | Generate a code |
regcode_get_categories | Return a list of distinct categories |
regcode_get_code | Retrieve a particular registration code identified by given code id, or assign it to a given user |
regcode_get_fields | Load the regcode field definitions from the schema file |
regcode_message | Return text message requested by given identifier/constant |
regcode_save_code | Save given code array to a record in the db |