/[drupal]/contributions/modules/xmpp/xmpp.module
ViewVC logotype

Diff of /contributions/modules/xmpp/xmpp.module

Parent Directory Parent Directory | Revision Log Revision Log | View Revision Graph Revision Graph | View Patch Patch

revision 1.2 by mkhitrov, Sun Jul 15 15:09:55 2007 UTC revision 1.3 by mkhitrov, Wed Aug 15 17:16:20 2007 UTC
# Line 13  Line 13 
13   * Implementation of hook_help().   * Implementation of hook_help().
14   */   */
15  function xmpp_help($section) {  function xmpp_help($section) {
16    switch ($section) {          switch ($section) {
17      case 'admin/help#xmpp':                  case 'admin/help#xmpp':
18        return '<p>'. t('                          return '<p>' . t('
19          The XMPP module provides other Drupal components with a way to                                  The XMPP module provides other Drupal components with a way to
20          communicate over the extensible messaging and presence protocol (aka                                  communicate over the extensible messaging and presence protocol (aka
21          Jabber). Once enabled and configured, other modules will be able to send                                  Jabber). Once enabled and configured, other modules will be able to send
22          instant messages to site users.                                  instant messages to site users.
23        ') .'</p>';                          ') . '</p>';
24            }
     case 'admin/settings/xmpp/server':  
       return '<p>'. t('  
         The built-in server is not currently implemented.  
       ') .'</p>';  
   }  
25  }  }
26    
27  /**  /**
28   * Implementation of hook_perm().   * Implementation of hook_perm().
29   */   */
30  function xmpp_perm() {  function xmpp_perm() {
31    return array(          return array('administer xmpp');
32      'administer xmpp'  }
33    );  
34    /**
35     * Implementation of hook_enable().
36     */
37    function xmpp_enable() {
38            $secret = sha1(uniqid(mt_rand(), true));
39      variable_set('xmpp_server_secret', $secret);
40      variable_set('xmpp_client_auth_passwd', $secret);
41  }  }
42    
43  /**  /**
44   * Implementation of hook_menu().   * Implementation of hook_menu().
45   */   */
46  function xmpp_menu($may_cache) {  function xmpp_menu($may_cache) {
47    $items = array();          $items = array();
48    
49    if ($may_cache) {          if ($may_cache) {
50                    $items[] = array(
51      $items[] = array(                          'path'               => 'admin/settings/xmpp',
52        'path'               => 'admin/settings/xmpp',                          'title'              => t('XMPP Settings'),
53        'title'              => t('XMPP Settings'),                          'description'        => t('Configure XMPP Module.'),
54        'description'        => t('Configure XMPP API.'),                          'callback'           => 'drupal_get_form',
55        'callback'           => 'drupal_get_form',                          'callback arguments' => array('xmpp_client_settings'),
56        'callback arguments' => array('xmpp_client_settings'),                          'access'             => user_access('administer xmpp')
57        'access'             => user_access('administer xmpp'),                  );
58      );  
59                    $items[] = array(
60      $items[] = array(                          'path'   => 'admin/settings/xmpp/client',
61        'path'   => 'admin/settings/xmpp/client',                          'title'  => t('Client'),
62        'title'  => t('Client'),                          'type'   => MENU_DEFAULT_LOCAL_TASK,
63        'type'   => MENU_DEFAULT_LOCAL_TASK,                          'access' => user_access('administer xmpp')
64        'access' => user_access('administer xmpp'),                  );
65      );  
66                    $items[] = array(
67      $items[] = array(                          'path'               => 'admin/settings/xmpp/server',
68        'path'               => 'admin/settings/xmpp/server',                          'title'              => t('Server'),
69        'title'              => t('Server'),                          'callback'           => 'drupal_get_form',
70        'callback'           => 'drupal_get_form',                          'callback arguments' => array('xmpp_server_settings'),
71        'callback arguments' => array('xmpp_server_settings'),                          'type'               => MENU_LOCAL_TASK,
72        'type'               => MENU_LOCAL_TASK,                          'access'             => user_access('administer xmpp')
73        'access'             => user_access('administer xmpp')                  );
74      );          }
75    }          else
76            {
77                    $items[] = array(
78                            'path'     => 'xmpp/server',
79                            'title'    => 'XMPP Server',
80                            'callback' => 'xmpp_server',
81                            'type'     => MENU_CALLBACK,
82                            'access'   => variable_get('xmpp_server_enabled', false)
83              );
84            }
85    
86            return $items;
87    }
88    
89    return $items;  /**
90     * Implementation of hook_form_alter().
91     */
92    function xmpp_form_alter($form_id, &$form) {
93            if ($form_id == 'xmpp_client_settings')
94                    $form['#submit']['xmpp_client_settings_test'] = array();
95  }  }
96    
97  /**  /**
98   * Client settings page.   * Client settings page.
99   */   */
100  function xmpp_client_settings() {  function xmpp_client_settings() {
101            $form            = array();
102            $fields          = array();
103            $crypto_disabled = !extension_loaded('openssl');
104            $crypto_text     = ($crypto_disabled ? ' (Requires OpenSSL extension)' : '');
105            $crypto          = ($crypto_disabled ? 'none' : 'tls');
106            $jid_format      = htmlspecialchars('<user>@<domain>[/<resource>]');
107    
108            $query = db_query(
109                    'SELECT fid, title FROM {profile_fields} WHERE type = \'textfield\''
110            );
111    
112            while ($record = db_fetch_array($query))
113                    $fields[$record['fid']] = $record['title'];
114    
115            $transport_methods = array(
116                    'tcp'    => t('External (TCP/IP)'),
117                    'webtcp' => t('Built-in (WebTCP)')
118            );
119    
120            $crypto_methods = array(
121                    'none' => t('None'),
122                    'tls'  => t('TLS'),
123                    'ssl'  => t('SSL')
124            );
125    
126            //
127            // Basic settings
128            //
129    
130            $form['client'] = array(
131                    '#type'        => 'fieldset',
132                    '#title'       => t('Basic settings')
133            );
134    
135            $form['client']['xmpp_client_auth_jid'] = array(
136                    '#type'          => 'textfield',
137                    '#title'         => t('Username'),
138                    '#description'   => t('JID to use for authentication ('.$jid_format.').'),
139                    '#default_value' => variable_get('xmpp_client_auth_jid', ''),
140                    '#required'      => true
141            );
142    
143            $form['client']['xmpp_client_auth_passwd'] = array(
144                    '#type'          => 'password',
145                    '#title'         => t('Password'),
146                    '#description'   => t('Password to use for authentication. Leave this '.
147                                          'field blank to keep the old password or when using '.
148                                          'the built-in server.')
149            );
150    
151            $form['client']['xmpp_client_jid_field'] = array(
152                    '#type'          => 'select',
153                    '#title'         => t('User JID Field'),
154                    '#description'   => t('Profile field which is used to store user JIDs. '.
155                                          'You should create this if it doesn\'t already '.
156                                          'exist.'),
157                    '#options'       => $fields,
158                    '#default_value' => variable_get('xmpp_client_jid_field', ''),
159                    '#required'      => true
160            );
161    
162            //
163            // Server type
164            //
165    
166            $form['server_type'] = array(
167                    '#type'  => 'fieldset',
168                    '#title' => t('Server type'),
169            );
170    
171            $form['server_type']['xmpp_client_transport'] = array(
172                    '#type'          => 'radios',
173                    '#title'         => t('Transport method'),
174                    '#description'   => t('Server type and transport method to be used.'),
175                    '#options'       => $transport_methods,
176                    '#default_value' => variable_get('xmpp_client_transport', 'tcp'),
177                    '#required'      => true
178            );
179    
180            //
181            // External (TCP/IP)
182            //
183    
184            $form['external_tcp'] = array(
185                    '#type'        => 'fieldset',
186                    '#title'       => t('External (TCP/IP)'),
187                    '#collapsible' => true,
188                    '#collapsed'   => true
189            );
190    
191            $form['external_tcp']['xmpp_client_tcp_host'] = array(
192                    '#type'          => 'textfield',
193                    '#title'         => t('Host'),
194                    '#description'   => t('Hostname or IP of the external server. This can '.
195                                          'usually be determined automatically from the JID.'),
196                    '#default_value' => variable_get('xmpp_client_tcp_host', '')
197            );
198    
199            $form['external_tcp']['xmpp_client_tcp_port'] = array(
200                    '#type'          => 'textfield',
201                    '#title'         => t('Port'),
202                    '#description'   => t('Port on which to establish the connection. The '.
203                                          'default is 5222, 5223 if SSL is used.'),
204                    '#default_value' => variable_get('xmpp_client_tcp_port', ''),
205                    '#maxlength'     => 5
206            );
207    
208            $form['external_tcp']['xmpp_client_tcp_use_dns'] = array(
209                    '#type'          => 'checkbox',
210                    '#title'         => t('Use DNS'),
211                    '#default_value' => variable_get('xmpp_client_tcp_use_dns', true),
212                    '#description'   => t('Enable DNS SRV look-ups.')
213            );
214    
215            $form['external_tcp']['xmpp_client_tcp_crypto'] = array(
216                    '#type'          => 'radios',
217                    '#title'         => t('Encryption mechanism'. $crypto_text),
218                    '#description'   => t('Type of encryption to use (if available).'),
219                    '#default_value' => variable_get('xmpp_client_tcp_crypto', $crypto),
220                    '#options'       => $crypto_methods,
221                    '#disabled'      => $crypto_disabled
222            );
223    
224            //
225            // Built-in (WebTCP)
226            //
227    
228            $form['builtin_webtcp'] = array(
229                    '#type'        => 'fieldset',
230                    '#title'       => t('Built-in (WebTCP)'),
231                    '#collapsible' => true,
232                    '#collapsed'   => true
233            );
234    
235            $form['builtin_webtcp']['xmpp_client_webtcp_url'] = array(
236                    '#type'          => 'textfield',
237                    '#title'         => t('URL'),
238                    '#description'   => t('Location of the WebTCP server. Usually this is '.
239                                          'http://[your_domain]/[path_to_drupal]/xmpp/server. '.
240                                          'Do not add a trailing slash.'),
241                    '#default_value' => variable_get('xmpp_client_webtcp_url', '')
242            );
243    
244            //
245            // Test configuration
246            //
247    
248            $form['test'] = array(
249                    '#type'  => 'fieldset',
250                    '#title' => t('Test configuration'),
251            );
252    
253            $form['test']['xmpp_client_test_jid'] = array(
254                    '#type'          => 'textfield',
255                    '#title'         => t('Recipient'),
256                    '#description'   => t('Send a test IM to the specified JID.')
257            );
258    
259    $form   = array();          return system_settings_form($form);
   $fields = array();  
   $query  = db_query(  
     'SELECT fid, title FROM {profile_fields}'.  
     ' WHERE type = \'textfield\''  
   );  
   
   while ($record = db_fetch_array($query))  
     $fields[$record['fid']] = $record['title'];  
   
   $transport_methods = array(  
     'tcp' => t('External (TCP/IP)')  
   );  
   
   $crypto_methods = array(  
     'tls_opt' => t('TLS (Optional)'),  
     'tls'     => t('TLS (Required)'),  
     'ssl'     => t('SSL'),  
   );  
   
   $crypto_disabled = !extension_loaded('openssl');  
   $crypto_text     = $crypto_disabled ? ' (Requires OpenSSL extension)' : '';  
   $jid_format      = htmlspecialchars('<user>@<domain>[/<resource>]');  
   
   //  
   // Basic settings  
   //  
   
   $form['auth'] = array(  
     '#type'        => 'fieldset',  
     '#title'       => t('Basic settings')  
   );  
   
   $form['auth']['xmpp_jid'] = array(  
     '#type'          => 'textfield',  
     '#title'         => t('Username'),  
     '#description'   => t('JID to use for authentication ('.$jid_format.').'),  
     '#default_value' => variable_get('xmpp_jid', '')  
   );  
   
   $form['auth']['xmpp_passwd'] = array(  
     '#type'          => 'password',  
     '#title'         => t('Password'),  
     '#description'   => t('Password to use for authentication.'),  
     '#default_value' => variable_get('xmpp_passwd', '')  
   );  
   
   $form['auth']['xmpp_jid_field'] = array(  
     '#type'          => 'select',  
     '#title'         => t('User JID Field'),  
     '#description'   => t('Profile field which is used to store user JIDs.'),  
     '#options'       => $fields,  
     '#default_value' => variable_get('xmpp_jid_field', '')  
   );  
   
   //  
   // Server type  
   //  
   
   $form['server_type'] = array(  
     '#type'  => 'fieldset',  
     '#title' => t('Server type'),  
   );  
   
   $form['server_type']['xmpp_transport_method'] = array(  
     '#type'          => 'radios',  
     '#title'         => t('Transport method'),  
     '#description'   => t('Server type and transport method to be used.'),  
     '#options'       => $transport_methods,  
     '#default_value' => variable_get('xmpp_transport_method', 'tcp')  
   );  
   
   //  
   // External (TCP/IP)  
   //  
   
   $form['external_tcp'] = array(  
     '#type'        => 'fieldset',  
     '#title'       => t('External (TCP/IP)'),  
     '#collapsible' => true,  
     '#collapsed'   => true,  
   );  
   
   $form['external_tcp']['xmpp_transport_tcp_host'] = array(  
     '#type'          => 'textfield',  
     '#title'         => t('Host'),  
     '#description'   => t('Hostname or IP of the external server.'),  
     '#default_value' => variable_get('xmpp_transport_tcp_host', ''),  
     '#maxlength'     => 255,  
   );  
   
   $form['external_tcp']['xmpp_transport_tcp_port'] = array(  
     '#type'          => 'textfield',  
     '#title'         => t('Port'),  
     '#description'   => t('Port on which to establish the connection.'),  
     '#default_value' => variable_get('xmpp_transport_tcp_port', '5222'),  
     '#maxlength'     => 5,  
   );  
   
   $form['external_tcp']['xmpp_transport_tcp_use_dns'] = array(  
     '#type'          => 'checkbox',  
     '#title'         => t('Use DNS'),  
     '#default_value' => variable_get('xmpp_transport_tcp_use_dns', true),  
     '#description'   => t('Enable DNS SRV look-ups.'),  
   );  
   
   $form['external_tcp']['xmpp_transport_tcp_crypto'] = array(  
     '#type'          => 'radios',  
     '#title'         => t('Encryption mechanism'. $crypto_text),  
     '#description'   => t('Type of encryption to use (if available).'),  
     '#default_value' => variable_get('xmpp_transport_tcp_crypto', 'tls_opt'),  
     '#options'       => $crypto_methods,  
     '#disabled'      => $crypto_disabled  
   );  
   
   //  
   // Test configuration  
   //  
   
   $form['test'] = array(  
     '#type'        => 'fieldset',  
     '#title'       => t('Test configuration'),  
     '#collapsible' => true,  
     '#collapsed'   => true,  
   );  
   
   $form['test']['xmpp_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);  
 }  
   
 /**  
  * Server settings page.  
  */  
 function xmpp_server_settings() {  
   $form = array();  
   return system_settings_form($form);  
260  }  }
261    
262  /**  /**
263   * Validate client settings form.   * Validate client settings form.
264   */   */
265  function xmpp_client_settings_validate($form_id, $form_values, $form) {  function xmpp_client_settings_validate($form_id, $values, $form) {
   
   variable_set('xmpp_client_configured', false);  
   
   if (empty($form_values['xmpp_passwd'])) {  
     $passwd = variable_get('xmpp_passwd', '');  
   
     if (empty($passwd)) {  
       form_set_error('', t('Please enter the login password'));  
       return;  
     }  
266    
267      form_set_value($form['auth']['xmpp_passwd'], $passwd);          if (!$values['xmpp_client_auth_passwd']) {
     $form_values['xmpp_passwd'] = $passwd;  
   }  
268    
269    if (!xmpp_client_settings_check($form_values, $error)) {                  if (!($passwd = variable_get('xmpp_client_auth_passwd', ''))) {
270      form_set_error('', t($error));                          form_set_error('', t('Please enter the password.'));
271      return;                          return;
272    }                  }
273    
274    variable_set('xmpp_client_configured', true);                  form_set_value($form['client']['xmpp_client_auth_passwd'], $passwd);
275            }
276    
277            $jid_regex = '/^[^@]+@[^\/]+(?:\/.+)?$/';
278    
279            if (!preg_match($jid_regex, $values['xmpp_client_auth_jid'])) {
280                    form_set_error('', t('Please enter a valid JID.'));
281                    return;
282            }
283    
284            if ($form['xmpp_client_test_jid']) {
285                    if (!preg_match($jid_regex, $values['xmpp_client_test_jid'])) {
286                            form_set_error('', t('Please enter a valid test JID.'));
287                            return;
288                    }
289            }
290  }  }
291    
292  /**  /**
293   * Submit client settings form.   * Submit client settings form.
294   */   */
295  function xmpp_client_settings_submit($form_id, $form_values) {  function xmpp_client_settings_test($form_id, $form) {
   
   $fields = array(  
     'xmpp_jid',  
     'xmpp_passwd',  
     'xmpp_jid_field',  
     'xmpp_transport_method',  
     'xmpp_transport_tcp_host',  
     'xmpp_transport_tcp_port',  
     'xmpp_transport_tcp_use_dns',  
     'xmpp_transport_tcp_crypto'  
   );  
   
   foreach ($fields as $field)  
     variable_set($field, $form_values[$field]);  
296    
297    $crypto = $form_values['xmpp_transport_tcp_crypto'];          variable_set('xmpp_client_configured', true);
   variable_set('xmpp_transport_tcp_scheme', ($crypto == 'ssl' ? 'ssl' : 'tcp'));  
298    
299    preg_match('/@([^\/]+)/', $form_values['xmpp_jid'], $matches);          if (!($test_jid = $form['xmpp_client_test_jid']))
300    variable_set('xmpp_stream_send_to', $matches[1]);                  return;
301    
302    $test_jid = $form_values['xmpp_test_jid'];          if (!xmpp_message($test_jid, 'Hello, this is a test IM from Drupal :)')) {
303    if (!empty($test_jid)) {                  drupal_set_message('Error sending message: '. xmpp_last_error(), 'error');
304                    return;
305            }
306    
307      if (!xmpp_message($test_jid, 'Hello, this is a test IM from Drupal :)')) {          drupal_set_message('Test message sent.');
       drupal_set_message('Error sending message: '. xmpp_last_error(), 'error');  
       return;  
     }  
   
     drupal_set_message('Test message sent.');  
   }  
   
   drupal_set_message('The configuration options have been saved.');  
308  }  }
309    
310  // -----------------------------------------------------------------------------  /**
311  // XMPP API   * Server settings page.
312  // -----------------------------------------------------------------------------   */
313    function xmpp_server_settings() {
314            $form = array();
315    
316            $form['server'] = array(
317                    '#type'  => 'fieldset',
318                    '#title' => t('Server configuration'),
319            );
320    
321            $form['server']['xmpp_server_enabled'] = array(
322                    '#type'          => 'checkbox',
323                    '#title'         => t('Enable server'),
324                    '#description'   => t('Turn the built-in server on or off.'),
325                    '#default_value' => variable_get('xmpp_server_enabled', false)
326            );
327    
328            $form['server']['xmpp_server_stream_from'] = array(
329                    '#type'          => 'textfield',
330                    '#title'         => t('Host'),
331                    '#description'   => t('Domain name hosted by this server.'),
332                    '#default_value' => variable_get('xmpp_server_stream_from', ''),
333                    '#required'      => true
334            );
335    
336            $form['server']['xmpp_server_secret'] = array(
337                    '#type'          => 'textfield',
338                    '#title'         => t('Secret'),
339                    '#description'   => t('Secret phrase needed to activate the server. This '.
340                                          'value needs to be set as the client\'s password '.
341                                          'in order for it to be able to access the server. '.
342                                          'By default, server is protected with a random sha1 '.
343                                          'hash string and you should only modify this field '.
344                                          'if you want other sites to use this server.'),
345                    '#default_value' => variable_get('xmpp_server_secret', ''),
346                    '#required'      => true
347            );
348    
349            $form['server']['xmpp_server_webtcp_port_start'] = array(
350                    '#type'          => 'textfield',
351                    '#title'         => t('Start port'),
352                    '#description'   => t('First port that can be used for incoming '.
353                                          'connections. Must be greater than 5269.'),
354                    '#default_value' => variable_get('xmpp_server_webtcp_port_start', '48004'),
355                    '#maxlength'     => 5,
356                    '#required'      => true
357            );
358    
359            $form['server']['xmpp_server_webtcp_port_end'] = array(
360                    '#type'          => 'textfield',
361                    '#title'         => t('End port'),
362                    '#description'   => t('Last port that can be used for incoming '.
363                                          'connections. Must be greater than the start port.'),
364                    '#default_value' => variable_get('xmpp_server_webtcp_port_end', '48127'),
365                    '#maxlength'     => 5,
366                    '#required'      => true
367            );
368    
369            return system_settings_form($form);
370    }
371    
372    /**
373     * Server node, responds to requests for /xmpp/server.
374     */
375    function xmpp_server($secret = '') {
376    
377            if (!is_string($secret) || $secret !== variable_get('xmpp_server_secret', 0))
378                    return drupal_access_denied();
379    
380            require_once dirname(__FILE__).'/lib/server.inc';
381    
382            $conf = array(
383                    'stream.from'       => variable_get('xmpp_server_stream_from', ''),
384                    'webtcp.port.start' => variable_get('xmpp_server_webtcp_port_start', ''),
385                    'webtcp.port.end'   => variable_get('xmpp_server_webtcp_port_end', '')
386            );
387    
388            try
389            {
390                    $sess = XMPP_Server::instance()->listen($conf);
391    
392                    while ($sess->ready)
393                            $sess->wait();
394            }
395            catch (Exception $ex)
396            {
397                    if (isset($sess))
398                            $sess->handleException($ex);
399            }
400    }
401    
402    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
403    // API
404    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
405    
406  /**  /**
407   * Get a connected XMPP_Session object.   * Get a connected XMPP_Session object.
408   */   */
409  function xmpp_get_session() {  function xmpp_get_session() {
410    static $sess = null;          static $sess  = null;
411            static $first = true;
412    
413    if (is_null($sess)) {          if ($first) {
414    
415      if (!xmpp_ready())                  $first = false;
       return null;  
416    
417      try {                  if (!variable_get('xmpp_client_configured', false))
418        $sess   = @XMPP_Client::connect(xmpp_client_config());                          return null;
       $crypto = variable_get('xmpp_transport_tcp_crypto', 'tls_opt');  
       $user   = variable_get('xmpp_jid', '');  
       $passwd = variable_get('xmpp_passwd', '');  
419    
420        if ($crypto != 'tls_opt' && !$sess['transport.encrypted'])                  require_once dirname(__FILE__).'/lib/client.inc';
         throw new Exception('Unable to use encryption');  
421    
422        if (!@$sess->Core->login($user, $passwd))                  $conf = array(
423          throw new Exception('Unable to bind to resource');                          'auth.jid'    => variable_get('xmpp_client_auth_jid', ''),
424      }                          'auth.passwd' => variable_get('xmpp_client_auth_passwd', ''),
425      catch (Exception $e) {                          'transport'   => variable_get('xmpp_client_transport', '')
426        $sess = null;                  );
       xmpp_last_error($e->getMessage());  
     }  
   }  
427    
428    return $sess;                  if ($conf['transport'] == 'tcp') {
429  }                          if ($host = variable_get('xmpp_client_tcp_host', ''))
430                                    $conf['tcp.host'] = $host;
431    
432  /**                          if ($port = variable_get('xmpp_client_tcp_port', ''))
433   * Map user id to their jabber id.                                  $conf['tcp.port'] = $port;
  */  
 function xmpp_get_jid($uid = null) {  
434    
435    $fid = variable_get('xmpp_jid_field', null);                          $conf['tcp.use_dns'] = variable_get('xmpp_client_tcp_use_dns', true);
436                            $crypto = variable_get('xmpp_client_tcp_crypto', 'none');
437    
438    if (is_null($fid))                          if ($crypto == 'none')
439      return '';                                  $conf['tcp.use_tls'] = false;
440    
441    if (is_null($uid)) {                          if ($crypto == 'ssl')
442      global $user;                                  $conf['tcp.use_ssl'] = true;
443      $uid = $user->uid;                  }
444    }                  else {
445                            $conf['webtcp.url']  = variable_get('xmpp_client_webtcp_url', '');
446                            $conf['webtcp.url'] .= '/'.variable_get('xmpp_client_auth_passwd', '');
447                    }
448    
449    $query  = "SELECT value FROM {profile_values} WHERE uid=$uid AND fid=$fid";                  try {
450    $result = db_result(db_query($query));                          $sess = XMPP_Client::instance()->connect($conf);
451                            $sess->Presence->set(1);
452                    }
453                    catch (Exception $ex) {
454                            $sess = null;
455                            xmpp_last_error($ex->getMessage());
456                    }
457            }
458    
459    return ($result ? $result : '');          return ($sess && $sess->ready ? $sess : null);
460  }  }
461    
462  /**  /**
463   * Send a simple message to the specified jid.   * Map user id to jabber id.
464   */   */
465  function xmpp_message($jid, $message) {  function xmpp_get_jid($uid = null) {
466    
467    if (is_null($sess = xmpp_get_session()))          static $jid_regex = '/^[^@]+@[^\/]+(?:\/.+)?$/';
468      return false;          $fid = variable_get('xmpp_client_jid_field', '');
469    
470    try {          if ($fid === '')
471      @$sess->Core->sendMessage($jid, $message);                  return (is_array($uid) ? array() : '');
   }  
   catch (Exception $e) {  
     xmpp_last_error($e->getMessage());  
     return false;  
   }  
472    
473    return true;          if (is_null($uid)) {
474                    global $user;
475                    $uid = $user->uid;
476            }
477    
478            $match  = (is_array($uid) ? 'uid IN ('.implode(',', $uid).')' : 'uid='.$uid);
479            $result = array();
480    
481            $query = db_query(
482                    "SELECT uid, value FROM {profile_values} WHERE $match AND fid=$fid"
483            );
484    
485            while ($record = db_fetch_array($query))
486            {
487                    if (preg_match($jid_regex, $record['value']))
488                            $result[$record['uid']] = $record['value'];
489            }
490    
491            return (is_array($uid) ? $result : ($result ? current($result) : ''));
492  }  }
493    
494  /**  /**
495   * Get the last XMPP error message.   * Send an instant message to the specified jid.
496   */   */
497  function xmpp_last_error($set = null) {  function xmpp_message($jid, $message) {
   static $error = '';  
498    
499    if (!is_null($set))          if (!xmpp_presence_subscribe($jid))
500      $error = t($set);                  return false;
501    
502    return $error;          if (!($sess = xmpp_get_session()))
503  }                  return false;
504    
505  // -----------------------------------------------------------------------------          try {
506  // Private functions                  $sess->IM->send($jid, $message);
507  // -----------------------------------------------------------------------------                  return true;
508            }
509            catch (Exception $ex) {
510                    $sess->handleException($ex);
511                    xmpp_last_error($ex->getMessage());
512                    return false;
513            }
514    }
515    
516  /**  /**
517   * Check submitted client settings.   * Subscribe to the presence status of a user.
518   */   */
519  function xmpp_client_settings_check($form, &$error) {  function xmpp_presence_subscribe($jid) {
520    
521    $jid_regex = '/^[^@]+@[^\/]+(?:\/.+)?$/';          if (!($sess = xmpp_get_session()))
522                    return false;
523    
524    if (empty($form['xmpp_jid']) || empty($form['xmpp_passwd'])) {          list($local)  = explode('/', variable_get('xmpp_client_auth_jid', ''), 2);
525      $error = 'Please enter the login username and password';          list($remote) = explode('/', $jid, 2);
526      return false;          $local        = db_escape_string($local);
527    }          $remote       = db_escape_string($remote);
528    
529    if (!preg_match($jid_regex, $form['xmpp_jid'])) {          $query = db_query(
530      $error = 'Please enter a valid login username';                  "SELECT * FROM {xmpp_presence} WHERE remote='$remote' AND local='$local'"
531      return false;          );
   }  
532    
533    if (empty($form['xmpp_jid_field'])) {          if (db_fetch_array($query))
534      $error = 'Please select a valid JID profile field';                  return true;
     return false;  
   }  
535    
536    if ($form['xmpp_transport_method'] == 'tcp') {          try {
537      if (empty($form['xmpp_transport_tcp_host'])) {                  $sess->Presence->subscribe($remote);
       $error = 'Please enter the tcp host';  
       return false;  
     }  
538    
539      if (intval($form['xmpp_transport_tcp_port']) == 0) {                  $query = db_query(
540        $error = 'Please enter a valid tcp port';                          "INSERT INTO {xmpp_presence} VALUES ('$remote', '$local')"
541        return false;                  );
     }  
   }  
542    
543    if (!empty($form['xmpp_test_jid'])) {                  return true;
544      if (!preg_match($jid_regex, $form['xmpp_test_jid'])) {          }
545        $error = 'Please enter a valid test JID';          catch (Exception $ex) {
546        return false;                  $sess->handleException($ex);
547      }                  xmpp_last_error($ex->getMessage());
548    }                  return false;
549            }
   return true;  
550  }  }
551    
552  /**  /**
553   * Check if the client is configured and ready to be used.   * Do not send any outgoing stanzas until xmpp_end_buffer is called.
554   */   */
555  function xmpp_ready() {  function xmpp_start_buffer() {
   
   if (!variable_get('xmpp_client_configured', false)) {  
     xmpp_last_error('Client is not configured');  
     return false;  
   }  
   
   require_once dirname(__FILE__).'/lib/client.inc';  
556    
557    try {          if (!($sess = xmpp_get_session()))
558      @XMPP_Client::init(false, variable_get('xmpp_lib_path', null));                  return false;
   }  
   catch (Exception $e) {  
     xmpp_last_error($e->getMessage());  
     return false;  
   }  
559    
560    return true;          $sess->stream->autosend = false;
561            return true;
562  }  }
563    
564  /**  /**
565   * Get current client configuration.   * Send all buffered stanzas and return to normal mode of operation.
566   */   */
567  function xmpp_client_config() {  function xmpp_end_buffer() {
   static $conf = null;  
568    
569    if (!xmpp_ready())          if (!($sess = xmpp_get_session()))
570      return null;                  return false;
571    
572    if (is_null($conf)) {          try {
573      $conf = array();                  $sess->stream->send();
574                    return true;
575      xmpp_set_conf($conf, 'stream.send.to');          }
576      xmpp_set_conf($conf, 'transport.method');          catch (Exception $ex) {
577                    $sess->handleException($ex);
578      if ($conf['transport.method'] == 'tcp') {                  xmpp_last_error($ex->getMessage());
579        xmpp_set_conf($conf, 'transport.tcp.scheme');                  return false;
580        xmpp_set_conf($conf, 'transport.tcp.host');          }
       xmpp_set_conf($conf, 'transport.tcp.port');  
       xmpp_set_conf($conf, 'transport.tcp.use_dns');  
     }  
   
     $conf = array_diff_assoc($conf, XMPP_Client::getDefaults());  
   }  
   
   return $conf;  
581  }  }
582    
583  /**  /**
584   * Set client configuration key.   * Get the last XMPP error message.
585   */   */
586  function xmpp_set_conf(&$conf, $key) {  function xmpp_last_error($set = null) {
587    $var        = 'xmpp_'.str_replace('.', '_', $key);          static $error = '';
588    $conf[$key] = variable_get($var, $conf[$key]);          return ($set ? $error = t($set) : $error);
589  }  }

Legend:
Removed from v.1.2  
changed lines
  Added in v.1.3

  ViewVC Help
Powered by ViewVC 1.1.3