Projet

Général

Profil

Paste
Télécharger (12,7 ko) Statistiques
| Branche: | Révision:

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

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
 *
52
 *  this attempts to find bad dns, but should only be used as warnings
53
 *  as the ldap spec allows for any old character to be escaped and ldap
54
 *  implementations may not follow the spec.
55
 *
56
 *  http://www.ietf.org/rfc/rfc2253.txt
57
 *
58
 */
59
function ldap_baddn($dn, $dn_name) {
60
  $result = array();
61
  $valid_attr_name = '[_a-zA-Z\d\s]';
62
  $valid_attr_values = '[_\-a-zA-Z\d\s]';
63
  $regex = '/^(' . $valid_attr_name . '*\=' . $valid_attr_values . '*[,]{1})*(' . $valid_attr_name . '*\=' . $valid_attr_values . '*){1}$/';
64
  $match = (preg_match($regex, $dn)) ? TRUE : FALSE;
65
  $result['boolean'] = $match;
66
  if (!$match) {
67
    $tokens = array('%dn' => htmlspecialchars($dn), '%dn_name' => $dn_name);
68
    $result['text'] = t('Possible invalid format for:', $tokens)
69
    . '<em>' . $tokens['%dn'] . '</em>.<br/>  ' .
70
    t('The format may be correct for your ldap, but please double check.', $tokens);
71
  }
72
  return $result;
73
}
74

    
75
/**
76
 *
77
 *  this attempts to find bad dns, but should only be used as warningswe
78
 *  as the ldap spec allows for any old character to be escaped and ldap
79
 *  implementations may not follow the spec.
80
 *
81
 *  http://www.ietf.org/rfc/rfc2253.txt
82
 *
83
 */
84

    
85
function ldap_badattr($attr, $attr_name) {
86
  $result = array();
87
  $valid_attr_name = '[_a-zA-Z\d\s]';
88
  $regex = '/^(' . $valid_attr_name . '){1,}$/';
89
  $match = (preg_match($regex, $attr)) ? TRUE : FALSE;
90
  $result['boolean'] = $match;
91
  if (!$match) {
92
    $tokens = array('%attr' => htmlspecialchars($attr), '%attr_name' => $attr_name);
93
    $result['text'] = t('Possible invalid format for %attr_name:', $tokens) . ' <code><em>' . $tokens['%attr']
94
      . '</em></code><br/>' . t('The format may be correct for your ldap, but please double check.', $tokens);
95
  }
96
  return $result;
97
}
98

    
99
/**
100
 * get array of required attributes for an ldap query
101

    
102
 * @param string $sid server id or ldap server object being used
103
 * @param string $direction LDAP_USER_PROV_DIRECTION_* constant
104
 * @param string $ldap_context
105
 * @param boolean $reset cache
106
 *
107
 */
108
function ldap_servers_attributes_needed($sid, $ldap_context = 'all', $reset = TRUE) {
109

    
110
  static $attributes;
111
  $sid = is_object($sid) ? $sid->sid : $sid;
112
  $static_cache_id = ($sid) ? $ldap_context . '__' . $sid : $ldap_context;
113
  if (!is_array($attributes)) {
114
    $attributes = array();
115
  }
116
  if (!isset($attributes[$static_cache_id]) || $reset) {
117
    $params = array(
118
      'sid' => $sid,
119
      'ldap_context' => $ldap_context,
120
    );
121
    drupal_alter('ldap_attributes_needed', $attributes[$static_cache_id], $params);
122
  }
123
  $return = $attributes[$static_cache_id];
124

    
125
  return $return;
126
}
127

    
128

    
129
/**
130
 * function to massage (change case, escape, unescape) ldap attribute names
131
 * and values.  The primary purpose of this is to articulate and ensure consistency
132
 * across ldap modules.
133
 *
134
 * @param mixed $value to be massaged
135
 * @param enum $value_type = 'attr_name' or 'attr_value;
136
 * @param enum $context...see LDAP_SERVER_MASSAGE_* constants
137
 *
138
 * .e.g. ldap_server_massage_text($value, 'attr_value', LDAP_SERVER_MASSAGE_QUERY_LDAP)
139
 */
140
function ldap_server_massage_text($value, $value_type, $context) {
141

    
142
  $scalar = is_scalar($value);
143

    
144
  if ($value_type == 'attr_value') {
145

    
146
    if ($context == LDAP_SERVER_MASSAGE_QUERY_LDAP) {
147
      $value = ldap_pear_escape_filter_value($value);
148
    }
149
    elseif ($context == LDAP_SERVER_MASSAGE_STORE_LDAP) {
150
      $value = ldap_pear_escape_dn_value($value);
151
    }
152

    
153
    switch ($context) {
154

    
155
      case LDAP_SERVER_MASSAGE_DISPLAY:
156
      case LDAP_SERVER_MASSAGE_TOKEN_REPLACE:
157

    
158
      case LDAP_SERVER_MASSAGE_QUERY_LDAP:
159
      case LDAP_SERVER_MASSAGE_QUERY_DB:
160
      case LDAP_SERVER_MASSAGE_QUERY_ARRAY:
161
      case LDAP_SERVER_MASSAGE_QUERY_PROPERTY:
162

    
163
      case LDAP_SERVER_MASSAGE_STORE_LDAP:
164
      case LDAP_SERVER_MASSAGE_STORE_DB:
165
      case LDAP_SERVER_MASSAGE_STORE_ARRAY:
166
      case LDAP_SERVER_MASSAGE_STORE_PROPERTY:
167

    
168
      break;
169

    
170
    }
171
  }
172
  elseif ($value_type == 'attr_name') { // attr_name
173
    switch ($context) {
174

    
175
      case LDAP_SERVER_MASSAGE_DISPLAY:
176
      break;
177

    
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
        if ($scalar) {
190
          $value = drupal_strtolower($value);
191
        }
192
        elseif (is_array($value)) {
193
          foreach ($value as $i => $val) {
194
            $value[$i] = drupal_strtolower($val);
195
          }
196
        }
197
        else {
198
         // neither scalar nor array $value
199
        }
200
      break;
201

    
202
    }
203
  }
204

    
205
  return $value;
206

    
207
}
208

    
209
 /**
210
    * from pear net_ldap2-2.0.11
211
    *
212
    * Escapes the given VALUES according to RFC 2254 so that they can be safely used in LDAP filters.
213
    *
214
    * Any control characters with an ACII code < 32 as well as the characters with special meaning in
215
    * LDAP filters "*", "(", ")", and "\" (the backslash) are converted into the representation of a
216
    * backslash followed by two hex digits representing the hexadecimal value of the character.
217
    *
218
    * @param array $values Array of values to escape
219
    *
220
    * @static
221
    * @return array Array $values, but escaped
222
    */
223
    function ldap_pear_escape_filter_value($values = array()) {
224
        // Parameter validation
225
        $is_scalar = is_scalar($values);
226
        if ($is_scalar) {
227
            $values = array($values);
228
        }
229

    
230
       foreach ($values as $key => $val) {
231
            // Escaping of filter meta characters
232
            $val = str_replace('\\', '\5c', $val);
233
            $val = str_replace('*',  '\2a', $val);
234
            $val = str_replace('(',  '\28', $val);
235
            $val = str_replace(')',  '\29', $val);
236

    
237
            // ASCII < 32 escaping
238
            $val = ldap_pear_asc2hex32($val);
239

    
240
            if (null === $val) {
241
              $val = '\0';
242
            }  // apply escaped "null" if string is empty
243

    
244
            $values[$key] = $val;
245
       }
246

    
247
        return ($is_scalar) ? $values[0] : $values;
248
    }
249

    
250
    /**
251
    * Undoes the conversion done by {@link escape_filter_value()}.
252
    *
253
    * Converts any sequences of a backslash followed by two hex digits into the corresponding character.
254
    *
255
    * @param array $values Array of values to escape
256
    *
257
    * @static
258
    * @return array Array $values, but unescaped
259
    */
260
    function ldap_pear_unescape_filter_value($values = array()) {
261
        // Parameter validation
262
        $is_scalar = is_scalar($values);
263
        if (!is_array($values)) {
264
            $values = array($values);
265
        }
266

    
267
        foreach ($values as $key => $value) {
268
            // Translate hex code into ascii
269
            $values[$key] = ldap_pear_hex2asc($value);
270
        }
271

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

    
275

    
276
 /**
277
    * Escapes a DN value according to RFC 2253
278
    *
279
    * Escapes the given VALUES according to RFC 2253 so that they can be safely used in LDAP DNs.
280
    * The characters ",", "+", """, "\", "<", ">", ";", "#", "=" with a special meaning in RFC 2252
281
    * are preceeded by ba backslash. Control characters with an ASCII code < 32 are represented as \hexpair.
282
    * Finally all leading and trailing spaces are converted to sequences of \20.
283
    *
284
    * @param array $values An array containing the DN values that should be escaped
285
    *
286
    * @static
287
    * @return array The array $values, but escaped
288
    */
289
    function ldap_pear_escape_dn_value($values = array()) {
290
        // Parameter validation
291
        $is_scalar = is_scalar($values);
292

    
293
        if (!is_array($values)) {
294
            $values = array($values);
295
        }
296

    
297
        foreach ($values as $key => $val) {
298
            // Escaping of filter meta characters
299
            $val = str_replace('\\', '\\\\', $val);
300
            $val = str_replace(',',    '\,', $val);
301
            $val = str_replace('+',    '\+', $val);
302
            $val = str_replace('"',    '\"', $val);
303
            $val = str_replace('<',    '\<', $val);
304
            $val = str_replace('>',    '\>', $val);
305
            $val = str_replace(';',    '\;', $val);
306
            $val = str_replace('#',    '\#', $val);
307
            $val = str_replace('=',    '\=', $val);
308

    
309
            // ASCII < 32 escaping
310
            $val = ldap_pear_asc2hex32($val);
311

    
312
            // Convert all leading and trailing spaces to sequences of \20.
313
            if (preg_match('/^(\s*)(.+?)(\s*)$/', $val, $matches)) {
314
                $val = $matches[2];
315
                for ($i = 0; $i < strlen($matches[1]); $i++) {
316
                    $val = '\20' . $val;
317
                }
318
                for ($i = 0; $i < strlen($matches[3]); $i++) {
319
                    $val = $val . '\20';
320
                }
321
            }
322

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

    
325
            $values[$key] = $val;
326
        }
327

    
328
        return ($is_scalar) ? $values[0] : $values;
329
    }
330

    
331
    /**
332
    * Undoes the conversion done by escape_dn_value().
333
    *
334
    * Any escape sequence starting with a baskslash - hexpair or special character -
335
    * will be transformed back to the corresponding character.
336
    *
337
    * @param array $values Array of DN Values
338
    *
339
    * @return array Same as $values, but unescaped
340
    * @static
341
    */
342
    function ldap_pear_unescape_dn_value($values = array()) {
343
      $is_scalar = is_scalar($values);
344

    
345
        // Parameter validation
346
        if (!is_array($values)) {
347
            $values = array($values);
348
        }
349

    
350
        foreach ($values as $key => $val) {
351
            // strip slashes from special chars
352
            $val = str_replace('\\\\', '\\', $val);
353
            $val = str_replace('\,',    ',', $val);
354
            $val = str_replace('\+',    '+', $val);
355
            $val = str_replace('\"',    '"', $val);
356
            $val = str_replace('\<',    '<', $val);
357
            $val = str_replace('\>',    '>', $val);
358
            $val = str_replace('\;',    ';', $val);
359
            $val = str_replace('\#',    '#', $val);
360
            $val = str_replace('\=',    '=', $val);
361

    
362
            // Translate hex code into ascii
363
            $values[$key] = ldap_pear_hex2asc($val);
364
        }
365

    
366
      return ($is_scalar) ? $values[0] : $values;
367
    }
368

    
369

    
370

    
371
    /**
372
    * Converts all Hex expressions ("\HEX") to their original ASCII characters
373
    *
374
    * @param string $string String to convert
375
    *
376
    * @static
377
    * @author beni@php.net, heavily based on work from DavidSmith@byu.net
378
    * @return string
379
    */
380

    
381
    function ldap_pear_hex2asc($string) {
382

    
383
      if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
384
        $string = preg_replace_callback(
385
          "/\\\([0-9A-Fa-f]{2})/",
386
          function ($m){
387
            return chr(hexdec($m[1]));
388
          },
389
          $string);
390
      }
391
      else {
392
        $string = preg_replace("/\\\([0-9A-Fa-f]{2})/e", "''.chr(hexdec('\\1')).''", $string);
393
      }
394

    
395
      return $string;
396
    }
397

    
398
    /**
399
    * Converts all ASCII chars < 32 to "\HEX"
400
    *
401
    * @param string $string String to convert
402
    *
403
    * @static
404
    * @return string
405
    */
406
    function ldap_pear_asc2hex32($string) {
407
        for ($i = 0; $i < strlen($string); $i++) {
408
            $char = substr($string, $i, 1);
409
            if (ord($char) < 32) {
410
                $hex = dechex(ord($char));
411
                if (strlen($hex) == 1) $hex = '0' . $hex;
412
                $string = str_replace($char, '\\' . $hex, $string);
413
            }
414
        }
415
        return $string;
416
    }