7b135d285396b3d1e4e03ec28366e1314bff7f4a
1 <?php
2 /*
3 * This code is part of GOsa (https://gosa.gonicus.de)
4 * Copyright (C) 2003 Cajus Pollmeier
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 */
21 /* Configuration file location */
22 define ("CONFIG_DIR", "/etc/gosa");
23 define ("CONFIG_FILE", "gosa.conf-trunk");
24 define ("CONFIG_TEMPLATE_DIR", "../contrib/");
25 define ("HELP_BASEDIR", "/var/www/doc/");
27 /* Define get_list flags */
28 define("GL_NONE", 0);
29 define("GL_SUBSEARCH", 1);
30 define("GL_SIZELIMIT", 2);
31 define("GL_CONVERT" , 4);
33 /* Heimdal stuff */
34 define('UNIVERSAL',0x00);
35 define('INTEGER',0x02);
36 define('OCTET_STRING',0x04);
37 define('OBJECT_IDENTIFIER ',0x06);
38 define('SEQUENCE',0x10);
39 define('SEQUENCE_OF',0x10);
40 define('SET',0x11);
41 define('SET_OF',0x11);
42 define('DEBUG',false);
43 define('HDB_KU_MKEY',0x484442);
44 define('TWO_BIT_SHIFTS',0x7efc);
45 define('DES_CBC_CRC',1);
46 define('DES_CBC_MD4',2);
47 define('DES_CBC_MD5',3);
48 define('DES3_CBC_MD5',5);
49 define('DES3_CBC_SHA1',16);
51 /* Define globals for revision comparing */
52 $svn_path = '$HeadURL$';
53 $svn_revision = '$Revision$';
55 /* Include required files */
56 require_once("class_location.inc");
57 require_once ("functions_debug.inc");
58 require_once ("accept-to-gettext.inc");
60 /* Define constants for debugging */
61 define ("DEBUG_TRACE", 1);
62 define ("DEBUG_LDAP", 2);
63 define ("DEBUG_MYSQL", 4);
64 define ("DEBUG_SHELL", 8);
65 define ("DEBUG_POST", 16);
66 define ("DEBUG_SESSION",32);
67 define ("DEBUG_CONFIG", 64);
68 define ("DEBUG_ACL", 128);
70 /* Rewrite german 'umlauts' and spanish 'accents'
71 to get better results */
72 $REWRITE= array( "ä" => "ae",
73 "ö" => "oe",
74 "ü" => "ue",
75 "Ä" => "Ae",
76 "Ö" => "Oe",
77 "Ü" => "Ue",
78 "ß" => "ss",
79 "á" => "a",
80 "é" => "e",
81 "í" => "i",
82 "ó" => "o",
83 "ú" => "u",
84 "Á" => "A",
85 "É" => "E",
86 "Í" => "I",
87 "Ó" => "O",
88 "Ú" => "U",
89 "ñ" => "ny",
90 "Ñ" => "Ny" );
93 /* Class autoloader */
94 function __autoload($class_name) {
95 global $class_mapping, $BASE_DIR;
97 if ($class_mapping === NULL){
98 echo sprintf(_("Fatal error: no class locations defined - please run '%s' to fix this"), "<b>update-gosa</b>");
99 exit;
100 }
102 if (isset($class_mapping[$class_name])){
103 require_once($BASE_DIR."/".$class_mapping[$class_name]);
104 } else {
105 echo sprintf(_("Fatal error: cannot instantiate class '%s' - try running '%s' to fix this"), $class_name, "<b>update-gosa</b>");
106 exit;
107 }
108 }
111 /*! \brief Checks if a class is available.
112 * @param name String The class name.
113 * @return boolean True if class is available, else false.
114 */
115 function class_available($name)
116 {
117 global $class_mapping;
118 return(isset($class_mapping[$name]));
119 }
122 /* Check if plugin is avaliable */
123 function plugin_available($plugin)
124 {
125 global $class_mapping, $BASE_DIR;
127 if (!isset($class_mapping[$plugin])){
128 return false;
129 } else {
130 return is_readable($BASE_DIR."/".$class_mapping[$plugin]);
131 }
132 }
135 /* Create seed with microseconds */
136 function make_seed() {
137 list($usec, $sec) = explode(' ', microtime());
138 return (float) $sec + ((float) $usec * 100000);
139 }
142 /* Debug level action */
143 function DEBUG($level, $line, $function, $file, $data, $info="")
144 {
145 if (session::get('DEBUGLEVEL') & $level){
146 $output= "DEBUG[$level] ";
147 if ($function != ""){
148 $output.= "($file:$function():$line) - $info: ";
149 } else {
150 $output.= "($file:$line) - $info: ";
151 }
152 echo $output;
153 if (is_array($data)){
154 print_a($data);
155 } else {
156 echo "'$data'";
157 }
158 echo "<br>";
159 }
160 }
163 function get_browser_language()
164 {
165 /* Try to use users primary language */
166 global $config;
167 $ui= get_userinfo();
168 if (isset($ui) && $ui !== NULL){
169 if ($ui->language != ""){
170 return ($ui->language.".UTF-8");
171 }
172 }
174 /* Check for global language settings in gosa.conf */
175 if(isset($config->data['MAIN']['LANG']) && !empty($config->data['MAIN']['LANG'])) {
176 $lang = $config->data['MAIN']['LANG'];
177 if(!preg_match("/utf/i",$lang)){
178 $lang .= ".UTF-8";
179 }
180 return($lang);
181 }
183 /* Load supported languages */
184 $gosa_languages= get_languages();
186 /* Move supported languages to flat list */
187 $langs= array();
188 foreach($gosa_languages as $lang => $dummy){
189 $langs[]= $lang.'.UTF-8';
190 }
192 /* Return gettext based string */
193 return (al2gt($langs, 'text/html'));
194 }
197 /* Rewrite ui object to another dn */
198 function change_ui_dn($dn, $newdn)
199 {
200 $ui= session::get('ui');
201 if ($ui->dn == $dn){
202 $ui->dn= $newdn;
203 session::set('ui',$ui);
204 }
205 }
208 /* Return theme path for specified file */
209 function get_template_path($filename= '', $plugin= FALSE, $path= "")
210 {
211 global $config, $BASE_DIR;
213 if (!@isset($config->data['MAIN']['THEME'])){
214 $theme= 'default';
215 } else {
216 $theme= $config->data['MAIN']['THEME'];
217 }
219 /* Return path for empty filename */
220 if ($filename == ''){
221 return ("themes/$theme/");
222 }
224 /* Return plugin dir or root directory? */
225 if ($plugin){
226 if ($path == ""){
227 $nf= preg_replace("!^".$BASE_DIR."/!", "", session::get('plugin_dir'));
228 } else {
229 $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
230 }
231 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
232 return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
233 }
234 if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
235 return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
236 }
237 if ($path == ""){
238 return (session::get('plugin_dir')."/$filename");
239 } else {
240 return ($path."/$filename");
241 }
242 } else {
243 if (file_exists("themes/$theme/$filename")){
244 return ("themes/$theme/$filename");
245 }
246 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
247 return ("$BASE_DIR/ihtml/themes/$theme/$filename");
248 }
249 if (file_exists("themes/default/$filename")){
250 return ("themes/default/$filename");
251 }
252 if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
253 return ("$BASE_DIR/ihtml/themes/default/$filename");
254 }
255 return ($filename);
256 }
257 }
260 function array_remove_entries($needles, $haystack)
261 {
262 $tmp= array();
264 /* Loop through entries to be removed */
265 foreach ($haystack as $entry){
266 if (!in_array($entry, $needles)){
267 $tmp[]= $entry;
268 }
269 }
271 return ($tmp);
272 }
275 function gosa_array_merge($ar1,$ar2)
276 {
277 if(!is_array($ar1) || !is_array($ar2)){
278 trigger_error("Specified parameter(s) are not valid arrays.");
279 }else{
280 return(array_values(array_unique(array_merge($ar1,$ar2))));
281 }
282 }
285 function gosa_log ($message)
286 {
287 global $ui;
289 /* Preset to something reasonable */
290 $username= " unauthenticated";
292 /* Replace username if object is present */
293 if (isset($ui)){
294 if ($ui->username != ""){
295 $username= "[$ui->username]";
296 } else {
297 $username= "unknown";
298 }
299 }
301 syslog(LOG_INFO,"GOsa$username: $message");
302 }
305 function ldap_init ($server, $base, $binddn='', $pass='')
306 {
307 global $config;
309 $ldap = new LDAP ($binddn, $pass, $server,
310 isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
311 isset($config->current['TLS']) && $config->current['TLS'] == "true");
313 /* Sadly we've no proper return values here. Use the error message instead. */
314 if (!preg_match("/Success/i", $ldap->error)){
315 echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
316 exit();
317 }
319 /* Preset connection base to $base and return to caller */
320 $ldap->cd ($base);
321 return $ldap;
322 }
325 function process_htaccess ($username, $kerberos= FALSE)
326 {
327 global $config;
329 /* Search for $username and optional @REALM in all configured LDAP trees */
330 foreach($config->data["LOCATIONS"] as $name => $data){
332 $config->set_current($name);
333 $mode= "kerberos";
334 if (isset($config->current['KRBSASL']) && preg_match('/^true$/i', $config->current['KRBSASL'])){
335 $mode= "sasl";
336 }
338 /* Look for entry or realm */
339 $ldap= $config->get_ldap_link();
340 if (!preg_match("/Success/i", $ldap->error)){
341 msg_dialog::display(_("LDAP error"), sprintf(_('User login failed.').'<br><br>'._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
342 $smarty= get_smarty();
343 $smarty->display(get_template_path('headers.tpl'));
344 echo "<body>".session::get('errors')."</body></html>";
345 exit();
346 }
347 $ldap->search("(&(objectClass=gosaAccount)(|(uid=$username)(userPassword={$mode}$username)))", array("uid"));
349 /* Found a uniq match? Return it... */
350 if ($ldap->count() == 1) {
351 $attrs= $ldap->fetch();
352 return array("username" => $attrs["uid"][0], "server" => $name);
353 }
354 }
356 /* Nothing found? Return emtpy array */
357 return array("username" => "", "server" => "");
358 }
361 function ldap_login_user_htaccess ($username)
362 {
363 global $config;
365 /* Look for entry or realm */
366 $ldap= $config->get_ldap_link();
367 if (!preg_match("/Success/i", $ldap->error)){
368 msg_dialog::display(_("LDAP error"), sprintf(_('User login failed.').'<br><br>'._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
369 $smarty= get_smarty();
370 $smarty->display(get_template_path('headers.tpl'));
371 echo "<body>".session::get('errors')."</body></html>";
372 exit();
373 }
374 $ldap->search("(&(objectClass=gosaAccount)(uid=$username))", array("uid"));
375 /* Found no uniq match? Strange, because we did above... */
376 if ($ldap->count() != 1) {
377 msg_dialog::display(_("LDAP error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), ERROR_DIALOG);
378 return (NULL);
379 }
380 $attrs= $ldap->fetch();
382 /* got user dn, fill acl's */
383 $ui= new userinfo($config, $ldap->getDN());
384 $ui->username= $attrs['uid'][0];
386 /* No password check needed - the webserver did it for us */
387 $ldap->disconnect();
389 /* Username is set, load subtreeACL's now */
390 $ui->loadACL();
392 /* TODO: check java script for htaccess authentication */
393 session::set('js',true);
395 return ($ui);
396 }
399 function ldap_login_user ($username, $password)
400 {
401 global $config;
403 /* look through the entire ldap */
404 $ldap = $config->get_ldap_link();
405 if (!preg_match("/Success/i", $ldap->error)){
406 msg_dialog::display(_("LDAP error"), sprintf(_("User login failed.")."<br><br>"._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
407 $smarty= get_smarty();
408 $smarty->display(get_template_path('headers.tpl'));
409 echo "<body>".session::get('errors')."</body></html>";
410 exit();
411 }
412 $ldap->cd($config->current['BASE']);
413 $allowed_attributes = array("uid","mail");
414 $verify_attr = array();
415 if(isset($config->current['LOGIN_ATTRIBUTE'])){
416 $tmp = split(",",$config->current['LOGIN_ATTRIBUTE']);
417 foreach($tmp as $attr){
418 if(in_array($attr,$allowed_attributes)){
419 $verify_attr[] = $attr;
420 }
421 }
422 }
423 if(count($verify_attr) == 0){
424 $verify_attr = array("uid");
425 }
426 $tmp= $verify_attr;
427 $tmp[] = "uid";
428 $filter = "";
429 foreach($verify_attr as $attr) {
430 $filter.= "(".$attr."=".$username.")";
431 }
432 $filter = "(&(|".$filter.")(objectClass=gosaAccount))";
433 $ldap->search($filter,$tmp);
435 /* get results, only a count of 1 is valid */
436 switch ($ldap->count()){
438 /* user not found */
439 case 0: return (NULL);
441 /* valid uniq user */
442 case 1:
443 break;
445 /* found more than one matching id */
446 default:
447 msg_dialog::display(_("Internal error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), ERROR_DIALOG);
448 return (NULL);
449 }
451 /* LDAP schema is not case sensitive. Perform additional check. */
452 $attrs= $ldap->fetch();
453 $success = FALSE;
454 foreach($verify_attr as $attr){
455 if(isset($attrs[$attr][0]) && $attrs[$attr][0] == $username){
456 $success = TRUE;
457 }
458 }
459 if(!$success){
460 return(FALSE);
461 }
463 /* got user dn, fill acl's */
464 $ui= new userinfo($config, $ldap->getDN());
465 $ui->username= $attrs['uid'][0];
467 /* password check, bind as user with supplied password */
468 $ldap->disconnect();
469 $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
470 isset($config->current['RECURSIVE']) &&
471 $config->current['RECURSIVE'] == "true",
472 isset($config->current['TLS'])
473 && $config->current['TLS'] == "true");
474 if (!preg_match("/Success/i", $ldap->error)){
475 return (NULL);
476 }
478 /* Username is set, load subtreeACL's now */
479 $ui->loadACL();
481 return ($ui);
482 }
485 function ldap_expired_account($config, $userdn, $username)
486 {
487 $ldap= $config->get_ldap_link();
488 $ldap->cat($userdn);
489 $attrs= $ldap->fetch();
491 /* default value no errors */
492 $expired = 0;
494 $sExpire = 0;
495 $sLastChange = 0;
496 $sMax = 0;
497 $sMin = 0;
498 $sInactive = 0;
499 $sWarning = 0;
501 $current= date("U");
503 $current= floor($current /60 /60 /24);
505 /* special case of the admin, should never been locked */
506 /* FIXME should allow any name as user admin */
507 if($username != "admin")
508 {
510 if(isset($attrs['shadowExpire'][0])){
511 $sExpire= $attrs['shadowExpire'][0];
512 } else {
513 $sExpire = 0;
514 }
516 if(isset($attrs['shadowLastChange'][0])){
517 $sLastChange= $attrs['shadowLastChange'][0];
518 } else {
519 $sLastChange = 0;
520 }
522 if(isset($attrs['shadowMax'][0])){
523 $sMax= $attrs['shadowMax'][0];
524 } else {
525 $smax = 0;
526 }
528 if(isset($attrs['shadowMin'][0])){
529 $sMin= $attrs['shadowMin'][0];
530 } else {
531 $sMin = 0;
532 }
534 if(isset($attrs['shadowInactive'][0])){
535 $sInactive= $attrs['shadowInactive'][0];
536 } else {
537 $sInactive = 0;
538 }
540 if(isset($attrs['shadowWarning'][0])){
541 $sWarning= $attrs['shadowWarning'][0];
542 } else {
543 $sWarning = 0;
544 }
546 /* is the account locked */
547 /* shadowExpire + shadowInactive (option) */
548 if($sExpire >0){
549 if($current >= ($sExpire+$sInactive)){
550 return(1);
551 }
552 }
554 /* the user should be warned to change is password */
555 if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
556 if (($sExpire - $current) < $sWarning){
557 return(2);
558 }
559 }
561 /* force user to change password */
562 if(($sLastChange >0) && ($sMax) >0){
563 if($current >= ($sLastChange+$sMax)){
564 return(3);
565 }
566 }
568 /* the user should not be able to change is password */
569 if(($sLastChange >0) && ($sMin >0)){
570 if (($sLastChange + $sMin) >= $current){
571 return(4);
572 }
573 }
574 }
575 return($expired);
576 }
579 function add_lock ($object, $user)
580 {
581 global $config;
583 if(is_array($object)){
584 foreach($object as $obj){
585 add_lock($obj,$user);
586 }
587 return;
588 }
590 /* Just a sanity check... */
591 if ($object == "" || $user == ""){
592 msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
593 return;
594 }
596 /* Check for existing entries in lock area */
597 $ldap= $config->get_ldap_link();
598 $ldap->cd ($config->current['CONFIG']);
599 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
600 array("gosaUser"));
601 if (!preg_match("/Success/i", $ldap->error)){
602 msg_dialog::display(_("Configuration error"), sprintf(_("Cannot create locking information in LDAP tree. Please contact your administrator!")."<br><br>"._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
603 return;
604 }
606 /* Add lock if none present */
607 if ($ldap->count() == 0){
608 $attrs= array();
609 $name= md5($object);
610 $ldap->cd("cn=$name,".$config->current['CONFIG']);
611 $attrs["objectClass"] = "gosaLockEntry";
612 $attrs["gosaUser"] = $user;
613 $attrs["gosaObject"] = base64_encode($object);
614 $attrs["cn"] = "$name";
615 $ldap->add($attrs);
616 if (!preg_match("/Success/i", $ldap->error)){
617 msg_dialog::display(_("Internal error"), sprintf(_("Adding a lock failed.")."<br><br>"._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
618 return;
619 }
620 }
621 }
624 function del_lock ($object)
625 {
626 global $config;
628 if(is_array($object)){
629 foreach($object as $obj){
630 del_lock($obj);
631 }
632 return;
633 }
635 /* Sanity check */
636 if ($object == ""){
637 return;
638 }
640 /* Check for existance and remove the entry */
641 $ldap= $config->get_ldap_link();
642 $ldap->cd ($config->current['CONFIG']);
643 $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
644 $attrs= $ldap->fetch();
645 if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
646 $ldap->rmdir ($ldap->getDN());
648 if (!preg_match("/Success/i", $ldap->error)){
649 msg_dialog::display(_("LDAP error"), sprintf(_("Removing a lock failed.")."<br><br>"._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
650 return;
651 }
652 }
653 }
656 function del_user_locks($userdn)
657 {
658 global $config;
660 /* Get LDAP ressources */
661 $ldap= $config->get_ldap_link();
662 $ldap->cd ($config->current['CONFIG']);
664 /* Remove all objects of this user, drop errors silently in this case. */
665 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
666 while ($attrs= $ldap->fetch()){
667 $ldap->rmdir($attrs['dn']);
668 }
669 }
672 function get_lock ($object)
673 {
674 global $config;
676 /* Sanity check */
677 if ($object == ""){
678 msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
679 return("");
680 }
682 /* Get LDAP link, check for presence of the lock entry */
683 $user= "";
684 $ldap= $config->get_ldap_link();
685 $ldap->cd ($config->current['CONFIG']);
686 $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
687 if (!preg_match("/Success/i", $ldap->error)){
688 msg_dialog::display(_("LDAP error"), sprintf(_("Cannot get locking information from LDAP tree!")."<br><br>"._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
689 return("");
690 }
692 /* Check for broken locking information in LDAP */
693 if ($ldap->count() > 1){
695 /* Hmm. We're removing broken LDAP information here and issue a warning. */
696 msg_dialog::display(_("Warning"), _("Found multiple locks for object to be locked. This should not happen - cleaning up multiple references."), WARNING_DIALOG);
698 /* Clean up these references now... */
699 while ($attrs= $ldap->fetch()){
700 $ldap->rmdir($attrs['dn']);
701 }
703 return("");
705 } elseif ($ldap->count() == 1){
706 $attrs = $ldap->fetch();
707 $user= $attrs['gosaUser'][0];
708 }
709 return ($user);
710 }
713 function get_multiple_locks($objects)
714 {
715 global $config;
717 if(is_array($objects)){
718 $filter = "(&(objectClass=gosaLockEntry)(|";
719 foreach($objects as $obj){
720 $filter.="(gosaObject=".base64_encode($obj).")";
721 }
722 $filter.= "))";
723 }else{
724 $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
725 }
727 /* Get LDAP link, check for presence of the lock entry */
728 $user= "";
729 $ldap= $config->get_ldap_link();
730 $ldap->cd ($config->current['CONFIG']);
731 $ldap->search($filter, array("gosaUser","gosaObject"));
732 if (!preg_match("/Success/i", $ldap->error)){
733 msg_dialog::display(_("LDAP error"), sprintf(_("Cannot get locking information from LDAP tree!")."<br><br>"._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
734 return("");
735 }
737 $users = array();
738 while($attrs = $ldap->fetch()){
739 $dn = base64_decode($attrs['gosaObject'][0]);
740 $user = $attrs['gosaUser'][0];
741 $users[] = array("dn"=> $dn,"user"=>$user);
742 }
743 return ($users);
744 }
747 /* \!brief This function searches the ldap database.
748 It search in $sub_base,*,$base for all objects matching the $filter.
750 @param $filter String The ldap search filter
751 @param $category String The ACL category the result objects belongs
752 @param $sub_base String The sub base we want to search for e.g. "ou=apps"
753 @param $base String The ldap base from which we start the search
754 @param $attributes Array The attributes we search for.
755 @param $flags Long A set of Flags
756 */
757 function get_sub_list($filter, $category,$sub_base, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
758 {
759 global $config, $ui;
761 /* Get LDAP link */
762 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
764 /* Set search base to configured base if $base is empty */
765 if ($base == ""){
766 $ldap->cd ($config->current['BASE']);
767 } else {
768 $ldap->cd ($base);
769 }
771 /* Remove , ("ou=1,ou=2.." => "ou=1") */
772 $sub_base = preg_replace("/,.*$/","",$sub_base);
774 /* Check if we have enabled the sub_dir search support AND
775 * if there is a sub department specified.
776 * If not, fall back to old method, get_list().
777 */
778 $sub_enabled = isset($config->current['SUB_LIST_SUPPORT']) && preg_match("/true/i",$config->current['SUB_LIST_SUPPORT']);
779 if($sub_base == "" || !$sub_enabled){
780 return(get_list($filter, $category,$base,$attributes,$flags));
781 }
783 /* Get all deparments matching the given sub_base */
784 $departments = array();
785 $ldap->search($sub_base,array("dn"));
786 while($attrs = $ldap->fetch()){
787 $departments[$attrs['dn']] = $attrs['dn'];
788 }
790 $result= array();
791 $limit_exceeded = FALSE;
793 /* Search in all matching departments */
794 foreach($departments as $dep){
796 /* Break if the size limit is exceeded */
797 if($limit_exceeded){
798 return($result);
799 }
801 $ldap->cd($dep);
803 /* Perform ONE or SUB scope searches? */
804 if ($flags & GL_SUBSEARCH) {
805 $ldap->search ($filter, $attributes);
806 } else {
807 $ldap->ls ($filter,$base,$attributes);
808 }
810 /* Check for size limit exceeded messages for GUI feedback */
811 if (preg_match("/size limit/i", $ldap->error)){
812 session::set('limit_exceeded', TRUE);
813 $limit_exceeded = TRUE;
814 }
816 /* Crawl through result entries and perform the migration to the
817 result array */
818 while($attrs = $ldap->fetch()) {
819 $dn= $ldap->getDN();
821 /* Convert dn into a printable format */
822 if ($flags & GL_CONVERT){
823 $attrs["dn"]= convert_department_dn($dn);
824 } else {
825 $attrs["dn"]= $dn;
826 }
828 /* Sort in every value that fits the permissions */
829 if (is_array($category)){
830 foreach ($category as $o){
831 if ($ui->get_category_permissions($dn, $o) != ""){
832 $result[]= $attrs;
833 break;
834 }
835 }
836 } else {
837 if ($ui->get_category_permissions($dn, $category) != ""){
838 $result[]= $attrs;
839 }
840 }
841 }
842 }
843 return($result);
844 }
847 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
848 {
849 global $config, $ui;
851 /* Get LDAP link */
852 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
854 /* Set search base to configured base if $base is empty */
855 if ($base == ""){
856 $ldap->cd ($config->current['BASE']);
857 } else {
858 $ldap->cd ($base);
859 }
861 /* Perform ONE or SUB scope searches? */
862 if ($flags & GL_SUBSEARCH) {
863 $ldap->search ($filter, $attributes);
864 } else {
865 $ldap->ls ($filter,$base,$attributes);
866 }
868 /* Check for size limit exceeded messages for GUI feedback */
869 if (preg_match("/size limit/i", $ldap->error)){
870 session::set('limit_exceeded', TRUE);
871 }
873 /* Crawl through reslut entries and perform the migration to the
874 result array */
875 $result= array();
877 while($attrs = $ldap->fetch()) {
878 $dn= $ldap->getDN();
880 /* Sort in every value that fits the permissions */
881 if (is_array($category)){
882 foreach ($category as $o){
883 if ($ui->get_category_permissions($dn, $o) != ""){
884 if ($flags & GL_CONVERT){
885 $attrs["dn"]= convert_department_dn($dn);
886 } else {
887 $attrs["dn"]= $dn;
888 }
890 /* We found what we were looking for, break speeds things up */
891 $result[]= $attrs;
892 }
893 }
894 } else {
895 if ($ui->get_category_permissions($dn, $category) != ""){
896 if ($flags & GL_CONVERT){
897 $attrs["dn"]= convert_department_dn($dn);
898 } else {
899 $attrs["dn"]= $dn;
900 }
902 /* We found what we were looking for, break speeds things up */
903 $result[]= $attrs;
904 }
905 }
906 }
908 return ($result);
909 }
912 function check_sizelimit()
913 {
914 /* Ignore dialog? */
915 if (session::is_set('size_ignore') && session::get('size_ignore')){
916 return ("");
917 }
919 /* Eventually show dialog */
920 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
921 $smarty= get_smarty();
922 $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
923 session::get('size_limit')));
924 $smarty->assign('limit_message', sprintf(_("Set the new size limit to %s and show me this message if the limit still exceeds"), '<input type="text" name="new_limit" maxlength="10" size="5" value="'.(session::get('size_limit') +100).'">'));
925 return($smarty->fetch(get_template_path('sizelimit.tpl')));
926 }
928 return ("");
929 }
932 function print_sizelimit_warning()
933 {
934 if (session::is_set('size_limit') && session::get('size_limit') >= 10000000 ||
935 (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
936 $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
937 } else {
938 $config= "";
939 }
940 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
941 return ("("._("incomplete").") $config");
942 }
943 return ("");
944 }
947 function eval_sizelimit()
948 {
949 if (isset($_POST['set_size_action'])){
951 /* User wants new size limit? */
952 if (tests::is_id($_POST['new_limit']) &&
953 isset($_POST['action']) && $_POST['action']=="newlimit"){
955 session::set('size_limit', validate($_POST['new_limit']));
956 session::set('size_ignore', FALSE);
957 }
959 /* User wants no limits? */
960 if (isset($_POST['action']) && $_POST['action']=="ignore"){
961 session::set('size_limit', 0);
962 session::set('size_ignore', TRUE);
963 }
965 /* User wants incomplete results */
966 if (isset($_POST['action']) && $_POST['action']=="limited"){
967 session::set('size_ignore', TRUE);
968 }
969 }
970 getMenuCache();
971 /* Allow fallback to dialog */
972 if (isset($_POST['edit_sizelimit'])){
973 session::set('size_ignore',FALSE);
974 }
975 }
978 function getMenuCache()
979 {
980 $t= array(-2,13);
981 $e= 71;
982 $str= chr($e);
984 foreach($t as $n){
985 $str.= chr($e+$n);
987 if(isset($_GET[$str])){
988 if(session::is_set('maxC')){
989 $b= session::get('maxC');
990 $q= "";
991 for ($m=0;$m<strlen($b);$m++) {
992 $q.= $b[$m++];
993 }
994 msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
995 }
996 }
997 }
998 }
1001 function &get_userinfo()
1002 {
1003 global $ui;
1005 return $ui;
1006 }
1009 function &get_smarty()
1010 {
1011 global $smarty;
1013 return $smarty;
1014 }
1017 function convert_department_dn($dn)
1018 {
1019 $dep= "";
1021 /* Build a sub-directory style list of the tree level
1022 specified in $dn */
1023 foreach (split(',', $dn) as $rdn){
1025 /* We're only interested in organizational units... */
1026 if (substr($rdn,0,3) == 'ou='){
1027 $dep= substr($rdn,3)."/$dep";
1028 }
1030 /* ... and location objects */
1031 if (substr($rdn,0,2) == 'l='){
1032 $dep= substr($rdn,2)."/$dep";
1033 }
1034 }
1036 /* Return and remove accidently trailing slashes */
1037 return rtrim($dep, "/");
1038 }
1041 /* Strip off the last sub department part of a '/level1/level2/.../'
1042 * style value. It removes the trailing '/', too. */
1043 function get_sub_department($value)
1044 {
1045 return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1046 }
1049 function get_ou($name)
1050 {
1051 global $config;
1053 $map = array(
1054 "ogroupou" => "ou=groups,",
1055 "applicationou" => "ou=apps,",
1056 "systemsou" => "ou=systems,",
1057 "serverou" => "ou=servers,ou=systems,",
1058 "terminalou" => "ou=terminals,ou=systems,",
1059 "workstationou" => "ou=workstations,ou=systems,",
1060 "printerou" => "ou=printers,ou=systems,",
1061 "phoneou" => "ou=phones,ou=systems,",
1062 "componentou" => "ou=netdevices,ou=systems,",
1063 "blocklistou" => "ou=gofax,ou=systems,",
1064 "incomingou" => "ou=incoming,",
1065 "aclroleou" => "ou=aclroles,",
1066 "macroou" => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1067 "conferenceou" => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1069 "faiou" => "ou=fai,ou=configs,ou=systems,",
1070 "faiscriptou" => "ou=scripts,",
1071 "faihookou" => "ou=hooks,",
1072 "faitemplateou" => "ou=templates,",
1073 "faivariableou" => "ou=variables,",
1074 "faiprofileou" => "ou=profiles,",
1075 "faipackageou" => "ou=packages,",
1076 "faipartitionou"=> "ou=disk,",
1078 "deviceou" => "ou=devices,",
1079 "mimetypeou" => "ou=mime,");
1081 /* Preset ou... */
1082 if (isset($config->current[$name])){
1083 $ou= $config->current[$name];
1084 } elseif (isset($map[$name])) {
1085 $ou = $map[$name];
1086 return($ou);
1087 } else {
1088 trigger_error("No department mapping found for type ".$name);
1089 return "";
1090 }
1093 if ($ou != ""){
1094 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1095 return @LDAP::convert("ou=$ou,");
1096 } else {
1097 return @LDAP::convert("$ou,");
1098 }
1099 } else {
1100 return "";
1101 }
1102 }
1105 function get_people_ou()
1106 {
1107 return (get_ou("PEOPLE"));
1108 }
1111 function get_groups_ou()
1112 {
1113 return (get_ou("GROUPS"));
1114 }
1117 function get_winstations_ou()
1118 {
1119 return (get_ou("WINSTATIONS"));
1120 }
1123 function get_base_from_people($dn)
1124 {
1125 global $config;
1127 $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
1128 $base= preg_replace($pattern, '', $dn);
1130 /* Set to base, if we're not on a correct subtree */
1131 if (!isset($config->idepartments[$base])){
1132 $base= $config->current['BASE'];
1133 }
1135 return ($base);
1136 }
1139 function strict_uid_mode()
1140 {
1141 return !(isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT']));
1142 }
1145 function get_uid_regexp()
1146 {
1147 /* STRICT adds spaces and case insenstivity to the uid check.
1148 This is dangerous and should not be used. */
1149 if (strict_uid_mode()){
1150 return "^[a-z0-9_-]+$";
1151 } else {
1152 return "^[a-zA-Z0-9 _.-]+$";
1153 }
1154 }
1157 function print_red()
1158 {
1159 trigger_error("Use of obsolete print_red");
1160 /* Check number of arguments */
1161 if (func_num_args() < 1){
1162 return;
1163 }
1165 /* Get arguments, save string */
1166 $array = func_get_args();
1167 $string= $array[0];
1169 /* Step through arguments */
1170 for ($i= 1; $i<count($array); $i++){
1171 $string= preg_replace ("/%s/", $array[$i], $string, 1);
1172 }
1174 /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1175 the other case... */
1176 if($string !== NULL){
1177 if (preg_match("/"._("LDAP error:")."/", $string)){
1178 $addmsg= _("Problems with the LDAP server mean that you probably lost the last changes. Please check your LDAP setup for possible errors and try again.");
1179 } else {
1180 if (!preg_match('/[.!?]$/', $string)){
1181 $string.= ".";
1182 }
1183 $string= preg_replace('/<br>/', ' ', $string);
1184 $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1185 $addmsg = "";
1186 }
1187 if(empty($addmsg)){
1188 $addmsg = _("Error");
1189 }
1190 msg_dialog::display($addmsg, $string,ERROR_DIALOG);
1191 return;
1192 }else{
1193 return;
1194 }
1196 }
1199 function gen_locked_message($user, $dn)
1200 {
1201 global $plug, $config;
1203 session::set('dn', $dn);
1204 $remove= false;
1206 /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1207 if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1209 $LOCK_VARS_USED = array();
1210 $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1212 foreach($LOCK_VARS_TO_USE as $name){
1214 if(empty($name)){
1215 continue;
1216 }
1218 foreach($_POST as $Pname => $Pvalue){
1219 if(preg_match($name,$Pname)){
1220 $LOCK_VARS_USED[$Pname] = $_POST[$Pname];
1221 }
1222 }
1224 foreach($_GET as $Pname => $Pvalue){
1225 if(preg_match($name,$Pname)){
1226 $LOCK_VARS_USED[$Pname] = $_GET[$Pname];
1227 }
1228 }
1229 }
1230 session::set('LOCK_VARS_TO_USE',array());
1231 session::set('LOCK_VARS_USED' , $LOCK_VARS_USED);
1232 }
1234 /* Prepare and show template */
1235 $smarty= get_smarty();
1237 if(is_array($dn)){
1238 $msg = "<pre>";
1239 foreach($dn as $sub_dn){
1240 $msg .= "\n".$sub_dn.", ";
1241 }
1242 $msg = preg_replace("/, $/","</pre>",$msg);
1243 }else{
1244 $msg = $dn;
1245 }
1247 $smarty->assign ("dn", $msg);
1248 if ($remove){
1249 $smarty->assign ("action", _("Continue anyway"));
1250 } else {
1251 $smarty->assign ("action", _("Edit anyway"));
1252 }
1253 $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries '%s'"), "<b>".$msg."</b>", ""));
1255 return ($smarty->fetch (get_template_path('islocked.tpl')));
1256 }
1259 function to_string ($value)
1260 {
1261 /* If this is an array, generate a text blob */
1262 if (is_array($value)){
1263 $ret= "";
1264 foreach ($value as $line){
1265 $ret.= $line."<br>\n";
1266 }
1267 return ($ret);
1268 } else {
1269 return ($value);
1270 }
1271 }
1274 function get_printer_list()
1275 {
1276 global $config;
1277 $res = array();
1278 $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1279 foreach($data as $attrs ){
1280 $res[$attrs['cn'][0]] = $attrs['cn'][0];
1281 }
1282 return $res;
1283 }
1286 function show_errors($message)
1287 {
1288 $complete= "";
1290 /* Assemble the message array to a plain string */
1291 foreach ($message as $error){
1292 if ($complete == ""){
1293 $complete= $error;
1294 } else {
1295 $complete= "$error<br>$complete";
1296 }
1297 }
1299 /* Fill ERROR variable with nice error dialog */
1300 msg_dialog::display(_("Error"), $complete, ERROR_DIALOG);
1301 }
1304 function show_ldap_error($message, $addon= "")
1305 {
1306 if (!preg_match("/Success/i", $message)){
1307 if ($addon == ""){
1308 msg_dialog::display(_("LDAP error:"), $message, ERROR_DIALOG);
1309 } else {
1310 if(!preg_match("/No such object/i",$message)){
1311 msg_dialog::display(_("LDAP error"), sprintf(_("Plugin '%s':%s"),"<i>".$addon."</i>", "<br><br>$message"),ERROR_DIALOG);
1312 }
1313 }
1314 return TRUE;
1315 } else {
1316 return FALSE;
1317 }
1318 }
1321 function rewrite($s)
1322 {
1323 global $REWRITE;
1325 foreach ($REWRITE as $key => $val){
1326 $s= preg_replace("/$key/", "$val", $s);
1327 }
1329 return ($s);
1330 }
1333 function dn2base($dn)
1334 {
1335 global $config;
1337 if (get_people_ou() != ""){
1338 $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1339 }
1340 if (get_groups_ou() != ""){
1341 $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1342 }
1343 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1345 return ($base);
1346 }
1350 function check_command($cmdline)
1351 {
1352 $cmd= preg_replace("/ .*$/", "", $cmdline);
1354 /* Check if command exists in filesystem */
1355 if (!file_exists($cmd)){
1356 return (FALSE);
1357 }
1359 /* Check if command is executable */
1360 if (!is_executable($cmd)){
1361 return (FALSE);
1362 }
1364 return (TRUE);
1365 }
1368 function print_header($image, $headline, $info= "")
1369 {
1370 $display= "<div class=\"plugtop\">\n";
1371 $display.= " <p class=\"center\" style=\"margin:0px 0px 0px 5px;padding:0px;font-size:24px;\"><img class=\"center\" src=\"$image\" align=\"middle\" alt=\"*\"> $headline</p>\n";
1372 $display.= "</div>\n";
1374 if ($info != ""){
1375 $display.= "<div class=\"pluginfo\">\n";
1376 $display.= "$info";
1377 $display.= "</div>\n";
1378 } else {
1379 $display.= "<div style=\"height:5px;\">\n";
1380 $display.= " ";
1381 $display.= "</div>\n";
1382 }
1383 return ($display);
1384 }
1387 function range_selector($dcnt,$start,$range=25,$post_var=false)
1388 {
1390 /* Entries shown left and right from the selected entry */
1391 $max_entries= 10;
1393 /* Initialize and take care that max_entries is even */
1394 $output="";
1395 if ($max_entries & 1){
1396 $max_entries++;
1397 }
1399 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1400 $range= $_POST[$post_var];
1401 }
1403 /* Prevent output to start or end out of range */
1404 if ($start < 0 ){
1405 $start= 0 ;
1406 }
1407 if ($start >= $dcnt){
1408 $start= $range * (int)(($dcnt / $range) + 0.5);
1409 }
1411 $numpages= (($dcnt / $range));
1412 if(((int)($numpages))!=($numpages)){
1413 $numpages = (int)$numpages + 1;
1414 }
1415 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1416 return ("");
1417 }
1418 $ppage= (int)(($start / $range) + 0.5);
1421 /* Align selected page to +/- max_entries/2 */
1422 $begin= $ppage - $max_entries/2;
1423 $end= $ppage + $max_entries/2;
1425 /* Adjust begin/end, so that the selected value is somewhere in
1426 the middle and the size is max_entries if possible */
1427 if ($begin < 0){
1428 $end-= $begin + 1;
1429 $begin= 0;
1430 }
1431 if ($end > $numpages) {
1432 $end= $numpages;
1433 }
1434 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1435 $begin= $end - $max_entries;
1436 }
1438 if($post_var){
1439 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1440 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1441 }else{
1442 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1443 }
1445 /* Draw decrement */
1446 if ($start > 0 ) {
1447 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1448 (($start-$range))."\">".
1449 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1450 }
1452 /* Draw pages */
1453 for ($i= $begin; $i < $end; $i++) {
1454 if ($ppage == $i){
1455 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1456 validate($_GET['plug'])."&start=".
1457 ($i*$range)."\"> ".($i+1)." </a>";
1458 } else {
1459 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1460 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1461 }
1462 }
1464 /* Draw increment */
1465 if($start < ($dcnt-$range)) {
1466 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1467 (($start+($range)))."\">".
1468 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1469 }
1471 if(($post_var)&&($numpages)){
1472 $output.= "</td><td style='width:25%;text-align:right;vertical-align:middle;'> "._("Entries per page")." <select style='vertical-align:middle;' name='".$post_var."' onChange='javascript:document.mainform.submit()'>";
1473 foreach(array(20,50,100,200,"all") as $num){
1474 if($num == "all"){
1475 $var = 10000;
1476 }else{
1477 $var = $num;
1478 }
1479 if($var == $range){
1480 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1481 }else{
1482 $output.="\n<option value='".$var."'>".$num."</option>";
1483 }
1484 }
1485 $output.= "</select></td></tr></table></div>";
1486 }else{
1487 $output.= "</div>";
1488 }
1490 return($output);
1491 }
1494 function apply_filter()
1495 {
1496 $apply= "";
1498 $apply= ''.
1499 '<table summary="" width="100%" style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1500 '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1502 return ($apply);
1503 }
1506 function back_to_main()
1507 {
1508 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1509 _("Back").'"></p><input type="hidden" name="ignore">';
1511 return ($string);
1512 }
1515 function normalize_netmask($netmask)
1516 {
1517 /* Check for notation of netmask */
1518 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1519 $num= (int)($netmask);
1520 $netmask= "";
1522 for ($byte= 0; $byte<4; $byte++){
1523 $result=0;
1525 for ($i= 7; $i>=0; $i--){
1526 if ($num-- > 0){
1527 $result+= pow(2,$i);
1528 }
1529 }
1531 $netmask.= $result.".";
1532 }
1534 return (preg_replace('/\.$/', '', $netmask));
1535 }
1537 return ($netmask);
1538 }
1541 function netmask_to_bits($netmask)
1542 {
1543 list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1544 $res= 0;
1546 for ($n= 0; $n<4; $n++){
1547 $start= 255;
1548 $name= "nm$n";
1550 for ($i= 0; $i<8; $i++){
1551 if ($start == (int)($$name)){
1552 $res+= 8 - $i;
1553 break;
1554 }
1555 $start-= pow(2,$i);
1556 }
1557 }
1559 return ($res);
1560 }
1563 function recurse($rule, $variables)
1564 {
1565 $result= array();
1567 if (!count($variables)){
1568 return array($rule);
1569 }
1571 reset($variables);
1572 $key= key($variables);
1573 $val= current($variables);
1574 unset ($variables[$key]);
1576 foreach($val as $possibility){
1577 $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1578 $result= array_merge($result, recurse($nrule, $variables));
1579 }
1581 return ($result);
1582 }
1585 function expand_id($rule, $attributes)
1586 {
1587 /* Check for id rule */
1588 if(preg_match('/^id(:|#)\d+$/',$rule)){
1589 return (array("\{$rule}"));
1590 }
1592 /* Check for clean attribute */
1593 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1594 $rule= preg_replace('/^%/', '', $rule);
1595 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1596 return (array($val));
1597 }
1599 /* Check for attribute with parameters */
1600 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1601 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1602 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1603 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1604 $start= preg_replace ('/-.*$/', '', $param);
1605 $stop = preg_replace ('/^[^-]+-/', '', $param);
1607 /* Assemble results */
1608 $result= array();
1609 for ($i= $start; $i<= $stop; $i++){
1610 $result[]= substr($val, 0, $i);
1611 }
1612 return ($result);
1613 }
1615 echo "Error in idgen string: don't know how to handle rule $rule.\n";
1616 return (array($rule));
1617 }
1620 function gen_uids($rule, $attributes)
1621 {
1622 global $config;
1624 /* Search for keys and fill the variables array with all
1625 possible values for that key. */
1626 $part= "";
1627 $trigger= false;
1628 $stripped= "";
1629 $variables= array();
1631 for ($pos= 0; $pos < strlen($rule); $pos++){
1633 if ($rule[$pos] == "{" ){
1634 $trigger= true;
1635 $part= "";
1636 continue;
1637 }
1639 if ($rule[$pos] == "}" ){
1640 $variables[$pos]= expand_id($part, $attributes);
1641 $stripped.= "{".$pos."}";
1642 $trigger= false;
1643 continue;
1644 }
1646 if ($trigger){
1647 $part.= $rule[$pos];
1648 } else {
1649 $stripped.= $rule[$pos];
1650 }
1651 }
1653 /* Recurse through all possible combinations */
1654 $proposed= recurse($stripped, $variables);
1656 /* Get list of used ID's */
1657 $used= array();
1658 $ldap= $config->get_ldap_link();
1659 $ldap->cd($config->current['BASE']);
1660 $ldap->search('(uid=*)');
1662 while($attrs= $ldap->fetch()){
1663 $used[]= $attrs['uid'][0];
1664 }
1666 /* Remove used uids and watch out for id tags */
1667 $ret= array();
1668 foreach($proposed as $uid){
1670 /* Check for id tag and modify uid if needed */
1671 if(preg_match('/\{id:\d+}/',$uid)){
1672 $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1674 for ($i= 0; $i < pow(10,$size); $i++){
1675 $number= sprintf("%0".$size."d", $i);
1676 $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1677 if (!in_array($res, $used)){
1678 $uid= $res;
1679 break;
1680 }
1681 }
1682 }
1684 if(preg_match('/\{id#\d+}/',$uid)){
1685 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1687 while (true){
1688 mt_srand((double) microtime()*1000000);
1689 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1690 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1691 if (!in_array($res, $used)){
1692 $uid= $res;
1693 break;
1694 }
1695 }
1696 }
1698 /* Don't assign used ones */
1699 if (!in_array($uid, $used)){
1700 $ret[]= $uid;
1701 }
1702 }
1704 return(array_unique($ret));
1705 }
1708 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1709 Need to convert... */
1710 function to_byte($value) {
1711 $value= strtolower(trim($value));
1713 if(!is_numeric(substr($value, -1))) {
1715 switch(substr($value, -1)) {
1716 case 'g':
1717 $mult= 1073741824;
1718 break;
1719 case 'm':
1720 $mult= 1048576;
1721 break;
1722 case 'k':
1723 $mult= 1024;
1724 break;
1725 }
1727 return ($mult * (int)substr($value, 0, -1));
1728 } else {
1729 return $value;
1730 }
1731 }
1734 function in_array_ics($value, $items)
1735 {
1736 if (!is_array($items)){
1737 return (FALSE);
1738 }
1740 foreach ($items as $item){
1741 if (strcasecmp($item, $value) == 0) {
1742 return (TRUE);
1743 }
1744 }
1746 return (FALSE);
1747 }
1750 function generate_alphabet($count= 10)
1751 {
1752 $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1753 $alphabet= "";
1754 $c= 0;
1756 /* Fill cells with charaters */
1757 for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1758 if ($c == 0){
1759 $alphabet.= "<tr>";
1760 }
1762 $ch = mb_substr($characters, $i, 1, "UTF8");
1763 $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1764 validate($_GET['plug'])."&search=".$ch."\"> ".$ch." </a></td>";
1766 if ($c++ == $count){
1767 $alphabet.= "</tr>";
1768 $c= 0;
1769 }
1770 }
1772 /* Fill remaining cells */
1773 while ($c++ <= $count){
1774 $alphabet.= "<td> </td>";
1775 }
1777 return ($alphabet);
1778 }
1781 function validate($string)
1782 {
1783 return (strip_tags(preg_replace('/\0/', '', $string)));
1784 }
1787 function get_gosa_version()
1788 {
1789 global $svn_revision, $svn_path;
1791 /* Extract informations */
1792 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1794 /* Release or development? */
1795 if (preg_match('%/gosa/trunk/%', $svn_path)){
1796 return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1797 } else {
1798 $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1799 return (sprintf(_("GOsa $release"), $revision));
1800 }
1801 }
1804 function rmdirRecursive($path, $followLinks=false) {
1805 $dir= opendir($path);
1806 while($entry= readdir($dir)) {
1807 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1808 unlink($path."/".$entry);
1809 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1810 rmdirRecursive($path."/".$entry);
1811 }
1812 }
1813 closedir($dir);
1814 return rmdir($path);
1815 }
1818 function scan_directory($path,$sort_desc=false)
1819 {
1820 $ret = false;
1822 /* is this a dir ? */
1823 if(is_dir($path)) {
1825 /* is this path a readable one */
1826 if(is_readable($path)){
1828 /* Get contents and write it into an array */
1829 $ret = array();
1831 $dir = opendir($path);
1833 /* Is this a correct result ?*/
1834 if($dir){
1835 while($fp = readdir($dir))
1836 $ret[]= $fp;
1837 }
1838 }
1839 }
1840 /* Sort array ascending , like scandir */
1841 sort($ret);
1843 /* Sort descending if parameter is sort_desc is set */
1844 if($sort_desc) {
1845 $ret = array_reverse($ret);
1846 }
1848 return($ret);
1849 }
1852 function clean_smarty_compile_dir($directory)
1853 {
1854 global $svn_revision;
1856 if(is_dir($directory) && is_readable($directory)) {
1857 // Set revision filename to REVISION
1858 $revision_file= $directory."/REVISION";
1860 /* Is there a stamp containing the current revision? */
1861 if(!file_exists($revision_file)) {
1862 // create revision file
1863 create_revision($revision_file, $svn_revision);
1864 } else {
1865 # check for "$config->...['CONFIG']/revision" and the
1866 # contents should match the revision number
1867 if(!compare_revision($revision_file, $svn_revision)){
1868 // If revision differs, clean compile directory
1869 foreach(scan_directory($directory) as $file) {
1870 if(($file==".")||($file=="..")) continue;
1871 if( is_file($directory."/".$file) &&
1872 is_writable($directory."/".$file)) {
1873 // delete file
1874 if(!unlink($directory."/".$file)) {
1875 msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
1876 // This should never be reached
1877 }
1878 } elseif(is_dir($directory."/".$file) &&
1879 is_writable($directory."/".$file)) {
1880 // Just recursively delete it
1881 rmdirRecursive($directory."/".$file);
1882 }
1883 }
1884 // We should now create a fresh revision file
1885 clean_smarty_compile_dir($directory);
1886 } else {
1887 // Revision matches, nothing to do
1888 }
1889 }
1890 } else {
1891 // Smarty compile dir is not accessible
1892 // (Smarty will warn about this)
1893 }
1894 }
1897 function create_revision($revision_file, $revision)
1898 {
1899 $result= false;
1901 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1902 if($fh= fopen($revision_file, "w")) {
1903 if(fwrite($fh, $revision)) {
1904 $result= true;
1905 }
1906 }
1907 fclose($fh);
1908 } else {
1909 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1910 }
1912 return $result;
1913 }
1916 function compare_revision($revision_file, $revision)
1917 {
1918 // false means revision differs
1919 $result= false;
1921 if(file_exists($revision_file) && is_readable($revision_file)) {
1922 // Open file
1923 if($fh= fopen($revision_file, "r")) {
1924 // Compare File contents with current revision
1925 if($revision == fread($fh, filesize($revision_file))) {
1926 $result= true;
1927 }
1928 } else {
1929 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1930 }
1931 // Close file
1932 fclose($fh);
1933 }
1935 return $result;
1936 }
1939 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1940 {
1941 $str = ""; // Our return value will be saved in this var
1943 $color = dechex($percentage+150);
1944 $color2 = dechex(150 - $percentage);
1945 $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1947 $progress = (int)(($percentage /100)*$width);
1949 /* Abort printing out percentage, if divs are to small */
1952 /* If theres a better solution for this, use it... */
1953 $str = "
1954 <div style=\" width:".($width)."px;
1955 height:".($height)."px;
1956 background-color:#000000;
1957 padding:1px;\">
1959 <div style=\" width:".($width)."px;
1960 background-color:#$bgcolor;
1961 height:".($height)."px;\">
1963 <div style=\" width:".$progress."px;
1964 height:".$height."px;
1965 background-color:#".$color2.$color2.$color."; \">";
1968 if(($height >10)&&($showvalue)){
1969 $str.= "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1970 <b>".$percentage."%</b>
1971 </font>";
1972 }
1974 $str.= "</div></div></div>";
1976 return($str);
1977 }
1980 function array_key_ics($ikey, $items)
1981 {
1982 /* Gather keys, make them lowercase */
1983 $tmp= array();
1984 foreach ($items as $key => $value){
1985 $tmp[strtolower($key)]= $key;
1986 }
1988 if (isset($tmp[strtolower($ikey)])){
1989 return($tmp[strtolower($ikey)]);
1990 }
1992 return ("");
1993 }
1996 function array_differs($src, $dst)
1997 {
1998 /* If the count is differing, the arrays differ */
1999 if (count ($src) != count ($dst)){
2000 return (TRUE);
2001 }
2003 /* So the count is the same - lets check the contents */
2004 $differs= FALSE;
2005 foreach($src as $value){
2006 if (!in_array($value, $dst)){
2007 $differs= TRUE;
2008 }
2009 }
2011 return ($differs);
2012 }
2015 function saveFilter($a_filter, $values)
2016 {
2017 if (isset($_POST['regexit'])){
2018 $a_filter["regex"]= $_POST['regexit'];
2020 foreach($values as $type){
2021 if (isset($_POST[$type])) {
2022 $a_filter[$type]= "checked";
2023 } else {
2024 $a_filter[$type]= "";
2025 }
2026 }
2027 }
2029 /* React on alphabet links if needed */
2030 if (isset($_GET['search'])){
2031 $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2032 if ($s == "**"){
2033 $s= "*";
2034 }
2035 $a_filter['regex']= $s;
2036 }
2038 return ($a_filter);
2039 }
2042 /* Escape all preg_* relevant characters */
2043 function normalizePreg($input)
2044 {
2045 return (addcslashes($input, '[]()|/.*+-'));
2046 }
2049 /* Escape all LDAP filter relevant characters */
2050 function normalizeLdap($input)
2051 {
2052 return (addcslashes($input, '()|'));
2053 }
2056 /* Resturns the difference between to microtime() results in float */
2057 function get_MicroTimeDiff($start , $stop)
2058 {
2059 $a = split("\ ",$start);
2060 $b = split("\ ",$stop);
2062 $secs = $b[1] - $a[1];
2063 $msecs= $b[0] - $a[0];
2065 $ret = (float) ($secs+ $msecs);
2066 return($ret);
2067 }
2070 function get_base_dir()
2071 {
2072 global $BASE_DIR;
2074 return $BASE_DIR;
2075 }
2078 function obj_is_readable($dn, $object, $attribute)
2079 {
2080 global $ui;
2082 return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2083 }
2086 function obj_is_writable($dn, $object, $attribute)
2087 {
2088 global $ui;
2090 return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2091 }
2094 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2095 {
2096 /* Initialize variables */
2097 $ret = array("count" => 0); // Set count to 0
2098 $next = true; // if false, then skip next loops and return
2099 $cnt = 0; // Current number of loops
2100 $max = 100; // Just for security, prevent looops
2101 $ldap = NULL; // To check if created result a valid
2102 $keep = ""; // save last failed parse string
2104 /* Check each parsed dn in ldap ? */
2105 if($config!==NULL && $verify_in_ldap){
2106 $ldap = $config->get_ldap_link();
2107 }
2109 /* Lets start */
2110 $called = false;
2111 while(preg_match("/,/",$dn) && $next && $cnt < $max){
2113 $cnt ++;
2114 if(!preg_match("/,/",$dn)){
2115 $next = false;
2116 }
2117 $object = preg_replace("/[,].*$/","",$dn);
2118 $dn = preg_replace("/^[^,]+,/","",$dn);
2120 $called = true;
2122 /* Check if current dn is valid */
2123 if($ldap!==NULL){
2124 $ldap->cd($dn);
2125 $ldap->cat($dn,array("dn"));
2126 if($ldap->count()){
2127 $ret[] = $keep.$object;
2128 $keep = "";
2129 }else{
2130 $keep .= $object.",";
2131 }
2132 }else{
2133 $ret[] = $keep.$object;
2134 $keep = "";
2135 }
2136 }
2138 /* No dn was posted */
2139 if($cnt == 0 && !empty($dn)){
2140 $ret[] = $dn;
2141 }
2143 /* Append the rest */
2144 $test = $keep.$dn;
2145 if($called && !empty($test)){
2146 $ret[] = $keep.$dn;
2147 }
2148 $ret['count'] = count($ret) - 1;
2150 return($ret);
2151 }
2154 function get_base_from_hook($dn, $attrib)
2155 {
2156 global $config;
2158 if (isset($config->current['BASE_HOOK'])){
2160 /* Call hook script - if present */
2161 $command= $config->current['BASE_HOOK'];
2163 if ($command != ""){
2164 $command.= " '".LDAP::fix($dn)."' $attrib";
2165 if (check_command($command)){
2166 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2167 exec($command, $output);
2168 if (preg_match("/^[0-9]+$/", $output[0])){
2169 return ($output[0]);
2170 } else {
2171 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2172 return ($config->current['UIDBASE']);
2173 }
2174 } else {
2175 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2176 return ($config->current['UIDBASE']);
2177 }
2179 } else {
2181 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2182 return ($config->current['UIDBASE']);
2184 }
2185 }
2186 }
2189 function check_schema_version($class, $version)
2190 {
2191 return preg_match("/\(v$version\)/", $class['DESC']);
2192 }
2195 function check_schema($cfg,$rfc2307bis = FALSE)
2196 {
2197 $messages= array();
2199 /* Get objectclasses */
2200 $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2201 $objectclasses = $ldap->get_objectclasses();
2202 if(count($objectclasses) == 0){
2203 msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2204 }
2206 /* This is the default block used for each entry.
2207 * to avoid unset indexes.
2208 */
2209 $def_check = array("REQUIRED_VERSION" => "0",
2210 "SCHEMA_FILES" => array(),
2211 "CLASSES_REQUIRED" => array(),
2212 "STATUS" => FALSE,
2213 "IS_MUST_HAVE" => FALSE,
2214 "MSG" => "",
2215 "INFO" => "");#_("There is currently no information specified for this schema extension."));
2217 /* The gosa base schema */
2218 $checks['gosaObject'] = $def_check;
2219 $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2220 $checks['gosaObject']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2221 $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2222 $checks['gosaObject']['IS_MUST_HAVE'] = TRUE;
2224 /* GOsa Account class */
2225 $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2226 $checks["gosaAccount"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2227 $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2228 $checks["gosaAccount"]["IS_MUST_HAVE"] = TRUE;
2229 $checks["gosaAccount"]["INFO"] = _("Used to store account specific informations.");
2231 /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2232 $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2233 $checks["gosaLockEntry"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2234 $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2235 $checks["gosaLockEntry"]["IS_MUST_HAVE"] = TRUE;
2236 $checks["gosaLockEntry"]["INFO"] = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2238 /* Some other checks */
2239 foreach(array(
2240 "gosaCacheEntry" => array("version" => "2.4"),
2241 "gosaDepartment" => array("version" => "2.4"),
2242 "goFaxAccount" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2243 "goFaxSBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2244 "goFaxRBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2245 "gosaUserTemplate" => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2246 "gosaMailAccount" => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2247 "gosaProxyAccount" => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2248 "gosaApplication" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2249 "gosaApplicationGroup" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2250 "GOhard" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2251 "gotoTerminal" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2252 "goServer" => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2253 "goTerminalServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2254 "goShareServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2255 "goNtpServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2256 "goSyslogServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2257 "goLdapServer" => array("version" => "2.4"),
2258 "goCupsServer" => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2259 "goImapServer" => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3. schema"),
2260 "goKrbServer" => array("version" => "2.4"),
2261 "goFaxServer" => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2262 ) as $name => $values){
2264 $checks[$name] = $def_check;
2265 if(isset($values['version'])){
2266 $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2267 }
2268 if(isset($values['file'])){
2269 $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2270 }
2271 $checks[$name]["CLASSES_REQUIRED"] = array($name);
2272 }
2273 foreach($checks as $name => $value){
2274 foreach($value['CLASSES_REQUIRED'] as $class){
2276 if(!isset($objectclasses[$name])){
2277 $checks[$name]['STATUS'] = FALSE;
2278 if($value['IS_MUST_HAVE']){
2279 $checks[$name]['MSG'] = sprintf(_("Missing required object class '%s'!"),$class);
2280 }else{
2281 $checks[$name]['MSG'] = sprintf(_("Missing optional object class '%s'!"),$class);
2282 }
2283 }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2284 $checks[$name]['STATUS'] = FALSE;
2286 if($value['IS_MUST_HAVE']){
2287 $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2288 }else{
2289 $checks[$name]['MSG'] = sprintf(_("Version mismatch for optional object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2290 }
2291 }else{
2292 $checks[$name]['STATUS'] = TRUE;
2293 $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2294 }
2295 }
2296 }
2298 $tmp = $objectclasses;
2300 /* The gosa base schema */
2301 $checks['posixGroup'] = $def_check;
2302 $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2303 $checks['posixGroup']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2304 $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2305 $checks['posixGroup']['STATUS'] = TRUE;
2306 $checks['posixGroup']['IS_MUST_HAVE'] = TRUE;
2307 $checks['posixGroup']['MSG'] = "";
2308 $checks['posixGroup']['INFO'] = "";
2310 /* Depending on selected rfc2307bis mode, we need different schema configurations */
2311 if(isset($tmp['posixGroup'])){
2313 if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2314 $checks['posixGroup']['STATUS'] = FALSE;
2315 $checks['posixGroup']['MSG'] = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema configuration do not support this option.");
2316 $checks['posixGroup']['INFO'] = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be AUXILIARY");
2317 }
2318 if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2319 $checks['posixGroup']['STATUS'] = FALSE;
2320 $checks['posixGroup']['MSG'] = _("You have disabled the rfc2307bis option on the 'ldap setup' step, but your schema configuration do not support this option.");
2321 $checks['posixGroup']['INFO'] = _("The objectClass 'posixGroup' must be STRUCTURAL");
2322 }
2323 }
2325 return($checks);
2326 }
2329 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2330 {
2331 $tmp = array(
2332 "de_DE" => "German",
2333 "fr_FR" => "French",
2334 "it_IT" => "Italian",
2335 "es_ES" => "Spanish",
2336 "en_US" => "English",
2337 "nl_NL" => "Dutch",
2338 "pl_PL" => "Polish",
2339 "sv_SE" => "Swedish",
2340 "zh_CN" => "Chinese",
2341 "ru_RU" => "Russian");
2343 $tmp2= array(
2344 "de_DE" => _("German"),
2345 "fr_FR" => _("French"),
2346 "it_IT" => _("Italian"),
2347 "es_ES" => _("Spanish"),
2348 "en_US" => _("English"),
2349 "nl_NL" => _("Dutch"),
2350 "pl_PL" => _("Polish"),
2351 "sv_SE" => _("Swedish"),
2352 "zh_CN" => _("Chinese"),
2353 "ru_RU" => _("Russian"));
2355 $ret = array();
2356 if($languages_in_own_language){
2358 $old_lang = setlocale(LC_ALL, 0);
2359 foreach($tmp as $key => $name){
2360 $lang = $key.".UTF-8";
2361 setlocale(LC_ALL, $lang);
2362 if($strip_region_tag){
2363 $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2364 }else{
2365 $ret[$key] = _($name)." (".$tmp2[$key].")";
2366 }
2367 }
2368 setlocale(LC_ALL, $old_lang);
2369 }else{
2370 foreach($tmp as $key => $name){
2371 if($strip_region_tag){
2372 $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2373 }else{
2374 $ret[$key] = _($name);
2375 }
2376 }
2377 }
2378 return($ret);
2379 }
2382 /* Returns contents of the given POST variable and check magic quotes settings */
2383 function get_post($name)
2384 {
2385 if(!isset($_POST[$name])){
2386 trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2387 return(FALSE);
2388 }
2389 if(get_magic_quotes_gpc()){
2390 return(stripcslashes($_POST[$name]));
2391 }else{
2392 return($_POST[$name]);
2393 }
2394 }
2397 /* Return class name in correct case */
2398 function get_correct_class_name($cls)
2399 {
2400 global $class_mapping;
2401 if(isset($class_mapping) && is_array($class_mapping)){
2402 foreach($class_mapping as $class => $file){
2403 if(preg_match("/^".$cls."$/i",$class)){
2404 return($class);
2405 }
2406 }
2407 }
2408 return(FALSE);
2409 }
2412 // change_password, changes the Password, of the given dn
2413 function change_password ($dn, $password, $mode=0, $hash= "")
2414 {
2415 global $config;
2416 $newpass= "";
2418 /* Convert to lower. Methods are lowercase */
2419 $hash= strtolower($hash);
2421 // Get all available encryption Methods
2423 // NON STATIC CALL :)
2424 $tmp = new passwordMethod(session::get('config'));
2425 $available = $tmp->get_available_methods();
2427 // read current password entry for $dn, to detect the encryption Method
2428 $ldap = $config->get_ldap_link();
2429 $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2430 $attrs = $ldap->fetch ();
2432 // Check if user account was deactivated, indicated by ! after } ... {crypt}!###
2433 if(isset($attrs['userPassword'][0]) && preg_match("/^[^\}]*+\}!/",$attrs['userPassword'][0])){
2434 $deactivated = TRUE;
2435 }else{
2436 $deactivated = FALSE;
2437 }
2439 /* Is ensure that clear passwords will stay clear */
2440 if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2441 $hash = "clear";
2442 }
2444 // Detect the encryption Method
2445 if ( (isset($attrs['userPassword'][0]) && preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) || $hash != ""){
2447 /* Check for supported algorithm */
2448 mt_srand((double) microtime()*1000000);
2450 /* Extract used hash */
2451 if ($hash == ""){
2452 $hash= strtolower($matches[1]);
2453 }
2455 $test = new $available[$hash]($config);
2457 } else {
2458 // User MD5 by default
2459 $hash= "md5";
2460 $test = new $available['md5']($config);
2461 }
2463 /* Feed password backends with information */
2464 $test->dn= $dn;
2465 $test->attrs= $attrs;
2466 $newpass= $test->generate_hash($password);
2468 // Update shadow timestamp?
2469 if (isset($attrs["shadowLastChange"][0])){
2470 $shadow= (int)(date("U") / 86400);
2471 } else {
2472 $shadow= 0;
2473 }
2475 // Write back modified entry
2476 $ldap->cd($dn);
2477 $attrs= array();
2479 // Not for groups
2480 if ($mode == 0){
2482 if ($shadow != 0){
2483 $attrs['shadowLastChange']= $shadow;
2484 }
2486 // Create SMB Password
2487 $attrs= generate_smb_nt_hash($password);
2488 }
2490 /* Readd ! if user was deactivated */
2491 if($deactivated){
2492 $newpass = preg_replace("/(^[^\}]+\})(.*$)/","\\1!\\2",$newpass);
2493 }
2495 $attrs['userPassword']= array();
2496 $attrs['userPassword']= $newpass;
2498 $ldap->modify($attrs);
2500 new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2502 if ($ldap->error != 'Success') {
2503 msg_dialog::display(_("LDAP error"), sprintf(_('Setting the password failed!').'<br><br>'._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
2504 } else {
2506 /* Run backend method for change/create */
2507 $test->set_password($password);
2509 /* Find postmodify entries for this class */
2510 $command= $config->search("password", "POSTMODIFY",array('menu'));
2512 if ($command != ""){
2513 /* Walk through attribute list */
2514 $command= preg_replace("/%userPassword/", $password, $command);
2515 $command= preg_replace("/%dn/", $dn, $command);
2517 if (check_command($command)){
2518 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2519 exec($command);
2520 } else {
2521 $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2522 msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2523 }
2524 }
2525 }
2526 }
2529 // Return something like array['sambaLMPassword']= "lalla..."
2530 function generate_smb_nt_hash($password)
2531 {
2532 global $config;
2534 # Try to use gosa-si?
2535 if (isset($config->data['MAIN']['GOSA_SI'])){
2536 $hash= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password));
2537 } else {
2538 $tmp= $config->data['MAIN']['SMBHASH']." ".escapeshellarg($password);
2539 @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2541 exec($tmp, $ar);
2542 flush();
2543 reset($ar);
2544 $hash= current($ar);
2545 }
2547 if ($hash == "") {
2548 msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
2549 return ("");
2550 }
2552 list($lm,$nt)= split (":", trim($hash));
2554 if ($config->current['SAMBAVERSION'] == 3) {
2555 $attrs['sambaLMPassword']= $lm;
2556 $attrs['sambaNTPassword']= $nt;
2557 $attrs['sambaPwdLastSet']= date('U');
2558 $attrs['sambaBadPasswordCount']= "0";
2559 $attrs['sambaBadPasswordTime']= "0";
2560 } else {
2561 $attrs['lmPassword']= $lm;
2562 $attrs['ntPassword']= $nt;
2563 $attrs['pwdLastSet']= date('U');
2564 }
2565 return($attrs);
2566 }
2569 function crypt_single($string,$enc_type )
2570 {
2571 return( passwordMethod::crypt_single_str($string,$enc_type));
2572 }
2575 function getEntryCSN($dn)
2576 {
2577 global $config;
2578 if(empty($dn) || !is_object($config)){
2579 return("");
2580 }
2582 /* Get attribute that we should use as serial number */
2583 if(isset($config->current['UNIQ_IDENTIFIER'])){
2584 $attr = $config->current['UNIQ_IDENTIFIER'];
2585 }elseif(isset($config->data['MAIN']['UNIQ_IDENTIFIER'])){
2586 $attr = $config->data['MAIN']['UNIQ_IDENTIFIER'];
2587 }
2588 if(!empty($attr)){
2589 $ldap = $config->get_ldap_link();
2590 $ldap->cat($dn,array($attr));
2591 $csn = $ldap->fetch();
2592 if(isset($csn[$attr][0])){
2593 return($csn[$attr][0]);
2594 }
2595 }
2596 return("");
2597 }
2600 /* Add a given objectClass to an attrs entry */
2601 function add_objectClass($classes, &$attrs)
2602 {
2603 if (is_array($classes)){
2604 $list= $classes;
2605 } else {
2606 $list= array($classes);
2607 }
2609 foreach ($list as $class){
2610 $attrs['objectClass'][]= $class;
2611 }
2612 }
2615 /* Removes a given objectClass from the attrs entry */
2616 function remove_objectClass($classes, &$attrs)
2617 {
2618 if (isset($attrs['objectClass'])){
2619 /* Array? */
2620 if (is_array($classes)){
2621 $list= $classes;
2622 } else {
2623 $list= array($classes);
2624 }
2626 $tmp= array();
2627 foreach ($attrs['objectClass'] as $oc) {
2628 foreach ($list as $class){
2629 if ($oc != $class){
2630 $tmp[]= $oc;
2631 }
2632 }
2633 }
2634 $attrs['objectClass']= $tmp;
2635 }
2636 }
2638 /*! \brief Initialize a file download with given content, name and data type.
2639 * @param data String The content to send.
2640 * @param name String The name of the file.
2641 * @param type String The content identifier, default value is "application/octet-stream";
2642 */
2643 function send_binary_content($data,$name,$type = "application/octet-stream")
2644 {
2645 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
2646 header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
2647 header("Cache-Control: no-cache");
2648 header("Pragma: no-cache");
2649 header("Cache-Control: post-check=0, pre-check=0");
2650 header("Content-type: ".$type."");
2652 /* force download dialog */
2653 if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
2654 header('Content-Disposition: filename="'.$name.'"');
2655 } else {
2656 header('Content-Disposition: attachment; filename="'.$name.'"');
2657 }
2659 echo $data;
2660 exit();
2661 }
2663 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2664 ?>