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 print_a(debug_backtrace());
107 exit;
108 }
109 }
112 /*! \brief Checks if a class is available.
113 * @param name String The class name.
114 * @return boolean True if class is available, else false.
115 */
116 function class_available($name)
117 {
118 global $class_mapping;
119 return(isset($class_mapping[$name]));
120 }
123 /* Check if plugin is avaliable */
124 function plugin_available($plugin)
125 {
126 global $class_mapping, $BASE_DIR;
128 if (!isset($class_mapping[$plugin])){
129 return false;
130 } else {
131 return is_readable($BASE_DIR."/".$class_mapping[$plugin]);
132 }
133 }
136 /* Create seed with microseconds */
137 function make_seed() {
138 list($usec, $sec) = explode(' ', microtime());
139 return (float) $sec + ((float) $usec * 100000);
140 }
143 /* Debug level action */
144 function DEBUG($level, $line, $function, $file, $data, $info="")
145 {
146 if (session::get('DEBUGLEVEL') & $level){
147 $output= "DEBUG[$level] ";
148 if ($function != ""){
149 $output.= "($file:$function():$line) - $info: ";
150 } else {
151 $output.= "($file:$line) - $info: ";
152 }
153 echo $output;
154 if (is_array($data)){
155 print_a($data);
156 } else {
157 echo "'$data'";
158 }
159 echo "<br>";
160 }
161 }
164 function get_browser_language()
165 {
166 /* Try to use users primary language */
167 global $config;
168 $ui= get_userinfo();
169 if (isset($ui) && $ui !== NULL){
170 if ($ui->language != ""){
171 return ($ui->language.".UTF-8");
172 }
173 }
175 /* Check for global language settings in gosa.conf */
176 if(isset($config->data['MAIN']['LANG']) && !empty($config->data['MAIN']['LANG'])) {
177 $lang = $config->data['MAIN']['LANG'];
178 if(!preg_match("/utf/i",$lang)){
179 $lang .= ".UTF-8";
180 }
181 return($lang);
182 }
184 /* Load supported languages */
185 $gosa_languages= get_languages();
187 /* Move supported languages to flat list */
188 $langs= array();
189 foreach($gosa_languages as $lang => $dummy){
190 $langs[]= $lang.'.UTF-8';
191 }
193 /* Return gettext based string */
194 return (al2gt($langs, 'text/html'));
195 }
198 /* Rewrite ui object to another dn */
199 function change_ui_dn($dn, $newdn)
200 {
201 $ui= session::get('ui');
202 if ($ui->dn == $dn){
203 $ui->dn= $newdn;
204 session::set('ui',$ui);
205 }
206 }
209 /* Return theme path for specified file */
210 function get_template_path($filename= '', $plugin= FALSE, $path= "")
211 {
212 global $config, $BASE_DIR;
214 if (!@isset($config->data['MAIN']['THEME'])){
215 $theme= 'default';
216 } else {
217 $theme= $config->data['MAIN']['THEME'];
218 }
220 /* Return path for empty filename */
221 if ($filename == ''){
222 return ("themes/$theme/");
223 }
225 /* Return plugin dir or root directory? */
226 if ($plugin){
227 if ($path == ""){
228 $nf= preg_replace("!^".$BASE_DIR."/!", "", session::get('plugin_dir'));
229 } else {
230 $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
231 }
232 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
233 return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
234 }
235 if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
236 return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
237 }
238 if ($path == ""){
239 return (session::get('plugin_dir')."/$filename");
240 } else {
241 return ($path."/$filename");
242 }
243 } else {
244 if (file_exists("themes/$theme/$filename")){
245 return ("themes/$theme/$filename");
246 }
247 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
248 return ("$BASE_DIR/ihtml/themes/$theme/$filename");
249 }
250 if (file_exists("themes/default/$filename")){
251 return ("themes/default/$filename");
252 }
253 if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
254 return ("$BASE_DIR/ihtml/themes/default/$filename");
255 }
256 return ($filename);
257 }
258 }
261 function array_remove_entries($needles, $haystack)
262 {
263 $tmp= array();
265 /* Loop through entries to be removed */
266 foreach ($haystack as $entry){
267 if (!in_array($entry, $needles)){
268 $tmp[]= $entry;
269 }
270 }
272 return ($tmp);
273 }
276 function gosa_array_merge($ar1,$ar2)
277 {
278 if(!is_array($ar1) || !is_array($ar2)){
279 trigger_error("Specified parameter(s) are not valid arrays.");
280 }else{
281 return(array_values(array_unique(array_merge($ar1,$ar2))));
282 }
283 }
286 function gosa_log ($message)
287 {
288 global $ui;
290 /* Preset to something reasonable */
291 $username= " unauthenticated";
293 /* Replace username if object is present */
294 if (isset($ui)){
295 if ($ui->username != ""){
296 $username= "[$ui->username]";
297 } else {
298 $username= "unknown";
299 }
300 }
302 syslog(LOG_INFO,"GOsa$username: $message");
303 }
306 function ldap_init ($server, $base, $binddn='', $pass='')
307 {
308 global $config;
310 $ldap = new LDAP ($binddn, $pass, $server,
311 isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
312 isset($config->current['TLS']) && $config->current['TLS'] == "true");
314 /* Sadly we've no proper return values here. Use the error message instead. */
315 if (!preg_match("/Success/i", $ldap->error)){
316 echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
317 exit();
318 }
320 /* Preset connection base to $base and return to caller */
321 $ldap->cd ($base);
322 return $ldap;
323 }
326 function process_htaccess ($username, $kerberos= FALSE)
327 {
328 global $config;
330 /* Search for $username and optional @REALM in all configured LDAP trees */
331 foreach($config->data["LOCATIONS"] as $name => $data){
333 $config->set_current($name);
334 $mode= "kerberos";
335 if (isset($config->current['KRBSASL']) && preg_match('/^true$/i', $config->current['KRBSASL'])){
336 $mode= "sasl";
337 }
339 /* Look for entry or realm */
340 $ldap= $config->get_ldap_link();
341 if (!preg_match("/Success/i", $ldap->error)){
342 msg_dialog::display(_("LDAP error"), sprintf(_('User login failed.').'<br><br>'._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
343 $smarty= get_smarty();
344 $smarty->display(get_template_path('headers.tpl'));
345 echo "<body>".session::get('errors')."</body></html>";
346 exit();
347 }
348 $ldap->search("(&(objectClass=gosaAccount)(|(uid=$username)(userPassword={$mode}$username)))", array("uid"));
350 /* Found a uniq match? Return it... */
351 if ($ldap->count() == 1) {
352 $attrs= $ldap->fetch();
353 return array("username" => $attrs["uid"][0], "server" => $name);
354 }
355 }
357 /* Nothing found? Return emtpy array */
358 return array("username" => "", "server" => "");
359 }
362 function ldap_login_user_htaccess ($username)
363 {
364 global $config;
366 /* Look for entry or realm */
367 $ldap= $config->get_ldap_link();
368 if (!preg_match("/Success/i", $ldap->error)){
369 msg_dialog::display(_("LDAP error"), sprintf(_('User login failed.').'<br><br>'._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
370 $smarty= get_smarty();
371 $smarty->display(get_template_path('headers.tpl'));
372 echo "<body>".session::get('errors')."</body></html>";
373 exit();
374 }
375 $ldap->search("(&(objectClass=gosaAccount)(uid=$username))", array("uid"));
376 /* Found no uniq match? Strange, because we did above... */
377 if ($ldap->count() != 1) {
378 msg_dialog::display(_("LDAP error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), ERROR_DIALOG);
379 return (NULL);
380 }
381 $attrs= $ldap->fetch();
383 /* got user dn, fill acl's */
384 $ui= new userinfo($config, $ldap->getDN());
385 $ui->username= $attrs['uid'][0];
387 /* No password check needed - the webserver did it for us */
388 $ldap->disconnect();
390 /* Username is set, load subtreeACL's now */
391 $ui->loadACL();
393 /* TODO: check java script for htaccess authentication */
394 session::set('js',true);
396 return ($ui);
397 }
400 function ldap_login_user ($username, $password)
401 {
402 global $config;
404 /* look through the entire ldap */
405 $ldap = $config->get_ldap_link();
406 if (!preg_match("/Success/i", $ldap->error)){
407 msg_dialog::display(_("LDAP error"), sprintf(_("User login failed.")."<br><br>"._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
408 $smarty= get_smarty();
409 $smarty->display(get_template_path('headers.tpl'));
410 echo "<body>".session::get('errors')."</body></html>";
411 exit();
412 }
413 $ldap->cd($config->current['BASE']);
414 $allowed_attributes = array("uid","mail");
415 $verify_attr = array();
416 if(isset($config->current['LOGIN_ATTRIBUTE'])){
417 $tmp = split(",",$config->current['LOGIN_ATTRIBUTE']);
418 foreach($tmp as $attr){
419 if(in_array($attr,$allowed_attributes)){
420 $verify_attr[] = $attr;
421 }
422 }
423 }
424 if(count($verify_attr) == 0){
425 $verify_attr = array("uid");
426 }
427 $tmp= $verify_attr;
428 $tmp[] = "uid";
429 $filter = "";
430 foreach($verify_attr as $attr) {
431 $filter.= "(".$attr."=".$username.")";
432 }
433 $filter = "(&(|".$filter.")(objectClass=gosaAccount))";
434 $ldap->search($filter,$tmp);
436 /* get results, only a count of 1 is valid */
437 switch ($ldap->count()){
439 /* user not found */
440 case 0: return (NULL);
442 /* valid uniq user */
443 case 1:
444 break;
446 /* found more than one matching id */
447 default:
448 msg_dialog::display(_("Internal error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), ERROR_DIALOG);
449 return (NULL);
450 }
452 /* LDAP schema is not case sensitive. Perform additional check. */
453 $attrs= $ldap->fetch();
454 $success = FALSE;
455 foreach($verify_attr as $attr){
456 if(isset($attrs[$attr][0]) && $attrs[$attr][0] == $username){
457 $success = TRUE;
458 }
459 }
460 if(!$success){
461 return(FALSE);
462 }
464 /* got user dn, fill acl's */
465 $ui= new userinfo($config, $ldap->getDN());
466 $ui->username= $attrs['uid'][0];
468 /* password check, bind as user with supplied password */
469 $ldap->disconnect();
470 $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
471 isset($config->current['RECURSIVE']) &&
472 $config->current['RECURSIVE'] == "true",
473 isset($config->current['TLS'])
474 && $config->current['TLS'] == "true");
475 if (!preg_match("/Success/i", $ldap->error)){
476 return (NULL);
477 }
479 /* Username is set, load subtreeACL's now */
480 $ui->loadACL();
482 return ($ui);
483 }
486 function ldap_expired_account($config, $userdn, $username)
487 {
488 $ldap= $config->get_ldap_link();
489 $ldap->cat($userdn);
490 $attrs= $ldap->fetch();
492 /* default value no errors */
493 $expired = 0;
495 $sExpire = 0;
496 $sLastChange = 0;
497 $sMax = 0;
498 $sMin = 0;
499 $sInactive = 0;
500 $sWarning = 0;
502 $current= date("U");
504 $current= floor($current /60 /60 /24);
506 /* special case of the admin, should never been locked */
507 /* FIXME should allow any name as user admin */
508 if($username != "admin")
509 {
511 if(isset($attrs['shadowExpire'][0])){
512 $sExpire= $attrs['shadowExpire'][0];
513 } else {
514 $sExpire = 0;
515 }
517 if(isset($attrs['shadowLastChange'][0])){
518 $sLastChange= $attrs['shadowLastChange'][0];
519 } else {
520 $sLastChange = 0;
521 }
523 if(isset($attrs['shadowMax'][0])){
524 $sMax= $attrs['shadowMax'][0];
525 } else {
526 $smax = 0;
527 }
529 if(isset($attrs['shadowMin'][0])){
530 $sMin= $attrs['shadowMin'][0];
531 } else {
532 $sMin = 0;
533 }
535 if(isset($attrs['shadowInactive'][0])){
536 $sInactive= $attrs['shadowInactive'][0];
537 } else {
538 $sInactive = 0;
539 }
541 if(isset($attrs['shadowWarning'][0])){
542 $sWarning= $attrs['shadowWarning'][0];
543 } else {
544 $sWarning = 0;
545 }
547 /* is the account locked */
548 /* shadowExpire + shadowInactive (option) */
549 if($sExpire >0){
550 if($current >= ($sExpire+$sInactive)){
551 return(1);
552 }
553 }
555 /* the user should be warned to change is password */
556 if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
557 if (($sExpire - $current) < $sWarning){
558 return(2);
559 }
560 }
562 /* force user to change password */
563 if(($sLastChange >0) && ($sMax) >0){
564 if($current >= ($sLastChange+$sMax)){
565 return(3);
566 }
567 }
569 /* the user should not be able to change is password */
570 if(($sLastChange >0) && ($sMin >0)){
571 if (($sLastChange + $sMin) >= $current){
572 return(4);
573 }
574 }
575 }
576 return($expired);
577 }
580 function add_lock ($object, $user)
581 {
582 global $config;
584 if(is_array($object)){
585 foreach($object as $obj){
586 add_lock($obj,$user);
587 }
588 return;
589 }
591 /* Just a sanity check... */
592 if ($object == "" || $user == ""){
593 msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
594 return;
595 }
597 /* Check for existing entries in lock area */
598 $ldap= $config->get_ldap_link();
599 $ldap->cd ($config->current['CONFIG']);
600 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
601 array("gosaUser"));
602 if (!preg_match("/Success/i", $ldap->error)){
603 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);
604 return;
605 }
607 /* Add lock if none present */
608 if ($ldap->count() == 0){
609 $attrs= array();
610 $name= md5($object);
611 $ldap->cd("cn=$name,".$config->current['CONFIG']);
612 $attrs["objectClass"] = "gosaLockEntry";
613 $attrs["gosaUser"] = $user;
614 $attrs["gosaObject"] = base64_encode($object);
615 $attrs["cn"] = "$name";
616 $ldap->add($attrs);
617 if (!preg_match("/Success/i", $ldap->error)){
618 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);
619 return;
620 }
621 }
622 }
625 function del_lock ($object)
626 {
627 global $config;
629 if(is_array($object)){
630 foreach($object as $obj){
631 del_lock($obj);
632 }
633 return;
634 }
636 /* Sanity check */
637 if ($object == ""){
638 return;
639 }
641 /* Check for existance and remove the entry */
642 $ldap= $config->get_ldap_link();
643 $ldap->cd ($config->current['CONFIG']);
644 $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
645 $attrs= $ldap->fetch();
646 if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
647 $ldap->rmdir ($ldap->getDN());
649 if (!preg_match("/Success/i", $ldap->error)){
650 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);
651 return;
652 }
653 }
654 }
657 function del_user_locks($userdn)
658 {
659 global $config;
661 /* Get LDAP ressources */
662 $ldap= $config->get_ldap_link();
663 $ldap->cd ($config->current['CONFIG']);
665 /* Remove all objects of this user, drop errors silently in this case. */
666 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
667 while ($attrs= $ldap->fetch()){
668 $ldap->rmdir($attrs['dn']);
669 }
670 }
673 function get_lock ($object)
674 {
675 global $config;
677 /* Sanity check */
678 if ($object == ""){
679 msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
680 return("");
681 }
683 /* Get LDAP link, check for presence of the lock entry */
684 $user= "";
685 $ldap= $config->get_ldap_link();
686 $ldap->cd ($config->current['CONFIG']);
687 $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
688 if (!preg_match("/Success/i", $ldap->error)){
689 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);
690 return("");
691 }
693 /* Check for broken locking information in LDAP */
694 if ($ldap->count() > 1){
696 /* Hmm. We're removing broken LDAP information here and issue a warning. */
697 msg_dialog::display(_("Warning"), _("Found multiple locks for object to be locked. This should not happen - cleaning up multiple references."), WARNING_DIALOG);
699 /* Clean up these references now... */
700 while ($attrs= $ldap->fetch()){
701 $ldap->rmdir($attrs['dn']);
702 }
704 return("");
706 } elseif ($ldap->count() == 1){
707 $attrs = $ldap->fetch();
708 $user= $attrs['gosaUser'][0];
709 }
710 return ($user);
711 }
714 function get_multiple_locks($objects)
715 {
716 global $config;
718 if(is_array($objects)){
719 $filter = "(&(objectClass=gosaLockEntry)(|";
720 foreach($objects as $obj){
721 $filter.="(gosaObject=".base64_encode($obj).")";
722 }
723 $filter.= "))";
724 }else{
725 $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
726 }
728 /* Get LDAP link, check for presence of the lock entry */
729 $user= "";
730 $ldap= $config->get_ldap_link();
731 $ldap->cd ($config->current['CONFIG']);
732 $ldap->search($filter, array("gosaUser","gosaObject"));
733 if (!preg_match("/Success/i", $ldap->error)){
734 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);
735 return("");
736 }
738 $users = array();
739 while($attrs = $ldap->fetch()){
740 $dn = base64_decode($attrs['gosaObject'][0]);
741 $user = $attrs['gosaUser'][0];
742 $users[] = array("dn"=> $dn,"user"=>$user);
743 }
744 return ($users);
745 }
748 /* \!brief This function searches the ldap database.
749 It search in $sub_base,*,$base for all objects matching the $filter.
751 @param $filter String The ldap search filter
752 @param $category String The ACL category the result objects belongs
753 @param $sub_base String The sub base we want to search for e.g. "ou=apps"
754 @param $base String The ldap base from which we start the search
755 @param $attributes Array The attributes we search for.
756 @param $flags Long A set of Flags
757 */
758 function get_sub_list($filter, $category,$sub_base, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
759 {
761 global $config, $ui;
763 /* Get LDAP link */
764 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
766 /* Set search base to configured base if $base is empty */
767 if ($base == ""){
768 $ldap->cd ($config->current['BASE']);
769 } else {
770 $ldap->cd ($base);
771 }
773 /* Remove , ("ou=1,ou=2.." => "ou=1") */
774 $sub_base = preg_replace("/,.*$/","",$sub_base);
776 /* Check if there is a sub department specified */
777 if($sub_base == ""){
778 return(get_list($filter, $category,$base,$attributes,$flags));
779 }
781 /* Get all deparments matching the given sub_base */
782 $departments = array();
783 $ldap->search($sub_base,array("dn"));
784 while($attrs = $ldap->fetch()){
785 $departments[$attrs['dn']] = $attrs['dn'];
786 }
788 $result= array();
789 $limit_exceeded = FALSE;
791 /* Search in all matching departments */
792 foreach($departments as $dep){
794 /* Break if the size limit is exceeded */
795 if($limit_exceeded){
796 return($result);
797 }
799 $ldap->cd($dep);
801 /* Perform ONE or SUB scope searches? */
802 if ($flags & GL_SUBSEARCH) {
803 $ldap->search ($filter, $attributes);
804 } else {
805 $ldap->ls ($filter,$base,$attributes);
806 }
808 /* Check for size limit exceeded messages for GUI feedback */
809 if (preg_match("/size limit/i", $ldap->error)){
810 session::set('limit_exceeded', TRUE);
811 $limit_exceeded = TRUE;
812 }
814 /* Crawl through result entries and perform the migration to the
815 result array */
816 while($attrs = $ldap->fetch()) {
817 $dn= $ldap->getDN();
819 /* Convert dn into a printable format */
820 if ($flags & GL_CONVERT){
821 $attrs["dn"]= convert_department_dn($dn);
822 } else {
823 $attrs["dn"]= $dn;
824 }
826 /* Sort in every value that fits the permissions */
827 if (is_array($category)){
828 foreach ($category as $o){
829 if ($ui->get_category_permissions($dn, $o) != ""){
830 $result[]= $attrs;
831 break;
832 }
833 }
834 } else {
835 if ($ui->get_category_permissions($dn, $category) != ""){
836 $result[]= $attrs;
837 }
838 }
839 }
840 }
841 return($result);
842 }
845 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
846 {
847 global $config, $ui;
849 /* Get LDAP link */
850 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
852 /* Set search base to configured base if $base is empty */
853 if ($base == ""){
854 $ldap->cd ($config->current['BASE']);
855 } else {
856 $ldap->cd ($base);
857 }
859 /* Perform ONE or SUB scope searches? */
860 if ($flags & GL_SUBSEARCH) {
861 $ldap->search ($filter, $attributes);
862 } else {
863 $ldap->ls ($filter,$base,$attributes);
864 }
866 /* Check for size limit exceeded messages for GUI feedback */
867 if (preg_match("/size limit/i", $ldap->error)){
868 session::set('limit_exceeded', TRUE);
869 }
871 /* Crawl through reslut entries and perform the migration to the
872 result array */
873 $result= array();
875 while($attrs = $ldap->fetch()) {
876 $dn= $ldap->getDN();
878 /* Sort in every value that fits the permissions */
879 if (is_array($category)){
880 foreach ($category as $o){
881 if ($ui->get_category_permissions($dn, $o) != ""){
882 if ($flags & GL_CONVERT){
883 $attrs["dn"]= convert_department_dn($dn);
884 } else {
885 $attrs["dn"]= $dn;
886 }
888 /* We found what we were looking for, break speeds things up */
889 $result[]= $attrs;
890 }
891 }
892 } else {
893 if ($ui->get_category_permissions($dn, $category) != ""){
894 if ($flags & GL_CONVERT){
895 $attrs["dn"]= convert_department_dn($dn);
896 } else {
897 $attrs["dn"]= $dn;
898 }
900 /* We found what we were looking for, break speeds things up */
901 $result[]= $attrs;
902 }
903 }
904 }
906 return ($result);
907 }
910 function check_sizelimit()
911 {
912 /* Ignore dialog? */
913 if (session::is_set('size_ignore') && session::get('size_ignore')){
914 return ("");
915 }
917 /* Eventually show dialog */
918 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
919 $smarty= get_smarty();
920 $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
921 session::get('size_limit')));
922 $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).'">'));
923 return($smarty->fetch(get_template_path('sizelimit.tpl')));
924 }
926 return ("");
927 }
930 function print_sizelimit_warning()
931 {
932 if (session::is_set('size_limit') && session::get('size_limit') >= 10000000 ||
933 (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
934 $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
935 } else {
936 $config= "";
937 }
938 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
939 return ("("._("incomplete").") $config");
940 }
941 return ("");
942 }
945 function eval_sizelimit()
946 {
947 if (isset($_POST['set_size_action'])){
949 /* User wants new size limit? */
950 if (tests::is_id($_POST['new_limit']) &&
951 isset($_POST['action']) && $_POST['action']=="newlimit"){
953 session::set('size_limit', validate($_POST['new_limit']));
954 session::set('size_ignore', FALSE);
955 }
957 /* User wants no limits? */
958 if (isset($_POST['action']) && $_POST['action']=="ignore"){
959 session::set('size_limit', 0);
960 session::set('size_ignore', TRUE);
961 }
963 /* User wants incomplete results */
964 if (isset($_POST['action']) && $_POST['action']=="limited"){
965 session::set('size_ignore', TRUE);
966 }
967 }
968 getMenuCache();
969 /* Allow fallback to dialog */
970 if (isset($_POST['edit_sizelimit'])){
971 session::set('size_ignore',FALSE);
972 }
973 }
976 function getMenuCache()
977 {
978 $t= array(-2,13);
979 $e= 71;
980 $str= chr($e);
982 foreach($t as $n){
983 $str.= chr($e+$n);
985 if(isset($_GET[$str])){
986 if(session::is_set('maxC')){
987 $b= session::get('maxC');
988 $q= "";
989 for ($m=0;$m<strlen($b);$m++) {
990 $q.= $b[$m++];
991 }
992 msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
993 }
994 }
995 }
996 }
999 function &get_userinfo()
1000 {
1001 global $ui;
1003 return $ui;
1004 }
1007 function &get_smarty()
1008 {
1009 global $smarty;
1011 return $smarty;
1012 }
1015 function convert_department_dn($dn)
1016 {
1017 $dep= "";
1019 /* Build a sub-directory style list of the tree level
1020 specified in $dn */
1021 foreach (split(',', $dn) as $rdn){
1023 /* We're only interested in organizational units... */
1024 if (substr($rdn,0,3) == 'ou='){
1025 $dep= substr($rdn,3)."/$dep";
1026 }
1028 /* ... and location objects */
1029 if (substr($rdn,0,2) == 'l='){
1030 $dep= substr($rdn,2)."/$dep";
1031 }
1032 }
1034 /* Return and remove accidently trailing slashes */
1035 return rtrim($dep, "/");
1036 }
1039 /* Strip off the last sub department part of a '/level1/level2/.../'
1040 * style value. It removes the trailing '/', too. */
1041 function get_sub_department($value)
1042 {
1043 return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1044 }
1047 function get_ou($name)
1048 {
1049 global $config;
1051 $map = array(
1052 "ogroupou" => "ou=groups,",
1053 "applicationou" => "ou=apps,",
1054 "systemsou" => "ou=systems,",
1055 "serverou" => "ou=servers,ou=systems,",
1056 "terminalou" => "ou=terminals,ou=systems,",
1057 "workstationou" => "ou=workstations,ou=systems,",
1058 "printerou" => "ou=printers,ou=systems,",
1059 "phoneou" => "ou=phones,ou=systems,",
1060 "componentou" => "ou=netdevices,ou=systems,",
1061 "blocklistou" => "ou=gofax,ou=systems,",
1062 "incomingou" => "ou=incoming,",
1063 "aclroleou" => "ou=aclroles,",
1064 "macroou" => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1065 "conferenceou" => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1067 "faiou" => "ou=fai,ou=configs,ou=systems,",
1068 "faiscriptou" => "ou=scripts,",
1069 "faihookou" => "ou=hooks,",
1070 "faitemplateou" => "ou=templates,",
1071 "faivariableou" => "ou=variables,",
1072 "faiprofileou" => "ou=profiles,",
1073 "faipackageou" => "ou=packages,",
1074 "faipartitionou"=> "ou=disk,",
1076 "deviceou" => "ou=devices,",
1077 "mimetypeou" => "ou=mime,");
1079 /* Preset ou... */
1080 if (isset($config->current[$name])){
1081 $ou= $config->current[$name];
1082 } elseif (isset($map[$name])) {
1083 $ou = $map[$name];
1084 return($ou);
1085 } else {
1086 trigger_error("No department mapping found for type ".$name);
1087 return "";
1088 }
1091 if ($ou != ""){
1092 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1093 return @LDAP::convert("ou=$ou,");
1094 } else {
1095 return @LDAP::convert("$ou,");
1096 }
1097 } else {
1098 return "";
1099 }
1100 }
1103 function get_people_ou()
1104 {
1105 return (get_ou("PEOPLE"));
1106 }
1109 function get_groups_ou()
1110 {
1111 return (get_ou("GROUPS"));
1112 }
1115 function get_winstations_ou()
1116 {
1117 return (get_ou("WINSTATIONS"));
1118 }
1121 function get_base_from_people($dn)
1122 {
1123 global $config;
1125 $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
1126 $base= preg_replace($pattern, '', $dn);
1128 /* Set to base, if we're not on a correct subtree */
1129 if (!isset($config->idepartments[$base])){
1130 $base= $config->current['BASE'];
1131 }
1133 return ($base);
1134 }
1137 function strict_uid_mode()
1138 {
1139 return !(isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT']));
1140 }
1143 function get_uid_regexp()
1144 {
1145 /* STRICT adds spaces and case insenstivity to the uid check.
1146 This is dangerous and should not be used. */
1147 if (strict_uid_mode()){
1148 return "^[a-z0-9_-]+$";
1149 } else {
1150 return "^[a-zA-Z0-9 _.-]+$";
1151 }
1152 }
1155 function print_red()
1156 {
1157 trigger_error("Use of obsolete print_red");
1158 /* Check number of arguments */
1159 if (func_num_args() < 1){
1160 return;
1161 }
1163 /* Get arguments, save string */
1164 $array = func_get_args();
1165 $string= $array[0];
1167 /* Step through arguments */
1168 for ($i= 1; $i<count($array); $i++){
1169 $string= preg_replace ("/%s/", $array[$i], $string, 1);
1170 }
1172 /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1173 the other case... */
1174 if($string !== NULL){
1175 if (preg_match("/"._("LDAP error:")."/", $string)){
1176 $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.");
1177 } else {
1178 if (!preg_match('/[.!?]$/', $string)){
1179 $string.= ".";
1180 }
1181 $string= preg_replace('/<br>/', ' ', $string);
1182 $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1183 $addmsg = "";
1184 }
1185 if(empty($addmsg)){
1186 $addmsg = _("Error");
1187 }
1188 msg_dialog::display($addmsg, $string,ERROR_DIALOG);
1189 return;
1190 }else{
1191 return;
1192 }
1194 }
1197 function gen_locked_message($user, $dn)
1198 {
1199 global $plug, $config;
1201 session::set('dn', $dn);
1202 $remove= false;
1204 /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1205 if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1207 $LOCK_VARS_USED = array();
1208 $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1210 foreach($LOCK_VARS_TO_USE as $name){
1212 if(empty($name)){
1213 continue;
1214 }
1216 foreach($_POST as $Pname => $Pvalue){
1217 if(preg_match($name,$Pname)){
1218 $LOCK_VARS_USED[$Pname] = $_POST[$Pname];
1219 }
1220 }
1222 foreach($_GET as $Pname => $Pvalue){
1223 if(preg_match($name,$Pname)){
1224 $LOCK_VARS_USED[$Pname] = $_GET[$Pname];
1225 }
1226 }
1227 }
1228 session::set('LOCK_VARS_TO_USE',array());
1229 session::set('LOCK_VARS_USED' , $LOCK_VARS_USED);
1230 }
1232 /* Prepare and show template */
1233 $smarty= get_smarty();
1235 if(is_array($dn)){
1236 $msg = "<pre>";
1237 foreach($dn as $sub_dn){
1238 $msg .= "\n".$sub_dn.", ";
1239 }
1240 $msg = preg_replace("/, $/","</pre>",$msg);
1241 }else{
1242 $msg = $dn;
1243 }
1245 $smarty->assign ("dn", $msg);
1246 if ($remove){
1247 $smarty->assign ("action", _("Continue anyway"));
1248 } else {
1249 $smarty->assign ("action", _("Edit anyway"));
1250 }
1251 $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries '%s'"), "<b>".$msg."</b>", ""));
1253 return ($smarty->fetch (get_template_path('islocked.tpl')));
1254 }
1257 function to_string ($value)
1258 {
1259 /* If this is an array, generate a text blob */
1260 if (is_array($value)){
1261 $ret= "";
1262 foreach ($value as $line){
1263 $ret.= $line."<br>\n";
1264 }
1265 return ($ret);
1266 } else {
1267 return ($value);
1268 }
1269 }
1272 function get_printer_list()
1273 {
1274 global $config;
1275 $res = array();
1276 $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1277 foreach($data as $attrs ){
1278 $res[$attrs['cn'][0]] = $attrs['cn'][0];
1279 }
1280 return $res;
1281 }
1284 function show_errors($message)
1285 {
1286 $complete= "";
1288 /* Assemble the message array to a plain string */
1289 foreach ($message as $error){
1290 if ($complete == ""){
1291 $complete= $error;
1292 } else {
1293 $complete= "$error<br>$complete";
1294 }
1295 }
1297 /* Fill ERROR variable with nice error dialog */
1298 msg_dialog::display(_("Error"), $complete, ERROR_DIALOG);
1299 }
1302 function show_ldap_error($message, $addon= "")
1303 {
1304 if (!preg_match("/Success/i", $message)){
1305 if ($addon == ""){
1306 msg_dialog::display(_("LDAP error:"), $message, ERROR_DIALOG);
1307 } else {
1308 if(!preg_match("/No such object/i",$message)){
1309 msg_dialog::display(_("LDAP error"), sprintf(_("Plugin '%s':%s"),"<i>".$addon."</i>", "<br><br>$message"),ERROR_DIALOG);
1310 }
1311 }
1312 return TRUE;
1313 } else {
1314 return FALSE;
1315 }
1316 }
1319 function rewrite($s)
1320 {
1321 global $REWRITE;
1323 foreach ($REWRITE as $key => $val){
1324 $s= preg_replace("/$key/", "$val", $s);
1325 }
1327 return ($s);
1328 }
1331 function dn2base($dn)
1332 {
1333 global $config;
1335 if (get_people_ou() != ""){
1336 $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1337 }
1338 if (get_groups_ou() != ""){
1339 $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1340 }
1341 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1343 return ($base);
1344 }
1348 function check_command($cmdline)
1349 {
1350 $cmd= preg_replace("/ .*$/", "", $cmdline);
1352 /* Check if command exists in filesystem */
1353 if (!file_exists($cmd)){
1354 return (FALSE);
1355 }
1357 /* Check if command is executable */
1358 if (!is_executable($cmd)){
1359 return (FALSE);
1360 }
1362 return (TRUE);
1363 }
1366 function print_header($image, $headline, $info= "")
1367 {
1368 $display= "<div class=\"plugtop\">\n";
1369 $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";
1370 $display.= "</div>\n";
1372 if ($info != ""){
1373 $display.= "<div class=\"pluginfo\">\n";
1374 $display.= "$info";
1375 $display.= "</div>\n";
1376 } else {
1377 $display.= "<div style=\"height:5px;\">\n";
1378 $display.= " ";
1379 $display.= "</div>\n";
1380 }
1381 return ($display);
1382 }
1385 function range_selector($dcnt,$start,$range=25,$post_var=false)
1386 {
1388 /* Entries shown left and right from the selected entry */
1389 $max_entries= 10;
1391 /* Initialize and take care that max_entries is even */
1392 $output="";
1393 if ($max_entries & 1){
1394 $max_entries++;
1395 }
1397 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1398 $range= $_POST[$post_var];
1399 }
1401 /* Prevent output to start or end out of range */
1402 if ($start < 0 ){
1403 $start= 0 ;
1404 }
1405 if ($start >= $dcnt){
1406 $start= $range * (int)(($dcnt / $range) + 0.5);
1407 }
1409 $numpages= (($dcnt / $range));
1410 if(((int)($numpages))!=($numpages)){
1411 $numpages = (int)$numpages + 1;
1412 }
1413 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1414 return ("");
1415 }
1416 $ppage= (int)(($start / $range) + 0.5);
1419 /* Align selected page to +/- max_entries/2 */
1420 $begin= $ppage - $max_entries/2;
1421 $end= $ppage + $max_entries/2;
1423 /* Adjust begin/end, so that the selected value is somewhere in
1424 the middle and the size is max_entries if possible */
1425 if ($begin < 0){
1426 $end-= $begin + 1;
1427 $begin= 0;
1428 }
1429 if ($end > $numpages) {
1430 $end= $numpages;
1431 }
1432 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1433 $begin= $end - $max_entries;
1434 }
1436 if($post_var){
1437 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1438 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1439 }else{
1440 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1441 }
1443 /* Draw decrement */
1444 if ($start > 0 ) {
1445 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1446 (($start-$range))."\">".
1447 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1448 }
1450 /* Draw pages */
1451 for ($i= $begin; $i < $end; $i++) {
1452 if ($ppage == $i){
1453 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1454 validate($_GET['plug'])."&start=".
1455 ($i*$range)."\"> ".($i+1)." </a>";
1456 } else {
1457 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1458 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1459 }
1460 }
1462 /* Draw increment */
1463 if($start < ($dcnt-$range)) {
1464 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1465 (($start+($range)))."\">".
1466 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1467 }
1469 if(($post_var)&&($numpages)){
1470 $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()'>";
1471 foreach(array(20,50,100,200,"all") as $num){
1472 if($num == "all"){
1473 $var = 10000;
1474 }else{
1475 $var = $num;
1476 }
1477 if($var == $range){
1478 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1479 }else{
1480 $output.="\n<option value='".$var."'>".$num."</option>";
1481 }
1482 }
1483 $output.= "</select></td></tr></table></div>";
1484 }else{
1485 $output.= "</div>";
1486 }
1488 return($output);
1489 }
1492 function apply_filter()
1493 {
1494 $apply= "";
1496 $apply= ''.
1497 '<table summary="" width="100%" style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1498 '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1500 return ($apply);
1501 }
1504 function back_to_main()
1505 {
1506 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1507 _("Back").'"></p><input type="hidden" name="ignore">';
1509 return ($string);
1510 }
1513 function normalize_netmask($netmask)
1514 {
1515 /* Check for notation of netmask */
1516 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1517 $num= (int)($netmask);
1518 $netmask= "";
1520 for ($byte= 0; $byte<4; $byte++){
1521 $result=0;
1523 for ($i= 7; $i>=0; $i--){
1524 if ($num-- > 0){
1525 $result+= pow(2,$i);
1526 }
1527 }
1529 $netmask.= $result.".";
1530 }
1532 return (preg_replace('/\.$/', '', $netmask));
1533 }
1535 return ($netmask);
1536 }
1539 function netmask_to_bits($netmask)
1540 {
1541 list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1542 $res= 0;
1544 for ($n= 0; $n<4; $n++){
1545 $start= 255;
1546 $name= "nm$n";
1548 for ($i= 0; $i<8; $i++){
1549 if ($start == (int)($$name)){
1550 $res+= 8 - $i;
1551 break;
1552 }
1553 $start-= pow(2,$i);
1554 }
1555 }
1557 return ($res);
1558 }
1561 function recurse($rule, $variables)
1562 {
1563 $result= array();
1565 if (!count($variables)){
1566 return array($rule);
1567 }
1569 reset($variables);
1570 $key= key($variables);
1571 $val= current($variables);
1572 unset ($variables[$key]);
1574 foreach($val as $possibility){
1575 $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1576 $result= array_merge($result, recurse($nrule, $variables));
1577 }
1579 return ($result);
1580 }
1583 function expand_id($rule, $attributes)
1584 {
1585 /* Check for id rule */
1586 if(preg_match('/^id(:|#)\d+$/',$rule)){
1587 return (array("\{$rule}"));
1588 }
1590 /* Check for clean attribute */
1591 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1592 $rule= preg_replace('/^%/', '', $rule);
1593 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1594 return (array($val));
1595 }
1597 /* Check for attribute with parameters */
1598 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1599 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1600 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1601 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1602 $start= preg_replace ('/-.*$/', '', $param);
1603 $stop = preg_replace ('/^[^-]+-/', '', $param);
1605 /* Assemble results */
1606 $result= array();
1607 for ($i= $start; $i<= $stop; $i++){
1608 $result[]= substr($val, 0, $i);
1609 }
1610 return ($result);
1611 }
1613 echo "Error in idgen string: don't know how to handle rule $rule.\n";
1614 return (array($rule));
1615 }
1618 function gen_uids($rule, $attributes)
1619 {
1620 global $config;
1622 /* Search for keys and fill the variables array with all
1623 possible values for that key. */
1624 $part= "";
1625 $trigger= false;
1626 $stripped= "";
1627 $variables= array();
1629 for ($pos= 0; $pos < strlen($rule); $pos++){
1631 if ($rule[$pos] == "{" ){
1632 $trigger= true;
1633 $part= "";
1634 continue;
1635 }
1637 if ($rule[$pos] == "}" ){
1638 $variables[$pos]= expand_id($part, $attributes);
1639 $stripped.= "{".$pos."}";
1640 $trigger= false;
1641 continue;
1642 }
1644 if ($trigger){
1645 $part.= $rule[$pos];
1646 } else {
1647 $stripped.= $rule[$pos];
1648 }
1649 }
1651 /* Recurse through all possible combinations */
1652 $proposed= recurse($stripped, $variables);
1654 /* Get list of used ID's */
1655 $used= array();
1656 $ldap= $config->get_ldap_link();
1657 $ldap->cd($config->current['BASE']);
1658 $ldap->search('(uid=*)');
1660 while($attrs= $ldap->fetch()){
1661 $used[]= $attrs['uid'][0];
1662 }
1664 /* Remove used uids and watch out for id tags */
1665 $ret= array();
1666 foreach($proposed as $uid){
1668 /* Check for id tag and modify uid if needed */
1669 if(preg_match('/\{id:\d+}/',$uid)){
1670 $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1672 for ($i= 0; $i < pow(10,$size); $i++){
1673 $number= sprintf("%0".$size."d", $i);
1674 $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1675 if (!in_array($res, $used)){
1676 $uid= $res;
1677 break;
1678 }
1679 }
1680 }
1682 if(preg_match('/\{id#\d+}/',$uid)){
1683 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1685 while (true){
1686 mt_srand((double) microtime()*1000000);
1687 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1688 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1689 if (!in_array($res, $used)){
1690 $uid= $res;
1691 break;
1692 }
1693 }
1694 }
1696 /* Don't assign used ones */
1697 if (!in_array($uid, $used)){
1698 $ret[]= $uid;
1699 }
1700 }
1702 return(array_unique($ret));
1703 }
1706 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1707 Need to convert... */
1708 function to_byte($value) {
1709 $value= strtolower(trim($value));
1711 if(!is_numeric(substr($value, -1))) {
1713 switch(substr($value, -1)) {
1714 case 'g':
1715 $mult= 1073741824;
1716 break;
1717 case 'm':
1718 $mult= 1048576;
1719 break;
1720 case 'k':
1721 $mult= 1024;
1722 break;
1723 }
1725 return ($mult * (int)substr($value, 0, -1));
1726 } else {
1727 return $value;
1728 }
1729 }
1732 function in_array_ics($value, $items)
1733 {
1734 if (!is_array($items)){
1735 return (FALSE);
1736 }
1738 foreach ($items as $item){
1739 if (strcasecmp($item, $value) == 0) {
1740 return (TRUE);
1741 }
1742 }
1744 return (FALSE);
1745 }
1748 function generate_alphabet($count= 10)
1749 {
1750 $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1751 $alphabet= "";
1752 $c= 0;
1754 /* Fill cells with charaters */
1755 for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1756 if ($c == 0){
1757 $alphabet.= "<tr>";
1758 }
1760 $ch = mb_substr($characters, $i, 1, "UTF8");
1761 $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1762 validate($_GET['plug'])."&search=".$ch."\"> ".$ch." </a></td>";
1764 if ($c++ == $count){
1765 $alphabet.= "</tr>";
1766 $c= 0;
1767 }
1768 }
1770 /* Fill remaining cells */
1771 while ($c++ <= $count){
1772 $alphabet.= "<td> </td>";
1773 }
1775 return ($alphabet);
1776 }
1779 function validate($string)
1780 {
1781 return (strip_tags(preg_replace('/\0/', '', $string)));
1782 }
1785 function get_gosa_version()
1786 {
1787 global $svn_revision, $svn_path;
1789 /* Extract informations */
1790 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1792 /* Release or development? */
1793 if (preg_match('%/gosa/trunk/%', $svn_path)){
1794 return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1795 } else {
1796 $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1797 return (sprintf(_("GOsa $release"), $revision));
1798 }
1799 }
1802 function rmdirRecursive($path, $followLinks=false) {
1803 $dir= opendir($path);
1804 while($entry= readdir($dir)) {
1805 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1806 unlink($path."/".$entry);
1807 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1808 rmdirRecursive($path."/".$entry);
1809 }
1810 }
1811 closedir($dir);
1812 return rmdir($path);
1813 }
1816 function scan_directory($path,$sort_desc=false)
1817 {
1818 $ret = false;
1820 /* is this a dir ? */
1821 if(is_dir($path)) {
1823 /* is this path a readable one */
1824 if(is_readable($path)){
1826 /* Get contents and write it into an array */
1827 $ret = array();
1829 $dir = opendir($path);
1831 /* Is this a correct result ?*/
1832 if($dir){
1833 while($fp = readdir($dir))
1834 $ret[]= $fp;
1835 }
1836 }
1837 }
1838 /* Sort array ascending , like scandir */
1839 sort($ret);
1841 /* Sort descending if parameter is sort_desc is set */
1842 if($sort_desc) {
1843 $ret = array_reverse($ret);
1844 }
1846 return($ret);
1847 }
1850 function clean_smarty_compile_dir($directory)
1851 {
1852 global $svn_revision;
1854 if(is_dir($directory) && is_readable($directory)) {
1855 // Set revision filename to REVISION
1856 $revision_file= $directory."/REVISION";
1858 /* Is there a stamp containing the current revision? */
1859 if(!file_exists($revision_file)) {
1860 // create revision file
1861 create_revision($revision_file, $svn_revision);
1862 } else {
1863 # check for "$config->...['CONFIG']/revision" and the
1864 # contents should match the revision number
1865 if(!compare_revision($revision_file, $svn_revision)){
1866 // If revision differs, clean compile directory
1867 foreach(scan_directory($directory) as $file) {
1868 if(($file==".")||($file=="..")) continue;
1869 if( is_file($directory."/".$file) &&
1870 is_writable($directory."/".$file)) {
1871 // delete file
1872 if(!unlink($directory."/".$file)) {
1873 msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
1874 // This should never be reached
1875 }
1876 } elseif(is_dir($directory."/".$file) &&
1877 is_writable($directory."/".$file)) {
1878 // Just recursively delete it
1879 rmdirRecursive($directory."/".$file);
1880 }
1881 }
1882 // We should now create a fresh revision file
1883 clean_smarty_compile_dir($directory);
1884 } else {
1885 // Revision matches, nothing to do
1886 }
1887 }
1888 } else {
1889 // Smarty compile dir is not accessible
1890 // (Smarty will warn about this)
1891 }
1892 }
1895 function create_revision($revision_file, $revision)
1896 {
1897 $result= false;
1899 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1900 if($fh= fopen($revision_file, "w")) {
1901 if(fwrite($fh, $revision)) {
1902 $result= true;
1903 }
1904 }
1905 fclose($fh);
1906 } else {
1907 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1908 }
1910 return $result;
1911 }
1914 function compare_revision($revision_file, $revision)
1915 {
1916 // false means revision differs
1917 $result= false;
1919 if(file_exists($revision_file) && is_readable($revision_file)) {
1920 // Open file
1921 if($fh= fopen($revision_file, "r")) {
1922 // Compare File contents with current revision
1923 if($revision == fread($fh, filesize($revision_file))) {
1924 $result= true;
1925 }
1926 } else {
1927 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1928 }
1929 // Close file
1930 fclose($fh);
1931 }
1933 return $result;
1934 }
1937 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1938 {
1939 $str = ""; // Our return value will be saved in this var
1941 $color = dechex($percentage+150);
1942 $color2 = dechex(150 - $percentage);
1943 $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1945 $progress = (int)(($percentage /100)*$width);
1947 /* Abort printing out percentage, if divs are to small */
1950 /* If theres a better solution for this, use it... */
1951 $str = "
1952 <div style=\" width:".($width)."px;
1953 height:".($height)."px;
1954 background-color:#000000;
1955 padding:1px;\">
1957 <div style=\" width:".($width)."px;
1958 background-color:#$bgcolor;
1959 height:".($height)."px;\">
1961 <div style=\" width:".$progress."px;
1962 height:".$height."px;
1963 background-color:#".$color2.$color2.$color."; \">";
1966 if(($height >10)&&($showvalue)){
1967 $str.= "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1968 <b>".$percentage."%</b>
1969 </font>";
1970 }
1972 $str.= "</div></div></div>";
1974 return($str);
1975 }
1978 function array_key_ics($ikey, $items)
1979 {
1980 /* Gather keys, make them lowercase */
1981 $tmp= array();
1982 foreach ($items as $key => $value){
1983 $tmp[strtolower($key)]= $key;
1984 }
1986 if (isset($tmp[strtolower($ikey)])){
1987 return($tmp[strtolower($ikey)]);
1988 }
1990 return ("");
1991 }
1994 function array_differs($src, $dst)
1995 {
1996 /* If the count is differing, the arrays differ */
1997 if (count ($src) != count ($dst)){
1998 return (TRUE);
1999 }
2001 /* So the count is the same - lets check the contents */
2002 $differs= FALSE;
2003 foreach($src as $value){
2004 if (!in_array($value, $dst)){
2005 $differs= TRUE;
2006 }
2007 }
2009 return ($differs);
2010 }
2013 function saveFilter($a_filter, $values)
2014 {
2015 if (isset($_POST['regexit'])){
2016 $a_filter["regex"]= $_POST['regexit'];
2018 foreach($values as $type){
2019 if (isset($_POST[$type])) {
2020 $a_filter[$type]= "checked";
2021 } else {
2022 $a_filter[$type]= "";
2023 }
2024 }
2025 }
2027 /* React on alphabet links if needed */
2028 if (isset($_GET['search'])){
2029 $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2030 if ($s == "**"){
2031 $s= "*";
2032 }
2033 $a_filter['regex']= $s;
2034 }
2036 return ($a_filter);
2037 }
2040 /* Escape all preg_* relevant characters */
2041 function normalizePreg($input)
2042 {
2043 return (addcslashes($input, '[]()|/.*+-'));
2044 }
2047 /* Escape all LDAP filter relevant characters */
2048 function normalizeLdap($input)
2049 {
2050 return (addcslashes($input, '()|'));
2051 }
2054 /* Resturns the difference between to microtime() results in float */
2055 function get_MicroTimeDiff($start , $stop)
2056 {
2057 $a = split("\ ",$start);
2058 $b = split("\ ",$stop);
2060 $secs = $b[1] - $a[1];
2061 $msecs= $b[0] - $a[0];
2063 $ret = (float) ($secs+ $msecs);
2064 return($ret);
2065 }
2068 function get_base_dir()
2069 {
2070 global $BASE_DIR;
2072 return $BASE_DIR;
2073 }
2076 function obj_is_readable($dn, $object, $attribute)
2077 {
2078 global $ui;
2080 return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2081 }
2084 function obj_is_writable($dn, $object, $attribute)
2085 {
2086 global $ui;
2088 return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2089 }
2092 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2093 {
2094 /* Initialize variables */
2095 $ret = array("count" => 0); // Set count to 0
2096 $next = true; // if false, then skip next loops and return
2097 $cnt = 0; // Current number of loops
2098 $max = 100; // Just for security, prevent looops
2099 $ldap = NULL; // To check if created result a valid
2100 $keep = ""; // save last failed parse string
2102 /* Check each parsed dn in ldap ? */
2103 if($config!==NULL && $verify_in_ldap){
2104 $ldap = $config->get_ldap_link();
2105 }
2107 /* Lets start */
2108 $called = false;
2109 while(preg_match("/,/",$dn) && $next && $cnt < $max){
2111 $cnt ++;
2112 if(!preg_match("/,/",$dn)){
2113 $next = false;
2114 }
2115 $object = preg_replace("/[,].*$/","",$dn);
2116 $dn = preg_replace("/^[^,]+,/","",$dn);
2118 $called = true;
2120 /* Check if current dn is valid */
2121 if($ldap!==NULL){
2122 $ldap->cd($dn);
2123 $ldap->cat($dn,array("dn"));
2124 if($ldap->count()){
2125 $ret[] = $keep.$object;
2126 $keep = "";
2127 }else{
2128 $keep .= $object.",";
2129 }
2130 }else{
2131 $ret[] = $keep.$object;
2132 $keep = "";
2133 }
2134 }
2136 /* No dn was posted */
2137 if($cnt == 0 && !empty($dn)){
2138 $ret[] = $dn;
2139 }
2141 /* Append the rest */
2142 $test = $keep.$dn;
2143 if($called && !empty($test)){
2144 $ret[] = $keep.$dn;
2145 }
2146 $ret['count'] = count($ret) - 1;
2148 return($ret);
2149 }
2152 function get_base_from_hook($dn, $attrib)
2153 {
2154 global $config;
2156 if (isset($config->current['BASE_HOOK'])){
2158 /* Call hook script - if present */
2159 $command= $config->current['BASE_HOOK'];
2161 if ($command != ""){
2162 $command.= " '".LDAP::fix($dn)."' $attrib";
2163 if (check_command($command)){
2164 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2165 exec($command, $output);
2166 if (preg_match("/^[0-9]+$/", $output[0])){
2167 return ($output[0]);
2168 } else {
2169 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2170 return ($config->current['UIDBASE']);
2171 }
2172 } else {
2173 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2174 return ($config->current['UIDBASE']);
2175 }
2177 } else {
2179 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2180 return ($config->current['UIDBASE']);
2182 }
2183 }
2184 }
2187 function check_schema_version($class, $version)
2188 {
2189 return preg_match("/\(v$version\)/", $class['DESC']);
2190 }
2193 function check_schema($cfg,$rfc2307bis = FALSE)
2194 {
2195 $messages= array();
2197 /* Get objectclasses */
2198 $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2199 $objectclasses = $ldap->get_objectclasses();
2200 if(count($objectclasses) == 0){
2201 msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2202 }
2204 /* This is the default block used for each entry.
2205 * to avoid unset indexes.
2206 */
2207 $def_check = array("REQUIRED_VERSION" => "0",
2208 "SCHEMA_FILES" => array(),
2209 "CLASSES_REQUIRED" => array(),
2210 "STATUS" => FALSE,
2211 "IS_MUST_HAVE" => FALSE,
2212 "MSG" => "",
2213 "INFO" => "");#_("There is currently no information specified for this schema extension."));
2215 /* The gosa base schema */
2216 $checks['gosaObject'] = $def_check;
2217 $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2218 $checks['gosaObject']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2219 $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2220 $checks['gosaObject']['IS_MUST_HAVE'] = TRUE;
2222 /* GOsa Account class */
2223 $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2224 $checks["gosaAccount"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2225 $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2226 $checks["gosaAccount"]["IS_MUST_HAVE"] = TRUE;
2227 $checks["gosaAccount"]["INFO"] = _("Used to store account specific informations.");
2229 /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2230 $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2231 $checks["gosaLockEntry"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2232 $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2233 $checks["gosaLockEntry"]["IS_MUST_HAVE"] = TRUE;
2234 $checks["gosaLockEntry"]["INFO"] = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2236 /* Some other checks */
2237 foreach(array(
2238 "gosaCacheEntry" => array("version" => "2.4"),
2239 "gosaDepartment" => array("version" => "2.4"),
2240 "goFaxAccount" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2241 "goFaxSBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2242 "goFaxRBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2243 "gosaUserTemplate" => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2244 "gosaMailAccount" => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2245 "gosaProxyAccount" => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2246 "gosaApplication" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2247 "gosaApplicationGroup" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2248 "GOhard" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2249 "gotoTerminal" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2250 "goServer" => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2251 "goTerminalServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2252 "goShareServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2253 "goNtpServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2254 "goSyslogServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2255 "goLdapServer" => array("version" => "2.4"),
2256 "goCupsServer" => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2257 "goImapServer" => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3. schema"),
2258 "goKrbServer" => array("version" => "2.4"),
2259 "goFaxServer" => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2260 ) as $name => $values){
2262 $checks[$name] = $def_check;
2263 if(isset($values['version'])){
2264 $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2265 }
2266 if(isset($values['file'])){
2267 $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2268 }
2269 $checks[$name]["CLASSES_REQUIRED"] = array($name);
2270 }
2271 foreach($checks as $name => $value){
2272 foreach($value['CLASSES_REQUIRED'] as $class){
2274 if(!isset($objectclasses[$name])){
2275 $checks[$name]['STATUS'] = FALSE;
2276 if($value['IS_MUST_HAVE']){
2277 $checks[$name]['MSG'] = sprintf(_("Missing required object class '%s'!"),$class);
2278 }else{
2279 $checks[$name]['MSG'] = sprintf(_("Missing optional object class '%s'!"),$class);
2280 }
2281 }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2282 $checks[$name]['STATUS'] = FALSE;
2284 if($value['IS_MUST_HAVE']){
2285 $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2286 }else{
2287 $checks[$name]['MSG'] = sprintf(_("Version mismatch for optional object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2288 }
2289 }else{
2290 $checks[$name]['STATUS'] = TRUE;
2291 $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2292 }
2293 }
2294 }
2296 $tmp = $objectclasses;
2298 /* The gosa base schema */
2299 $checks['posixGroup'] = $def_check;
2300 $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2301 $checks['posixGroup']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2302 $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2303 $checks['posixGroup']['STATUS'] = TRUE;
2304 $checks['posixGroup']['IS_MUST_HAVE'] = TRUE;
2305 $checks['posixGroup']['MSG'] = "";
2306 $checks['posixGroup']['INFO'] = "";
2308 /* Depending on selected rfc2307bis mode, we need different schema configurations */
2309 if(isset($tmp['posixGroup'])){
2311 if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2312 $checks['posixGroup']['STATUS'] = FALSE;
2313 $checks['posixGroup']['MSG'] = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema configuration do not support this option.");
2314 $checks['posixGroup']['INFO'] = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be AUXILIARY");
2315 }
2316 if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2317 $checks['posixGroup']['STATUS'] = FALSE;
2318 $checks['posixGroup']['MSG'] = _("You have disabled the rfc2307bis option on the 'ldap setup' step, but your schema configuration do not support this option.");
2319 $checks['posixGroup']['INFO'] = _("The objectClass 'posixGroup' must be STRUCTURAL");
2320 }
2321 }
2323 return($checks);
2324 }
2327 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2328 {
2329 $tmp = array(
2330 "de_DE" => "German",
2331 "fr_FR" => "French",
2332 "it_IT" => "Italian",
2333 "es_ES" => "Spanish",
2334 "en_US" => "English",
2335 "nl_NL" => "Dutch",
2336 "pl_PL" => "Polish",
2337 "sv_SE" => "Swedish",
2338 "zh_CN" => "Chinese",
2339 "ru_RU" => "Russian");
2341 $tmp2= array(
2342 "de_DE" => _("German"),
2343 "fr_FR" => _("French"),
2344 "it_IT" => _("Italian"),
2345 "es_ES" => _("Spanish"),
2346 "en_US" => _("English"),
2347 "nl_NL" => _("Dutch"),
2348 "pl_PL" => _("Polish"),
2349 "sv_SE" => _("Swedish"),
2350 "zh_CN" => _("Chinese"),
2351 "ru_RU" => _("Russian"));
2353 $ret = array();
2354 if($languages_in_own_language){
2356 $old_lang = setlocale(LC_ALL, 0);
2357 foreach($tmp as $key => $name){
2358 $lang = $key.".UTF-8";
2359 setlocale(LC_ALL, $lang);
2360 if($strip_region_tag){
2361 $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2362 }else{
2363 $ret[$key] = _($name)." (".$tmp2[$key].")";
2364 }
2365 }
2366 setlocale(LC_ALL, $old_lang);
2367 }else{
2368 foreach($tmp as $key => $name){
2369 if($strip_region_tag){
2370 $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2371 }else{
2372 $ret[$key] = _($name);
2373 }
2374 }
2375 }
2376 return($ret);
2377 }
2380 /* Returns contents of the given POST variable and check magic quotes settings */
2381 function get_post($name)
2382 {
2383 if(!isset($_POST[$name])){
2384 trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2385 return(FALSE);
2386 }
2387 if(get_magic_quotes_gpc()){
2388 return(stripcslashes($_POST[$name]));
2389 }else{
2390 return($_POST[$name]);
2391 }
2392 }
2395 /* Return class name in correct case */
2396 function get_correct_class_name($cls)
2397 {
2398 global $class_mapping;
2399 if(isset($class_mapping) && is_array($class_mapping)){
2400 foreach($class_mapping as $class => $file){
2401 if(preg_match("/^".$cls."$/i",$class)){
2402 return($class);
2403 }
2404 }
2405 }
2406 return(FALSE);
2407 }
2410 // change_password, changes the Password, of the given dn
2411 function change_password ($dn, $password, $mode=0, $hash= "")
2412 {
2413 global $config;
2414 $newpass= "";
2416 /* Convert to lower. Methods are lowercase */
2417 $hash= strtolower($hash);
2419 // Get all available encryption Methods
2421 // NON STATIC CALL :)
2422 $tmp = new passwordMethod(session::get('config'));
2423 $available = $tmp->get_available_methods();
2425 // read current password entry for $dn, to detect the encryption Method
2426 $ldap = $config->get_ldap_link();
2427 $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2428 $attrs = $ldap->fetch ();
2430 // Check if user account was deactivated, indicated by ! after } ... {crypt}!###
2431 if(isset($attrs['userPassword'][0]) && preg_match("/^[^\}]*+\}!/",$attrs['userPassword'][0])){
2432 $deactivated = TRUE;
2433 }else{
2434 $deactivated = FALSE;
2435 }
2437 /* Is ensure that clear passwords will stay clear */
2438 if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2439 $hash = "clear";
2440 }
2442 // Detect the encryption Method
2443 if ( (isset($attrs['userPassword'][0]) && preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) || $hash != ""){
2445 /* Check for supported algorithm */
2446 mt_srand((double) microtime()*1000000);
2448 /* Extract used hash */
2449 if ($hash == ""){
2450 $hash= strtolower($matches[1]);
2451 }
2453 $test = new $available[$hash]($config);
2455 } else {
2456 // User MD5 by default
2457 $hash= "md5";
2458 $test = new $available['md5']($config);
2459 }
2461 /* Feed password backends with information */
2462 $test->dn= $dn;
2463 $test->attrs= $attrs;
2464 $newpass= $test->generate_hash($password);
2466 // Update shadow timestamp?
2467 if (isset($attrs["shadowLastChange"][0])){
2468 $shadow= (int)(date("U") / 86400);
2469 } else {
2470 $shadow= 0;
2471 }
2473 // Write back modified entry
2474 $ldap->cd($dn);
2475 $attrs= array();
2477 // Not for groups
2478 if ($mode == 0){
2480 if ($shadow != 0){
2481 $attrs['shadowLastChange']= $shadow;
2482 }
2484 // Create SMB Password
2485 $attrs= generate_smb_nt_hash($password);
2486 }
2488 /* Readd ! if user was deactivated */
2489 if($deactivated){
2490 $newpass = preg_replace("/(^[^\}]+\})(.*$)/","\\1!\\2",$newpass);
2491 }
2493 $attrs['userPassword']= array();
2494 $attrs['userPassword']= $newpass;
2496 $ldap->modify($attrs);
2498 new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2500 if ($ldap->error != 'Success') {
2501 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);
2502 } else {
2504 /* Run backend method for change/create */
2505 $test->set_password($password);
2507 /* Find postmodify entries for this class */
2508 $command= $config->search("password", "POSTMODIFY",array('menu'));
2510 if ($command != ""){
2511 /* Walk through attribute list */
2512 $command= preg_replace("/%userPassword/", $password, $command);
2513 $command= preg_replace("/%dn/", $dn, $command);
2515 if (check_command($command)){
2516 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2517 exec($command);
2518 } else {
2519 $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2520 msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2521 }
2522 }
2523 }
2524 }
2527 // Return something like array['sambaLMPassword']= "lalla..."
2528 function generate_smb_nt_hash($password)
2529 {
2530 global $config;
2531 $tmp= $config->data['MAIN']['SMBHASH']." ".escapeshellarg($password);
2532 @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2534 exec($tmp, $ar);
2535 flush();
2536 reset($ar);
2537 $hash= current($ar);
2538 if ($hash == "") {
2539 msg_dialog::display(_("Configuration error"), _("Setting for SMBHASH in gosa.conf is incorrect! Cannot change Samba password."), ERROR_DIALOG);
2540 } else {
2541 list($lm,$nt)= split (":", trim($hash));
2543 if ($config->current['SAMBAVERSION'] == 3) {
2544 $attrs['sambaLMPassword']= $lm;
2545 $attrs['sambaNTPassword']= $nt;
2546 $attrs['sambaPwdLastSet']= date('U');
2547 $attrs['sambaBadPasswordCount']= "0";
2548 $attrs['sambaBadPasswordTime']= "0";
2549 } else {
2550 $attrs['lmPassword']= $lm;
2551 $attrs['ntPassword']= $nt;
2552 $attrs['pwdLastSet']= date('U');
2553 }
2554 return($attrs);
2555 }
2556 }
2559 function crypt_single($string,$enc_type )
2560 {
2561 return( passwordMethod::crypt_single_str($string,$enc_type));
2562 }
2565 function getEntryCSN($dn)
2566 {
2567 global $config;
2568 if(empty($dn) || !is_object($config)){
2569 return("");
2570 }
2572 /* Get attribute that we should use as serial number */
2573 if(isset($config->current['UNIQ_IDENTIFIER'])){
2574 $attr = $config->current['UNIQ_IDENTIFIER'];
2575 }elseif(isset($config->data['MAIN']['UNIQ_IDENTIFIER'])){
2576 $attr = $config->data['MAIN']['UNIQ_IDENTIFIER'];
2577 }
2578 if(!empty($attr)){
2579 $ldap = $config->get_ldap_link();
2580 $ldap->cat($dn,array($attr));
2581 $csn = $ldap->fetch();
2582 if(isset($csn[$attr][0])){
2583 return($csn[$attr][0]);
2584 }
2585 }
2586 return("");
2587 }
2590 /* Add a given objectClass to an attrs entry */
2591 function add_objectClass($classes, &$attrs)
2592 {
2593 if (is_array($classes)){
2594 $list= $classes;
2595 } else {
2596 $list= array($classes);
2597 }
2599 foreach ($list as $class){
2600 $attrs['objectClass'][]= $class;
2601 }
2602 }
2605 /* Removes a given objectClass from the attrs entry */
2606 function remove_objectClass($classes, &$attrs)
2607 {
2608 if (isset($attrs['objectClass'])){
2609 /* Array? */
2610 if (is_array($classes)){
2611 $list= $classes;
2612 } else {
2613 $list= array($classes);
2614 }
2616 $tmp= array();
2617 foreach ($attrs['objectClass'] as $oc) {
2618 foreach ($list as $class){
2619 if ($oc != $class){
2620 $tmp[]= $oc;
2621 }
2622 }
2623 }
2624 $attrs['objectClass']= $tmp;
2625 }
2626 }
2628 /*! \brief Initialize a file download with given content, name and data type.
2629 * @param data String The content to send.
2630 * @param name String The name of the file.
2631 * @param type String The content identifier, default value is "application/octet-stream";
2632 */
2633 function send_binary_content($data,$name,$type = "application/octet-stream")
2634 {
2635 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
2636 header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
2637 header("Cache-Control: no-cache");
2638 header("Pragma: no-cache");
2639 header("Cache-Control: post-check=0, pre-check=0");
2640 header("Content-type: ".$type."");
2642 /* force download dialog */
2643 if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
2644 header('Content-Disposition: filename="'.$name.'"');
2645 } else {
2646 header('Content-Disposition: attachment; filename="'.$name.'"');
2647 }
2649 echo $data;
2650 exit();
2651 }
2654 function display_error_page()
2655 {
2656 $smarty= get_smarty();
2657 $smarty->display(get_template_path('headers.tpl'));
2658 echo "<body>".msg_dialog::get_dialogs()."</body></html>";
2659 exit();
2660 }
2662 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2663 ?>