avatar_selection.module in Avatar Selection 5.2
Same filename and directory in other branches
The Avatar Selection module allows the user to pick an avatar image from a list already loaded by an administrative user, and to the administrator to disable uploading other avatar files by the user.
File
avatar_selection.moduleView source
<?php
/**
* @file
* The Avatar Selection module allows the user to pick an avatar image from a
* list already loaded by an administrative user, and to the administrator to
* disable uploading other avatar files by the user.
*/
/**
* Implementation of hook_help().
*/
function avatar_selection_help($section = '') {
$output = '';
switch ($section) {
case "admin/help#avatar_selection":
$output .= '<p>' . t("Allows the user to pick an avatar from a list.") . '</p>';
return $output;
case "admin/modules#description":
return t("Allows the user to pick an avatar from a list.");
case "admin/settings/avatar_selection/images":
return t("Upload images to display as a user avatar. These images can be anything you like, but it is recommended that you maintain a uniform icon size for all of your avatars. Maximum dimensions are 85x85 and the maximum size is 30 kB.");
}
}
/**
* Implementation of hook_perm().
*
* Define the permissions this module uses.
*/
function avatar_selection_perm() {
return array(
'administer avatar selection',
'access avatars',
'upload avatar in profile',
);
}
/**
* Implementation of hook_access().
*/
function avatar_selection_access($op, $node) {
if ($op == 'view') {
return user_access('access avatars');
}
elseif ($op == 'create' || $op == 'update' || $op == 'delete') {
return user_access('administer avatar selection');
}
}
/**
* Implementation of hook_menu().
*/
function avatar_selection_menu($may_cache) {
$access = user_access('administer avatar selection');
$items = array();
if ($may_cache) {
$items[] = array(
'path' => 'admin/settings/avatar_selection',
'title' => t('Avatar Selection'),
'callback' => 'avatar_selection_settings_page',
'access' => $access,
'description' => t('Allows the user to upload and delete avatars.'),
);
$items[] = array(
'path' => 'admin/settings/avatar_selection/config',
'title' => t('Configure'),
'description' => t('Allows the user to configure avatar settings.'),
'callback' => 'drupal_get_form',
'callback arguments' => array(
'avatar_selection_config_form',
),
'access' => $access,
'type' => MENU_DEFAULT_LOCAL_TASK,
'weight' => -10,
);
$items[] = array(
'path' => 'admin/settings/avatar_selection/upload',
'title' => t('Upload'),
'description' => t('Allows the user to upload avatars.'),
'callback' => 'drupal_get_form',
'callback arguments' => array(
'avatar_selection_upload_form',
),
'access' => $access,
'type' => MENU_LOCAL_TASK,
'weight' => -9,
);
$items[] = array(
'path' => 'admin/settings/avatar_selection/edit',
'title' => t('Manage avatars'),
'description' => t('Allows the user to modify or delete an avatar from a list.'),
'callback' => 'avatar_selection_roles_page',
'callback arguments' => NULL,
'access' => $access,
'type' => MENU_LOCAL_TASK,
);
if (arg(0) == 'admin' && arg(1) == 'settings' && arg(2) == 'avatar_selection' && arg(3) == 'edit') {
if ((arg(4) == 'role' || arg(4) == 'og') && is_numeric(arg(5))) {
$items[] = array(
'path' => 'admin/settings/avatar_selection/edit/' . arg(4) . '/' . arg(5),
'title' => t('Manage avatars'),
'description' => t('Allows the user to modify or delete an avatar from a list.'),
'callback' => 'avatar_selection_roles_page',
'callback arguments' => array(
'op' => 'list',
),
'access' => $access,
);
}
}
}
return $items;
}
/**
* Implementation of hook_form_alter().
*
* Create the form structure for adding an avatar on the user registration and
* user profile forms.
*
* @param $form_id
* The id of the form to modify.
* @param &$form
* General reference used in drupal, defining the structure & the fields of
* a form.
*/
function avatar_selection_form_alter($form_id, &$form) {
global $user, $_GET;
// If user pictures aren't enabled, nothing to do here.
if (!variable_get('user_pictures', 0)) {
return;
}
// See if user has access to avatars.
$disable_upload = variable_get('avatar_selection_disable_user_upload', 0) & !user_access('upload avatar in profile');
if (!user_access('access avatars')) {
// If uploads also disabled, remove the field altogether.
if ($disable_upload) {
unset($form['picture']);
}
return;
}
// We find out the current page number.
$page = 0;
if (isset($_GET['page']) && is_numeric($_GET['page'])) {
$page = $_GET['page'];
}
$avatars_per_page = variable_get('avatar_selection_avatar_per_page', 30);
$js_file = drupal_get_path('module', 'avatar_selection') . '/js/avatar_selection.js';
if ('user_edit' == $form_id && is_array($form['picture'])) {
drupal_add_css(drupal_get_path('module', 'avatar_selection') . '/avatar_selection.css');
$force_choose = variable_get('avatar_selection_force_user_avatar', 0);
// If upload support has been disabled, remove the ability to upload and
// delete pictures.
if ($disable_upload) {
unset($form['picture']['picture_delete']);
unset($form['picture']['picture_upload']);
}
else {
$force_choose = 0;
}
// Show selection options.
$selects = _avatar_selection_image_list($user, "", 0, $page * $avatars_per_page, $avatars_per_page);
if (count($selects['avatars'])) {
$user_form = drupal_retrieve_form($form_id);
$current_avatar = basename($user_form['_account']['#value']->picture);
drupal_add_js(drupal_get_path('module', 'avatar_selection') . '/js/avatar_selection_pager.js', 'module', 'header');
$form['picture']['select_avatar'] = array(
'#type' => 'radios',
'#title' => $disable_upload ? t('Select an avatar') : t('Or simply select an icon'),
'#description' => $disable_upload ? t('Your virtual face or picture.') : '',
'#options' => $selects['avatars'],
'#default_value' => array_key_exists($current_avatar, $selects['avatars']) ? $current_avatar : '',
'#required' => $force_choose ? TRUE : FALSE,
'#attributes' => array(
'class' => 'user-avatar-select',
),
'#prefix' => '<div id="avatar-selection-loading"></div>',
'#suffix' => theme('avatar_selection_pager', 'form#user-edit', 'div.user-avatar-select', $selects['total'], $avatars_per_page, '/' . $js_file),
);
}
// Don't allow user to delete a selected avatar.
$path = '/avatar_selection/';
if (!empty($form['picture']['current_picture']['#value']) && preg_match($path, $form['picture']['current_picture']['#value'])) {
unset($form['picture']['picture_delete']);
}
drupal_add_js($js_file, 'module', 'header');
}
elseif ('user_register' == $form_id) {
$anon_user = drupal_anonymous_user();
$force_choose = variable_get('avatar_selection_force_user_avatar_reg', 0);
$selects = _avatar_selection_image_list($anon_user, "", 0, $page * $avatars_per_page, $avatars_per_page);
if (count($selects['avatars'])) {
drupal_add_css(drupal_get_path('module', 'avatar_selection') . '/avatar_selection.css');
drupal_add_js(drupal_get_path('module', 'avatar_selection') . '/js/avatar_selection_pager.js', 'module', 'header');
$upload = 1;
if (!is_array($form['picture'])) {
$upload = 0;
// I.e. Not provided by "register with picture" contributed module.
$form['picture'] = array(
'#type' => 'fieldset',
'#title' => t('Picture'),
'#weight' => 1,
);
}
$form['picture']['select_avatar'] = array(
'#type' => 'radios',
'#title' => $upload == 0 ? t('Select an avatar') : t('Or simply select an icon'),
'#description' => $upload ? '' : t('Your virtual face or picture.'),
'#options' => $selects['avatars'],
'#required' => $force_choose ? TRUE : FALSE,
'#attributes' => array(
'class' => 'user-avatar-select',
),
'#prefix' => '<div id="avatar-selection-loading"></div>',
'#suffix' => theme('avatar_selection_pager', 'form#user-register', 'div.user-avatar-select', $selects['total'], $avatars_per_page, '/' . $js_file),
);
}
drupal_add_js($js_file, 'module', 'header');
}
return $form;
}
/**
* Implementation of hook_user().
*
* Validate and upload the user's picture.
*/
function avatar_selection_user($op, &$edit, &$user, $category = 'account') {
global $form_values;
switch ($op) {
case 'validate':
$file = file_check_upload('picture_upload');
if (!$file && $edit['select_avatar']) {
unset($edit['picture_delete']);
$path = file_create_path('avatar_selection') . '/';
$form_values['picture'] = $path . $edit['select_avatar'];
}
elseif (!$file && variable_get('avatar_selection_set_random_default', FALSE)) {
if ($user->picture && $edit['picture_delete'] != 1) {
$form_values['picture'] = $user->picture;
}
else {
unset($edit['picture_delete']);
$form_values['picture'] = avatar_selection_get_random_image($user);
}
}
break;
}
}
/**
* Select a random avatar picture for a certain user.
*
* @param $user
* User object.
* @return
* Return the path to the image to be shown as avatar.
*/
function avatar_selection_get_random_image($user) {
$avatars = _avatar_selection_image_list($user);
if ($avatars['total'] > 0) {
$avatar = array_rand($avatars['avatars'], 1);
if ($avatar) {
$path = file_create_path('avatar_selection');
$avatar = $path . '/' . $avatar;
return $avatar;
}
}
return ' ';
}
/**
* Get the list of avatars available to a certain user.
*
* @param $user
* User object (optional).
* @param $set_type
* Set type, can be 'role' or 'og' (optional).
* @param $set_id
* The unique identifier of the set (optional).
* @param $from
* The offset.
* @param $count
* Number of avatars to return.
* @return
* Return an array with the list of avatars for the current user, together
* with the number of avatars.
*/
function _avatar_selection_image_list($user = "", $set_type = "", $set_id = 0, $from = 0, $count = 0) {
$avatars = array();
$dir = file_create_path('avatar_selection');
$url = file_create_url($dir);
$total = 0;
// If we're searching on a particular role.
if ($set_type == 'role') {
if ($set_id) {
$total = db_result(db_query("SELECT count(*) FROM {avatar_selection} avs, {avatar_selection_roles} avsr WHERE avs.aid = avsr.aid AND avsr.rid = %d", $set_id));
$result = db_query_range("SELECT DISTINCT avatar, name, weight FROM {avatar_selection} avs, {avatar_selection_roles} avsr WHERE avs.aid = avsr.aid AND avsr.rid = %d ORDER BY weight, name, avatar", $set_id, $from, $count);
}
else {
$total = db_result(db_query("SELECT count(*) FROM {avatar_selection} avs LEFT JOIN {avatar_selection_roles} avsr ON avs.aid = avsr.aid WHERE avsr.rid IS NULL"));
$result = db_query_range("SELECT DISTINCT avatar, name, weight FROM {avatar_selection} avs LEFT JOIN {avatar_selection_roles} avsr ON avs.aid = avsr.aid WHERE avsr.rid IS NULL ORDER BY weight, name, avatar", $from, $count);
}
}
elseif ($set_type == 'og') {
if ($set_id) {
$total = db_result(db_query("SELECT count(*) FROM {avatar_selection} avs, {avatar_selection_og} og WHERE avs.aid = og.aid AND og.ogid = %d", $set_id));
$result = db_query_range("SELECT DISTINCT avatar, name, weight FROM {avatar_selection} avs, {avatar_selection_og} og WHERE avs.aid = og.aid AND og.ogid = %d ORDER BY weight, name, avatar", $set_id, $from, $count);
}
else {
$total = db_result(db_query("SELECT count(*) FROM {avatar_selection} avs LEFT JOIN {avatar_selection_og} og ON avs.aid = og.aid WHERE og.ogid IS NULL"));
$result = db_query_range("SELECT DISTINCT avatar, name, weight FROM {avatar_selection} avs LEFT JOIN {avatar_selection_og} og ON avs.aid = og.aid WHERE og.ogid IS NULL ORDER BY weight, name, avatar", $from, $count);
}
}
elseif (!empty($user)) {
// Set up some variables.
$user_roles = array();
$user_roles_placeholders = '';
if (is_array($user->roles) && !empty($user->roles)) {
$user_roles = array_keys($user->roles);
$user_roles_placeholders = implode(',', array_fill(0, count($user_roles), '%d'));
}
$user_og = array();
$user_og_placeholders = '';
if (module_exists("og")) {
if (!empty($user->og_groups) && is_array($user->og_groups)) {
$user_og = array_keys($user->og_groups);
$user_og_placeholders = implode(',', array_fill(0, count($user_og), '%d'));
}
}
// Distinct avatars are enabled.
if (variable_get('avatar_selection_distinctive_avatars', FALSE)) {
// Organic groups enabled.
if (module_exists("og") && !empty($user_og)) {
$total = db_result(db_query("SELECT count(distinct avs.aid) FROM {avatar_selection} avs LEFT JOIN {users} u ON u.picture = concat('%s/', avs.avatar) LEFT JOIN {avatar_selection_roles} avsr ON avs.aid = avsr.aid LEFT JOIN {avatar_selection_og} avso ON avs.aid = avso.aid WHERE u.picture IS NULL AND (avsr.rid IS NULL OR avsr.rid NOT IN (" . $user_roles_placeholders . ")) AND (avso.ogid IS NULL OR avso.ogid NOT IN (" . $user_og_placeholders . "))", $dir, $user_roles, $user_og));
if ($count == 0) {
$count = $total;
}
$result = db_query_range("SELECT DISTINCT avatar, avs.name, avs.weight FROM {avatar_selection} avs LEFT JOIN {users} u ON u.picture = concat('%s/', avs.avatar) LEFT JOIN {avatar_selection_roles} avsr ON avs.aid = avsr.aid LEFT JOIN {avatar_selection_og} avso ON avs.aid = avso.aid WHERE u.picture IS NULL AND (avsr.rid IS NULL OR avsr.rid NOT IN (" . $user_roles_placeholders . ")) AND (avso.ogid IS NULL OR avso.ogid NOT IN (" . $user_og_placeholders . ")) ORDER BY avs.weight, avs.name, avatar", $dir, $user_roles, $user_og, $from, $count);
}
else {
$total = db_result(db_query("SELECT count(distinct avs.aid) FROM {avatar_selection} avs LEFT JOIN {users} u ON u.picture = concat('%s/', avs.avatar) LEFT JOIN {avatar_selection_roles} avsr ON avs.aid = avsr.aid WHERE u.picture IS NULL AND (avsr.rid IS NULL OR avsr.rid NOT IN (" . $user_roles_placeholders . "))", $dir, $user_roles));
if ($count == 0) {
$count = $total;
}
$result = db_query_range("SELECT DISTINCT avatar, avs.name, avs.weight FROM {avatar_selection} avs LEFT JOIN {users} u ON u.picture = concat('%s/', avs.avatar) LEFT JOIN {avatar_selection_roles} avsr ON avs.aid = avsr.aid WHERE u.picture IS NULL AND (avsr.rid IS NULL OR avsr.rid NOT IN (" . $user_roles_placeholders . ")) ORDER BY avs.weight, avs.name, avatar", $dir, $user_roles, $from, $count);
}
}
elseif ($user->uid > 1 || in_array(1, array_keys($user->roles))) {
// Organic groups enabled.
if (module_exists("og") && !empty($user_og)) {
$total = db_result(db_query("SELECT count(distinct avs.aid) FROM {avatar_selection} avs LEFT JOIN {avatar_selection_roles} avsr ON avs.aid = avsr.aid LEFT JOIN {avatar_selection_og} avso ON avs.aid = avso.aid WHERE (avsr.rid IS NULL OR avsr.rid IN (" . $user_roles_placeholders . ")) AND (avso.ogid IS NULL OR avso.ogid IN (" . $user_og_placeholders . "))", $user_roles, $user_og));
if ($count == 0) {
$count = $total;
}
$result = db_query_range("SELECT DISTINCT avatar, name, weight FROM {avatar_selection} avs LEFT JOIN {avatar_selection_roles} avsr ON avs.aid = avsr.aid LEFT JOIN {avatar_selection_og} avso ON avs.aid = avso.aid WHERE (avsr.rid IS NULL OR avsr.rid IN (" . $user_roles_placeholders . ")) AND (avso.ogid IS NULL OR avso.ogid IN (" . $user_og_placeholders . ")) ORDER BY weight, name, avatar", $user_roles, $user_og, $from, $count);
}
else {
$total = db_result(db_query("SELECT count(distinct avs.aid) FROM {avatar_selection} avs LEFT JOIN {avatar_selection_roles} avsr ON avs.aid = avsr.aid WHERE avsr.rid IS NULL OR avsr.rid IN (" . $user_roles_placeholders . ")", $user_roles));
if ($count == 0) {
$count = $total;
}
$result = db_query_range("SELECT DISTINCT avatar, name, weight FROM {avatar_selection} avs LEFT JOIN {avatar_selection_roles} avsr ON avs.aid = avsr.aid WHERE avsr.rid IS NULL OR avsr.rid IN (" . $user_roles_placeholders . ") ORDER BY weight, name, avatar", $user_roles, $from, $count);
}
}
else {
$total = db_result(db_query("SELECT count(*) FROM {avatar_selection} avs"));
if ($count == 0) {
$count = $total;
}
$result = db_query_range("SELECT aid, avatar, name, weight FROM {avatar_selection} avs ORDER BY weight, name, avatar", $from, $count);
}
}
while ($avatar = db_fetch_object($result)) {
$avs_image = $avatar->avatar;
$name = $avatar->name;
$avatars[$avs_image] = theme('image', $url . '/' . $avs_image, $name, $name, NULL, FALSE);
}
$selects['avatars'] = $avatars;
$selects['total'] = $total;
return $selects;
}
/**
* Scan the directory for new files.
*
* @param $name
* The name to assign the new avatar(s).
* @param $access
* The permission - the value determines which user roles have rights to see
* the avatar.
* @param $og
* Organic group (optional).
* @param $weight
* Avatar weight to assign.
* @return
* Number of images found.
*/
function _avatar_selection_scan_images($name, $access, $og = array(), $weight = 0) {
$avatars = array();
$add_count = 0;
$delete_count = 0;
$dir = file_create_path('avatar_selection');
$mask = '.*\\.(gif|GIF|Gif|jpg|JPG|Jpg|jpeg|JPEG|Jpeg|png|PNG|Png)';
$listings = file_scan_directory($dir, $mask, array(
'.',
'..',
'CVS',
), 0, TRUE);
$result = db_query("SELECT avatar FROM {avatar_selection} avs");
while ($avatar = db_fetch_object($result)) {
$avatars[$avatar->avatar] = $avatar->avatar;
}
// Search for new files. Remove matching records from avatars array.
foreach ($listings as $listing) {
$filename = str_replace("{$dir}/", '', $listing->filename);
if (in_array($filename, $avatars)) {
unset($avatars[$filename]);
}
else {
_avatar_selection_save_avatar_info(0, $filename, empty($name) ? $filename : $name, $access, $og, $weight);
$add_count++;
}
}
// Remove records from database where we have an avatar entry but no
// corresponding file.
foreach ($avatars as $avatar) {
avatar_selection_image_delete($avatar);
$delete_count++;
}
$count['add'] = $add_count;
$count['delete'] = $delete_count;
return $count;
}
/**
* Select which form will be shown to the user, according to the permissions.
*
* @param $op
* Default NULL; the action the user wants to do after the function checks
& the permission.
* @return
* Return the structure of the form.
*/
function avatar_selection_settings_page($op = NULL) {
switch ($op) {
case 'edit':
$output = drupal_get_form('avatar_selection_config_form');
break;
case 'upload':
$output = drupal_get_form('avatar_selection_upload_form');
break;
case 'list':
$output = drupal_get_form('avatar_selection_edit_form');
break;
default:
$form[] = array(
'#type' => 'fieldset',
'#title' => t('Add another'),
);
$output .= drupal_get_form('avatar_selection_config_form');
break;
}
return $output;
}
/**
* Create the form structure for configuring the avatar module settings; seen
* in the 'Configure' tab under the Avatar Selection administration page.
*
* @return
* Return the structure of the form.
*/
function avatar_selection_config_form() {
if (!variable_get('user_pictures', 0)) {
drupal_set_message(t('User Pictures option is disabled. You will need to enable this option before you can use the Avatar Selection module. You may configure this setting on the <a href="@url">User settings</a> page.', array(
'@url' => url('admin/user/settings'),
)));
}
// To store how many avatars per page are displayed.
$form['update']['avatar_per_page'] = array(
'#type' => 'textfield',
'#title' => t('How many avatars per page'),
'#description' => t('The number of avatars to show per page.'),
'#default_value' => variable_get('avatar_selection_avatar_per_page', 30),
'#size' => 3,
);
$form['update']['disable_user_upload'] = array(
'#type' => 'checkbox',
'#title' => t('Disable users uploading pictures to profile'),
'#description' => t('Allow users to pick their avatar from the selection but prevent them from uploading new avatars when editing their account.'),
'#default_value' => variable_get('avatar_selection_disable_user_upload', FALSE),
);
$form['update']['force_set_image_reg'] = array(
'#type' => 'checkbox',
'#title' => t('Force users to select an avatar image on user registration.'),
'#description' => t('This only applies on the user registration screen.'),
'#default_value' => variable_get('avatar_selection_force_user_avatar_reg', FALSE),
);
$form['update']['force_set_image'] = array(
'#type' => 'checkbox',
'#title' => t('Force users to select an avatar image when editing their account'),
'#description' => t('This only applies when the user is editing their account details and image uploads are disabled.'),
'#default_value' => variable_get('avatar_selection_force_user_avatar', FALSE),
);
$form['update']['set_random_default'] = array(
'#type' => 'checkbox',
'#title' => t('Enable random default avatar image.'),
'#description' => t("Automatically set a random avatar image to be used when the user doesn't set one for their account."),
'#default_value' => variable_get('avatar_selection_set_random_default', FALSE),
);
$form['update']['distinctive_avatars'] = array(
'#type' => 'checkbox',
'#title' => t('Enable unique avatars.'),
'#description' => t("Only allow users to pick an avatar that isn't already in use by another user. If there are no available avatars left, the default avatar image will be used."),
'#default_value' => variable_get('avatar_selection_distinctive_avatars', FALSE),
);
$form['update']['submit'] = array(
'#type' => 'submit',
'#value' => t('Update'),
);
return $form;
}
/**
* Create the form structure for uploading an avatar.
*
* @return
* Return the structure of the form.
*/
function avatar_selection_upload_form() {
if (!variable_get('user_pictures', 0)) {
drupal_set_message(t('User Pictures option is disabled. You will need to enable this option before you can use the Avatar Selection module. You may configure this setting on the <a href="@url">User settings</a> page.', array(
'@url' => url('admin/user/settings'),
)));
}
$form['#attributes']['enctype'] = 'multipart/form-data';
$form['bulk_upload'] = array(
'#type' => 'fieldset',
'#title' => t('Bulk Upload / Delete'),
'#description' => t("To upload a large number of avatars, first copy the images manually to the %dir folder, using ftp for example. To make these new avatar images available, check the 'Scan for new avatars' option. All new images will then be added to the list. By removing files from this directory and checking the box, you can also perform a bulk delete.", array(
'%dir' => file_create_path('avatar_selection'),
)),
'#collapsed' => TRUE,
'#collapsible' => TRUE,
);
$form['bulk_upload']['scan_avatars'] = array(
'#type' => 'checkbox',
'#title' => t('Scan avatars'),
'#description' => t('All new avatar images found will be added to the list of available avatars with the name, weight and permissions defined below. Scanning for new avatars may be slow depending on the number of files. All avatar entries which no longer have a corresponding file will be be removed.'),
'#default_value' => 0,
);
$form['picture_upload'] = array(
'#type' => 'file',
'#title' => t('Upload image'),
'#size' => 48,
'#description' => t('A new avatar image. Maximum dimensions are %dimensions and the maximum size is %size kB. Images must have one of the following extensions (case sensitive): png, jpg, jpeg, gif, PNG, JPG, JPEG, GIF.', array(
'%dimensions' => variable_get('user_picture_dimensions', '85x85'),
'%size' => variable_get('user_picture_file_size', 30),
)) . ' ' . variable_get('user_picture_guidelines', ''),
);
$form['avatar_name'] = array(
'#type' => 'textfield',
'#title' => t('Name'),
'#description' => t("Image name or title which will be displayed when hovering over the image. It's also used in conjunction with the weight setting for sorting the avatars."),
'#size' => 48,
);
$form['avatar_weight'] = array(
'#type' => 'weight',
'#title' => t('Weight'),
'#delta' => 100,
'#description' => t('Avatars with a lower weight appear before higher weighted avatars in lists.'),
);
$form['permissions'] = array(
'#type' => 'fieldset',
'#title' => t('Permissions'),
'#weight' => 2,
);
$form['permissions']['access'] = array(
'#type' => 'checkboxes',
'#title' => t('User Roles'),
'#options' => avatar_selection_handler_filter_role(),
'#description' => t('Only the checked roles will be able to see this avatar icon; if no roles are checked, access will not be restricted.'),
);
if (module_exists("og")) {
$form['permissions']['og_access'] = array(
'#type' => 'checkboxes',
'#title' => t('Organic Groups'),
'#options' => og_all_groups_options(),
'#description' => t('Only users in the checked organic groups will be able to see this avatar icon; if no groups are checked, access will not be restricted.'),
);
}
$form['upload'] = array(
'#type' => 'submit',
'#value' => t('Upload'),
'#weight' => 10,
);
return $form;
}
function avatar_selection_roles_page($op = NULL) {
$output = "";
// Display the form where appropriate.
if (isset($op) && ($op == 'role' || $op == 'og')) {
$output .= drupal_get_form('avatar_selection_edit_form');
}
else {
$avs_access = array();
$og_access = array();
$avs_access[0] = 0;
$og_access[0] = 0;
// Get the list of access roles and initialise the count to 0.
$roles = avatar_selection_handler_filter_role();
foreach ($roles as $rid => $role_name) {
$avs_access[$rid] = 0;
}
// Get the list of organic groups and initialise the count to 0.
if (module_exists("og")) {
$ogroups = og_all_groups_options();
foreach ($ogroups as $ogid => $ogroup_name) {
$og_access[$ogid] = 0;
}
}
// Get the total number of avatars available on the system.
$total_count = 0;
$result = db_query("SELECT count(*) AS count FROM {avatar_selection} avs");
while ($avatar = db_fetch_object($result)) {
$total_count = $avatar->count;
}
$output .= '<p>' . t('There is a total of %count avatars configured.', array(
'%count' => $total_count,
)) . '</p>';
// Get the count of avatars per role.
$result = db_query("SELECT avsr.rid, count(*) AS count FROM {avatar_selection} avs LEFT JOIN {avatar_selection_roles} avsr ON avs.aid = avsr.aid GROUP BY avsr.rid");
while ($avatar = db_fetch_object($result)) {
if (empty($avatar->rid)) {
$avs_access[0] += $avatar->count;
}
else {
$avs_access[$avatar->rid] += $avatar->count;
}
}
// Get the count of avatars per organic group.
$result = db_query("SELECT avso.ogid, count(*) AS count FROM {avatar_selection} avs LEFT JOIN {avatar_selection_og} avso ON avs.aid = avso.aid GROUP BY avso.ogid");
while ($avatar = db_fetch_object($result)) {
if (empty($avatar->ogid)) {
$og_access[0] += $avatar->count;
}
else {
$og_access[$avatar->ogid] += $avatar->count;
}
}
// Format the user roles table.
$avs_rows = array();
$header = array(
t('User Role'),
t('Number of Avatars'),
);
$edit = l(t('edit'), 'admin/settings/avatar_selection/edit/role/0');
$avs_rows[] = array(
t('Available to all roles'),
$avs_access[0],
$edit,
);
foreach ($roles as $rid => $role_name) {
$edit = l(t('edit'), 'admin/settings/avatar_selection/edit/role/' . $rid);
$avs_rows[] = array(
$role_name,
$avs_access[$rid],
$edit,
);
}
$output .= theme('table', $header, $avs_rows);
// Format the organic groups table.
if (module_exists("og")) {
$og_rows = array();
$header = array(
t('Organic Group'),
t('Number of Avatars'),
);
$edit = l(t('edit'), 'admin/settings/avatar_selection/edit/og/0');
$og_rows[] = array(
t('Available to all groups'),
$og_access[0],
$edit,
);
foreach ($ogroups as $ogid => $ogroup_name) {
$edit = l(t('edit'), 'admin/settings/avatar_selection/edit/og/' . $ogid);
$og_rows[] = array(
$ogroup_name,
$og_access[$ogid],
$edit,
);
}
$output .= theme('table', $header, $og_rows);
}
}
return $output;
}
/**
* Create the form structure for listing the avatars and managing them in the
* 'Manage Avatars' tab under the Avatar Selection administration page.
*
* @param $form_values
* Array containing the form values submitted.
* @return
* Return the structure of the form.
*/
function avatar_selection_edit_form($form_values = NULL) {
// We need the pager global variables.
global $_GET;
if (!variable_get('user_pictures', 0)) {
drupal_set_message(t('User Pictures option is disabled. You will need to enable this option before you can use the Avatar Selection module. You may configure this setting on the <a href="@url">User settings</a> page.', array(
'@url' => url('admin/user/settings'),
)));
}
drupal_add_css(drupal_get_path('module', 'avatar_selection') . '/avatar_selection.css');
$set_type = arg(4);
$set_id = arg(5);
// We find out the current page number.
$page = 0;
if (isset($_GET['page']) && is_numeric($_GET['page'])) {
$page = $_GET['page'];
}
$avatars_per_page = variable_get('avatar_selection_avatar_per_page', 30);
$selects = _avatar_selection_image_list("", $set_type, $set_id, $page * $avatars_per_page, $avatars_per_page);
if (!count($selects['avatars'])) {
drupal_set_message(t('There are no avatars configured.'));
}
else {
if (!isset($form_values)) {
$step = "list";
}
else {
$step = "edit";
}
$form['step'] = array(
'#type' => 'value',
'#value' => $step,
);
$form['#multistep'] = TRUE;
if ($step == "list") {
$form['#redirect'] = FALSE;
if ($set_type == 'role') {
$sets = avatar_selection_handler_filter_role();
$set_name = $sets[$set_id];
if ($set_id == 0) {
$set_name = 'All roles';
}
$form['title'] = array(
'#value' => '<strong>' . t('Role: %name', array(
'%name' => $set_name,
)) . '</strong>',
);
}
elseif ($set_type == 'og') {
$sets = og_all_groups_options();
$set_name = $sets[$set_id];
if ($set_id == 0) {
$set_name = 'All groups';
}
$form['title'] = array(
'#value' => '<strong>' . t('Organic Group: %name', array(
'%name' => $set_name,
)) . '</strong>',
);
}
drupal_add_js(drupal_get_path('module', 'avatar_selection') . '/js/avatar_selection_pager.js', 'module', 'header');
$js_file = drupal_get_path('module', 'avatar_selection') . '/js/avatar_selection.js';
$form['select_avatar'] = array(
'#type' => 'radios',
'#title' => t('Select an avatar to edit'),
'#options' => $selects['avatars'],
'#required' => TRUE,
'#attributes' => array(
'class' => 'user-avatar-select',
),
'#suffix' => theme('avatar_selection_pager', 'form#avatar-selection-edit-form', 'div.user-avatar-select', $selects['total'], $avatars_per_page, '/' . $js_file),
);
$form['search'] = array(
'#type' => 'submit',
'#value' => t('Edit'),
);
drupal_add_js($js_file, 'module', 'header');
}
elseif ($step == "edit") {
$form['#redirect'] = array(
'admin/settings/avatar_selection/edit',
);
$roles = avatar_selection_handler_filter_role();
$aid = 0;
$weight = 0;
$name = "";
$avs_access = array();
$og_access = array();
$result = db_query("SELECT avs.aid, avatar, name, weight, rid, ogid FROM {avatar_selection} avs LEFT JOIN {avatar_selection_roles} avsr ON avs.aid = avsr.aid LEFT JOIN {avatar_selection_og} avso ON avs.aid = avso.aid WHERE avatar = '%s' ORDER BY weight, name, avatar", $form_values['select_avatar']);
while ($avatar = db_fetch_object($result)) {
$aid = $avatar->aid;
$name = $avatar->name;
$weight = $avatar->weight;
if ($avatar->rid) {
array_push($avs_access, $avatar->rid);
}
if ($avatar->ogid) {
array_push($og_access, $avatar->ogid);
}
}
$image_path = file_create_path('avatar_selection');
$selected_avatar = $form_values['select_avatar'];
$image = theme('image', $image_path . '/' . $selected_avatar);
$form['avatar_image'] = array(
'#value' => $image,
);
$form['aid'] = array(
'#type' => 'value',
'#value' => $aid,
);
$form['select_avatar'] = array(
'#type' => 'value',
'#value' => $form_values['select_avatar'],
);
$form['avatar_name'] = array(
'#type' => 'textfield',
'#title' => t('Name'),
'#description' => t("Image name or title which will be displayed when hovering over the image. It's also used in conjunction with the weight setting for sorting the avatars."),
'#size' => 48,
'#default_value' => $name,
);
$form['avatar_weight'] = array(
'#type' => 'weight',
'#title' => t('Weight'),
'#delta' => 100,
'#description' => t('Avatars with a lower weight appear before higher weighted avatars in lists.'),
'#default_value' => $weight,
);
$form['permissions'] = array(
'#type' => 'fieldset',
'#title' => t('Permissions'),
'#weight' => 1,
);
$form['permissions']['access'] = array(
'#type' => 'checkboxes',
'#title' => t('User Roles'),
'#default_value' => $avs_access,
'#options' => $roles,
'#description' => t('Only the checked roles will be able to see this avatar icon; if no roles are checked, access will not be restricted.'),
);
if (module_exists("og")) {
$form['permissions']['og_access'] = array(
'#type' => 'checkboxes',
'#title' => t('Organic Groups'),
'#default_value' => $og_access,
'#options' => og_all_groups_options(),
'#description' => t('Only users in the checked organic groups will be able to see this avatar icon; if no groups are checked, access will not be restricted.'),
);
}
$form['update'] = array(
'#type' => 'submit',
'#value' => t('Update'),
'#weight' => 9,
);
$form['delete'] = array(
'#type' => 'submit',
'#value' => t('Delete'),
'#weight' => 10,
);
}
}
return $form;
}
/**
* Validate the submission.
*
* Ensure the number of avatars page setting is numeric.
*
* @param $form_id
* The form id.
* @param $form_values
* Array containing the form values submitted.
*/
function avatar_selection_config_form_validate($form_id, $form_values) {
$error = FALSE;
if ($form_values['op'] == t('Update')) {
if (!is_numeric($form_values['avatar_per_page'])) {
form_set_error('avatar_per_page', t('Must be a number.'));
$error = TRUE;
}
}
}
/**
* Validate and upload the image.
*
* @param $form_id
* The form id.
* @param $form_values
* Array containing the form values submitted.
*/
function avatar_selection_upload_form_validate($form_id, $form_values) {
$error = FALSE;
if ($form_values['op'] == t('Upload')) {
if ($file = file_check_upload('picture_upload')) {
avatar_selection_validate_picture($file);
}
}
}
/**
* Validate the submission.
*
* Check if Delete has been chosen AND a checkbox has been selected.
*
* @param $form_id
* The form id.
* @param $form_values
* Array containing the form values submitted.
*/
function avatar_selection_delete_form_validate($form_id, $form_values) {
if ($form_values['op'] == t('Delete')) {
if (count(array_filter($form_values['images'])) == 0) {
form_set_error('images', t('Please select images to delete.'));
}
}
}
/**
* Validate the picture.
*/
function avatar_selection_validate_picture($file) {
global $form_values;
// Check that uploaded file is an image, with a maximum file size
// and maximum height/width.
$info = image_get_info($file->filepath);
list($maxwidth, $maxheight) = explode('x', variable_get('user_picture_dimensions', '85x85'));
if (!$info || !$info['extension']) {
form_set_error('picture_upload', t('The uploaded file was not an image.'));
}
elseif (image_get_toolkit()) {
image_scale($file->filepath, $file->filepath, $maxwidth, $maxheight);
}
elseif (filesize($file->filepath) > variable_get('user_picture_file_size', 30) * 1000) {
form_set_error('picture_upload', t('The uploaded image is too large; the maximum file size is %size kB.', array(
'%size' => variable_get('user_picture_file_size', 30),
)));
}
elseif ($info['width'] > $maxwidth || $info['height'] > $maxheight) {
form_set_error('picture_upload', t('The uploaded image is too large; the maximum dimensions are %dimensions pixels.', array(
'%dimensions' => variable_get('user_picture_dimensions', '85x85'),
)));
}
}
/**
* Submit the settings form in the Avatar Selection administration page.
*
* @param $form_id
* The form id.
* @param $form_values
* Array containing the form values submitted.
*/
function avatar_selection_config_form_submit($form_id, $form_values) {
$op = $form_values['op'];
if ($op == t('Update')) {
// Save system variables.
variable_set('avatar_selection_disable_user_upload', $form_values['disable_user_upload']);
variable_set('avatar_selection_force_user_avatar_reg', $form_values['force_set_image_reg']);
variable_set('avatar_selection_force_user_avatar', $form_values['force_set_image']);
variable_set('avatar_selection_avatar_per_page', $form_values['avatar_per_page']);
variable_set('avatar_selection_set_random_default', $form_values['set_random_default']);
variable_set('avatar_selection_distinctive_avatars', $form_values['distinctive_avatars']);
drupal_set_message(t('Configuration has been updated.'));
}
}
/**
* Submit the image upload form in the Avatar Selection administration page.
*
* @param $form_id
* The form id.
* @param $form_values
* Array containing the form values submitted.
*/
function avatar_selection_upload_form_submit($form_id, $form_values) {
$op = $form_values['op'];
if ($op == t('Upload')) {
// Get access settings.
$access = array_keys(array_filter($form_values['access']));
$og = array();
if (module_exists("og")) {
$og = array_keys(array_filter($form_values['og_access']));
}
$name = $form_values['avatar_name'];
$weight = $form_values['avatar_weight'];
// Scan for new files.
if ($form_values['scan_avatars'] == 1) {
$count = _avatar_selection_scan_images($name, $access, $og, $weight);
drupal_set_message(t('Scan complete: %added new avatars found. %deleted avatars removed.', array(
'%added' => $count['add'],
'%deleted' => $count['delete'],
)));
}
// Save uploaded files.
$dir = file_create_path('avatar_selection');
$is_writable = file_check_directory($dir, 1);
if ($is_writable) {
if ($source = file_check_upload('picture_upload')) {
if ($file = file_save_upload($source, $dir)) {
if (image_get_info($file->filepath)) {
_avatar_selection_save_avatar_info(0, $file->filename, $name, $access, $og, $weight);
drupal_set_message(t('New image saved.'));
}
else {
file_delete($file->filepath);
drupal_set_message(t('Uploaded file does not appear to be a valid image file. Please try again.'));
}
}
}
}
else {
form_set_error('picture_upload', t('Directory not writable: !dir', array(
'!dir' => $dir,
)));
}
}
}
/**
* Submit the image list form in the Avatar Selection - 'Manage Avatars' page.
*
* Function called when the Update button is pressed.
*
* @param $form_id
* The form id.
* @param $form_values
* Array containing the form values submitted.
*/
function avatar_selection_edit_form_submit($form_id, $form_values) {
$op = $form_values['op'];
if ($op == t('Update')) {
$access = array_keys(array_filter($form_values['access']));
if (module_exists("og")) {
$og = array_keys(array_filter($form_values['og_access']));
}
$name = $form_values['avatar_name'];
$weight = $form_values['avatar_weight'];
_avatar_selection_save_avatar_info($form_values['aid'], $form_values['select_avatar'], $name, $access, $og, $weight);
drupal_set_message(t('Image updated.'));
}
elseif ($op == t('Delete')) {
$image = $form_values['select_avatar'];
$deleted = avatar_selection_image_delete($image);
if ($deleted) {
drupal_set_message(t('Image deleted.'));
}
}
}
/**
* Delete the specified avatar image.
*
* @param $image
* Path to the image to be deleted.
*/
function avatar_selection_image_delete($image) {
$dir = file_create_path('avatar_selection');
if (file_check_location($dir . '/' . $image, $dir)) {
$aid = db_result(db_query("SELECT aid FROM {avatar_selection} WHERE avatar = '%s'", $image));
if ($aid) {
$result = db_query("DELETE FROM {avatar_selection} WHERE aid = %d", $aid);
$result = db_query("DELETE FROM {avatar_selection_roles} WHERE aid = %d", $aid);
$result = db_query("DELETE FROM {avatar_selection_og} WHERE aid = %d", $aid);
file_delete($dir . '/' . $image);
if (!image_get_info($dir . '/' . $image)) {
return 1;
}
}
}
return 0;
}
/**
* Implementation of hook_file_download().
*
* Ensure that user pictures (avatars) are always downloadable.
* @param $file
* The path to the file that will be checked if downloadable.
* @return
* An array containing the file mime type and size, generated by the array()
* function, if everything is fine. NULL, if the file is not downloadable.
*/
function avatar_selection_file_download($file) {
if (user_access('access content')) {
$data = explode('/', $file);
$icon = array_pop($data);
$folder = implode('/', $data);
if ('avatar_selection' == $folder) {
$info = image_get_info(file_create_path($file));
return array(
'Content-type: ' . $info['mime_type'],
'Content-length: ' . $info['file_size'],
);
}
else {
return NULL;
}
}
}
/**
* Return a list of the existing roles.
*
* @return
* Return the role id(s).
*/
function avatar_selection_handler_filter_role() {
$rids = array();
$result = db_query("SELECT r.rid, r.name FROM {role} r ORDER BY r.name");
while ($obj = db_fetch_object($result)) {
$rids[$obj->rid] = $obj->name;
}
return $rids;
}
/**
* Create the SQL queries in order to save the avatar path and data into the
* database, and perform them according to the SQL server type.
*
* @param $aid
* The avatar id.
* @param $image
* The avatar image.
* @param $name
* The avatar name, used as the image alternative text on the forms.
* @param $access
* Array of roles - the value determines which user roles have rights to see
* the avatar.
* @param $og
* Array of organic groups (optional).
* @param $weight
* The weight of the avatar. Lower weighted avatars appear before higher
* weighted avatars in the list.
*/
function _avatar_selection_save_avatar_info($aid, $image, $name, $access, $og = array(), $weight = 0) {
// Add or update avatar_selection table.
if ($aid) {
$result = db_query("UPDATE {avatar_selection} SET name = '%s', weight = %d WHERE aid = %d AND avatar = '%s'", $name, $weight, $aid, $image);
$result = db_query("DELETE FROM {avatar_selection_roles} WHERE aid = %d", $aid);
$result = db_query("DELETE FROM {avatar_selection_og} WHERE aid = %d", $aid);
}
else {
$aid = db_next_id("{avatar_selection}_aid");
$result = db_query("INSERT INTO {avatar_selection} (aid, avatar, name, weight) VALUES(%d, '%s', '%s', %d)", $aid, $image, $name, $weight);
}
// Add access settings.
if (is_array($access) && count($access)) {
foreach ($access as $rid) {
$result = db_query("INSERT INTO {avatar_selection_roles} (aid, rid) VALUES(%d, %d)", $aid, $rid);
}
}
if (is_array($og) && count($og)) {
foreach ($og as $ogid) {
$result = db_query("INSERT INTO {avatar_selection_og} (aid, ogid) VALUES(%d, %d)", $aid, $ogid);
}
}
}
/**
* Output themed pager navigation.
*
* @param $form_id
* CSS identifier for the form to modify.
* @param $dom_identifier
* CSS identifier of form element to replace.
* @param $total
* Total number of elements to navigate through.
* @param $limit
* Maximum number of elements to show on one page.
* @param $js_file
* Javascript file to load and execute after successful ajax call.
* @return
* HTML formatted pager navigation.
*/
function theme_avatar_selection_pager($form_id, $dom_identifier, $total = 10, $limit = 10, $js_file = NULL) {
$path = $_GET['q'];
$total_pages = ceil($total / $limit);
$current_page = isset($_GET['page']) ? $_GET['page'] : 0;
// Calculate various markers within this pager piece:
// Middle is used to "center" pages around the current page.
$middle_page = 5;
$first_page = $current_page - $middle_page + 1;
$last_page = $current_page + $middle_page + 1;
$output = '<div class="avatar-selection-pager-nav">';
if ($current_page > 0) {
$output .= theme('avatar_selection_pager_link', t('« first'), $path, 0, $form_id, $dom_identifier, $js_file);
$output .= theme('avatar_selection_pager_link', t('‹ previous'), $path, $current_page - 1, $form_id, $dom_identifier, $js_file);
}
$i = $first_page;
// Adjust "center" if at end of query.
if ($last_page > $total_pages) {
$i = $i + ($total_pages - $last_page);
$last_page = $total_pages;
}
// Adjust "center" if at start of query.
if ($i <= 0) {
$last_page = $last_page + (1 - $i);
$i = 1;
}
// When there is more than one page, create the pager list.
if ($total_pages > 1) {
for (; $i <= $last_page && $i <= $total_pages; $i++) {
if ($i < $current_page + 1) {
$output .= theme('avatar_selection_pager_link', $i, $path, $i - 1, $form_id, $dom_identifier, $js_file);
}
if ($i == $current_page + 1) {
$output .= '<strong class="pager-current">' . $i . '</strong>';
}
if ($i > $current_page + 1) {
$output .= theme('avatar_selection_pager_link', $i, $path, $i - 1, $form_id, $dom_identifier, $js_file);
}
}
}
if ($current_page + 1 < $total_pages) {
$output .= theme('avatar_selection_pager_link', t('next ›'), $path, $current_page + 1, $form_id, $dom_identifier, $js_file);
$output .= theme('avatar_selection_pager_link', t('last »'), $path, $total_pages - 1, $form_id, $dom_identifier, $js_file);
}
$output .= '</div>';
return $output;
}
/**
* Output themed pager navigation link.
*
* @param $text
* Link (human-readable) text.
* @param $path
* Current page.
* @param $page
* Page number to display.
* @param $form_id
* CSS identifier for the form to modify.
* @param $dom_identifier
* CSS identifier of form element to replace.
* @param $js_file
* Javascript file to load and execute after successful ajax call.
* @return
* HTML formatted link for pager.
*/
function theme_avatar_selection_pager_link($text, $path, $page, $form_id, $dom_identifier, $js_file) {
$url = url($path);
$onclick = "return fetchPage('{$form_id}', '{$dom_identifier}', '{$url}', {$page}, '{$js_file}');";
$output .= l($text, $path, array(
'onclick' => $onclick,
), "page={$page}");
return $output;
}
Functions
Name![]() |
Description |
---|---|
avatar_selection_access | Implementation of hook_access(). |
avatar_selection_config_form | Create the form structure for configuring the avatar module settings; seen in the 'Configure' tab under the Avatar Selection administration page. |
avatar_selection_config_form_submit | Submit the settings form in the Avatar Selection administration page. |
avatar_selection_config_form_validate | Validate the submission. |
avatar_selection_delete_form_validate | Validate the submission. |
avatar_selection_edit_form | Create the form structure for listing the avatars and managing them in the 'Manage Avatars' tab under the Avatar Selection administration page. |
avatar_selection_edit_form_submit | Submit the image list form in the Avatar Selection - 'Manage Avatars' page. |
avatar_selection_file_download | Implementation of hook_file_download(). |
avatar_selection_form_alter | Implementation of hook_form_alter(). |
avatar_selection_get_random_image | Select a random avatar picture for a certain user. |
avatar_selection_handler_filter_role | Return a list of the existing roles. |
avatar_selection_help | Implementation of hook_help(). |
avatar_selection_image_delete | Delete the specified avatar image. |
avatar_selection_menu | Implementation of hook_menu(). |
avatar_selection_perm | Implementation of hook_perm(). |
avatar_selection_roles_page | |
avatar_selection_settings_page | Select which form will be shown to the user, according to the permissions. |
avatar_selection_upload_form | Create the form structure for uploading an avatar. |
avatar_selection_upload_form_submit | Submit the image upload form in the Avatar Selection administration page. |
avatar_selection_upload_form_validate | Validate and upload the image. |
avatar_selection_user | Implementation of hook_user(). |
avatar_selection_validate_picture | Validate the picture. |
theme_avatar_selection_pager | Output themed pager navigation. |
theme_avatar_selection_pager_link | Output themed pager navigation link. |
_avatar_selection_image_list | Get the list of avatars available to a certain user. |
_avatar_selection_save_avatar_info | Create the SQL queries in order to save the avatar path and data into the database, and perform them according to the SQL server type. |
_avatar_selection_scan_images | Scan the directory for new files. |