Projet

Général

Profil

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

root / drupal7 / sites / all / modules / ldap / ldap_views / plugins / ldap_views_plugin_query_ldap.inc @ b42754b9

1
<?php
2

    
3
/**
4
 * @file
5
 * Defines the default query object which builds and execute a ldap query
6
 */
7
class ldap_views_plugin_query_ldap extends views_plugin_query {
8

    
9
  /**
10
   * The base dn for the LDAP search
11
   */
12
  private $basedn = '';
13

    
14
  /**
15
   * A list of filters to apply to the LDAP search
16
   */
17
  private $filter = array();
18

    
19
  /**
20
   * Builds the necessary info to execute the query.
21
   */
22
  function build(&$view) {
23
    $view->init_pager($view);
24

    
25
    // Let the pager modify the query to add limits.
26
    $this->pager->query();
27
  }
28

    
29
  function add_field($table, $field, $alias = '', $params = array()) {
30
    // We check for this specifically because it gets a special alias.
31
    if ($table == $this->base_table && $field == $this->base_field && empty($alias)) {
32
      $alias = $this->base_field;
33
    }
34

    
35
    if (!$alias && $table) {
36
      $alias = $table . '_' . $field;
37
    }
38

    
39
    // Make sure an alias is assigned
40
    $alias = $alias ? $alias : $field;
41

    
42
    // PostgreSQL truncates aliases to 63 characters: http://drupal.org/node/571548
43

    
44
    // We limit the length of the original alias up to 60 characters
45
    // to get a unique alias later if its have duplicates
46
    $alias = drupal_substr($alias, 0, 60);
47

    
48
    // Create a field info array.
49
    $field_info = array(
50
      'field' => $field,
51
      'table' => $table,
52
      'alias' => $alias,
53
    ) + $params;
54

    
55
    // Test to see if the field is actually the same or not. Due to
56
    // differing parameters changing the aggregation function, we need
57
    // to do some automatic alias collision detection:
58
    $base = $alias;
59
    $counter = 0;
60
    while (!empty($this->fields[$alias]) && $this->fields[$alias] != $field_info) {
61
      $field_info['alias'] = $alias = $base . '_' . ++$counter;
62
    }
63

    
64
    if (empty($this->fields[$alias])) {
65
      $this->fields[$alias] = $field_info;
66
    }
67

    
68
    return $alias;
69
  }
70

    
71
  function add_orderby($table, $field, $order, $alias = '', $params = array()) {
72
    $this->orderby[] = array(
73
      'field' => $field,
74
      'direction' => drupal_strtoupper($order)
75
    );
76
  }
77

    
78
  function add_basedn($basedn) {
79
    $this->basedn = !empty($this->basedn) ? $this->basedn : $basedn;
80
  }
81

    
82
  function add_filter($filter) {
83
    if (empty($filter)) {
84
      return;
85
    }
86
    $this->filter[] = $filter;
87
  }
88

    
89
  /**
90
   * Add a simple WHERE clause to the query. The caller is responsible for
91
   * ensuring that all fields are fully qualified (TABLE.FIELD) and that
92
   * the table already exists in the query.
93
   *
94
   * @param $group
95
   *   The WHERE group to add these to; groups are used to create AND/OR
96
   *   sections. Groups cannot be nested. Use 0 as the default group.
97
   *   If the group does not yet exist it will be created as an AND group.
98
   * @param $field
99
   *   The name of the field to check.
100
   * @param $value
101
   *   The value to test the field against. In most cases, this is a scalar. For more
102
   *   complex options, it is an array. The meaning of each element in the array is
103
   *   dependent on the $operator.
104
   * @param $operator
105
   *   The comparison operator, such as =, <, or >=. It also accepts more complex
106
   *   options such as IN, LIKE, or BETWEEN. Defaults to IN if $value is an array
107
   *   = otherwise. If $field is a string you have to use 'formula' here.
108
   *
109
   * @see QueryConditionInterface::condition()
110
   */
111
  function add_where($group, $field, $value = NULL, $operator = NULL) {
112
    // Ensure all variants of 0 are actually 0. Thus '', 0 and NULL are all
113
    // the default group.
114
    if (empty($group)) {
115
      $group = 0;
116
    }
117

    
118
    // Check for a group.
119
    if (!isset($this->where[$group])) {
120
      $this->set_where_group('AND', $group);
121
    }
122

    
123
    $this->where[$group]['conditions'][] = array(
124
      'field' => $field,
125
      'value' => $value,
126
      'operator' => ltrim($operator, '!'),
127
      'negate' => drupal_substr($operator, 0, 1) == '!',
128
    );
129
  }
130

    
131
  /**
132
   * Construct the filter
133
   *
134
   * @param $where
135
   *   'where' or 'having'.
136
   */
137
  function build_condition() {
138
    $operator = array('AND' => '&', 'OR' => '|');
139
    $main_group = '';
140
    if (!isset($this->where)) {
141
      $this->where = array(); // Initialize where clause if not set
142
    }
143
    foreach ($this->where as $group => $info) {
144
      if (!empty($info['conditions'])) {
145
        $sub_group = '';
146
        foreach ($info['conditions'] as $key => $clause) {
147
          $item       = '(' . $clause['field'] . $clause['operator'] . $clause['value'] . ')';
148
          $sub_group .= $clause['negate'] ? "(!$item)" : $item;
149
        }
150
        $main_group .= count($info['conditions']) <= 1 ? $sub_group : '(' . $operator[$info['type']] . $sub_group . ')';
151
      }
152
    }
153
    return count($this->where) <= 1 ? $main_group : '(' . $operator[$this->group_operator] . $main_group . ')';
154
  }
155

    
156
  function build_ldap_basedn($basedn) {
157
    return !empty($this->basedn) ? array($this->basedn) : $basedn;
158
  }
159

    
160
  function build_contextual_filter() {
161
    $contextual_filter = '';
162
    foreach ($this->filter as $condition) {
163
      $contextual_filter .= drupal_substr($condition, 0, 1) != '(' ? "($condition)" : $condition;
164
    }
165
    return $contextual_filter;
166
  }
167

    
168
  function build_ldap_filter($filter) {
169
    $condition     = $this->build_condition();
170
    $contextual    = $this->build_contextual_filter();
171
    $search_filter = !empty($contextual) && !empty($condition)? '(&' . $condition . $contextual . ')' : $condition . $contextual;
172
    return !empty($search_filter) ? $search_filter : $filter;
173
  }
174

    
175
  /**
176
   * Ensure a table exists in the queue; if it already exists it won't
177
   * do anything, but if it doesn't it will add the table queue. It will ensure
178
   * a path leads back to the relationship table.
179
   *
180
   * @param $table
181
   *   The unaliased name of the table to ensure.
182
   * @param $relationship
183
   *   The relationship to ensure the table links to. Each relationship will
184
   *   get a unique instance of the table being added. If not specified,
185
   *   will be the primary table.
186
   * @param $join
187
   *   A views_join object (or derived object) to join the alias in.
188
   *
189
   * @return
190
   *   The alias used to refer to this specific table, or NULL if the table
191
   *   cannot be ensured.
192
   */
193
  function ensure_table($table, $relationship = NULL, $join = NULL) {
194
    return $table;
195
  }
196

    
197
  /**
198
   * Executes the query and fills the associated view object with according
199
   * values.
200
   *
201
   * Values to set: $view->result, $view->total_rows, $view->execute_time,
202
   * $view->pager['current_page'].
203
   *
204
   * $view->result should contain an array of objects.
205
   */
206
  function execute(&$view) {
207
    $start       = microtime(TRUE);
208
    $entries     = array();
209
    $num_entries = 0;
210

    
211
    if (empty($this->options['qid'])) {
212
      watchdog('ldap_views', 'Query definition is empty');
213
      return;
214
    }
215
    foreach ($this->fields as $field) {
216
      $attributes[$field['alias']] = $field['field'];
217
      $field_alias[$field['alias']] = drupal_strtolower($field['field']);
218
    }
219

    
220
    $ldap_data   = new LdapQuery(ldap_views_get_qid($view));
221
    $ldap_server = new LdapServer($ldap_data->sid);
222
    $ldap_server->connect();
223
    $ldap_server->bind();
224
    // TODO: Can't use sizelimit if it must be ordered || cache?
225
    // $ldap_server->search() hasn't orderby (ldap_sort)
226
    // But we can't use ldap_sort because there's no DESC option
227
    foreach ($this->build_ldap_basedn($ldap_data->baseDn) as $basedn) {
228

    
229
      $result = $ldap_server->search($basedn, $this->build_ldap_filter($ldap_data->filter), array_values($attributes), 0, $ldap_data->sizelimit, $ldap_data->timelimit, $ldap_data->deref, $ldap_data->scope);
230
/**
231
    // ldap_sort can't be used because there's no DESC option
232
    if (!empty($this->orderby)) {
233
      // Array reverse, because the most specific are first - PHP works the opposite way of SQL.
234
      foreach (array_reverse($this->orderby) as $field) {
235
        @ldap_sort($ldap_server->connection, $result, $field['field']);
236
      }
237
    }
238
 */
239
    if ($result !== FALSE) { // not an error
240
        $entries = array_merge($entries, $result);
241
        $num_entries += $result['count'];
242
        unset($result['count']);
243
      }
244
    }
245
    if (property_exists($view->query, 'limit')) {
246
      $limit     = $view->query->limit;
247
    }
248
    $offset = property_exists($view->query, 'offset')? $view->query->offset : 0;
249
    $result      = array();
250
    $sort_fields = array();
251
    if (!empty($this->orderby)) {
252
      foreach ($this->orderby as $orderby) {
253
        $sort_fields[drupal_strtolower($orderby['field'])]['direction'] = $orderby['direction'];
254
        $sort_fields[drupal_strtolower($orderby['field'])]['data']      = array();
255
      }
256

    
257
    }
258

    
259
    foreach ($entries as $key => &$entry) {
260
      if (isset($entry['jpegphoto'])) {
261
        $entry['jpegphoto'][0] = '<img src="data:image/jpeg;base64,' . base64_encode($entry['jpegphoto'][0]) . '" alt="photo" />';
262
      }
263
      if (isset($entry['thumbnailphoto'])) {
264
        $entry['thumbnailphoto'][0] = '<img src="data:image/jpeg;base64,' . base64_encode($entry['thumbnailphoto'][0]) . '" alt="photo" />';
265
      }
266
      foreach ($view->field as $field) {
267
        if (! isset($field_alias[$field->field_alias])) {
268
          continue;
269
        }
270
        $alias = $field_alias[$field->field_alias];
271
        if (is_array($entry) && array_key_exists($alias, $entry)) {
272
          if (is_array($entry[$alias])) {
273
            switch ($field->options['multivalue']) {
274
              case 'v-all':
275
                // remove 'count' index
276
                unset($entry[$alias]['count']);
277
                $entry[$alias] = implode($field->options['value_separator'], $entry[$alias]);
278
                break;
279
              case 'v-count':
280
                $entry[$alias] = $entry[$alias]['count'];
281
                break;
282
              case 'v-index':
283
                $index = $field->options['index_value'] >= 0 ? intval($field->options['index_value']) : $entry[$alias]['count'] + $field->options['index_value'];
284
                $entry[$alias] = array_key_exists($index, $entry[$alias]) ? $entry[$alias][$index] :
285
                                                                            $entry[$alias][0];
286
                break;
287
            }
288
          }
289
          // order criteria
290
          //If the field with alias $alias has a corresponding entry in $sort_fields, copy its value into the data key of $sort_fields for later sorting.
291
          if (array_key_exists($alias, $sort_fields)) {
292
            $sort_fields[$alias]['data'][$key] = $entry[$alias];
293
          }
294
        }
295
      }
296
    }
297
    if (!empty($this->orderby) && !empty($entries)) {
298
      $params = array();
299
      // In PHP 5.3 every parameter in the array has to be a reference when calling array_multisort() with call_user_func_array().
300
      $asc  = SORT_ASC;
301
      $desc = SORT_DESC;
302
      foreach ($sort_fields as &$field) {
303
        $params[] = &$field['data'];
304
        if (drupal_strtoupper($field['direction']) == 'ASC') {
305
          $params[] = &$asc;
306
        }
307
        else {
308
          $params[] = &$desc;
309
        }
310
      }
311
      $params[] = &$entries;
312

    
313
      // Some LDAP setups output a 'count' variable in the array, which changes the array size;
314
      // temporarily remove it, sort the arrays, and then put it back.
315
      if (array_key_exists('count', $entries)) {
316
        $countValue = $entries['count']; // remove the count variable
317
        unset($entries['count']);
318
        $params[] = &$entries;
319
        call_user_func_array('array_multisort', $params);
320
        $params['count'] = $countValue;
321
      }
322
      else {
323
        $params[] = &$entries;
324
        call_user_func_array('array_multisort', $params);
325
      }
326
    }
327

    
328
    for ($i = 0; (!isset($limit) || $i < $limit) && $offset + $i < $num_entries; $i++) {
329
      $row = array();
330
      $entry = &$entries[$offset + $i];
331
      foreach ($view->field as $field) {
332
        if (! isset($field_alias[$field->field_alias])) {
333
          continue;
334
        }
335
        if (array_key_exists($field_alias[$field->field_alias], $entry)) {
336
          $row[$field->field_alias] = $entry[$field_alias[$field->field_alias]];
337
        }
338
      }
339
      $result[] = $row;
340
    }
341

    
342
    $view->result       = $result;
343
    $view->total_rows   = $num_entries;
344
    $view->execute_time = microtime(TRUE) - $start;
345
    $view->query->pager->total_items  = $num_entries;
346
    $view->query->pager->update_page_info();
347

    
348
  }
349

    
350
  function option_definition() {
351
    $options = parent::option_definition();
352
    $options['qid'] = array('default' => '');
353

    
354
    return $options;
355
  }
356

    
357
  function options_form(&$form, &$form_state) {
358
/**
359
    $ldap_data = entity_load('ldap_data', FALSE);
360
    $options   = array();
361
    foreach ($ldap_data as $data) {
362
        $options[$data->qid] = $data->name;
363
    }
364
 */
365
    $queries = array();
366
    $queries['all'] = LdapQueryAdmin::getLdapQueryObjects();
367

    
368
  foreach ($queries['all'] as $_sid => $ldap_query) {
369
    if ($ldap_query->status == 1) {
370
      //$queries['enabled'][$_qid] = $ldap_query;
371
      $options[$ldap_query->qid] = $ldap_query->name;
372
    }
373
  }
374
// ******************************************************
375
      $form['qid'] = array(
376
      '#type' => 'select',
377
      '#title' => t('LDAP Search'),
378
      '#options' => $options,
379
      '#default_value' => $this->options['qid'],
380
      '#description' => t("The LDAP server to query."),
381
    );
382
  }
383

    
384

    
385
  /**
386
   * Let modules modify the query just prior to finalizing it.
387
   */
388
  function alter(&$view) {
389
    foreach (module_implements('views_query_alter') as $module) {
390
      $function = $module . '_views_query_alter';
391
      $function($view, $this);
392
    }
393
  }
394

    
395
/* Only when adding dynamic fields in ldap_views_views_data_alter()
396
  function options_submit(&$form, &$form_state) {
397
    parent::options_submit(&$form, &$form_state);
398
    if ($form_state['values']['query']['options']['qid'] != $form_state['view']->query->options['qid']) {
399
      views_invalidate_cache();
400
    }
401
  }
402
 */
403
}