<?php
/* $Id$ */

/**
 * @file
 * Extensible Messaging and Presence Protocol API.
 *
 * When enabled, allows Drupal components to send messages to users via the
 * extensible messaging and presence protocol.
 */

/**
 * Server types.
 */
define('XMPP_SERVER_TCP',      0);
define('XMPP_SERVER_BOSH',     1);
define('XMPP_SERVER_INTERNAL', 2);

/**
 * TCP encryption methods.
 */
define('XMPP_CRYPTO_TLS', 0);
define('XMPP_CRYPTO_SSL', 1);

/**
 * Implementation of hook_help().
 */
function xmpp_help($section) {
	switch ($section) {
		case 'admin/help#xmpp':
			return t('
				<p>The XMPP module provides Drupal components with a way to communicate
				over the extensible messaging and presence protocol (aka Jabber). Once
				enabled, other modules will be able to send instant messages to site
				users.</p>
			');

		case 'admin/settings/xmpp/client':
			return t('
				<p>Configure the XMPP client to act on your site\'s behalf.</p>
			');

		case 'admin/settings/xmpp/server':
			return t('
				<p>The built-in server is not currently implemented.</p>
			');
	}
}

/**
 * Implementation of hook_perm().
 */
function xmpp_perm() {
	return array(
		'administer xmpp'
	);
}

/**
 * Implementation of hook_menu().
 */
function xmpp_menu($may_cache) {
	$items = array();

	if ($may_cache) {

		$items[] = array(
			'path'               => 'admin/settings/xmpp',
			'title'              => t('XMPP Settings'),
			'description'        => t('Configure XMPP API.'),
			'callback'           => 'drupal_get_form',
			'callback arguments' => array('xmpp_client_settings'),
			'access'             => user_access('administer xmpp'),
		);

		$items[] = array(
			'path'  => 'admin/settings/xmpp/client',
			'title' => t('Client'),
			'type'  => MENU_DEFAULT_LOCAL_TASK,
		);

		$items[] = array(
			'path'               => 'admin/settings/xmpp/server',
			'title'              => t('Server'),
			'callback'           => 'drupal_get_form',
			'callback arguments' => array('xmpp_server_settings'),
			'type'               => MENU_LOCAL_TASK
		);
	}

	return $items;
}

/**
 * XMPP client settings page.
 */
function xmpp_client_settings() {
	$form = array();

	$fields_sql = 'SELECT fid, title FROM {profile_fields}'.
								' WHERE type = \'textfield\'';

	$jid_format  = '&lt;user&gt;@&lt;domain&gt;[/&lt;resource&gt;]';
	$server_type = variable_get('xmpp_server_type', XMPP_SERVER_TCP);
	$query       = db_query($fields_sql);
	$fields      = array();

	while ($record = db_fetch_array($query))
		$fields[$record['fid']] = $record['title'];

	$server_types = array(
		XMPP_SERVER_TCP => t('External (TCP/IP)')
	);

	$crypto_methods = array(
		XMPP_CRYPTO_TLS => t('TLS'),
		XMPP_CRYPTO_SSL => t('SSL'),
	);

	$crypto_disabled = !extension_loaded('openssl');
	$crypto_text     = $crypto_disabled ? ' (Requires OpenSSL extension)' : '';



	$form['auth'] = array(
		'#type'        => 'fieldset',
		'#title'       => t('User info'),
	);

	$form['auth']['xmpp_client_jid'] = array(
		'#type'          => 'textfield',
		'#title'         => t('Username'),
		'#description'   => t('JID to use for authentication ('.$jid_format.').'),
		'#default_value' => variable_get('xmpp_client_jid', ''),
	);

	$form['auth']['xmpp_client_password'] = array(
		'#type'          => 'password',
		'#title'         => t('Password'),
		'#description'   => t('Password to use for authentication'),
		'#default_value' => variable_get('xmpp_client_password', ''),
	);

	$form['auth']['xmpp_client_jid_field'] = array(
		'#type'          => 'select',
		'#title'         => t('User JID Field'),
		'#description'   => t('Profile field which is used to store JIDs.'),
		'#options'       => $fields,
		'#default_value' => variable_get('xmpp_client_jid_field', null)
	);



	$form['server_type'] = array(
		'#type'  => 'fieldset',
		'#title' => t('Server type'),
	);

	$form['server_type']['xmpp_server_type'] = array(
		'#type'          => 'radios',
		'#title'         => t('Server type'),
		'#default_value' => $server_type,
		'#options'       => $server_types,
		'#description'   => t('Server type and connection method to be used.'),
	);



	$form['external_tcp'] = array(
		'#type'        => 'fieldset',
		'#title'       => t('External server (TCP/IP)'),
		'#collapsible' => true,
		'#collapsed'   => true,
	);

	$form['external_tcp']['xmpp_client_tcp_hostname'] = array(
		'#type'          => 'textfield',
		'#title'         => t('Hostname (optional)'),
		'#description'   => t('Hostname or IP of the external server.'),
		'#default_value' => variable_get('xmpp_client_tcp_hostname', ''),
		'#maxlength'     => 255,
	);

	$form['external_tcp']['xmpp_client_tcp_port'] = array(
		'#type'          => 'textfield',
		'#title'         => t('Port (optional)'),
		'#description'   => t('Port on which to establish the connection.'),
		'#default_value' => variable_get('xmpp_client_tcp_port', ''),
		'#maxlength'     => 5,
	);

	$form['external_tcp']['xmpp_client_tcp_use_dns'] = array(
		'#type'          => 'checkbox',
		'#title'         => t('Use DNS'),
		'#default_value' => variable_get('xmpp_client_tcp_use_dns', true),
		'#description'   => t('Enable DNS SRV look-ups.'),
	);

	$form['external_tcp']['xmpp_client_tcp_crypto'] = array(
		'#type'          => 'radios',
		'#title'         => t('Encryption mechanism'.$crypto_text),
		'#default_value' => variable_get('xmpp_client_tcp_crypto', XMPP_CRYPTO_TLS),
		'#options'       => $crypto_methods,
		'#description'   => t('Type of encryption to use (if available).'),
		'#disabled'      => $crypto_disabled
	);

	$form['external_tcp']['xmpp_client_tcp_require_crypto'] = array(
		'#type'          => 'checkbox',
		'#title'         => t('Require encryption'.$crypto_text),
		'#default_value' => variable_get('xmpp_client_tcp_require_crypto', false),
		'#description'   => t('Require the use of encryption.'),
		'#disabled'      => $crypto_disabled
	);



	$form['test'] = array(
		'#type'        => 'fieldset',
		'#title'       => t('Test settings'),
		'#collapsible' => true,
		'#collapsed'   => true,
	);

	$form['test']['xmpp_client_test_jid'] = array(
		'#type'          => 'textfield',
		'#title'         => t('Recipient'),
		'#description'   => t('Send a test IM to the specified JID.'),
		'#default_value' => '',
	);



	return system_settings_form($form);
}

/**
 * We can't execute any 'Update options' if no comments were selected.
 */
//function xmpp_client_settings_validate($form_id, $form_values) {
	//form_set_error('', t('Please select one or more comments to perform the update on.'));
	//drupal_goto('admin/settings/xmpp');`
//}

/**
 * Execute the chosen 'Update option' on the selected comments, such as
 * publishing, unpublishing or deleting.
 */
function xmpp_client_settings_submit($form_id, $form_values) {
	if (!empty($form_values['xmpp_client_test_jid']))
	{
	}

	drupal_set_message(print_r($_SESSION, true));
	drupal_goto('admin/settings/xmpp');
}

/**
 * Send a simple message to
 */
function xmpp_message($uid, $message)
{

}

/**
 * Map user id to their jabber id.
 */
function xmpp_uid_to_jid($uid = null)
{
	$fid = variable_get('xmpp_client_jid_field', null);

	if (is_null($fid))
		return null;

	if (is_null($uid)) {
		global $user;
		$uid = $user->uid;
	}

	$query = 'SELECT value FROM {profile_values} WHERE uid='.$uid.' AND'.
					 ' fid='.$fid;

	return db_result(db_query($fields_sql));
}
