forked from cakephp/datasources
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLdapSource.php
More file actions
1504 lines (1352 loc) · 41.1 KB
/
LdapSource.php
File metadata and controls
1504 lines (1352 loc) · 41.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* LDAP Datasource
*
* Connect to LDAPv3 style datasource with full CRUD support.
* Still needs HABTM support
* Discussion at http://www.analogrithems.com/rant/2009/06/12/cakephp-with-full-crud-a-living-example/
* Tested with OpenLDAP, Netscape Style LDAP {iPlanet, Fedora, RedhatDS} Active Directory.
* Supports TLS, multiple ldap servers (Failover not, mirroring), Scheme Detection
*
* PHP Version 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP Datasources v 0.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('Inflector', 'Utility');
/**
* Ldap Datasource
*
*/
class LdapSource extends DataSource {
/**
* Datasource description
*
* @var string
*/
public $description = 'Ldap Data Source';
/**
* Cache Sources
*
* @var boolean
*/
public $cacheSources = true;
/**
* Schema Results
*
* @var boolean
*/
public $SchemaResults = false;
/**
* Database
*
* @var mixed
*/
public $database = false;
/**
* Count
*
* @var integer
*/
public $count = 0;
/**
* Model
*
* @var mixed
*/
public $model;
/**
* Operational Attributes
*
* @var mixed
*/
public $OperationalAttributes;
/**
* Schema DN
*
* @var string
*/
public $SchemaDN;
/**
* Schema Attributes
*
* @var string
*/
public $SchemaAtributes;
/**
* Schema Filter
*
* @var string
*/
public $SchemaFilter;
/**
* Result for formal queries
*
* @var mixed
*/
protected $_result = false;
/**
* Base configuration
*
* @var array
*/
protected $_baseConfig = array(
'host' => 'localhost',
'port' => 389,
'version' => 3
);
/**
* MultiMaster Use
*
* @var integer
*/
protected $_multiMasterUse = 0;
/**
* Descriptions
*
* @var array
*/
protected $_descriptions = array();
/**
* Constructor
*
* @param array $config Configuration
*/
public function __construct($config = array()) {
$this->debug = Configure::read('debug') > 0;
$this->fullDebug = Configure::read('debug') > 1;
parent::__construct($config);
$link = $this->connect();
// People Have been asking for this forever.
if (isset($config['type']) && !empty($config['type'])) {
switch ($config['type']) {
case 'Netscape':
$this->setNetscapeEnv();
break;
case 'OpenLDAP':
$this->setOpenLDAPEnv();
break;
case 'ActiveDirectory':
$this->setActiveDirectoryEnv();
break;
default:
$this->setNetscapeEnv();
break;
}
}
$this->setSchemaPath();
return $link;
}
/**
* Destructor
*
* Closes connection to the server
*
* @return void
*/
public function __destruct() {
$this->close();
parent::__destruct();
}
/**
* Field name
*
* This looks weird, but for LDAP we just return the name of the field thats passed as an argument.
*
* @param string $field Field name
* @return string Field name
* @author Graham Weldon
*/
public function name($field) {
return $field;
}
/**
* connect([$bindDN], [$passwd]) create the actual connection to the ldap server
* This function supports failover, so if your config['host'] is an array it will try the first one, if it fails,
* jumps to the next and attempts to connect and so on. If will also check try to setup any special connection options
* needed like referal chasing and tls support
*
* @param string the users dn to bind with
* @param string the password for the previously state bindDN
* @return boolean the status of the connection
*/
public function connect($bindDN = null, $passwd = null) {
$config = array_merge($this->_baseConfig, $this->config);
$this->connected = false;
$hasFailover = false;
if (isset($config['host']) && is_array($config['host'])) {
$config['host'] = $config['host'][$this->_multiMasterUse];
if (count($this->config['host']) > (1 + $this->_multiMasterUse)) {
$hasFailOver = true;
}
}
$bindDN = empty($bindDN) ? $config['login'] : $bindDN;
$bindPasswd = empty($passwd) ? $config['password'] : $passwd;
$this->database = @ldap_connect($config['host']);
if (!$this->database) {
//Try Next Server Listed
if ($hasFailover) {
$this->log('Trying Next LDAP Server in list:' . $this->config['host'][$this->_multiMasterUse], 'ldap.error');
$this->_multiMasterUse++;
$this->connect($bindDN, $passwd);
if ($this->connected) {
return $this->connected;
}
}
}
//Set our protocol version usually version 3
ldap_set_option($this->database, LDAP_OPT_PROTOCOL_VERSION, $config['version']);
if ($config['tls']) {
if (!ldap_start_tls($this->database)) {
$this->log("Ldap_start_tls failed", 'ldap.error');
return $this->disconnect();
}
}
//So little known fact, if your php-ldap lib is built against openldap like pretty much every linux
//distro out their like redhat, suse etc. The connect doesn't acutally happen when you call ldap_connect
//it happens when you call ldap_bind. So if you are using failover then you have to test here also.
$bindResult = @ldap_bind($this->database, $bindDN, $bindPasswd);
if (!$bindResult) {
if (ldap_errno($this->database) == 49) {
$this->log("Auth failed for '$bindDN'!", 'ldap.error');
} else {
$this->log('Trying Next LDAP Server in list:' . $this->config['host'][$this->_multiMasterUse], 'ldap.error');
$this->_multiMasterUse++;
$this->connect($bindDN, $passwd);
if ($this->connected) {
return $this->connected;
}
}
} else {
$this->connected = true;
}
return $this->connected;
}
/**
* auth($dn, $passwd)
* Test if the dn/passwd combo is valid
* This may actually belong in the component code, will look into that
*
* @param string bindDN to connect as
* @param string password for the bindDN
* @param boolean or string on error
*/
public function auth($dn, $passwd) {
$this->connect($dn, $passwd);
if ($this->connected) {
return true;
}
$this->log("Auth Error: for '$dn': " . $this->lastError(), 'ldap.error');
return $this->lastError();
}
/**
* Disconnects database, kills the connection and says the connection is closed,
* and if DEBUG is turned on, the log for this object is shown.
*
*/
public function close() {
if ($this->fullDebug && Configure::read('debug') > 1) {
$this->showLog();
}
$this->disconnect();
}
/**
* disconnect close connection and release any remaining results in the buffer
*
*/
public function disconnect() {
@ldap_free_result($this->results);
@ldap_unbind($this->database);
$this->connected = false;
return $this->connected;
}
/**
* Checks if it's connected to the database
*
* @return boolean True if the database is connected, else false
*/
public function isConnected() {
return $this->connected;
}
/**
* Reconnects to database server with optional new settings
*
* @param array $config An array defining the new configuration settings
* @return boolean True on success, false on failure
*/
public function reconnect($config = null) {
$this->disconnect();
if ($config != null) {
$this->config = array_merge($this->_baseConfig, $this->config, $config);
}
return $this->connect();
}
/**
* The "C" in CRUD
*
* @param Model $model
* @param array $fields containing the field names
* @param array $values containing the fields' values
* @return true on success, false on error
*/
public function create(Model $model, $fields = null, $values = null) {
$basedn = $this->config['basedn'];
$key = $model->primaryKey;
$table = $model->useTable;
$fieldsData = array();
$id = null;
$objectclasses = null;
if ($fields == null) {
unset($fields, $values);
$fields = array_keys($model->data);
$values = array_values($model->data);
}
$count = count($fields);
for ($i = 0; $i < $count; $i++) {
if ($fields[$i] == $key) {
$id = $values[$i];
} elseif ($fields[$i] === 'cn') {
$cn = $values[$i];
}
$fieldsData[$fields[$i]] = $values[$i];
}
//Lets make our DN, this is made from the useTable & basedn + primary key. Logically this corelate to LDAP
if (isset($table) && preg_match('/=/', $table)) {
$table = $table . ', ';
} else {
$table = '';
}
if (isset($key) && !empty($key)) {
$key = "$key=$id, ";
} else {
//Almost everything has a cn, this is a good fall back.
$key = "cn=$cn, ";
}
$dn = $key . $table . $basedn;
$res = @ldap_add($this->database, $dn, $fieldsData);
// Add the entry
if ($res) {
$model->setInsertID($id);
$model->id = $id;
return true;
}
$this->log("Failed to add ldap entry: dn:$dn\nData:" . print_r($fieldsData, true) . "\n" . ldap_error($this->database), 'ldap.error');
$model->onError();
return false;
}
/**
* Returns the query
*
* @return mixed
*/
public function query($find, $query, $model) {
if (isset($query[0]) && is_array($query[0])) {
$query = $query[0];
}
if (isset($find)) {
switch ($find) {
case 'auth':
return $this->auth($query['dn'], $query['password']);
case 'findSchema':
$query = $this->_getLDAPschema();
//$this->findSchema($query);
break;
case 'findConfig':
return $this->config;
default:
$query = $this->read($model, $query);
break;
}
}
return $query;
}
/**
* The "R" in CRUD
*
* @param Model $model
* @param array $queryData
* @param integer $recursive Number of levels of association
* @return unknown
*/
public function read(Model $model, $queryData = array(), $recursive = null) {
$this->model = $model;
$this->_scrubQueryData($queryData);
if ($recursive !== null) {
$_recursive = $model->recursive;
$model->recursive = $recursive;
}
// Check if we are doing a 'count' .. this is kinda ugly but i couldn't find a better way to do this, yet
if (is_string($queryData['fields']) && $queryData['fields'] === 'COUNT(*) AS ' . $this->name('count')) {
$queryData['fields'] = array();
}
// Prepare query data ------------------------
$queryData['conditions'] = $this->_conditions($queryData['conditions'], $model);
if (empty($queryData['targetDn'])) {
$queryData['targetDn'] = $model->useTable;
}
$queryData['type'] = 'search';
if (empty($queryData['order'])) {
$queryData['order'] = array($model->primaryKey);
}
// Associations links --------------------------
foreach ($model->_associations as $type) {
foreach ($model->{$type} as $assoc => $assocData) {
if ($model->recursive > -1) {
$linkModel = $model->{$assoc};
$linkedModels[] = $type . '/' . $assoc;
}
}
}
// Execute search query ------------------------
$res = $this->_executeQuery($queryData);
if ($this->lastNumRows() == 0) {
return false;
}
// Format results -----------------------------
ldap_sort($this->database, $res, $queryData['order'][0]);
$resultSet = ldap_get_entries($this->database, $res);
$resultSet = $this->_ldapFormat($model, $resultSet);
// Query on linked models ----------------------
if ($model->recursive > 0) {
foreach ($model->_associations as $type) {
foreach ($model->{$type} as $assoc => $assocData) {
$db = null;
$linkModel = $model->{$assoc};
if ($model->useDbConfig === $linkModel->useDbConfig) {
$db = $this;
} else {
$db = ConnectionManager::getDataSource($linkModel->useDbConfig);
}
if ($db !== null) {
$stack = array($assoc);
$array = array();
$db->queryAssociation($model, $linkModel, $type, $assoc, $assocData, $array, true, $resultSet, $model->recursive - 1, $stack);
unset ($db);
}
}
}
}
if ($recursive !== null) {
$model->recursive = $_recursive;
}
// Add the count field to the resultSet (needed by find() to work out how many entries we got back .. used when $model->exists() is called)
$resultSet[0][0]['count'] = $this->lastNumRows();
return $resultSet;
}
/**
* The "U" in CRUD
*/
public function update(Model $model, $fields = null, $values = null) {
$fieldsData = array();
if ($fields === null) {
unset($fields, $values);
$fields = array_keys($model->data);
$values = array_values($model->data);
}
$fieldCount = count($fields);
for ($i = 0; $i < $fieldCount; $i++) {
$fieldsData[$fields[$i]] = $values[$i];
}
//set our scope
$queryData['scope'] = 'base';
if ($model->primaryKey === 'dn') {
$queryData['targetDn'] = $model->id;
} elseif (isset($model->useTable) && !empty($model->useTable)) {
$queryData['targetDn'] = $model->primaryKey . '=' . $model->id . ', ' . $model->useTable;
}
// fetch the record
// Find the user we will update as we need their dn
$resultSet = $this->read($model, $queryData, $model->recursive);
//now we need to find out what's different about the old entry and the new one and only changes those parts
$current = $resultSet[0][$model->alias];
$update = $model->data[$model->alias];
foreach ($update as $attr => $value) {
if (isset($update[$attr]) && !empty($update[$attr])) {
$entry[$attr] = $update[$attr];
} elseif (!empty($current[$attr]) && (isset($update[$attr]) && empty($update[$attr]))) {
$entry[$attr] = array();
}
}
//if this isn't a password reset, then remove the password field to avoid constraint violations...
if (!$this->inArrayInsensitive('userpassword', $update)) {
unset($entry['userpassword']);
}
unset($entry['count']);
unset($entry['dn']);
if ($resultSet) {
$dn = $resultSet[0][$model->alias]['dn'];
if (@ldap_modify($this->database, $dn, $entry)) {
return true;
}
$this->log("Error updating $dn: " . ldap_error($this->database) . "\nHere is what I sent: " . print_r($entry, true), 'ldap.error');
return false;
}
// If we get this far, something went horribly wrong ..
$model->onError();
return false;
}
/**
* The "D" in CRUD
*/
public function delete(Model $model) {
// Boolean to determine if we want to recursively delete or not
//$recursive = true;
$recursive = false;
if (preg_match('/dn/i', $model->primaryKey)) {
$dn = $model->id;
} else {
// Find the user we will update as we need their dn
if ($model->defaultObjectClass) {
$options['conditions'] = sprintf( '(&(objectclass=%s)(%s=%s))', $model->defaultObjectClass, $model->primaryKey, $model->id);
} else {
$options['conditions'] = sprintf( '%s=%s', $model->primaryKey, $model->id);
}
$options['targetDn'] = $model->useTable;
$options['scope'] = 'sub';
$entry = $this->read($model, $options, $model->recursive);
$dn = $entry[0][$model->name]['dn'];
}
if ($dn) {
if ($recursive === true) {
// Recursively delete LDAP entries
if ($this->_deleteRecursively($dn)) {
return true;
}
} else {
// Single entry delete
if (@ldap_delete($this->database, $dn)) {
return true;
}
}
}
$model->onError();
$errMsg = ldap_error($this->database);
$this->log("Failed Trying to delete: $dn \nLdap Erro:$errMsg", 'ldap.error');
return false;
}
/**
* Courtesy of gabriel at hrz dot uni-marburg dot de @ http://ar.php.net/ldap_delete
*/
protected function _deleteRecursively($dn) {
// Search for sub entries
$subentries = ldap_list($this->database, $dn, "objectClass=*", array());
$info = ldap_get_entries($this->database, $subentries);
for ($i = 0; $i < $info['count']; $i++) {
// deleting recursively sub entries
$result = $this->_deleteRecursively($info[$i]['dn']);
if (!$result) {
return false;
}
}
return @ldap_delete($this->database, $dn);
}
public function generateAssociationQuery(Model $model, Model $linkModel, $type, $association, $assocData, &$queryData, $external, &$resultSet) {
$this->_scrubQueryData($queryData);
switch ($type) {
case 'hasOne':
$id = $resultSet[$model->name][$model->primaryKey];
$queryData['conditions'] = trim($assocData['foreignKey']) . '=' . trim($id);
$queryData['targetDn'] = $linkModel->useTable;
$queryData['type'] = 'search';
$queryData['limit'] = 1;
return $queryData;
case 'belongsTo':
$id = $resultSet[$model->name][$assocData['foreignKey']];
$queryData['conditions'] = trim($linkModel->primaryKey) . '=' . trim($id);
$queryData['targetDn'] = $linkModel->useTable;
$queryData['type'] = 'search';
$queryData['limit'] = 1;
return $queryData;
case 'hasMany':
$id = $resultSet[$model->name][$model->primaryKey];
$queryData['conditions'] = trim($assocData['foreignKey']) . '=' . trim($id);
$queryData['targetDn'] = $linkModel->useTable;
$queryData['type'] = 'search';
$queryData['limit'] = $assocData['limit'];
return $queryData;
case 'hasAndBelongsToMany':
return null;
}
return null;
}
public function queryAssociation(Model $model, &$linkModel, $type, $association, $assocData, &$queryData, $external, &$resultSet, $recursive, $stack) {
if (!isset($resultSet) || !is_array($resultSet)) {
if (Configure::read('debug') > 0) {
echo '<div style = "font: Verdana bold 12px; color: #FF0000">SQL Error in model ' . $model->name . ': ';
if (isset($this->error) && $this->error != null) {
echo $this->error;
}
echo '</div>';
}
return null;
}
$count = count($resultSet);
for ($i = 0; $i < $count; $i++) {
$row = $resultSet[$i];
$queryData = $this->generateAssociationQuery($model, $linkModel, $type, $association, $assocData, $queryData, $external, $row);
$fetch = $this->_executeQuery($queryData);
$fetch = ldap_get_entries($this->database, $fetch);
$fetch = $this->_ldapFormat($linkModel, $fetch);
if (!empty($fetch) && is_array($fetch)) {
if ($recursive > 0) {
foreach ($linkModel->_associations as $type1) {
foreach ($linkModel->{$type1 } as $assoc1 => $assocData1) {
$deepModel = $linkModel->{$assocData1['className']};
if ($deepModel->alias !== $model->name) {
$tmpStack = $stack;
$tmpStack[] = $assoc1;
if ($linkModel->useDbConfig == $deepModel->useDbConfig) {
$db = $this;
} else {
$db = ConnectionManager::getDataSource($deepModel->useDbConfig);
}
$queryData = array();
$db->queryAssociation($linkModel, $deepModel, $type1, $assoc1, $assocData1, $queryData, true, $fetch, $recursive - 1, $tmpStack);
}
}
}
}
$this->_mergeAssociation($resultSet[$i], $fetch, $association, $type);
} else {
$tempArray[0][$association] = false;
$this->_mergeAssociation($resultSet[$i], $tempArray, $association, $type);
}
}
}
/**
* Returns a formatted error message from previous database operation.
*
* @return string Error message with error number
*/
public function lastError() {
if (ldap_errno($this->database)) {
return ldap_errno($this->database) . ': ' . ldap_error($this->database);
}
return null;
}
/**
* Returns number of rows in previous resultset. If no previous resultset exists,
* this returns false.
*
* @return integer Number of rows in resultset
*/
public function lastNumRows() {
if ($this->_result && is_resource($this->_result)) {
return @ldap_count_entries($this->database, $this->_result);
}
return null;
}
/**
* Convert Active Directory timestamps to unix ones
*
* @param integer $adTimestamp Active directory timestamp
* @return integer Unix timestamp
*/
public function convertTimestampADToUnix($adTimestamp) {
$epochDiff = 11644473600; // difference 1601<>1970 in seconds. see reference URL
$dateTimestamp = $adTimestamp * 0.0000001;
$unixTimestamp = $dateTimestamp - $epochDiff;
return $unixTimestamp;
}
/**
* The following was kindly "borrowed" from the excellent phpldapadmin project
*
* @return array
*/
protected function _getLDAPschema() {
$schemaTypes = array('objectclasses', 'attributetypes');
$this->results = @ldap_read($this->database, $this->SchemaDN, $this->SchemaFilter, $schemaTypes, 0, 0, 0, LDAP_DEREF_ALWAYS);
if ($this->results === null) {
$this->log( "LDAP schema filter $schemaFilter is invalid!", 'ldap.error');
return array();
}
$schemaEntries = @ldap_get_entries($this->database, $this->results);
if (!$schemaEntries) {
return array();
}
$return = array();
foreach ($schemaTypes as $n) {
$schemaTypeEntries = $schemaEntries[0][$n];
for ($x = 0; $x < $schemaTypeEntries['count']; $x++) {
$entry = array();
$strings = preg_split('/[\s,]+/', $schemaTypeEntries[$x], -1, PREG_SPLIT_DELIM_CAPTURE);
$strCount = count($strings);
for ($i = 0; $i < $strCount; $i++) {
switch ($strings[$i]) {
case '(':
break;
case 'NAME':
if ($strings[$i + 1] !== '(') {
do {
$i++;
if (!isset($entry['name']) || strlen($entry['name']) === 0) {
$entry['name'] = $strings[$i];
} else {
$entry['name'] .= ' ' . $strings[$i];
}
} while (!preg_match('/\'$/s', $strings[$i]));
} else {
$i++;
do {
$i++;
if (!isset($entry['name'] ) || strlen($entry['name']) === 0) {
$entry['name'] = $strings[$i];
} else {
$entry['name'] .= ' ' . $strings[$i];
}
} while (!preg_match( '/\'$/s', $strings[$i]));
do {
$i++;
} while (!preg_match( '/\)+\)?/', $strings[$i]));
}
$entry['name'] = preg_replace('/^\'/', '', $entry['name']);
$entry['name'] = preg_replace('/\'$/', '', $entry['name']);
break;
case 'DESC':
do {
$i++;
if (!isset($entry['description']) || strlen($entry['description']) === 0) {
$entry['description'] = $strings[$i];
} else {
$entry['description'] .= ' ' . $strings[$i];
}
} while (!preg_match( '/\'$/s', $strings[$i]));
break;
case 'OBSOLETE':
$entry['is_obsolete'] = true;
break;
case 'SUP':
$entry['sup_classes'] = array();
if ($strings[$i + 1] !== '(') {
$i++;
array_push($entry['sup_classes'], preg_replace( "/'/", '', $strings[$i]));
} else {
$i++;
do {
$i++;
if ($strings[$i] !== '$') {
array_push($entry['sup_classes'], preg_replace( "/'/", '', $strings[$i]));
}
} while (! preg_match('/\)+\)?/', $strings[$i + 1]));
}
break;
case 'ABSTRACT':
$entry['type'] = 'abstract';
break;
case 'STRUCTURAL':
$entry['type'] = 'structural';
break;
case 'SINGLE-VALUE':
$entry['multiValue'] = 'false';
break;
case 'AUXILIARY':
$entry['type'] = 'auxiliary';
break;
case 'MUST':
$entry['must'] = array();
$i = $this->_parseList(++$i, $strings, $entry['must']);
break;
case 'MAY':
$entry['may'] = array();
$i = $this->_parseList(++$i, $strings, $entry['may']);
break;
default:
if (preg_match( '/[\d\.]+/i', $strings[$i]) && $i == 1) {
$entry['oid'] = $strings[$i];
}
break;
}
}
if (!isset($return[$n]) || !is_array($return[$n])) {
$return[$n] = array();
}
// Make lowercase for consistency
$return[strtolower($n)][strtolower($entry['name'])] = $entry;
//array_push($return[$n][$entry['name']], $entry);
}
}
return $return;
}
/**
* LdapSource::_parseList()
*
* @param integer $i
* @param array $strings
* @param array $attrs
* @return integer
*/
protected function _parseList($i, $strings, &$attrs) {
/**
** A list starts with a ( followed by a list of attributes separated by $ terminated by )
** The first token can therefore be a ( or a (NAME or a (NAME)
** The last token can therefore be a ) or NAME)
** The last token may be terminate by more than one bracket
*/
$string = $strings[$i];
if (!preg_match('/^\(/', $string)) {
// A bareword only - can be terminated by a ) if the last item
if (preg_match('/\)+$/', $string)) {
$string = preg_replace('/\)+$/', '', $string);
}
array_push($attrs, $string);
} elseif (preg_match('/^\(.*\)$/', $string)) {
$string = preg_replace('/^\(/', '', $string);
$string = preg_replace('/\)+$/', '', $string);
array_push($attrs, $string);
} else {
// Handle the opening cases first
if ($string === '(') {
$i++;
} elseif (preg_match('/^\(./', $string)) {
$string = preg_replace('/^\(/', '', $string);
array_push($attrs, $string);
$i++;
}
// Token is either a name, a $ or a ')'
// NAME can be terminated by one or more ')'
while (!preg_match('/\)+$/', $strings[$i])) {
$string = $strings[$i];
if ($string === '$') {
$i++;
continue;
}
if (preg_match('/\)$/', $string)) {
$string = preg_replace('/\)+$/', '', $string);
} else {
$i++;
}
array_push($attrs, $string);
}
}
sort($attrs);
return $i;
}
/**
* Function not supported
*/
public function execute($query) {
return null;
}
/**
* Function not supported
*/
public function fetchAll($query, $cache = true) {
return array();
}
/**
* Log given LDAP query.
*
* @param string $query LDAP statement
* @todo: Add hook to log errors instead of returning false
*/
public function logQuery($query) {
$this->_queriesCnt++;
$this->_queriesTime += $this->took;
$this->_queriesLog[] = array(
'query' => $query,
'error' => $this->error,
'affected' => $this->affected,
'numRows' => $this->numRows,
'took' => $this->took
);
if (count($this->_queriesLog) > $this->_queriesLogMax) {
array_pop($this->_queriesLog);
}
if ($this->error) {
return false;
}
}
/**
* Outputs the contents of the queries log.
*
* @param boolean $sorted
*/
public function showLog($sorted = false) {
if ($sorted) {
$log = sortByKey($this->_queriesLog, 'took', 'desc', SORT_NUMERIC);
} else {
$log = $this->_queriesLog;
}
if ($this->_queriesCnt > 1) {
$text = 'queries';
} else {
$text = 'query';
}
if (php_sapi_name() !== 'cli') {
print ("<table id=\"cakeSqlLog\" cellspacing=\"0\" border = \"0\">\n<caption>{$this->_queriesCnt} {$text} took {$this->_queriesTime} ms</caption>\n");
print ("<thead>\n<tr><th>Nr</th><th>Query</th><th>Error</th><th>Affected</th><th>Num. rows</th><th>Took (ms)</th></tr>\n</thead>\n<tbody>\n");
foreach ($log as $k => $i) {
print ("<tr><td>" . ($k + 1) . "</td><td>{$i['query']}</td><td>{$i['error']}</td><td style = \"text-align: right\">{$i['affected']}</td><td style = \"text-align: right\">{$i['numRows']}</td><td style = \"text-align: right\">{$i['took']}</td></tr>\n");
}
print ("</table>\n");
} else {
foreach ($log as $k => $i) {
print (($k + 1) . ". {$i['query']} {$i['error']}\n");
}
}
}
/**
* Output information about a LDAP query. The query, number of rows in resultset,
* and execution time in microseconds. If the query fails, an error is output instead.
*
* @param string $query Query to show information on.