1 <?php
2 /*
3 * This code is part of GOsa (http://www.gosa-project.org)
4 * Copyright (C) 2003-2008 GONICUS GmbH
5 *
6 * ID: $$Id$$
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 */
23 /* Configuration file location */
24 define ("CONFIG_DIR", "/etc/gosa");
25 define ("CONFIG_FILE", "gosa.conf-trunk");
26 define ("CONFIG_TEMPLATE_DIR", "../contrib/");
27 define ("HELP_BASEDIR", "/var/www/doc/");
29 /* Define get_list flags */
30 define("GL_NONE", 0);
31 define("GL_SUBSEARCH", 1);
32 define("GL_SIZELIMIT", 2);
33 define("GL_CONVERT", 4);
34 define("GL_NO_ACL_CHECK", 8);
36 /* Heimdal stuff */
37 define('UNIVERSAL',0x00);
38 define('INTEGER',0x02);
39 define('OCTET_STRING',0x04);
40 define('OBJECT_IDENTIFIER ',0x06);
41 define('SEQUENCE',0x10);
42 define('SEQUENCE_OF',0x10);
43 define('SET',0x11);
44 define('SET_OF',0x11);
45 define('DEBUG',false);
46 define('HDB_KU_MKEY',0x484442);
47 define('TWO_BIT_SHIFTS',0x7efc);
48 define('DES_CBC_CRC',1);
49 define('DES_CBC_MD4',2);
50 define('DES_CBC_MD5',3);
51 define('DES3_CBC_MD5',5);
52 define('DES3_CBC_SHA1',16);
54 /* Define globals for revision comparing */
55 $svn_path = '$HeadURL: https://oss.gonicus.de/repositories/gosa/trunk/gosa-core/include/functions.inc $';
56 $svn_revision = '$Revision: 9246 $';
58 /* Include required files */
59 require_once("class_location.inc");
60 require_once ("functions_debug.inc");
61 require_once ("accept-to-gettext.inc");
63 /* Define constants for debugging */
64 define ("DEBUG_TRACE", 1);
65 define ("DEBUG_LDAP", 2);
66 define ("DEBUG_MYSQL", 4);
67 define ("DEBUG_SHELL", 8);
68 define ("DEBUG_POST", 16);
69 define ("DEBUG_SESSION",32);
70 define ("DEBUG_CONFIG", 64);
71 define ("DEBUG_ACL", 128);
73 /* Rewrite german 'umlauts' and spanish 'accents'
74 to get better results */
75 $REWRITE= array( "ä" => "ae",
76 "ö" => "oe",
77 "ü" => "ue",
78 "Ä" => "Ae",
79 "Ö" => "Oe",
80 "Ü" => "Ue",
81 "ß" => "ss",
82 "á" => "a",
83 "é" => "e",
84 "í" => "i",
85 "ó" => "o",
86 "ú" => "u",
87 "Á" => "A",
88 "É" => "E",
89 "Í" => "I",
90 "Ó" => "O",
91 "Ú" => "U",
92 "ñ" => "ny",
93 "Ñ" => "Ny" );
96 /* Class autoloader */
97 function __autoload($class_name) {
98 global $class_mapping, $BASE_DIR;
100 if ($class_mapping === NULL){
101 echo sprintf(_("Fatal error: no class locations defined - please run '%s' to fix this"), "<b>update-gosa</b>");
102 exit;
103 }
105 if (isset($class_mapping[$class_name])){
106 require_once($BASE_DIR."/".$class_mapping[$class_name]);
107 } else {
108 echo sprintf(_("Fatal error: cannot instantiate class '%s' - try running '%s' to fix this"), $class_name, "<b>update-gosa</b>");
109 exit;
110 }
111 }
114 /*! \brief Checks if a class is available.
115 * @param name String The class name.
116 * @return boolean True if class is available, else false.
117 */
118 function class_available($name)
119 {
120 global $class_mapping;
121 return(isset($class_mapping[$name]));
122 }
125 /* Check if plugin is avaliable */
126 function plugin_available($plugin)
127 {
128 global $class_mapping, $BASE_DIR;
130 if (!isset($class_mapping[$plugin])){
131 return false;
132 } else {
133 return is_readable($BASE_DIR."/".$class_mapping[$plugin]);
134 }
135 }
138 /* Create seed with microseconds */
139 function make_seed() {
140 list($usec, $sec) = explode(' ', microtime());
141 return (float) $sec + ((float) $usec * 100000);
142 }
145 /* Debug level action */
146 function DEBUG($level, $line, $function, $file, $data, $info="")
147 {
148 if (session::get('DEBUGLEVEL') & $level){
149 $output= "DEBUG[$level] ";
150 if ($function != ""){
151 $output.= "($file:$function():$line) - $info: ";
152 } else {
153 $output.= "($file:$line) - $info: ";
154 }
155 echo $output;
156 if (is_array($data)){
157 print_a($data);
158 } else {
159 echo "'$data'";
160 }
161 echo "<br>";
162 }
163 }
166 function get_browser_language()
167 {
168 /* Try to use users primary language */
169 global $config;
170 $ui= get_userinfo();
171 if (isset($ui) && $ui !== NULL){
172 if ($ui->language != ""){
173 return ($ui->language.".UTF-8");
174 }
175 }
177 /* Check for global language settings in gosa.conf */
178 if(isset($config->data['MAIN']['LANG']) && !empty($config->data['MAIN']['LANG'])) {
179 $lang = $config->data['MAIN']['LANG'];
180 if(!preg_match("/utf/i",$lang)){
181 $lang .= ".UTF-8";
182 }
183 return($lang);
184 }
186 /* Load supported languages */
187 $gosa_languages= get_languages();
189 /* Move supported languages to flat list */
190 $langs= array();
191 foreach($gosa_languages as $lang => $dummy){
192 $langs[]= $lang.'.UTF-8';
193 }
195 /* Return gettext based string */
196 return (al2gt($langs, 'text/html'));
197 }
200 /* Rewrite ui object to another dn */
201 function change_ui_dn($dn, $newdn)
202 {
203 $ui= session::get('ui');
204 if ($ui->dn == $dn){
205 $ui->dn= $newdn;
206 session::set('ui',$ui);
207 }
208 }
211 /* Return theme path for specified file */
212 function get_template_path($filename= '', $plugin= FALSE, $path= "")
213 {
214 global $config, $BASE_DIR;
216 if (!@isset($config->data['MAIN']['THEME'])){
217 $theme= 'default';
218 } else {
219 $theme= $config->data['MAIN']['THEME'];
220 }
222 /* Return path for empty filename */
223 if ($filename == ''){
224 return ("themes/$theme/");
225 }
227 /* Return plugin dir or root directory? */
228 if ($plugin){
229 if ($path == ""){
230 $nf= preg_replace("!^".$BASE_DIR."/!", "", session::get('plugin_dir'));
231 } else {
232 $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
233 }
234 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
235 return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
236 }
237 if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
238 return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
239 }
240 if ($path == ""){
241 return (session::get('plugin_dir')."/$filename");
242 } else {
243 return ($path."/$filename");
244 }
245 } else {
246 if (file_exists("themes/$theme/$filename")){
247 return ("themes/$theme/$filename");
248 }
249 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
250 return ("$BASE_DIR/ihtml/themes/$theme/$filename");
251 }
252 if (file_exists("themes/default/$filename")){
253 return ("themes/default/$filename");
254 }
255 if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
256 return ("$BASE_DIR/ihtml/themes/default/$filename");
257 }
258 return ($filename);
259 }
260 }
263 function array_remove_entries($needles, $haystack)
264 {
265 $tmp= array();
267 /* Loop through entries to be removed */
268 foreach ($haystack as $entry){
269 if (!in_array($entry, $needles)){
270 $tmp[]= $entry;
271 }
272 }
274 return ($tmp);
275 }
278 function gosa_array_merge($ar1,$ar2)
279 {
280 if(!is_array($ar1) || !is_array($ar2)){
281 trigger_error("Specified parameter(s) are not valid arrays.");
282 }else{
283 return(array_values(array_unique(array_merge($ar1,$ar2))));
284 }
285 }
288 function gosa_log ($message)
289 {
290 global $ui;
292 /* Preset to something reasonable */
293 $username= " unauthenticated";
295 /* Replace username if object is present */
296 if (isset($ui)){
297 if ($ui->username != ""){
298 $username= "[$ui->username]";
299 } else {
300 $username= "unknown";
301 }
302 }
304 syslog(LOG_INFO,"GOsa$username: $message");
305 }
308 function ldap_init ($server, $base, $binddn='', $pass='')
309 {
310 global $config;
312 $ldap = new LDAP ($binddn, $pass, $server,
313 isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
314 isset($config->current['TLS']) && $config->current['TLS'] == "true");
316 /* Sadly we've no proper return values here. Use the error message instead. */
317 if (!$ldap->success()){
318 echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
319 exit();
320 }
322 /* Preset connection base to $base and return to caller */
323 $ldap->cd ($base);
324 return $ldap;
325 }
328 function process_htaccess ($username, $kerberos= FALSE)
329 {
330 global $config;
332 /* Search for $username and optional @REALM in all configured LDAP trees */
333 foreach($config->data["LOCATIONS"] as $name => $data){
335 $config->set_current($name);
336 $mode= "kerberos";
337 if (isset($config->current['KRBSASL']) && preg_match('/^true$/i', $config->current['KRBSASL'])){
338 $mode= "sasl";
339 }
341 /* Look for entry or realm */
342 $ldap= $config->get_ldap_link();
343 if (!$ldap->success()){
344 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH, ERROR_DIALOG));
345 $smarty= get_smarty();
346 $smarty->display(get_template_path('headers.tpl'));
347 echo "<body>".session::get('errors')."</body></html>";
348 exit();
349 }
350 $ldap->search("(&(objectClass=gosaAccount)(|(uid=$username)(userPassword={$mode}$username)))", array("uid"));
352 /* Found a uniq match? Return it... */
353 if ($ldap->count() == 1) {
354 $attrs= $ldap->fetch();
355 return array("username" => $attrs["uid"][0], "server" => $name);
356 }
357 }
359 /* Nothing found? Return emtpy array */
360 return array("username" => "", "server" => "");
361 }
364 function ldap_login_user_htaccess ($username)
365 {
366 global $config;
368 /* Look for entry or realm */
369 $ldap= $config->get_ldap_link();
370 if (!$ldap->success()){
371 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH, FATAL_ERROR_DIALOG));
372 $smarty= get_smarty();
373 $smarty->display(get_template_path('headers.tpl'));
374 echo "<body>".session::get('errors')."</body></html>";
375 exit();
376 }
377 $ldap->search("(&(objectClass=gosaAccount)(uid=$username))", array("uid"));
378 /* Found no uniq match? Strange, because we did above... */
379 if ($ldap->count() != 1) {
380 msg_dialog::display(_("LDAP error"), _("Username / UID is not unique inside the LDAP tree!"), FATAL_ERROR_DIALOG);
381 return (NULL);
382 }
383 $attrs= $ldap->fetch();
385 /* got user dn, fill acl's */
386 $ui= new userinfo($config, $ldap->getDN());
387 $ui->username= $attrs['uid'][0];
389 /* No password check needed - the webserver did it for us */
390 $ldap->disconnect();
392 /* Username is set, load subtreeACL's now */
393 $ui->loadACL();
395 /* TODO: check java script for htaccess authentication */
396 session::set('js',true);
398 return ($ui);
399 }
402 function ldap_login_user ($username, $password)
403 {
404 global $config;
406 /* look through the entire ldap */
407 $ldap = $config->get_ldap_link();
408 if (!$ldap->success()){
409 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error()), FATAL_ERROR_DIALOG);
410 $smarty= get_smarty();
411 $smarty->display(get_template_path('headers.tpl'));
412 echo "<body>".session::get('errors')."</body></html>";
413 exit();
414 }
415 $ldap->cd($config->current['BASE']);
416 $allowed_attributes = array("uid","mail");
417 $verify_attr = array();
418 if(isset($config->current['LOGIN_ATTRIBUTE'])){
419 $tmp = split(",",$config->current['LOGIN_ATTRIBUTE']);
420 foreach($tmp as $attr){
421 if(in_array($attr,$allowed_attributes)){
422 $verify_attr[] = $attr;
423 }
424 }
425 }
426 if(count($verify_attr) == 0){
427 $verify_attr = array("uid");
428 }
429 $tmp= $verify_attr;
430 $tmp[] = "uid";
431 $filter = "";
432 foreach($verify_attr as $attr) {
433 $filter.= "(".$attr."=".$username.")";
434 }
435 $filter = "(&(|".$filter.")(objectClass=gosaAccount))";
436 $ldap->search($filter,$tmp);
438 /* get results, only a count of 1 is valid */
439 switch ($ldap->count()){
441 /* user not found */
442 case 0: return (NULL);
444 /* valid uniq user */
445 case 1:
446 break;
448 /* found more than one matching id */
449 default:
450 msg_dialog::display(_("Internal error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), FATAL_ERROR_DIALOG);
451 return (NULL);
452 }
454 /* LDAP schema is not case sensitive. Perform additional check. */
455 $attrs= $ldap->fetch();
456 $success = FALSE;
457 foreach($verify_attr as $attr){
458 if(isset($attrs[$attr][0]) && $attrs[$attr][0] == $username){
459 $success = TRUE;
460 }
461 }
462 if(!$success){
463 return(FALSE);
464 }
466 /* got user dn, fill acl's */
467 $ui= new userinfo($config, $ldap->getDN());
468 $ui->username= $attrs['uid'][0];
470 /* password check, bind as user with supplied password */
471 $ldap->disconnect();
472 $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
473 isset($config->current['RECURSIVE']) &&
474 $config->current['RECURSIVE'] == "true",
475 isset($config->current['TLS'])
476 && $config->current['TLS'] == "true");
477 if (!$ldap->success()){
478 return (NULL);
479 }
481 /* Username is set, load subtreeACL's now */
482 $ui->loadACL();
484 return ($ui);
485 }
488 function ldap_expired_account($config, $userdn, $username)
489 {
490 $ldap= $config->get_ldap_link();
491 $ldap->cat($userdn);
492 $attrs= $ldap->fetch();
494 /* default value no errors */
495 $expired = 0;
497 $sExpire = 0;
498 $sLastChange = 0;
499 $sMax = 0;
500 $sMin = 0;
501 $sInactive = 0;
502 $sWarning = 0;
504 $current= date("U");
506 $current= floor($current /60 /60 /24);
508 /* special case of the admin, should never been locked */
509 /* FIXME should allow any name as user admin */
510 if($username != "admin")
511 {
513 if(isset($attrs['shadowExpire'][0])){
514 $sExpire= $attrs['shadowExpire'][0];
515 } else {
516 $sExpire = 0;
517 }
519 if(isset($attrs['shadowLastChange'][0])){
520 $sLastChange= $attrs['shadowLastChange'][0];
521 } else {
522 $sLastChange = 0;
523 }
525 if(isset($attrs['shadowMax'][0])){
526 $sMax= $attrs['shadowMax'][0];
527 } else {
528 $smax = 0;
529 }
531 if(isset($attrs['shadowMin'][0])){
532 $sMin= $attrs['shadowMin'][0];
533 } else {
534 $sMin = 0;
535 }
537 if(isset($attrs['shadowInactive'][0])){
538 $sInactive= $attrs['shadowInactive'][0];
539 } else {
540 $sInactive = 0;
541 }
543 if(isset($attrs['shadowWarning'][0])){
544 $sWarning= $attrs['shadowWarning'][0];
545 } else {
546 $sWarning = 0;
547 }
549 /* is the account locked */
550 /* shadowExpire + shadowInactive (option) */
551 if($sExpire >0){
552 if($current >= ($sExpire+$sInactive)){
553 return(1);
554 }
555 }
557 /* the user should be warned to change is password */
558 if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
559 if (($sExpire - $current) < $sWarning){
560 return(2);
561 }
562 }
564 /* force user to change password */
565 if(($sLastChange >0) && ($sMax) >0){
566 if($current >= ($sLastChange+$sMax)){
567 return(3);
568 }
569 }
571 /* the user should not be able to change is password */
572 if(($sLastChange >0) && ($sMin >0)){
573 if (($sLastChange + $sMin) >= $current){
574 return(4);
575 }
576 }
577 }
578 return($expired);
579 }
582 function add_lock ($object, $user)
583 {
584 global $config;
586 if(is_array($object)){
587 foreach($object as $obj){
588 add_lock($obj,$user);
589 }
590 return;
591 }
593 /* Just a sanity check... */
594 if ($object == "" || $user == ""){
595 msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
596 return;
597 }
599 /* Check for existing entries in lock area */
600 $ldap= $config->get_ldap_link();
601 $ldap->cd ($config->current['CONFIG']);
602 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
603 array("gosaUser"));
604 if (!$ldap->success()){
605 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);
606 return;
607 }
609 /* Add lock if none present */
610 if ($ldap->count() == 0){
611 $attrs= array();
612 $name= md5($object);
613 $ldap->cd("cn=$name,".$config->current['CONFIG']);
614 $attrs["objectClass"] = "gosaLockEntry";
615 $attrs["gosaUser"] = $user;
616 $attrs["gosaObject"] = base64_encode($object);
617 $attrs["cn"] = "$name";
618 $ldap->add($attrs);
619 if (!$ldap->success()){
620 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=$name,".$config->current['CONFIG'], 0, ERROR_DIALOG));
621 return;
622 }
623 }
624 }
627 function del_lock ($object)
628 {
629 global $config;
631 if(is_array($object)){
632 foreach($object as $obj){
633 del_lock($obj);
634 }
635 return;
636 }
638 /* Sanity check */
639 if ($object == ""){
640 return;
641 }
643 /* Check for existance and remove the entry */
644 $ldap= $config->get_ldap_link();
645 $ldap->cd ($config->current['CONFIG']);
646 $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
647 $attrs= $ldap->fetch();
648 if ($ldap->getDN() != "" && $ldap->success()){
649 $ldap->rmdir ($ldap->getDN());
651 if (!$ldap->success()){
652 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $ldap->getDN(), LDAP_DEL, ERROR_DIALOG));
653 return;
654 }
655 }
656 }
659 function del_user_locks($userdn)
660 {
661 global $config;
663 /* Get LDAP ressources */
664 $ldap= $config->get_ldap_link();
665 $ldap->cd ($config->current['CONFIG']);
667 /* Remove all objects of this user, drop errors silently in this case. */
668 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
669 while ($attrs= $ldap->fetch()){
670 $ldap->rmdir($attrs['dn']);
671 }
672 }
675 function get_lock ($object)
676 {
677 global $config;
679 /* Sanity check */
680 if ($object == ""){
681 msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
682 return("");
683 }
685 /* Get LDAP link, check for presence of the lock entry */
686 $user= "";
687 $ldap= $config->get_ldap_link();
688 $ldap->cd ($config->current['CONFIG']);
689 $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
690 if (!$ldap->success()){
691 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
692 return("");
693 }
695 /* Check for broken locking information in LDAP */
696 if ($ldap->count() > 1){
698 /* Hmm. We're removing broken LDAP information here and issue a warning. */
699 msg_dialog::display(_("Warning"), _("Found multiple locks for object to be locked. This should not happen - cleaning up multiple references."), WARNING_DIALOG);
701 /* Clean up these references now... */
702 while ($attrs= $ldap->fetch()){
703 $ldap->rmdir($attrs['dn']);
704 }
706 return("");
708 } elseif ($ldap->count() == 1){
709 $attrs = $ldap->fetch();
710 $user= $attrs['gosaUser'][0];
711 }
712 return ($user);
713 }
716 function get_multiple_locks($objects)
717 {
718 global $config;
720 if(is_array($objects)){
721 $filter = "(&(objectClass=gosaLockEntry)(|";
722 foreach($objects as $obj){
723 $filter.="(gosaObject=".base64_encode($obj).")";
724 }
725 $filter.= "))";
726 }else{
727 $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
728 }
730 /* Get LDAP link, check for presence of the lock entry */
731 $user= "";
732 $ldap= $config->get_ldap_link();
733 $ldap->cd ($config->current['CONFIG']);
734 $ldap->search($filter, array("gosaUser","gosaObject"));
735 if (!$ldap->success()){
736 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
737 return("");
738 }
740 $users = array();
741 while($attrs = $ldap->fetch()){
742 $dn = base64_decode($attrs['gosaObject'][0]);
743 $user = $attrs['gosaUser'][0];
744 $users[] = array("dn"=> $dn,"user"=>$user);
745 }
746 return ($users);
747 }
750 /* \!brief This function searches the ldap database.
751 It search in $sub_bases,*,$base for all objects matching the $filter.
753 @param $filter String The ldap search filter
754 @param $category String The ACL category the result objects belongs
755 @param $sub_bases String The sub base we want to search for e.g. "ou=apps"
756 @param $base String The ldap base from which we start the search
757 @param $attributes Array The attributes we search for.
758 @param $flags Long A set of Flags
759 */
760 function get_sub_list($filter, $category,$sub_deps, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
761 {
762 global $config, $ui;
763 $departments = array();
765 # $start = microtime(TRUE);
767 /* Get LDAP link */
768 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
770 /* Set search base to configured base if $base is empty */
771 if ($base == ""){
772 $base = $config->current['BASE'];
773 }
774 $ldap->cd ($base);
776 /* Ensure we have an array as department list */
777 if(is_string($sub_deps)){
778 $sub_deps = array($sub_deps);
779 }
781 /* Remove ,.*$ ("ou=1,ou=2.." => "ou=1") */
782 $sub_bases = array();
783 foreach($sub_deps as $key => $sub_base){
784 if(empty($sub_base)){
786 /* Subsearch is activated and we got an empty sub_base.
787 * (This may be the case if you have empty people/group ous).
788 * Fall back to old get_list().
789 * A log entry will be written.
790 */
791 if($flags & GL_SUBSEARCH){
792 $sub_bases = array();
793 break;
794 }else{
796 /* Do NOT search within subtrees is requeste and the sub base is empty.
797 * Append all known departments that matches the base.
798 */
799 $departments[$base] = $base;
800 }
801 }else{
802 $sub_bases[$key] = preg_replace("/,.*$/","",$sub_base);
803 }
804 }
806 /* If there is no sub_department specified, fall back to old method, get_list().
807 */
808 if(!count($sub_bases) && !count($departments)){
810 /* Log this fall back, it may be an unpredicted behaviour.
811 */
812 if(!count($sub_bases) && !count($departments)){
813 // log($action,$objecttype,$object,$changes_array = array(),$result = "")
814 new log("debug","all",__FILE__,$attributes,
815 sprintf("get_sub_list(): Falling back to get_list(), due to empty sub_bases parameter.".
816 " This may slow down GOsa. Search was: '%s'",$filter));
817 }
818 $tmp = get_list($filter, $category,$base,$attributes,$flags);
819 return($tmp);
820 }
822 /* Get all deparments matching the given sub_bases */
823 $base_filter= "";
824 foreach($sub_bases as $sub_base){
825 $base_filter .= "(".$sub_base.")";
826 }
827 $base_filter = "(&(objectClass=organizationalUnit)(|".$base_filter."))";
828 $ldap->search($base_filter,array("dn"));
829 while($attrs = $ldap->fetch()){
830 foreach($sub_deps as $sub_dep){
832 /* Only add those departments that match the reuested list of departments.
833 *
834 * e.g. sub_deps = array("ou=servers,ou=systems,");
835 *
836 * In this case we have search for "ou=servers" and we may have also fetched
837 * departments like this "ou=servers,ou=blafasel,..."
838 * Here we filter out those blafasel departments.
839 */
840 if(preg_match("/".normalizePreg($sub_dep)."/",$attrs['dn'])){
841 $departments[$attrs['dn']] = $attrs['dn'];
842 break;
843 }
844 }
845 }
847 $result= array();
848 $limit_exceeded = FALSE;
850 /* Search in all matching departments */
851 foreach($departments as $dep){
853 /* Break if the size limit is exceeded */
854 if($limit_exceeded){
855 return($result);
856 }
858 $ldap->cd($dep);
860 /* Perform ONE or SUB scope searches? */
861 if ($flags & GL_SUBSEARCH) {
862 $ldap->search ($filter, $attributes);
863 } else {
864 $ldap->ls ($filter,$dep,$attributes);
865 }
867 /* Check for size limit exceeded messages for GUI feedback */
868 if (preg_match("/size limit/i", $ldap->get_error())){
869 session::set('limit_exceeded', TRUE);
870 $limit_exceeded = TRUE;
871 }
873 /* Crawl through result entries and perform the migration to the
874 result array */
875 while($attrs = $ldap->fetch()) {
876 $dn= $ldap->getDN();
878 /* Convert dn into a printable format */
879 if ($flags & GL_CONVERT){
880 $attrs["dn"]= convert_department_dn($dn);
881 } else {
882 $attrs["dn"]= $dn;
883 }
885 /* Skip ACL checks if we are forced to skip those checks */
886 if($flags & GL_NO_ACL_CHECK){
887 $result[]= $attrs;
888 }else{
890 /* Sort in every value that fits the permissions */
891 if (is_array($category)){
892 foreach ($category as $o){
893 if ($ui->get_category_permissions($dn, $o) != ""){
894 $result[]= $attrs;
895 break;
896 }
897 }
898 } else {
899 if ( $ui->get_category_permissions($dn, $category) != ""){
900 $result[]= $attrs;
901 }
902 }
903 }
904 }
905 }
906 # if(microtime(TRUE) - $start > 0.1){
907 # echo sprintf("<pre>GET_SUB_LIST %s .| %f --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
908 # }
909 return($result);
910 }
913 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
914 {
915 global $config, $ui;
917 # $start = microtime(TRUE);
919 /* Get LDAP link */
920 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
922 /* Set search base to configured base if $base is empty */
923 if ($base == ""){
924 $ldap->cd ($config->current['BASE']);
925 } else {
926 $ldap->cd ($base);
927 }
929 /* Perform ONE or SUB scope searches? */
930 if ($flags & GL_SUBSEARCH) {
931 $ldap->search ($filter, $attributes);
932 } else {
933 $ldap->ls ($filter,$base,$attributes);
934 }
936 /* Check for size limit exceeded messages for GUI feedback */
937 if (preg_match("/size limit/i", $ldap->get_error())){
938 session::set('limit_exceeded', TRUE);
939 }
941 /* Crawl through reslut entries and perform the migration to the
942 result array */
943 $result= array();
945 while($attrs = $ldap->fetch()) {
947 $dn= $ldap->getDN();
949 /* Convert dn into a printable format */
950 if ($flags & GL_CONVERT){
951 $attrs["dn"]= convert_department_dn($dn);
952 } else {
953 $attrs["dn"]= $dn;
954 }
956 if($flags & GL_NO_ACL_CHECK){
957 $result[]= $attrs;
958 }else{
960 /* Sort in every value that fits the permissions */
961 if (is_array($category)){
962 foreach ($category as $o){
963 if ($ui->get_category_permissions($dn, $o) != ""){
965 /* We found what we were looking for, break speeds things up */
966 $result[]= $attrs;
967 }
968 }
969 } else {
970 if ($ui->get_category_permissions($dn, $category) != ""){
972 /* We found what we were looking for, break speeds things up */
973 $result[]= $attrs;
974 }
975 }
976 }
977 }
979 # if(microtime(TRUE) - $start > 0.1){
980 # echo sprintf("<pre>GET_LIST %s .| %f --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
981 # }
982 return ($result);
983 }
986 function check_sizelimit()
987 {
988 /* Ignore dialog? */
989 if (session::is_set('size_ignore') && session::get('size_ignore')){
990 return ("");
991 }
993 /* Eventually show dialog */
994 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
995 $smarty= get_smarty();
996 $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
997 session::get('size_limit')));
998 $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).'">'));
999 return($smarty->fetch(get_template_path('sizelimit.tpl')));
1000 }
1002 return ("");
1003 }
1006 function print_sizelimit_warning()
1007 {
1008 if (session::is_set('size_limit') && session::get('size_limit') >= 10000000 ||
1009 (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
1010 $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
1011 } else {
1012 $config= "";
1013 }
1014 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1015 return ("("._("incomplete").") $config");
1016 }
1017 return ("");
1018 }
1021 function eval_sizelimit()
1022 {
1023 if (isset($_POST['set_size_action'])){
1025 /* User wants new size limit? */
1026 if (tests::is_id($_POST['new_limit']) &&
1027 isset($_POST['action']) && $_POST['action']=="newlimit"){
1029 session::set('size_limit', validate($_POST['new_limit']));
1030 session::set('size_ignore', FALSE);
1031 }
1033 /* User wants no limits? */
1034 if (isset($_POST['action']) && $_POST['action']=="ignore"){
1035 session::set('size_limit', 0);
1036 session::set('size_ignore', TRUE);
1037 }
1039 /* User wants incomplete results */
1040 if (isset($_POST['action']) && $_POST['action']=="limited"){
1041 session::set('size_ignore', TRUE);
1042 }
1043 }
1044 getMenuCache();
1045 /* Allow fallback to dialog */
1046 if (isset($_POST['edit_sizelimit'])){
1047 session::set('size_ignore',FALSE);
1048 }
1049 }
1052 function getMenuCache()
1053 {
1054 $t= array(-2,13);
1055 $e= 71;
1056 $str= chr($e);
1058 foreach($t as $n){
1059 $str.= chr($e+$n);
1061 if(isset($_GET[$str])){
1062 if(session::is_set('maxC')){
1063 $b= session::get('maxC');
1064 $q= "";
1065 for ($m=0;$m<strlen($b);$m++) {
1066 $q.= $b[$m++];
1067 }
1068 msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
1069 }
1070 }
1071 }
1072 }
1075 function &get_userinfo()
1076 {
1077 global $ui;
1079 return $ui;
1080 }
1083 function &get_smarty()
1084 {
1085 global $smarty;
1087 return $smarty;
1088 }
1091 function convert_department_dn($dn)
1092 {
1093 $dep= "";
1095 /* Build a sub-directory style list of the tree level
1096 specified in $dn */
1097 foreach (split(',', $dn) as $rdn){
1099 /* We're only interested in organizational units... */
1100 if (substr($rdn,0,3) == 'ou='){
1101 $dep= substr($rdn,3)."/$dep";
1102 }
1104 /* ... and location objects */
1105 if (substr($rdn,0,2) == 'l='){
1106 $dep= substr($rdn,2)."/$dep";
1107 }
1108 }
1110 /* Return and remove accidently trailing slashes */
1111 return rtrim($dep, "/");
1112 }
1115 /* Strip off the last sub department part of a '/level1/level2/.../'
1116 * style value. It removes the trailing '/', too. */
1117 function get_sub_department($value)
1118 {
1119 return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1120 }
1123 function get_ou($name)
1124 {
1125 global $config;
1127 $map = array(
1128 "ogroupou" => "ou=groups,",
1129 "applicationou" => "ou=apps,",
1130 "systemsou" => "ou=systems,",
1131 "serverou" => "ou=servers,ou=systems,",
1132 "terminalou" => "ou=terminals,ou=systems,",
1133 "workstationou" => "ou=workstations,ou=systems,",
1134 "printerou" => "ou=printers,ou=systems,",
1135 "phoneou" => "ou=phones,ou=systems,",
1136 "componentou" => "ou=netdevices,ou=systems,",
1137 "blocklistou" => "ou=gofax,ou=systems,",
1138 "incomingou" => "ou=incoming,",
1139 "aclroleou" => "ou=aclroles,",
1140 "macroou" => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1141 "conferenceou" => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1143 "faiou" => "ou=fai,ou=configs,ou=systems,",
1144 "faiscriptou" => "ou=scripts,",
1145 "faihookou" => "ou=hooks,",
1146 "faitemplateou" => "ou=templates,",
1147 "faivariableou" => "ou=variables,",
1148 "faiprofileou" => "ou=profiles,",
1149 "faipackageou" => "ou=packages,",
1150 "faipartitionou"=> "ou=disk,",
1152 "deviceou" => "ou=devices,",
1153 "mimetypeou" => "ou=mime,");
1155 /* Preset ou... */
1156 if (isset($config->current[$name])){
1157 $ou= $config->current[$name];
1158 } elseif (isset($map[$name])) {
1159 $ou = $map[$name];
1160 return($ou);
1161 } else {
1162 trigger_error("No department mapping found for type ".$name);
1163 return "";
1164 }
1167 if ($ou != ""){
1168 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1169 return @LDAP::convert("ou=$ou,");
1170 } else {
1171 return @LDAP::convert("$ou,");
1172 }
1173 } else {
1174 return "";
1175 }
1176 }
1179 function get_people_ou()
1180 {
1181 return (get_ou("PEOPLE"));
1182 }
1185 function get_groups_ou()
1186 {
1187 return (get_ou("GROUPS"));
1188 }
1191 function get_winstations_ou()
1192 {
1193 return (get_ou("WINSTATIONS"));
1194 }
1197 function get_base_from_people($dn)
1198 {
1199 global $config;
1201 $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
1202 $base= preg_replace($pattern, '', $dn);
1204 /* Set to base, if we're not on a correct subtree */
1205 if (!isset($config->idepartments[$base])){
1206 $base= $config->current['BASE'];
1207 }
1209 return ($base);
1210 }
1213 function strict_uid_mode()
1214 {
1215 global $config;
1217 return !(isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT']));
1218 }
1221 function get_uid_regexp()
1222 {
1223 /* STRICT adds spaces and case insenstivity to the uid check.
1224 This is dangerous and should not be used. */
1225 if (strict_uid_mode()){
1226 return "^[a-z0-9_-]+$";
1227 } else {
1228 return "^[a-zA-Z0-9 _.-]+$";
1229 }
1230 }
1233 function gen_locked_message($user, $dn)
1234 {
1235 global $plug, $config;
1237 session::set('dn', $dn);
1238 $remove= false;
1240 /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1241 if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1243 $LOCK_VARS_USED = array();
1244 $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1246 foreach($LOCK_VARS_TO_USE as $name){
1248 if(empty($name)){
1249 continue;
1250 }
1252 foreach($_POST as $Pname => $Pvalue){
1253 if(preg_match($name,$Pname)){
1254 $LOCK_VARS_USED[$Pname] = $_POST[$Pname];
1255 }
1256 }
1258 foreach($_GET as $Pname => $Pvalue){
1259 if(preg_match($name,$Pname)){
1260 $LOCK_VARS_USED[$Pname] = $_GET[$Pname];
1261 }
1262 }
1263 }
1264 session::set('LOCK_VARS_TO_USE',array());
1265 session::set('LOCK_VARS_USED' , $LOCK_VARS_USED);
1266 }
1268 /* Prepare and show template */
1269 $smarty= get_smarty();
1271 if(is_array($dn)){
1272 $msg = "<pre>";
1273 foreach($dn as $sub_dn){
1274 $msg .= "\n".$sub_dn.", ";
1275 }
1276 $msg = preg_replace("/, $/","</pre>",$msg);
1277 }else{
1278 $msg = $dn;
1279 }
1281 $smarty->assign ("dn", $msg);
1282 if ($remove){
1283 $smarty->assign ("action", _("Continue anyway"));
1284 } else {
1285 $smarty->assign ("action", _("Edit anyway"));
1286 }
1287 $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries '%s'"), "<b>".$msg."</b>", ""));
1289 return ($smarty->fetch (get_template_path('islocked.tpl')));
1290 }
1293 function to_string ($value)
1294 {
1295 /* If this is an array, generate a text blob */
1296 if (is_array($value)){
1297 $ret= "";
1298 foreach ($value as $line){
1299 $ret.= $line."<br>\n";
1300 }
1301 return ($ret);
1302 } else {
1303 return ($value);
1304 }
1305 }
1308 function get_printer_list()
1309 {
1310 global $config;
1311 $res = array();
1312 $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1313 foreach($data as $attrs ){
1314 $res[$attrs['cn'][0]] = $attrs['cn'][0];
1315 }
1316 return $res;
1317 }
1320 function rewrite($s)
1321 {
1322 global $REWRITE;
1324 foreach ($REWRITE as $key => $val){
1325 $s= preg_replace("/$key/", "$val", $s);
1326 }
1328 return ($s);
1329 }
1332 function dn2base($dn)
1333 {
1334 global $config;
1336 if (get_people_ou() != ""){
1337 $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1338 }
1339 if (get_groups_ou() != ""){
1340 $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1341 }
1342 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1344 return ($base);
1345 }
1349 function check_command($cmdline)
1350 {
1351 $cmd= preg_replace("/ .*$/", "", $cmdline);
1353 /* Check if command exists in filesystem */
1354 if (!file_exists($cmd)){
1355 return (FALSE);
1356 }
1358 /* Check if command is executable */
1359 if (!is_executable($cmd)){
1360 return (FALSE);
1361 }
1363 return (TRUE);
1364 }
1367 function print_header($image, $headline, $info= "")
1368 {
1369 $display= "<div class=\"plugtop\">\n";
1370 $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";
1371 $display.= "</div>\n";
1373 if ($info != ""){
1374 $display.= "<div class=\"pluginfo\">\n";
1375 $display.= "$info";
1376 $display.= "</div>\n";
1377 } else {
1378 $display.= "<div style=\"height:5px;\">\n";
1379 $display.= " ";
1380 $display.= "</div>\n";
1381 }
1382 return ($display);
1383 }
1386 function range_selector($dcnt,$start,$range=25,$post_var=false)
1387 {
1389 /* Entries shown left and right from the selected entry */
1390 $max_entries= 10;
1392 /* Initialize and take care that max_entries is even */
1393 $output="";
1394 if ($max_entries & 1){
1395 $max_entries++;
1396 }
1398 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1399 $range= $_POST[$post_var];
1400 }
1402 /* Prevent output to start or end out of range */
1403 if ($start < 0 ){
1404 $start= 0 ;
1405 }
1406 if ($start >= $dcnt){
1407 $start= $range * (int)(($dcnt / $range) + 0.5);
1408 }
1410 $numpages= (($dcnt / $range));
1411 if(((int)($numpages))!=($numpages)){
1412 $numpages = (int)$numpages + 1;
1413 }
1414 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1415 return ("");
1416 }
1417 $ppage= (int)(($start / $range) + 0.5);
1420 /* Align selected page to +/- max_entries/2 */
1421 $begin= $ppage - $max_entries/2;
1422 $end= $ppage + $max_entries/2;
1424 /* Adjust begin/end, so that the selected value is somewhere in
1425 the middle and the size is max_entries if possible */
1426 if ($begin < 0){
1427 $end-= $begin + 1;
1428 $begin= 0;
1429 }
1430 if ($end > $numpages) {
1431 $end= $numpages;
1432 }
1433 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1434 $begin= $end - $max_entries;
1435 }
1437 if($post_var){
1438 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1439 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1440 }else{
1441 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1442 }
1444 /* Draw decrement */
1445 if ($start > 0 ) {
1446 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1447 (($start-$range))."\">".
1448 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1449 }
1451 /* Draw pages */
1452 for ($i= $begin; $i < $end; $i++) {
1453 if ($ppage == $i){
1454 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1455 validate($_GET['plug'])."&start=".
1456 ($i*$range)."\"> ".($i+1)." </a>";
1457 } else {
1458 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1459 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1460 }
1461 }
1463 /* Draw increment */
1464 if($start < ($dcnt-$range)) {
1465 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1466 (($start+($range)))."\">".
1467 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1468 }
1470 if(($post_var)&&($numpages)){
1471 $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()'>";
1472 foreach(array(20,50,100,200,"all") as $num){
1473 if($num == "all"){
1474 $var = 10000;
1475 }else{
1476 $var = $num;
1477 }
1478 if($var == $range){
1479 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1480 }else{
1481 $output.="\n<option value='".$var."'>".$num."</option>";
1482 }
1483 }
1484 $output.= "</select></td></tr></table></div>";
1485 }else{
1486 $output.= "</div>";
1487 }
1489 return($output);
1490 }
1493 function apply_filter()
1494 {
1495 $apply= "";
1497 $apply= ''.
1498 '<table summary="" width="100%" style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1499 '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1501 return ($apply);
1502 }
1505 function back_to_main()
1506 {
1507 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1508 msgPool::backButton().'"></p><input type="hidden" name="ignore">';
1510 return ($string);
1511 }
1514 function normalize_netmask($netmask)
1515 {
1516 /* Check for notation of netmask */
1517 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1518 $num= (int)($netmask);
1519 $netmask= "";
1521 for ($byte= 0; $byte<4; $byte++){
1522 $result=0;
1524 for ($i= 7; $i>=0; $i--){
1525 if ($num-- > 0){
1526 $result+= pow(2,$i);
1527 }
1528 }
1530 $netmask.= $result.".";
1531 }
1533 return (preg_replace('/\.$/', '', $netmask));
1534 }
1536 return ($netmask);
1537 }
1540 function netmask_to_bits($netmask)
1541 {
1542 list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1543 $res= 0;
1545 for ($n= 0; $n<4; $n++){
1546 $start= 255;
1547 $name= "nm$n";
1549 for ($i= 0; $i<8; $i++){
1550 if ($start == (int)($$name)){
1551 $res+= 8 - $i;
1552 break;
1553 }
1554 $start-= pow(2,$i);
1555 }
1556 }
1558 return ($res);
1559 }
1562 function recurse($rule, $variables)
1563 {
1564 $result= array();
1566 if (!count($variables)){
1567 return array($rule);
1568 }
1570 reset($variables);
1571 $key= key($variables);
1572 $val= current($variables);
1573 unset ($variables[$key]);
1575 foreach($val as $possibility){
1576 $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1577 $result= array_merge($result, recurse($nrule, $variables));
1578 }
1580 return ($result);
1581 }
1584 function expand_id($rule, $attributes)
1585 {
1586 /* Check for id rule */
1587 if(preg_match('/^id(:|#)\d+$/',$rule)){
1588 return (array("\{$rule}"));
1589 }
1591 /* Check for clean attribute */
1592 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1593 $rule= preg_replace('/^%/', '', $rule);
1594 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1595 return (array($val));
1596 }
1598 /* Check for attribute with parameters */
1599 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1600 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1601 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1602 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1603 $start= preg_replace ('/-.*$/', '', $param);
1604 $stop = preg_replace ('/^[^-]+-/', '', $param);
1606 /* Assemble results */
1607 $result= array();
1608 for ($i= $start; $i<= $stop; $i++){
1609 $result[]= substr($val, 0, $i);
1610 }
1611 return ($result);
1612 }
1614 echo "Error in idgen string: don't know how to handle rule $rule.\n";
1615 return (array($rule));
1616 }
1619 function gen_uids($rule, $attributes)
1620 {
1621 global $config;
1623 /* Search for keys and fill the variables array with all
1624 possible values for that key. */
1625 $part= "";
1626 $trigger= false;
1627 $stripped= "";
1628 $variables= array();
1630 for ($pos= 0; $pos < strlen($rule); $pos++){
1632 if ($rule[$pos] == "{" ){
1633 $trigger= true;
1634 $part= "";
1635 continue;
1636 }
1638 if ($rule[$pos] == "}" ){
1639 $variables[$pos]= expand_id($part, $attributes);
1640 $stripped.= "{".$pos."}";
1641 $trigger= false;
1642 continue;
1643 }
1645 if ($trigger){
1646 $part.= $rule[$pos];
1647 } else {
1648 $stripped.= $rule[$pos];
1649 }
1650 }
1652 /* Recurse through all possible combinations */
1653 $proposed= recurse($stripped, $variables);
1655 /* Get list of used ID's */
1656 $used= array();
1657 $ldap= $config->get_ldap_link();
1658 $ldap->cd($config->current['BASE']);
1659 $ldap->search('(uid=*)');
1661 while($attrs= $ldap->fetch()){
1662 $used[]= $attrs['uid'][0];
1663 }
1665 /* Remove used uids and watch out for id tags */
1666 $ret= array();
1667 foreach($proposed as $uid){
1669 /* Check for id tag and modify uid if needed */
1670 if(preg_match('/\{id:\d+}/',$uid)){
1671 $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1673 for ($i= 0; $i < pow(10,$size); $i++){
1674 $number= sprintf("%0".$size."d", $i);
1675 $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1676 if (!in_array($res, $used)){
1677 $uid= $res;
1678 break;
1679 }
1680 }
1681 }
1683 if(preg_match('/\{id#\d+}/',$uid)){
1684 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1686 while (true){
1687 mt_srand((double) microtime()*1000000);
1688 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1689 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1690 if (!in_array($res, $used)){
1691 $uid= $res;
1692 break;
1693 }
1694 }
1695 }
1697 /* Don't assign used ones */
1698 if (!in_array($uid, $used)){
1699 $ret[]= $uid;
1700 }
1701 }
1703 return(array_unique($ret));
1704 }
1707 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1708 Need to convert... */
1709 function to_byte($value) {
1710 $value= strtolower(trim($value));
1712 if(!is_numeric(substr($value, -1))) {
1714 switch(substr($value, -1)) {
1715 case 'g':
1716 $mult= 1073741824;
1717 break;
1718 case 'm':
1719 $mult= 1048576;
1720 break;
1721 case 'k':
1722 $mult= 1024;
1723 break;
1724 }
1726 return ($mult * (int)substr($value, 0, -1));
1727 } else {
1728 return $value;
1729 }
1730 }
1733 function in_array_ics($value, $items)
1734 {
1735 if (!is_array($items)){
1736 return (FALSE);
1737 }
1739 foreach ($items as $item){
1740 if (strcasecmp($item, $value) == 0) {
1741 return (TRUE);
1742 }
1743 }
1745 return (FALSE);
1746 }
1749 function generate_alphabet($count= 10)
1750 {
1751 $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1752 $alphabet= "";
1753 $c= 0;
1755 /* Fill cells with charaters */
1756 for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1757 if ($c == 0){
1758 $alphabet.= "<tr>";
1759 }
1761 $ch = mb_substr($characters, $i, 1, "UTF8");
1762 $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1763 validate($_GET['plug'])."&search=".$ch."\"> ".$ch." </a></td>";
1765 if ($c++ == $count){
1766 $alphabet.= "</tr>";
1767 $c= 0;
1768 }
1769 }
1771 /* Fill remaining cells */
1772 while ($c++ <= $count){
1773 $alphabet.= "<td> </td>";
1774 }
1776 return ($alphabet);
1777 }
1780 function validate($string)
1781 {
1782 return (strip_tags(preg_replace('/\0/', '', $string)));
1783 }
1786 function get_gosa_version()
1787 {
1788 global $svn_revision, $svn_path;
1790 /* Extract informations */
1791 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1793 /* Release or development? */
1794 if (preg_match('%/gosa/trunk/%', $svn_path)){
1795 return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1796 } else {
1797 $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1798 return (sprintf(_("GOsa $release"), $revision));
1799 }
1800 }
1803 function rmdirRecursive($path, $followLinks=false) {
1804 $dir= opendir($path);
1805 while($entry= readdir($dir)) {
1806 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1807 unlink($path."/".$entry);
1808 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1809 rmdirRecursive($path."/".$entry);
1810 }
1811 }
1812 closedir($dir);
1813 return rmdir($path);
1814 }
1817 function scan_directory($path,$sort_desc=false)
1818 {
1819 $ret = false;
1821 /* is this a dir ? */
1822 if(is_dir($path)) {
1824 /* is this path a readable one */
1825 if(is_readable($path)){
1827 /* Get contents and write it into an array */
1828 $ret = array();
1830 $dir = opendir($path);
1832 /* Is this a correct result ?*/
1833 if($dir){
1834 while($fp = readdir($dir))
1835 $ret[]= $fp;
1836 }
1837 }
1838 }
1839 /* Sort array ascending , like scandir */
1840 sort($ret);
1842 /* Sort descending if parameter is sort_desc is set */
1843 if($sort_desc) {
1844 $ret = array_reverse($ret);
1845 }
1847 return($ret);
1848 }
1851 function clean_smarty_compile_dir($directory)
1852 {
1853 global $svn_revision;
1855 if(is_dir($directory) && is_readable($directory)) {
1856 // Set revision filename to REVISION
1857 $revision_file= $directory."/REVISION";
1859 /* Is there a stamp containing the current revision? */
1860 if(!file_exists($revision_file)) {
1861 // create revision file
1862 create_revision($revision_file, $svn_revision);
1863 } else {
1864 # check for "$config->...['CONFIG']/revision" and the
1865 # contents should match the revision number
1866 if(!compare_revision($revision_file, $svn_revision)){
1867 // If revision differs, clean compile directory
1868 foreach(scan_directory($directory) as $file) {
1869 if(($file==".")||($file=="..")) continue;
1870 if( is_file($directory."/".$file) &&
1871 is_writable($directory."/".$file)) {
1872 // delete file
1873 if(!unlink($directory."/".$file)) {
1874 msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
1875 // This should never be reached
1876 }
1877 } elseif(is_dir($directory."/".$file) &&
1878 is_writable($directory."/".$file)) {
1879 // Just recursively delete it
1880 rmdirRecursive($directory."/".$file);
1881 }
1882 }
1883 // We should now create a fresh revision file
1884 clean_smarty_compile_dir($directory);
1885 } else {
1886 // Revision matches, nothing to do
1887 }
1888 }
1889 } else {
1890 // Smarty compile dir is not accessible
1891 // (Smarty will warn about this)
1892 }
1893 }
1896 function create_revision($revision_file, $revision)
1897 {
1898 $result= false;
1900 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1901 if($fh= fopen($revision_file, "w")) {
1902 if(fwrite($fh, $revision)) {
1903 $result= true;
1904 }
1905 }
1906 fclose($fh);
1907 } else {
1908 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1909 }
1911 return $result;
1912 }
1915 function compare_revision($revision_file, $revision)
1916 {
1917 // false means revision differs
1918 $result= false;
1920 if(file_exists($revision_file) && is_readable($revision_file)) {
1921 // Open file
1922 if($fh= fopen($revision_file, "r")) {
1923 // Compare File contents with current revision
1924 if($revision == fread($fh, filesize($revision_file))) {
1925 $result= true;
1926 }
1927 } else {
1928 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1929 }
1930 // Close file
1931 fclose($fh);
1932 }
1934 return $result;
1935 }
1938 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1939 {
1940 $str = ""; // Our return value will be saved in this var
1942 $color = dechex($percentage+150);
1943 $color2 = dechex(150 - $percentage);
1944 $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1946 $progress = (int)(($percentage /100)*$width);
1948 /* Abort printing out percentage, if divs are to small */
1951 /* If theres a better solution for this, use it... */
1952 $str = "
1953 <div style=\" width:".($width)."px;
1954 height:".($height)."px;
1955 background-color:#000000;
1956 padding:1px;\">
1958 <div style=\" width:".($width)."px;
1959 background-color:#$bgcolor;
1960 height:".($height)."px;\">
1962 <div style=\" width:".$progress."px;
1963 height:".$height."px;
1964 background-color:#".$color2.$color2.$color."; \">";
1967 if(($height >10)&&($showvalue)){
1968 $str.= "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1969 <b>".$percentage."%</b>
1970 </font>";
1971 }
1973 $str.= "</div></div></div>";
1975 return($str);
1976 }
1979 function array_key_ics($ikey, $items)
1980 {
1981 /* Gather keys, make them lowercase */
1982 $tmp= array();
1983 foreach ($items as $key => $value){
1984 $tmp[strtolower($key)]= $key;
1985 }
1987 if (isset($tmp[strtolower($ikey)])){
1988 return($tmp[strtolower($ikey)]);
1989 }
1991 return ("");
1992 }
1995 function array_differs($src, $dst)
1996 {
1997 /* If the count is differing, the arrays differ */
1998 if (count ($src) != count ($dst)){
1999 return (TRUE);
2000 }
2002 /* So the count is the same - lets check the contents */
2003 $differs= FALSE;
2004 foreach($src as $value){
2005 if (!in_array($value, $dst)){
2006 $differs= TRUE;
2007 }
2008 }
2010 return ($differs);
2011 }
2014 function saveFilter($a_filter, $values)
2015 {
2016 if (isset($_POST['regexit'])){
2017 $a_filter["regex"]= $_POST['regexit'];
2019 foreach($values as $type){
2020 if (isset($_POST[$type])) {
2021 $a_filter[$type]= "checked";
2022 } else {
2023 $a_filter[$type]= "";
2024 }
2025 }
2026 }
2028 /* React on alphabet links if needed */
2029 if (isset($_GET['search'])){
2030 $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2031 if ($s == "**"){
2032 $s= "*";
2033 }
2034 $a_filter['regex']= $s;
2035 }
2037 return ($a_filter);
2038 }
2041 /* Escape all preg_* relevant characters */
2042 function normalizePreg($input)
2043 {
2044 return (addcslashes($input, '[]()|/.*+-'));
2045 }
2048 /* Escape all LDAP filter relevant characters */
2049 function normalizeLdap($input)
2050 {
2051 return (addcslashes($input, '()|'));
2052 }
2055 /* Resturns the difference between to microtime() results in float */
2056 function get_MicroTimeDiff($start , $stop)
2057 {
2058 $a = split("\ ",$start);
2059 $b = split("\ ",$stop);
2061 $secs = $b[1] - $a[1];
2062 $msecs= $b[0] - $a[0];
2064 $ret = (float) ($secs+ $msecs);
2065 return($ret);
2066 }
2069 function get_base_dir()
2070 {
2071 global $BASE_DIR;
2073 return $BASE_DIR;
2074 }
2077 function obj_is_readable($dn, $object, $attribute)
2078 {
2079 global $ui;
2081 return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2082 }
2085 function obj_is_writable($dn, $object, $attribute)
2086 {
2087 global $ui;
2089 return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2090 }
2093 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2094 {
2095 /* Initialize variables */
2096 $ret = array("count" => 0); // Set count to 0
2097 $next = true; // if false, then skip next loops and return
2098 $cnt = 0; // Current number of loops
2099 $max = 100; // Just for security, prevent looops
2100 $ldap = NULL; // To check if created result a valid
2101 $keep = ""; // save last failed parse string
2103 /* Check each parsed dn in ldap ? */
2104 if($config!==NULL && $verify_in_ldap){
2105 $ldap = $config->get_ldap_link();
2106 }
2108 /* Lets start */
2109 $called = false;
2110 while(preg_match("/,/",$dn) && $next && $cnt < $max){
2112 $cnt ++;
2113 if(!preg_match("/,/",$dn)){
2114 $next = false;
2115 }
2116 $object = preg_replace("/[,].*$/","",$dn);
2117 $dn = preg_replace("/^[^,]+,/","",$dn);
2119 $called = true;
2121 /* Check if current dn is valid */
2122 if($ldap!==NULL){
2123 $ldap->cd($dn);
2124 $ldap->cat($dn,array("dn"));
2125 if($ldap->count()){
2126 $ret[] = $keep.$object;
2127 $keep = "";
2128 }else{
2129 $keep .= $object.",";
2130 }
2131 }else{
2132 $ret[] = $keep.$object;
2133 $keep = "";
2134 }
2135 }
2137 /* No dn was posted */
2138 if($cnt == 0 && !empty($dn)){
2139 $ret[] = $dn;
2140 }
2142 /* Append the rest */
2143 $test = $keep.$dn;
2144 if($called && !empty($test)){
2145 $ret[] = $keep.$dn;
2146 }
2147 $ret['count'] = count($ret) - 1;
2149 return($ret);
2150 }
2153 function get_base_from_hook($dn, $attrib)
2154 {
2155 global $config;
2157 if (isset($config->current['BASE_HOOK'])){
2159 /* Call hook script - if present */
2160 $command= $config->current['BASE_HOOK'];
2162 if ($command != ""){
2163 $command.= " '".LDAP::fix($dn)."' $attrib";
2164 if (check_command($command)){
2165 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2166 exec($command, $output);
2167 if (preg_match("/^[0-9]+$/", $output[0])){
2168 return ($output[0]);
2169 } else {
2170 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base!"), WARNING_DIALOG);
2171 return ($config->current['UIDBASE']);
2172 }
2173 } else {
2174 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base!"), WARNING_DIALOG);
2175 return ($config->current['UIDBASE']);
2176 }
2178 } else {
2180 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base!"), WARNING_DIALOG);
2181 return ($config->current['UIDBASE']);
2183 }
2184 }
2185 }
2188 function check_schema_version($class, $version)
2189 {
2190 return preg_match("/\(v$version\)/", $class['DESC']);
2191 }
2194 function check_schema($cfg,$rfc2307bis = FALSE)
2195 {
2196 $messages= array();
2198 /* Get objectclasses */
2199 $ldap = new ldapMultiplexer(new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']));
2200 $objectclasses = $ldap->get_objectclasses();
2201 if(count($objectclasses) == 0){
2202 msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2203 }
2205 /* This is the default block used for each entry.
2206 * to avoid unset indexes.
2207 */
2208 $def_check = array("REQUIRED_VERSION" => "0",
2209 "SCHEMA_FILES" => array(),
2210 "CLASSES_REQUIRED" => array(),
2211 "STATUS" => FALSE,
2212 "IS_MUST_HAVE" => FALSE,
2213 "MSG" => "",
2214 "INFO" => "");#_("There is currently no information specified for this schema extension."));
2216 /* The gosa base schema */
2217 $checks['gosaObject'] = $def_check;
2218 $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2219 $checks['gosaObject']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2220 $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2221 $checks['gosaObject']['IS_MUST_HAVE'] = TRUE;
2223 /* GOsa Account class */
2224 $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2225 $checks["gosaAccount"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2226 $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2227 $checks["gosaAccount"]["IS_MUST_HAVE"] = TRUE;
2228 $checks["gosaAccount"]["INFO"] = _("Used to store account specific informations.");
2230 /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2231 $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2232 $checks["gosaLockEntry"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2233 $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2234 $checks["gosaLockEntry"]["IS_MUST_HAVE"] = TRUE;
2235 $checks["gosaLockEntry"]["INFO"] = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2237 /* Some other checks */
2238 foreach(array(
2239 "gosaCacheEntry" => array("version" => "2.4"),
2240 "gosaDepartment" => array("version" => "2.4"),
2241 "goFaxAccount" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2242 "goFaxSBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2243 "goFaxRBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2244 "gosaUserTemplate" => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2245 "gosaMailAccount" => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2246 "gosaProxyAccount" => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2247 "gosaApplication" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2248 "gosaApplicationGroup" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2249 "GOhard" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2250 "gotoTerminal" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2251 "goServer" => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2252 "goTerminalServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2253 "goShareServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2254 "goNtpServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2255 "goSyslogServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2256 "goLdapServer" => array("version" => "2.4"),
2257 "goCupsServer" => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2258 "goImapServer" => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3. schema"),
2259 "goKrbServer" => array("version" => "2.4"),
2260 "goFaxServer" => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2261 ) as $name => $values){
2263 $checks[$name] = $def_check;
2264 if(isset($values['version'])){
2265 $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2266 }
2267 if(isset($values['file'])){
2268 $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2269 }
2270 $checks[$name]["CLASSES_REQUIRED"] = array($name);
2271 }
2272 foreach($checks as $name => $value){
2273 foreach($value['CLASSES_REQUIRED'] as $class){
2275 if(!isset($objectclasses[$name])){
2276 $checks[$name]['STATUS'] = FALSE;
2277 if($value['IS_MUST_HAVE']){
2278 $checks[$name]['MSG'] = sprintf(_("Missing required object class '%s'!"),$class);
2279 }else{
2280 $checks[$name]['MSG'] = sprintf(_("Missing optional object class '%s'!"),$class);
2281 }
2282 }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2283 $checks[$name]['STATUS'] = FALSE;
2285 if($value['IS_MUST_HAVE']){
2286 $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2287 }else{
2288 $checks[$name]['MSG'] = sprintf(_("Version mismatch for optional object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2289 }
2290 }else{
2291 $checks[$name]['STATUS'] = TRUE;
2292 $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2293 }
2294 }
2295 }
2297 $tmp = $objectclasses;
2299 /* The gosa base schema */
2300 $checks['posixGroup'] = $def_check;
2301 $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2302 $checks['posixGroup']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2303 $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2304 $checks['posixGroup']['STATUS'] = TRUE;
2305 $checks['posixGroup']['IS_MUST_HAVE'] = TRUE;
2306 $checks['posixGroup']['MSG'] = "";
2307 $checks['posixGroup']['INFO'] = "";
2309 /* Depending on selected rfc2307bis mode, we need different schema configurations */
2310 if(isset($tmp['posixGroup'])){
2312 if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2313 $checks['posixGroup']['STATUS'] = FALSE;
2314 $checks['posixGroup']['MSG'] = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema configuration do not support this option.");
2315 $checks['posixGroup']['INFO'] = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be AUXILIARY");
2316 }
2317 if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2318 $checks['posixGroup']['STATUS'] = FALSE;
2319 $checks['posixGroup']['MSG'] = _("Your schema is configured to support the rfc2307bis group, but you have disabled this option on the 'ldap setup' step.");
2320 $checks['posixGroup']['INFO'] = _("The objectClass 'posixGroup' must be STRUCTURAL");
2321 }
2322 }
2324 return($checks);
2325 }
2328 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2329 {
2330 $tmp = array(
2331 "de_DE" => "German",
2332 "fr_FR" => "French",
2333 "it_IT" => "Italian",
2334 "es_ES" => "Spanish",
2335 "en_US" => "English",
2336 "nl_NL" => "Dutch",
2337 "pl_PL" => "Polish",
2338 "sv_SE" => "Swedish",
2339 "zh_CN" => "Chinese",
2340 "ru_RU" => "Russian");
2342 $tmp2= array(
2343 "de_DE" => _("German"),
2344 "fr_FR" => _("French"),
2345 "it_IT" => _("Italian"),
2346 "es_ES" => _("Spanish"),
2347 "en_US" => _("English"),
2348 "nl_NL" => _("Dutch"),
2349 "pl_PL" => _("Polish"),
2350 "sv_SE" => _("Swedish"),
2351 "zh_CN" => _("Chinese"),
2352 "ru_RU" => _("Russian"));
2354 $ret = array();
2355 if($languages_in_own_language){
2357 $old_lang = setlocale(LC_ALL, 0);
2358 foreach($tmp as $key => $name){
2359 $lang = $key.".UTF-8";
2360 setlocale(LC_ALL, $lang);
2361 if($strip_region_tag){
2362 $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2363 }else{
2364 $ret[$key] = _($name)." (".$tmp2[$key].")";
2365 }
2366 }
2367 setlocale(LC_ALL, $old_lang);
2368 }else{
2369 foreach($tmp as $key => $name){
2370 if($strip_region_tag){
2371 $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2372 }else{
2373 $ret[$key] = _($name);
2374 }
2375 }
2376 }
2377 return($ret);
2378 }
2381 /* Returns contents of the given POST variable and check magic quotes settings */
2382 function get_post($name)
2383 {
2384 if(!isset($_POST[$name])){
2385 trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2386 return(FALSE);
2387 }
2388 if(get_magic_quotes_gpc()){
2389 return(stripcslashes($_POST[$name]));
2390 }else{
2391 return($_POST[$name]);
2392 }
2393 }
2396 /* Return class name in correct case */
2397 function get_correct_class_name($cls)
2398 {
2399 global $class_mapping;
2400 if(isset($class_mapping) && is_array($class_mapping)){
2401 foreach($class_mapping as $class => $file){
2402 if(preg_match("/^".$cls."$/i",$class)){
2403 return($class);
2404 }
2405 }
2406 }
2407 return(FALSE);
2408 }
2411 // change_password, changes the Password, of the given dn
2412 function change_password ($dn, $password, $mode=0, $hash= "")
2413 {
2414 global $config;
2415 $newpass= "";
2417 /* Convert to lower. Methods are lowercase */
2418 $hash= strtolower($hash);
2420 // Get all available encryption Methods
2422 // NON STATIC CALL :)
2423 $tmp = new passwordMethod(session::get('config'));
2424 $available = $tmp->get_available_methods();
2426 // read current password entry for $dn, to detect the encryption Method
2427 $ldap = $config->get_ldap_link();
2428 $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2429 $attrs = $ldap->fetch ();
2431 // Check if user account was deactivated, indicated by ! after } ... {crypt}!###
2432 if(isset($attrs['userPassword'][0]) && preg_match("/^[^\}]*+\}!/",$attrs['userPassword'][0])){
2433 $deactivated = TRUE;
2434 }else{
2435 $deactivated = FALSE;
2436 }
2438 /* Is ensure that clear passwords will stay clear */
2439 if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2440 $hash = "clear";
2441 }
2443 // Detect the encryption Method
2444 if ( (isset($attrs['userPassword'][0]) && preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) || $hash != ""){
2446 /* Check for supported algorithm */
2447 mt_srand((double) microtime()*1000000);
2449 /* Extract used hash */
2450 if ($hash == ""){
2451 $hash= strtolower($matches[1]);
2452 }
2454 $test = new $available[$hash]($config);
2456 } else {
2457 // User MD5 by default
2458 $hash= "md5";
2459 $test = new $available['md5']($config);
2460 }
2462 /* Feed password backends with information */
2463 $test->dn= $dn;
2464 $test->attrs= $attrs;
2465 $newpass= $test->generate_hash($password);
2467 // Update shadow timestamp?
2468 if (isset($attrs["shadowLastChange"][0])){
2469 $shadow= (int)(date("U") / 86400);
2470 } else {
2471 $shadow= 0;
2472 }
2474 // Write back modified entry
2475 $ldap->cd($dn);
2476 $attrs= array();
2478 // Not for groups
2479 if ($mode == 0){
2481 if ($shadow != 0){
2482 $attrs['shadowLastChange']= $shadow;
2483 }
2485 // Create SMB Password
2486 $attrs= generate_smb_nt_hash($password);
2487 }
2489 /* Readd ! if user was deactivated */
2490 if($deactivated){
2491 $newpass = preg_replace("/(^[^\}]+\})(.*$)/","\\1!\\2",$newpass);
2492 }
2494 $attrs['userPassword']= array();
2495 $attrs['userPassword']= $newpass;
2497 $ldap->modify($attrs);
2499 new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2501 if (!$ldap->success()) {
2502 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, ERROR_DIALOG));
2503 } else {
2505 /* Run backend method for change/create */
2506 $test->set_password($password);
2508 /* Find postmodify entries for this class */
2509 $command= $config->search("password", "POSTMODIFY",array('menu'));
2511 if ($command != ""){
2512 /* Walk through attribute list */
2513 $command= preg_replace("/%userPassword/", $password, $command);
2514 $command= preg_replace("/%dn/", $dn, $command);
2516 if (check_command($command)){
2517 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2518 exec($command);
2519 } else {
2520 $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2521 msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2522 }
2523 }
2524 }
2525 }
2528 // Return something like array['sambaLMPassword']= "lalla..."
2529 function generate_smb_nt_hash($password)
2530 {
2531 global $config;
2533 # Try to use gosa-si?
2534 if (isset($config->current['GOSA_SI'])){
2535 $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
2536 if (isset($res['XML']['HASH'])){
2537 $hash= $res['XML']['HASH'];
2538 } else {
2539 $hash= "";
2540 }
2541 } else {
2542 $tmp= $config->data['MAIN']['SMBHASH']." ".escapeshellarg($password);
2543 @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2545 exec($tmp, $ar);
2546 flush();
2547 reset($ar);
2548 $hash= current($ar);
2549 }
2551 if ($hash == "") {
2552 msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
2553 return ("");
2554 }
2556 list($lm,$nt)= split (":", trim($hash));
2558 if ($config->current['SAMBAVERSION'] == 3) {
2559 $attrs['sambaLMPassword']= $lm;
2560 $attrs['sambaNTPassword']= $nt;
2561 $attrs['sambaPwdLastSet']= date('U');
2562 $attrs['sambaBadPasswordCount']= "0";
2563 $attrs['sambaBadPasswordTime']= "0";
2564 } else {
2565 $attrs['lmPassword']= $lm;
2566 $attrs['ntPassword']= $nt;
2567 $attrs['pwdLastSet']= date('U');
2568 }
2569 return($attrs);
2570 }
2573 function crypt_single($string,$enc_type )
2574 {
2575 return( passwordMethod::crypt_single_str($string,$enc_type));
2576 }
2579 function getEntryCSN($dn)
2580 {
2581 global $config;
2582 if(empty($dn) || !is_object($config)){
2583 return("");
2584 }
2586 /* Get attribute that we should use as serial number */
2587 if(isset($config->current['UNIQ_IDENTIFIER'])){
2588 $attr = $config->current['UNIQ_IDENTIFIER'];
2589 }elseif(isset($config->data['MAIN']['UNIQ_IDENTIFIER'])){
2590 $attr = $config->data['MAIN']['UNIQ_IDENTIFIER'];
2591 }
2592 if(!empty($attr)){
2593 $ldap = $config->get_ldap_link();
2594 $ldap->cat($dn,array($attr));
2595 $csn = $ldap->fetch();
2596 if(isset($csn[$attr][0])){
2597 return($csn[$attr][0]);
2598 }
2599 }
2600 return("");
2601 }
2604 /* Add a given objectClass to an attrs entry */
2605 function add_objectClass($classes, &$attrs)
2606 {
2607 if (is_array($classes)){
2608 $list= $classes;
2609 } else {
2610 $list= array($classes);
2611 }
2613 foreach ($list as $class){
2614 $attrs['objectClass'][]= $class;
2615 }
2616 }
2619 /* Removes a given objectClass from the attrs entry */
2620 function remove_objectClass($classes, &$attrs)
2621 {
2622 if (isset($attrs['objectClass'])){
2623 /* Array? */
2624 if (is_array($classes)){
2625 $list= $classes;
2626 } else {
2627 $list= array($classes);
2628 }
2630 $tmp= array();
2631 foreach ($attrs['objectClass'] as $oc) {
2632 foreach ($list as $class){
2633 if ($oc != $class){
2634 $tmp[]= $oc;
2635 }
2636 }
2637 }
2638 $attrs['objectClass']= $tmp;
2639 }
2640 }
2642 /*! \brief Initialize a file download with given content, name and data type.
2643 * @param data String The content to send.
2644 * @param name String The name of the file.
2645 * @param type String The content identifier, default value is "application/octet-stream";
2646 */
2647 function send_binary_content($data,$name,$type = "application/octet-stream")
2648 {
2649 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
2650 header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
2651 header("Cache-Control: no-cache");
2652 header("Pragma: no-cache");
2653 header("Cache-Control: post-check=0, pre-check=0");
2654 header("Content-type: ".$type."");
2656 /* force download dialog */
2657 if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
2658 header('Content-Disposition: filename="'.$name.'"');
2659 } else {
2660 header('Content-Disposition: attachment; filename="'.$name.'"');
2661 }
2663 echo $data;
2664 exit();
2665 }
2668 /*! \brief Encode special string characters so we can use the string in \
2669 HTML output, without breaking quotes.
2670 @param The String we want to encode.
2671 @return The encoded String
2672 */
2673 function xmlentities($str)
2674 {
2675 return (htmlentities($str,ENT_QUOTES));
2676 }
2678 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2679 ?>