Projet

Général

Profil

Paste
Télécharger (13,6 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / ldap / ldap_servers / ldap_servers.functions.inc @ bc175c27

1
<?php
2

    
3
/**
4
 * @file
5
 * collection of functions that don't belong in server object
6
 */
7

    
8
/**
9
  * Modify an LDAP Entry
10
  *
11
  * this has been depracated in favor or $ldap_server->modifyLdapEntry($dn, $attributes)
12
  * which handles empty attributes better.
13
  *
14
  */
15
function ldap_user_modify($dn, $attributes, $ldap_server) {
16
  $result = ldap_modify($ldap_server->connection, $dn, $attributes);
17
  if (!$result) {
18
    $error = "LDAP Server ldap_modify(%dn) in ldap_user_modify() Error Server ID = %sid, LDAP Err No: %ldap_errno LDAP Err Message: %ldap_err2str ";
19
    $tokens = array('%dn' => $dn, '%sid' => $this->sid, '%ldap_errno' => ldap_errno($this->connection), '%ldap_err2str' => ldap_err2str(ldap_errno($this->connection)));
20
    watchdog('ldap_servers', $error, $tokens, WATCHDOG_ERROR);
21
  }
22
  return $result;
23
}
24

    
25
/**
26
 * Modify a password
27
 */
28
function ldap_password_modify($userdn, $new_password, $ldap_server) {
29

    
30
  $new_password = "\"" . $new_password . "\"";
31
  $len = drupal_strlen($new_password);
32
  $new_pass = NULL;
33
  for ($i = 0; $i < $len; $i++) {
34
    $new_pass .= "{$new_password{$i}}\000";
35
  }
36

    
37
  $status = ldap_mod_replace($ldap_server->connection, $userdn, array('unicodePwd' => $new_pass));
38
  if (!$status) {
39
    watchdog(
40
      'ldap_servers',
41
      'Error: password_modify() failed to modify ldap password w/ base DN "!dn"',
42
      array('!dn' => $userdn),
43
      WATCHDOG_ERROR
44
    );
45
  }
46

    
47
  return $status;
48
}
49

    
50
/**
51
 * Converts a password to the format that Active Directory supports (for the 
52
 * purpose of changing or setting).  Note that AD needs the field to be called
53
 * unicodePwd (as opposed to userPassword)
54
 * 
55
 * @param string $password
56
 *    The password that is being formatted for Active Directory unicodePwd field
57
 * @return string
58
 *    $password surrounded with quotes and in UTF-16LE encoding
59
 */
60
function ldap_servers_convert_password_for_active_directory_unicodePwd($password) {
61
  // This function can be called with $attributes['unicodePwd'] as an array.
62
  if (!is_array($password)) {
63
    return mb_convert_encoding("\"{$password}\"", "UTF-16LE");
64
  }
65
  else {
66
    // Presumably there is no use case for there being more than one password in
67
    // the $attributes array, hence it will be at index 0 and we return in kind.
68
    return array(mb_convert_encoding("\"{$password[0]}\"", "UTF-16LE"));
69
  }
70
}
71

    
72
/**
73
 *
74
 *  this attempts to find bad dns, but should only be used as warnings
75
 *  as the ldap spec allows for any old character to be escaped and ldap
76
 *  implementations may not follow the spec.
77
 *
78
 *  http://www.ietf.org/rfc/rfc2253.txt
79
 *
80
 */
81
function ldap_baddn($dn, $dn_name) {
82
  $result = array();
83
  $valid_attr_name = '[_a-zA-Z\d\s]';
84
  $valid_attr_values = '[_\-a-zA-Z\d\s]';
85
  $regex = '/^(' . $valid_attr_name . '*\=' . $valid_attr_values . '*[,]{1})*(' . $valid_attr_name . '*\=' . $valid_attr_values . '*){1}$/';
86
  $match = (preg_match($regex, $dn)) ? TRUE : FALSE;
87
  $result['boolean'] = $match;
88
  if (!$match) {
89
    $tokens = array('%dn' => htmlspecialchars($dn), '%dn_name' => $dn_name);
90
    $result['text'] = t('Possible invalid format for:', $tokens)
91
    . '<em>' . $tokens['%dn'] . '</em>.<br/>  ' .
92
    t('The format may be correct for your ldap, but please double check.', $tokens);
93
  }
94
  return $result;
95
}
96

    
97
/**
98
 *
99
 *  this attempts to find bad dns, but should only be used as warningswe
100
 *  as the ldap spec allows for any old character to be escaped and ldap
101
 *  implementations may not follow the spec.
102
 *
103
 *  http://www.ietf.org/rfc/rfc2253.txt
104
 *
105
 */
106

    
107
function ldap_badattr($attr, $attr_name) {
108
  $result = array();
109
  $valid_attr_name = '[_a-zA-Z\d\s]';
110
  $regex = '/^(' . $valid_attr_name . '){1,}$/';
111
  $match = (preg_match($regex, $attr)) ? TRUE : FALSE;
112
  $result['boolean'] = $match;
113
  if (!$match) {
114
    $tokens = array('%attr' => htmlspecialchars($attr), '%attr_name' => $attr_name);
115
    $result['text'] = t('Possible invalid format for %attr_name:', $tokens) . ' <code><em>' . $tokens['%attr']
116
      . '</em></code><br/>' . t('The format may be correct for your ldap, but please double check.', $tokens);
117
  }
118
  return $result;
119
}
120

    
121
/**
122
 * get array of required attributes for an ldap query
123

    
124
 * @param string $sid server id or ldap server object being used
125
 * @param string $direction LDAP_USER_PROV_DIRECTION_* constant
126
 * @param string $ldap_context
127
 * @param boolean $reset cache
128
 *
129
 */
130
function ldap_servers_attributes_needed($sid, $ldap_context = 'all', $reset = TRUE) {
131

    
132
  static $attributes;
133
  $sid = is_object($sid) ? $sid->sid : $sid;
134
  $static_cache_id = ($sid) ? $ldap_context . '__' . $sid : $ldap_context;
135
  if (!is_array($attributes)) {
136
    $attributes = array();
137
  }
138
  if (!isset($attributes[$static_cache_id]) || $reset) {
139
    $params = array(
140
      'sid' => $sid,
141
      'ldap_context' => $ldap_context,
142
    );
143
    drupal_alter('ldap_attributes_needed', $attributes[$static_cache_id], $params);
144
  }
145
  $return = $attributes[$static_cache_id];
146

    
147
  return $return;
148
}
149

    
150

    
151
/**
152
 * function to massage (change case, escape, unescape) ldap attribute names
153
 * and values.  The primary purpose of this is to articulate and ensure consistency
154
 * across ldap modules.
155
 *
156
 * @param mixed $value to be massaged
157
 * @param enum $value_type = 'attr_name' or 'attr_value;
158
 * @param enum $context...see LDAP_SERVER_MASSAGE_* constants
159
 *
160
 * .e.g. ldap_server_massage_text($value, 'attr_value', LDAP_SERVER_MASSAGE_QUERY_LDAP)
161
 */
162
function ldap_server_massage_text($value, $value_type, $context) {
163

    
164
  $scalar = is_scalar($value);
165

    
166
  if ($value_type == 'attr_value') {
167

    
168
    if ($context == LDAP_SERVER_MASSAGE_QUERY_LDAP) {
169
      $value = ldap_pear_escape_filter_value($value);
170
    }
171
    elseif ($context == LDAP_SERVER_MASSAGE_STORE_LDAP) {
172
      $value = ldap_pear_escape_dn_value($value);
173
    }
174

    
175
    switch ($context) {
176

    
177
      case LDAP_SERVER_MASSAGE_DISPLAY:
178
      case LDAP_SERVER_MASSAGE_TOKEN_REPLACE:
179

    
180
      case LDAP_SERVER_MASSAGE_QUERY_LDAP:
181
      case LDAP_SERVER_MASSAGE_QUERY_DB:
182
      case LDAP_SERVER_MASSAGE_QUERY_ARRAY:
183
      case LDAP_SERVER_MASSAGE_QUERY_PROPERTY:
184

    
185
      case LDAP_SERVER_MASSAGE_STORE_LDAP:
186
      case LDAP_SERVER_MASSAGE_STORE_DB:
187
      case LDAP_SERVER_MASSAGE_STORE_ARRAY:
188
      case LDAP_SERVER_MASSAGE_STORE_PROPERTY:
189

    
190
      break;
191

    
192
    }
193
  }
194
  elseif ($value_type == 'attr_name') { // attr_name
195
    switch ($context) {
196

    
197
      case LDAP_SERVER_MASSAGE_DISPLAY:
198
      break;
199

    
200
      case LDAP_SERVER_MASSAGE_TOKEN_REPLACE:
201

    
202
      case LDAP_SERVER_MASSAGE_QUERY_LDAP:
203
      case LDAP_SERVER_MASSAGE_QUERY_DB:
204
      case LDAP_SERVER_MASSAGE_QUERY_ARRAY:
205
      case LDAP_SERVER_MASSAGE_QUERY_PROPERTY:
206

    
207
      case LDAP_SERVER_MASSAGE_STORE_LDAP:
208
      case LDAP_SERVER_MASSAGE_STORE_DB:
209
      case LDAP_SERVER_MASSAGE_STORE_ARRAY:
210
      case LDAP_SERVER_MASSAGE_STORE_PROPERTY:
211
        if ($scalar) {
212
          $value = drupal_strtolower($value);
213
        }
214
        elseif (is_array($value)) {
215
          foreach ($value as $i => $val) {
216
            $value[$i] = drupal_strtolower($val);
217
          }
218
        }
219
        else {
220
         // neither scalar nor array $value
221
        }
222
      break;
223

    
224
    }
225
  }
226

    
227
  return $value;
228

    
229
}
230

    
231
 /**
232
    * from pear net_ldap2-2.0.11
233
    *
234
    * Escapes the given VALUES according to RFC 2254 so that they can be safely used in LDAP filters.
235
    *
236
    * Any control characters with an ACII code < 32 as well as the characters with special meaning in
237
    * LDAP filters "*", "(", ")", and "\" (the backslash) are converted into the representation of a
238
    * backslash followed by two hex digits representing the hexadecimal value of the character.
239
    *
240
    * @param array $values Array of values to escape
241
    *
242
    * @static
243
    * @return array Array $values, but escaped
244
    */
245
    function ldap_pear_escape_filter_value($values = array()) {
246
        // Parameter validation
247
        $is_scalar = is_scalar($values);
248
        if ($is_scalar) {
249
            $values = array($values);
250
        }
251
        if ($values === NULL) {
252
          return NULL;
253
        }
254

    
255
       foreach ($values as $key => $val) {
256
            // Escaping of filter meta characters
257
            $val = str_replace('\\', '\5c', $val);
258
            $val = str_replace('*', '\2a', $val);
259
            $val = str_replace('(', '\28', $val);
260
            $val = str_replace(')', '\29', $val);
261

    
262
            // ASCII < 32 escaping
263
            $val = ldap_pear_asc2hex32($val);
264

    
265
            if (null === $val) {
266
              $val = '\0';
267
            }  // apply escaped "null" if string is empty
268

    
269
            $values[$key] = $val;
270
       }
271

    
272
        return ($is_scalar) ? $values[0] : $values;
273
    }
274

    
275
    /**
276
    * Undoes the conversion done by {@link escape_filter_value()}.
277
    *
278
    * Converts any sequences of a backslash followed by two hex digits into the corresponding character.
279
    *
280
    * @param array $values Array of values to escape
281
    *
282
    * @static
283
    * @return array Array $values, but unescaped
284
    */
285
    function ldap_pear_unescape_filter_value($values = array()) {
286
        // Parameter validation
287
        $is_scalar = is_scalar($values);
288
        if (!is_array($values)) {
289
            $values = array($values);
290
        }
291

    
292
        foreach ($values as $key => $value) {
293
            // Translate hex code into ascii
294
            $values[$key] = ldap_pear_hex2asc($value);
295
        }
296

    
297
        return ($is_scalar) ? $values[0] : $values;
298
    }
299

    
300

    
301
 /**
302
    * Escapes a DN value according to RFC 2253
303
    *
304
    * Escapes the given VALUES according to RFC 2253 so that they can be safely used in LDAP DNs.
305
    * The characters ",", "+", """, "\", "<", ">", ";", "#", "=" with a special meaning in RFC 2252
306
    * are preceeded by ba backslash. Control characters with an ASCII code < 32 are represented as \hexpair.
307
    * Finally all leading and trailing spaces are converted to sequences of \20.
308
    *
309
    * @param array $values An array containing the DN values that should be escaped
310
    *
311
    * @static
312
    * @return array The array $values, but escaped
313
    */
314
    function ldap_pear_escape_dn_value($values = array()) {
315
        // Parameter validation
316
        $is_scalar = is_scalar($values);
317

    
318
        if (!is_array($values)) {
319
            $values = array($values);
320
        }
321

    
322
        foreach ($values as $key => $val) {
323
            // Escaping of filter meta characters
324
            $val = str_replace('\\', '\\\\', $val);
325
            $val = str_replace(',', '\,', $val);
326
            $val = str_replace('+', '\+', $val);
327
            $val = str_replace('"', '\"', $val);
328
            $val = str_replace('<', '\<', $val);
329
            $val = str_replace('>', '\>', $val);
330
            $val = str_replace(';', '\;', $val);
331
            $val = str_replace('#', '\#', $val);
332
            $val = str_replace('=', '\=', $val);
333

    
334
            // ASCII < 32 escaping
335
            $val = ldap_pear_asc2hex32($val);
336

    
337
            // Convert all leading and trailing spaces to sequences of \20.
338
            if (preg_match('/^(\s*)(.+?)(\s*)$/', $val, $matches)) {
339
                $val = $matches[2];
340
                for ($i = 0; $i < strlen($matches[1]); $i++) {
341
                    $val = '\20' . $val;
342
                }
343
                for ($i = 0; $i < strlen($matches[3]); $i++) {
344
                    $val = $val . '\20';
345
                }
346
            }
347

    
348
            if (null === $val) $val = '\0';  // apply escaped "null" if string is empty
349

    
350
            $values[$key] = $val;
351
        }
352

    
353
        return ($is_scalar) ? $values[0] : $values;
354
    }
355

    
356
    /**
357
    * Undoes the conversion done by escape_dn_value().
358
    *
359
    * Any escape sequence starting with a baskslash - hexpair or special character -
360
    * will be transformed back to the corresponding character.
361
    *
362
    * @param array $values Array of DN Values
363
    *
364
    * @return array Same as $values, but unescaped
365
    * @static
366
    */
367
    function ldap_pear_unescape_dn_value($values = array()) {
368
      $is_scalar = is_scalar($values);
369

    
370
        // Parameter validation
371
        if (!is_array($values)) {
372
            $values = array($values);
373
        }
374

    
375
        foreach ($values as $key => $val) {
376
            // strip slashes from special chars
377
            $val = str_replace('\\\\', '\\', $val);
378
            $val = str_replace('\,', ',', $val);
379
            $val = str_replace('\+', '+', $val);
380
            $val = str_replace('\"', '"', $val);
381
            $val = str_replace('\<', '<', $val);
382
            $val = str_replace('\>', '>', $val);
383
            $val = str_replace('\;', ';', $val);
384
            $val = str_replace('\#', '#', $val);
385
            $val = str_replace('\=', '=', $val);
386

    
387
            // Translate hex code into ascii
388
            $values[$key] = ldap_pear_hex2asc($val);
389
        }
390

    
391
      return ($is_scalar) ? $values[0] : $values;
392
    }
393

    
394

    
395

    
396
    /**
397
    * Converts all Hex expressions ("\HEX") to their original ASCII characters
398
    *
399
    * @param string $string String to convert
400
    *
401
    * @static
402
    * @author beni@php.net, heavily based on work from DavidSmith@byu.net
403
    * @return string
404
    */
405

    
406
    function ldap_pear_hex2asc($string) {
407

    
408
      if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
409
        $string = preg_replace_callback(
410
          "/\\\([0-9A-Fa-f]{2})/",
411
          function ($m){
412
            return chr(hexdec($m[1]));
413
          },
414
          $string);
415
      }
416
      else {
417
        $string = preg_replace("/\\\([0-9A-Fa-f]{2})/e", "''.chr(hexdec('\\1')).''", $string);
418
      }
419

    
420
      return $string;
421
    }
422

    
423
    /**
424
    * Converts all ASCII chars < 32 to "\HEX"
425
    *
426
    * @param string $string String to convert
427
    *
428
    * @static
429
    * @return string
430
    */
431
    function ldap_pear_asc2hex32($string) {
432
        for ($i = 0; $i < strlen($string); $i++) {
433
            $char = substr($string, $i, 1);
434
            if (ord($char) < 32) {
435
                $hex = dechex(ord($char));
436
                if (strlen($hex) == 1) $hex = '0' . $hex;
437
                $string = str_replace($char, '\\' . $hex, $string);
438
            }
439
        }
440
        return $string;
441
    }