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");
26 define ("CONFIG_TEMPLATE_DIR", "../contrib/");
27 define ("TEMP_DIR","/var/cache/gosa/tmp");
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 global $config;
1098 $dn = preg_replace("/".normalizePreg($config->current['BASE'])."$/i","",$dn);
1099 if(empty($dn)) return("/");
1101 foreach (split(',', $dn) as $rdn){
1103 /* We're only interested in organizational units... */
1104 if (substr($rdn,0,3) == 'ou='){
1105 $dep= substr($rdn,3)."/$dep";
1106 }
1108 /* ... and location objects */
1109 if (substr($rdn,0,2) == 'l='){
1110 $dep= substr($rdn,2)."/$dep";
1111 }
1112 }
1114 /* Return and remove accidently trailing slashes */
1115 return rtrim($dep, "/");
1116 }
1119 /* Strip off the last sub department part of a '/level1/level2/.../'
1120 * style value. It removes the trailing '/', too. */
1121 function get_sub_department($value)
1122 {
1123 return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1124 }
1127 function get_ou($name)
1128 {
1129 global $config;
1131 $map = array(
1132 "ogroupou" => "ou=groups,",
1133 "applicationou" => "ou=apps,",
1134 "systemsou" => "ou=systems,",
1135 "serverou" => "ou=servers,ou=systems,",
1136 "terminalou" => "ou=terminals,ou=systems,",
1137 "workstationou" => "ou=workstations,ou=systems,",
1138 "printerou" => "ou=printers,ou=systems,",
1139 "phoneou" => "ou=phones,ou=systems,",
1140 "componentou" => "ou=netdevices,ou=systems,",
1141 "blocklistou" => "ou=gofax,ou=systems,",
1142 "incomingou" => "ou=incoming,",
1143 "aclroleou" => "ou=aclroles,",
1144 "macroou" => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1145 "conferenceou" => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1147 "faiou" => "ou=fai,ou=configs,ou=systems,",
1148 "faiscriptou" => "ou=scripts,",
1149 "faihookou" => "ou=hooks,",
1150 "faitemplateou" => "ou=templates,",
1151 "faivariableou" => "ou=variables,",
1152 "faiprofileou" => "ou=profiles,",
1153 "faipackageou" => "ou=packages,",
1154 "faipartitionou"=> "ou=disk,",
1156 "deviceou" => "ou=devices,",
1157 "mimetypeou" => "ou=mime,");
1159 /* Preset ou... */
1160 if (isset($config->current[strtoupper($name)])){
1161 $ou= $config->current[strtoupper($name)];
1162 } elseif (isset($map[$name])) {
1163 $ou = $map[$name];
1164 return($ou);
1165 } else {
1166 trigger_error("No department mapping found for type ".$name);
1167 return "";
1168 }
1171 if ($ou != ""){
1172 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1173 $ou = @LDAP::convert("ou=$ou");
1174 } else {
1175 $ou = @LDAP::convert("$ou");
1176 }
1178 if(preg_match("/".normalizePreg($config->current['BASE'])."$/",$ou)){
1179 return($ou);
1180 }else{
1181 return("$ou,");
1182 }
1184 } else {
1185 return "";
1186 }
1187 }
1190 function get_people_ou()
1191 {
1192 return (get_ou("PEOPLE"));
1193 }
1196 function get_groups_ou()
1197 {
1198 return (get_ou("GROUPS"));
1199 }
1202 function get_winstations_ou()
1203 {
1204 return (get_ou("WINSTATIONS"));
1205 }
1208 function get_base_from_people($dn)
1209 {
1210 global $config;
1212 $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
1213 $base= preg_replace($pattern, '', $dn);
1215 /* Set to base, if we're not on a correct subtree */
1216 if (!isset($config->idepartments[$base])){
1217 $base= $config->current['BASE'];
1218 }
1220 return ($base);
1221 }
1224 function strict_uid_mode()
1225 {
1226 global $config;
1228 return !(isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT']));
1229 }
1232 function get_uid_regexp()
1233 {
1234 /* STRICT adds spaces and case insenstivity to the uid check.
1235 This is dangerous and should not be used. */
1236 if (strict_uid_mode()){
1237 return "^[a-z0-9_-]+$";
1238 } else {
1239 return "^[a-zA-Z0-9 _.-]+$";
1240 }
1241 }
1244 function gen_locked_message($user, $dn)
1245 {
1246 global $plug, $config;
1248 session::set('dn', $dn);
1249 $remove= false;
1251 /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1252 if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1254 $LOCK_VARS_USED = array();
1255 $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1257 foreach($LOCK_VARS_TO_USE as $name){
1259 if(empty($name)){
1260 continue;
1261 }
1263 foreach($_POST as $Pname => $Pvalue){
1264 if(preg_match($name,$Pname)){
1265 $LOCK_VARS_USED[$Pname] = $_POST[$Pname];
1266 }
1267 }
1269 foreach($_GET as $Pname => $Pvalue){
1270 if(preg_match($name,$Pname)){
1271 $LOCK_VARS_USED[$Pname] = $_GET[$Pname];
1272 }
1273 }
1274 }
1275 session::set('LOCK_VARS_TO_USE',array());
1276 session::set('LOCK_VARS_USED' , $LOCK_VARS_USED);
1277 }
1279 /* Prepare and show template */
1280 $smarty= get_smarty();
1282 if(is_array($dn)){
1283 $msg = "<pre>";
1284 foreach($dn as $sub_dn){
1285 $msg .= "\n".$sub_dn.", ";
1286 }
1287 $msg = preg_replace("/, $/","</pre>",$msg);
1288 }else{
1289 $msg = $dn;
1290 }
1292 $smarty->assign ("dn", $msg);
1293 if ($remove){
1294 $smarty->assign ("action", _("Continue anyway"));
1295 } else {
1296 $smarty->assign ("action", _("Edit anyway"));
1297 }
1298 $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries %s"), "<b>".$msg."</b>", ""));
1300 return ($smarty->fetch (get_template_path('islocked.tpl')));
1301 }
1304 function to_string ($value)
1305 {
1306 /* If this is an array, generate a text blob */
1307 if (is_array($value)){
1308 $ret= "";
1309 foreach ($value as $line){
1310 $ret.= $line."<br>\n";
1311 }
1312 return ($ret);
1313 } else {
1314 return ($value);
1315 }
1316 }
1319 function get_printer_list()
1320 {
1321 global $config;
1322 $res = array();
1323 $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1324 foreach($data as $attrs ){
1325 $res[$attrs['cn'][0]] = $attrs['cn'][0];
1326 }
1327 return $res;
1328 }
1331 function rewrite($s)
1332 {
1333 global $REWRITE;
1335 foreach ($REWRITE as $key => $val){
1336 $s= preg_replace("/$key/", "$val", $s);
1337 }
1339 return ($s);
1340 }
1343 function dn2base($dn)
1344 {
1345 global $config;
1347 if (get_people_ou() != ""){
1348 $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1349 }
1350 if (get_groups_ou() != ""){
1351 $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1352 }
1353 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1355 return ($base);
1356 }
1360 function check_command($cmdline)
1361 {
1362 $cmd= preg_replace("/ .*$/", "", $cmdline);
1364 /* Check if command exists in filesystem */
1365 if (!file_exists($cmd)){
1366 return (FALSE);
1367 }
1369 /* Check if command is executable */
1370 if (!is_executable($cmd)){
1371 return (FALSE);
1372 }
1374 return (TRUE);
1375 }
1378 function print_header($image, $headline, $info= "")
1379 {
1380 $display= "<div class=\"plugtop\">\n";
1381 $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";
1382 $display.= "</div>\n";
1384 if ($info != ""){
1385 $display.= "<div class=\"pluginfo\">\n";
1386 $display.= "$info";
1387 $display.= "</div>\n";
1388 } else {
1389 $display.= "<div style=\"height:5px;\">\n";
1390 $display.= " ";
1391 $display.= "</div>\n";
1392 }
1393 return ($display);
1394 }
1397 function range_selector($dcnt,$start,$range=25,$post_var=false)
1398 {
1400 /* Entries shown left and right from the selected entry */
1401 $max_entries= 10;
1403 /* Initialize and take care that max_entries is even */
1404 $output="";
1405 if ($max_entries & 1){
1406 $max_entries++;
1407 }
1409 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1410 $range= $_POST[$post_var];
1411 }
1413 /* Prevent output to start or end out of range */
1414 if ($start < 0 ){
1415 $start= 0 ;
1416 }
1417 if ($start >= $dcnt){
1418 $start= $range * (int)(($dcnt / $range) + 0.5);
1419 }
1421 $numpages= (($dcnt / $range));
1422 if(((int)($numpages))!=($numpages)){
1423 $numpages = (int)$numpages + 1;
1424 }
1425 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1426 return ("");
1427 }
1428 $ppage= (int)(($start / $range) + 0.5);
1431 /* Align selected page to +/- max_entries/2 */
1432 $begin= $ppage - $max_entries/2;
1433 $end= $ppage + $max_entries/2;
1435 /* Adjust begin/end, so that the selected value is somewhere in
1436 the middle and the size is max_entries if possible */
1437 if ($begin < 0){
1438 $end-= $begin + 1;
1439 $begin= 0;
1440 }
1441 if ($end > $numpages) {
1442 $end= $numpages;
1443 }
1444 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1445 $begin= $end - $max_entries;
1446 }
1448 if($post_var){
1449 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1450 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1451 }else{
1452 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1453 }
1455 /* Draw decrement */
1456 if ($start > 0 ) {
1457 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1458 (($start-$range))."\">".
1459 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1460 }
1462 /* Draw pages */
1463 for ($i= $begin; $i < $end; $i++) {
1464 if ($ppage == $i){
1465 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1466 validate($_GET['plug'])."&start=".
1467 ($i*$range)."\"> ".($i+1)." </a>";
1468 } else {
1469 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1470 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1471 }
1472 }
1474 /* Draw increment */
1475 if($start < ($dcnt-$range)) {
1476 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1477 (($start+($range)))."\">".
1478 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1479 }
1481 if(($post_var)&&($numpages)){
1482 $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()'>";
1483 foreach(array(20,50,100,200,"all") as $num){
1484 if($num == "all"){
1485 $var = 10000;
1486 }else{
1487 $var = $num;
1488 }
1489 if($var == $range){
1490 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1491 }else{
1492 $output.="\n<option value='".$var."'>".$num."</option>";
1493 }
1494 }
1495 $output.= "</select></td></tr></table></div>";
1496 }else{
1497 $output.= "</div>";
1498 }
1500 return($output);
1501 }
1504 function apply_filter()
1505 {
1506 $apply= "";
1508 $apply= ''.
1509 '<table summary="" width="100%" style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1510 '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1512 return ($apply);
1513 }
1516 function back_to_main()
1517 {
1518 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1519 msgPool::backButton().'"></p><input type="hidden" name="ignore">';
1521 return ($string);
1522 }
1525 function normalize_netmask($netmask)
1526 {
1527 /* Check for notation of netmask */
1528 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1529 $num= (int)($netmask);
1530 $netmask= "";
1532 for ($byte= 0; $byte<4; $byte++){
1533 $result=0;
1535 for ($i= 7; $i>=0; $i--){
1536 if ($num-- > 0){
1537 $result+= pow(2,$i);
1538 }
1539 }
1541 $netmask.= $result.".";
1542 }
1544 return (preg_replace('/\.$/', '', $netmask));
1545 }
1547 return ($netmask);
1548 }
1551 function netmask_to_bits($netmask)
1552 {
1553 list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1554 $res= 0;
1556 for ($n= 0; $n<4; $n++){
1557 $start= 255;
1558 $name= "nm$n";
1560 for ($i= 0; $i<8; $i++){
1561 if ($start == (int)($$name)){
1562 $res+= 8 - $i;
1563 break;
1564 }
1565 $start-= pow(2,$i);
1566 }
1567 }
1569 return ($res);
1570 }
1573 function recurse($rule, $variables)
1574 {
1575 $result= array();
1577 if (!count($variables)){
1578 return array($rule);
1579 }
1581 reset($variables);
1582 $key= key($variables);
1583 $val= current($variables);
1584 unset ($variables[$key]);
1586 foreach($val as $possibility){
1587 $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1588 $result= array_merge($result, recurse($nrule, $variables));
1589 }
1591 return ($result);
1592 }
1595 function expand_id($rule, $attributes)
1596 {
1597 /* Check for id rule */
1598 if(preg_match('/^id(:|#)\d+$/',$rule)){
1599 return (array("\{$rule}"));
1600 }
1602 /* Check for clean attribute */
1603 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1604 $rule= preg_replace('/^%/', '', $rule);
1605 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1606 return (array($val));
1607 }
1609 /* Check for attribute with parameters */
1610 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1611 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1612 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1613 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1614 $start= preg_replace ('/-.*$/', '', $param);
1615 $stop = preg_replace ('/^[^-]+-/', '', $param);
1617 /* Assemble results */
1618 $result= array();
1619 for ($i= $start; $i<= $stop; $i++){
1620 $result[]= substr($val, 0, $i);
1621 }
1622 return ($result);
1623 }
1625 echo "Error in idgen string: don't know how to handle rule $rule.\n";
1626 return (array($rule));
1627 }
1630 function gen_uids($rule, $attributes)
1631 {
1632 global $config;
1634 /* Search for keys and fill the variables array with all
1635 possible values for that key. */
1636 $part= "";
1637 $trigger= false;
1638 $stripped= "";
1639 $variables= array();
1641 for ($pos= 0; $pos < strlen($rule); $pos++){
1643 if ($rule[$pos] == "{" ){
1644 $trigger= true;
1645 $part= "";
1646 continue;
1647 }
1649 if ($rule[$pos] == "}" ){
1650 $variables[$pos]= expand_id($part, $attributes);
1651 $stripped.= "{".$pos."}";
1652 $trigger= false;
1653 continue;
1654 }
1656 if ($trigger){
1657 $part.= $rule[$pos];
1658 } else {
1659 $stripped.= $rule[$pos];
1660 }
1661 }
1663 /* Recurse through all possible combinations */
1664 $proposed= recurse($stripped, $variables);
1666 /* Get list of used ID's */
1667 $used= array();
1668 $ldap= $config->get_ldap_link();
1669 $ldap->cd($config->current['BASE']);
1670 $ldap->search('(uid=*)');
1672 while($attrs= $ldap->fetch()){
1673 $used[]= $attrs['uid'][0];
1674 }
1676 /* Remove used uids and watch out for id tags */
1677 $ret= array();
1678 foreach($proposed as $uid){
1680 /* Check for id tag and modify uid if needed */
1681 if(preg_match('/\{id:\d+}/',$uid)){
1682 $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1684 for ($i= 0; $i < pow(10,$size); $i++){
1685 $number= sprintf("%0".$size."d", $i);
1686 $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1687 if (!in_array($res, $used)){
1688 $uid= $res;
1689 break;
1690 }
1691 }
1692 }
1694 if(preg_match('/\{id#\d+}/',$uid)){
1695 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1697 while (true){
1698 mt_srand((double) microtime()*1000000);
1699 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1700 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1701 if (!in_array($res, $used)){
1702 $uid= $res;
1703 break;
1704 }
1705 }
1706 }
1708 /* Don't assign used ones */
1709 if (!in_array($uid, $used)){
1710 $ret[]= $uid;
1711 }
1712 }
1714 return(array_unique($ret));
1715 }
1718 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1719 Need to convert... */
1720 function to_byte($value) {
1721 $value= strtolower(trim($value));
1723 if(!is_numeric(substr($value, -1))) {
1725 switch(substr($value, -1)) {
1726 case 'g':
1727 $mult= 1073741824;
1728 break;
1729 case 'm':
1730 $mult= 1048576;
1731 break;
1732 case 'k':
1733 $mult= 1024;
1734 break;
1735 }
1737 return ($mult * (int)substr($value, 0, -1));
1738 } else {
1739 return $value;
1740 }
1741 }
1744 function in_array_ics($value, $items)
1745 {
1746 if (!is_array($items)){
1747 return (FALSE);
1748 }
1750 foreach ($items as $item){
1751 if (strcasecmp($item, $value) == 0) {
1752 return (TRUE);
1753 }
1754 }
1756 return (FALSE);
1757 }
1760 function generate_alphabet($count= 10)
1761 {
1762 $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1763 $alphabet= "";
1764 $c= 0;
1766 /* Fill cells with charaters */
1767 for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1768 if ($c == 0){
1769 $alphabet.= "<tr>";
1770 }
1772 $ch = mb_substr($characters, $i, 1, "UTF8");
1773 $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1774 validate($_GET['plug'])."&search=".$ch."\"> ".$ch." </a></td>";
1776 if ($c++ == $count){
1777 $alphabet.= "</tr>";
1778 $c= 0;
1779 }
1780 }
1782 /* Fill remaining cells */
1783 while ($c++ <= $count){
1784 $alphabet.= "<td> </td>";
1785 }
1787 return ($alphabet);
1788 }
1791 function validate($string)
1792 {
1793 return (strip_tags(preg_replace('/\0/', '', $string)));
1794 }
1797 function get_gosa_version()
1798 {
1799 global $svn_revision, $svn_path;
1801 /* Extract informations */
1802 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1804 /* Release or development? */
1805 if (preg_match('%/gosa/trunk/%', $svn_path)){
1806 return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1807 } else {
1808 $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1809 return (sprintf(_("GOsa $release"), $revision));
1810 }
1811 }
1814 function rmdirRecursive($path, $followLinks=false) {
1815 $dir= opendir($path);
1816 while($entry= readdir($dir)) {
1817 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1818 unlink($path."/".$entry);
1819 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1820 rmdirRecursive($path."/".$entry);
1821 }
1822 }
1823 closedir($dir);
1824 return rmdir($path);
1825 }
1828 function scan_directory($path,$sort_desc=false)
1829 {
1830 $ret = false;
1832 /* is this a dir ? */
1833 if(is_dir($path)) {
1835 /* is this path a readable one */
1836 if(is_readable($path)){
1838 /* Get contents and write it into an array */
1839 $ret = array();
1841 $dir = opendir($path);
1843 /* Is this a correct result ?*/
1844 if($dir){
1845 while($fp = readdir($dir))
1846 $ret[]= $fp;
1847 }
1848 }
1849 }
1850 /* Sort array ascending , like scandir */
1851 sort($ret);
1853 /* Sort descending if parameter is sort_desc is set */
1854 if($sort_desc) {
1855 $ret = array_reverse($ret);
1856 }
1858 return($ret);
1859 }
1862 function clean_smarty_compile_dir($directory)
1863 {
1864 global $svn_revision;
1866 if(is_dir($directory) && is_readable($directory)) {
1867 // Set revision filename to REVISION
1868 $revision_file= $directory."/REVISION";
1870 /* Is there a stamp containing the current revision? */
1871 if(!file_exists($revision_file)) {
1872 // create revision file
1873 create_revision($revision_file, $svn_revision);
1874 } else {
1875 # check for "$config->...['CONFIG']/revision" and the
1876 # contents should match the revision number
1877 if(!compare_revision($revision_file, $svn_revision)){
1878 // If revision differs, clean compile directory
1879 foreach(scan_directory($directory) as $file) {
1880 if(($file==".")||($file=="..")) continue;
1881 if( is_file($directory."/".$file) &&
1882 is_writable($directory."/".$file)) {
1883 // delete file
1884 if(!unlink($directory."/".$file)) {
1885 msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
1886 // This should never be reached
1887 }
1888 } elseif(is_dir($directory."/".$file) &&
1889 is_writable($directory."/".$file)) {
1890 // Just recursively delete it
1891 rmdirRecursive($directory."/".$file);
1892 }
1893 }
1894 // We should now create a fresh revision file
1895 clean_smarty_compile_dir($directory);
1896 } else {
1897 // Revision matches, nothing to do
1898 }
1899 }
1900 } else {
1901 // Smarty compile dir is not accessible
1902 // (Smarty will warn about this)
1903 }
1904 }
1907 function create_revision($revision_file, $revision)
1908 {
1909 $result= false;
1911 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1912 if($fh= fopen($revision_file, "w")) {
1913 if(fwrite($fh, $revision)) {
1914 $result= true;
1915 }
1916 }
1917 fclose($fh);
1918 } else {
1919 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1920 }
1922 return $result;
1923 }
1926 function compare_revision($revision_file, $revision)
1927 {
1928 // false means revision differs
1929 $result= false;
1931 if(file_exists($revision_file) && is_readable($revision_file)) {
1932 // Open file
1933 if($fh= fopen($revision_file, "r")) {
1934 // Compare File contents with current revision
1935 if($revision == fread($fh, filesize($revision_file))) {
1936 $result= true;
1937 }
1938 } else {
1939 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1940 }
1941 // Close file
1942 fclose($fh);
1943 }
1945 return $result;
1946 }
1949 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1950 {
1951 $str = ""; // Our return value will be saved in this var
1953 $color = dechex($percentage+150);
1954 $color2 = dechex(150 - $percentage);
1955 $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1957 $progress = (int)(($percentage /100)*$width);
1959 /* Abort printing out percentage, if divs are to small */
1962 /* If theres a better solution for this, use it... */
1963 $str = "
1964 <div style=\" width:".($width)."px;
1965 height:".($height)."px;
1966 background-color:#000000;
1967 padding:1px;\">
1969 <div style=\" width:".($width)."px;
1970 background-color:#$bgcolor;
1971 height:".($height)."px;\">
1973 <div style=\" width:".$progress."px;
1974 height:".$height."px;
1975 background-color:#".$color2.$color2.$color."; \">";
1978 if(($height >10)&&($showvalue)){
1979 $str.= "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1980 <b>".$percentage."%</b>
1981 </font>";
1982 }
1984 $str.= "</div></div></div>";
1986 return($str);
1987 }
1990 function array_key_ics($ikey, $items)
1991 {
1992 /* Gather keys, make them lowercase */
1993 $tmp= array();
1994 foreach ($items as $key => $value){
1995 $tmp[strtolower($key)]= $key;
1996 }
1998 if (isset($tmp[strtolower($ikey)])){
1999 return($tmp[strtolower($ikey)]);
2000 }
2002 return ("");
2003 }
2006 function array_differs($src, $dst)
2007 {
2008 /* If the count is differing, the arrays differ */
2009 if (count ($src) != count ($dst)){
2010 return (TRUE);
2011 }
2013 /* So the count is the same - lets check the contents */
2014 $differs= FALSE;
2015 foreach($src as $value){
2016 if (!in_array($value, $dst)){
2017 $differs= TRUE;
2018 }
2019 }
2021 return ($differs);
2022 }
2025 function saveFilter($a_filter, $values)
2026 {
2027 if (isset($_POST['regexit'])){
2028 $a_filter["regex"]= $_POST['regexit'];
2030 foreach($values as $type){
2031 if (isset($_POST[$type])) {
2032 $a_filter[$type]= "checked";
2033 } else {
2034 $a_filter[$type]= "";
2035 }
2036 }
2037 }
2039 /* React on alphabet links if needed */
2040 if (isset($_GET['search'])){
2041 $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2042 if ($s == "**"){
2043 $s= "*";
2044 }
2045 $a_filter['regex']= $s;
2046 }
2048 return ($a_filter);
2049 }
2052 /* Escape all preg_* relevant characters */
2053 function normalizePreg($input)
2054 {
2055 return (addcslashes($input, '[]()|/.*+-'));
2056 }
2059 /* Escape all LDAP filter relevant characters */
2060 function normalizeLdap($input)
2061 {
2062 return (addcslashes($input, '()|'));
2063 }
2066 /* Resturns the difference between to microtime() results in float */
2067 function get_MicroTimeDiff($start , $stop)
2068 {
2069 $a = split("\ ",$start);
2070 $b = split("\ ",$stop);
2072 $secs = $b[1] - $a[1];
2073 $msecs= $b[0] - $a[0];
2075 $ret = (float) ($secs+ $msecs);
2076 return($ret);
2077 }
2080 function get_base_dir()
2081 {
2082 global $BASE_DIR;
2084 return $BASE_DIR;
2085 }
2088 function obj_is_readable($dn, $object, $attribute)
2089 {
2090 global $ui;
2092 return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2093 }
2096 function obj_is_writable($dn, $object, $attribute)
2097 {
2098 global $ui;
2100 return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2101 }
2104 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2105 {
2106 /* Initialize variables */
2107 $ret = array("count" => 0); // Set count to 0
2108 $next = true; // if false, then skip next loops and return
2109 $cnt = 0; // Current number of loops
2110 $max = 100; // Just for security, prevent looops
2111 $ldap = NULL; // To check if created result a valid
2112 $keep = ""; // save last failed parse string
2114 /* Check each parsed dn in ldap ? */
2115 if($config!==NULL && $verify_in_ldap){
2116 $ldap = $config->get_ldap_link();
2117 }
2119 /* Lets start */
2120 $called = false;
2121 while(preg_match("/,/",$dn) && $next && $cnt < $max){
2123 $cnt ++;
2124 if(!preg_match("/,/",$dn)){
2125 $next = false;
2126 }
2127 $object = preg_replace("/[,].*$/","",$dn);
2128 $dn = preg_replace("/^[^,]+,/","",$dn);
2130 $called = true;
2132 /* Check if current dn is valid */
2133 if($ldap!==NULL){
2134 $ldap->cd($dn);
2135 $ldap->cat($dn,array("dn"));
2136 if($ldap->count()){
2137 $ret[] = $keep.$object;
2138 $keep = "";
2139 }else{
2140 $keep .= $object.",";
2141 }
2142 }else{
2143 $ret[] = $keep.$object;
2144 $keep = "";
2145 }
2146 }
2148 /* No dn was posted */
2149 if($cnt == 0 && !empty($dn)){
2150 $ret[] = $dn;
2151 }
2153 /* Append the rest */
2154 $test = $keep.$dn;
2155 if($called && !empty($test)){
2156 $ret[] = $keep.$dn;
2157 }
2158 $ret['count'] = count($ret) - 1;
2160 return($ret);
2161 }
2164 function get_base_from_hook($dn, $attrib)
2165 {
2166 global $config;
2168 if (isset($config->current['BASE_HOOK'])){
2170 /* Call hook script - if present */
2171 $command= $config->current['BASE_HOOK'];
2173 if ($command != ""){
2174 $command.= " '".LDAP::fix($dn)."' $attrib";
2175 if (check_command($command)){
2176 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2177 exec($command, $output);
2178 if (preg_match("/^[0-9]+$/", $output[0])){
2179 return ($output[0]);
2180 } else {
2181 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base!"), WARNING_DIALOG);
2182 return ($config->current['UIDBASE']);
2183 }
2184 } else {
2185 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base!"), WARNING_DIALOG);
2186 return ($config->current['UIDBASE']);
2187 }
2189 } else {
2191 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base!"), WARNING_DIALOG);
2192 return ($config->current['UIDBASE']);
2194 }
2195 }
2196 }
2199 function check_schema_version($class, $version)
2200 {
2201 return preg_match("/\(v$version\)/", $class['DESC']);
2202 }
2205 function check_schema($cfg,$rfc2307bis = FALSE)
2206 {
2207 $messages= array();
2209 /* Get objectclasses */
2210 $ldap = new ldapMultiplexer(new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']));
2211 $objectclasses = $ldap->get_objectclasses();
2212 if(count($objectclasses) == 0){
2213 msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2214 }
2216 /* This is the default block used for each entry.
2217 * to avoid unset indexes.
2218 */
2219 $def_check = array("REQUIRED_VERSION" => "0",
2220 "SCHEMA_FILES" => array(),
2221 "CLASSES_REQUIRED" => array(),
2222 "STATUS" => FALSE,
2223 "IS_MUST_HAVE" => FALSE,
2224 "MSG" => "",
2225 "INFO" => "");#_("There is currently no information specified for this schema extension."));
2227 /* The gosa base schema */
2228 $checks['gosaObject'] = $def_check;
2229 $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2230 $checks['gosaObject']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2231 $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2232 $checks['gosaObject']['IS_MUST_HAVE'] = TRUE;
2234 /* GOsa Account class */
2235 $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2236 $checks["gosaAccount"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2237 $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2238 $checks["gosaAccount"]["IS_MUST_HAVE"] = TRUE;
2239 $checks["gosaAccount"]["INFO"] = _("Used to store account specific informations.");
2241 /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2242 $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2243 $checks["gosaLockEntry"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2244 $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2245 $checks["gosaLockEntry"]["IS_MUST_HAVE"] = TRUE;
2246 $checks["gosaLockEntry"]["INFO"] = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2248 /* Some other checks */
2249 foreach(array(
2250 "gosaCacheEntry" => array("version" => "2.4"),
2251 "gosaDepartment" => array("version" => "2.4"),
2252 "goFaxAccount" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2253 "goFaxSBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2254 "goFaxRBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2255 "gosaUserTemplate" => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2256 "gosaMailAccount" => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2257 "gosaProxyAccount" => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2258 "gosaApplication" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2259 "gosaApplicationGroup" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2260 "GOhard" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2261 "gotoTerminal" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2262 "goServer" => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2263 "goTerminalServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2264 "goShareServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2265 "goNtpServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2266 "goSyslogServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2267 "goLdapServer" => array("version" => "2.4"),
2268 "goCupsServer" => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2269 "goImapServer" => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3. schema"),
2270 "goKrbServer" => array("version" => "2.4"),
2271 "goFaxServer" => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2272 ) as $name => $values){
2274 $checks[$name] = $def_check;
2275 if(isset($values['version'])){
2276 $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2277 }
2278 if(isset($values['file'])){
2279 $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2280 }
2281 $checks[$name]["CLASSES_REQUIRED"] = array($name);
2282 }
2283 foreach($checks as $name => $value){
2284 foreach($value['CLASSES_REQUIRED'] as $class){
2286 if(!isset($objectclasses[$name])){
2287 $checks[$name]['STATUS'] = FALSE;
2288 if($value['IS_MUST_HAVE']){
2289 $checks[$name]['MSG'] = sprintf(_("Missing required object class '%s'!"),$class);
2290 }else{
2291 $checks[$name]['MSG'] = sprintf(_("Missing optional object class '%s'!"),$class);
2292 }
2293 }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2294 $checks[$name]['STATUS'] = FALSE;
2296 if($value['IS_MUST_HAVE']){
2297 $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2298 }else{
2299 $checks[$name]['MSG'] = sprintf(_("Version mismatch for optional object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2300 }
2301 }else{
2302 $checks[$name]['STATUS'] = TRUE;
2303 $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2304 }
2305 }
2306 }
2308 $tmp = $objectclasses;
2310 /* The gosa base schema */
2311 $checks['posixGroup'] = $def_check;
2312 $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2313 $checks['posixGroup']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2314 $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2315 $checks['posixGroup']['STATUS'] = TRUE;
2316 $checks['posixGroup']['IS_MUST_HAVE'] = TRUE;
2317 $checks['posixGroup']['MSG'] = "";
2318 $checks['posixGroup']['INFO'] = "";
2320 /* Depending on selected rfc2307bis mode, we need different schema configurations */
2321 if(isset($tmp['posixGroup'])){
2323 if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2324 $checks['posixGroup']['STATUS'] = FALSE;
2325 $checks['posixGroup']['MSG'] = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema configuration do not support this option.");
2326 $checks['posixGroup']['INFO'] = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be AUXILIARY");
2327 }
2328 if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2329 $checks['posixGroup']['STATUS'] = FALSE;
2330 $checks['posixGroup']['MSG'] = _("Your schema is configured to support the rfc2307bis group, but you have disabled this option on the 'ldap setup' step.");
2331 $checks['posixGroup']['INFO'] = _("The objectClass 'posixGroup' must be STRUCTURAL");
2332 }
2333 }
2335 return($checks);
2336 }
2339 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2340 {
2341 $tmp = 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 $tmp2= array(
2354 "de_DE" => _("German"),
2355 "fr_FR" => _("French"),
2356 "it_IT" => _("Italian"),
2357 "es_ES" => _("Spanish"),
2358 "en_US" => _("English"),
2359 "nl_NL" => _("Dutch"),
2360 "pl_PL" => _("Polish"),
2361 "sv_SE" => _("Swedish"),
2362 "zh_CN" => _("Chinese"),
2363 "ru_RU" => _("Russian"));
2365 $ret = array();
2366 if($languages_in_own_language){
2368 $old_lang = setlocale(LC_ALL, 0);
2370 /* If the locale wasn't correclty set before, there may be an incorrect
2371 locale returned. Something like this:
2372 C_CTYPE=de_DE.UTF-8;LC_NUMERIC=C;LC_TIME=de_DE.UTF-8;LC ...
2373 Extract the locale name from this string and use it to restore old locale.
2374 */
2375 if(preg_match("/LC_CTYPE/",$old_lang)){
2376 $old_lang = preg_replace("/^.*LC_CTYPE=([^;]*).*$/","\\1",$old_lang);
2377 }
2379 foreach($tmp as $key => $name){
2380 $lang = $key.".UTF-8";
2381 setlocale(LC_ALL, $lang);
2382 if($strip_region_tag){
2383 $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2384 }else{
2385 $ret[$key] = _($name)." (".$tmp2[$key].")";
2386 }
2387 }
2388 setlocale(LC_ALL, $old_lang);
2389 }else{
2390 foreach($tmp as $key => $name){
2391 if($strip_region_tag){
2392 $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2393 }else{
2394 $ret[$key] = _($name);
2395 }
2396 }
2397 }
2398 return($ret);
2399 }
2402 /* Returns contents of the given POST variable and check magic quotes settings */
2403 function get_post($name)
2404 {
2405 if(!isset($_POST[$name])){
2406 trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2407 return(FALSE);
2408 }
2409 if(get_magic_quotes_gpc()){
2410 return(stripcslashes($_POST[$name]));
2411 }else{
2412 return($_POST[$name]);
2413 }
2414 }
2417 /* Return class name in correct case */
2418 function get_correct_class_name($cls)
2419 {
2420 global $class_mapping;
2421 if(isset($class_mapping) && is_array($class_mapping)){
2422 foreach($class_mapping as $class => $file){
2423 if(preg_match("/^".$cls."$/i",$class)){
2424 return($class);
2425 }
2426 }
2427 }
2428 return(FALSE);
2429 }
2432 // change_password, changes the Password, of the given dn
2433 function change_password ($dn, $password, $mode=0, $hash= "")
2434 {
2435 global $config;
2436 $newpass= "";
2438 /* Convert to lower. Methods are lowercase */
2439 $hash= strtolower($hash);
2441 // Get all available encryption Methods
2443 // NON STATIC CALL :)
2444 $methods = new passwordMethod(session::get('config'));
2445 $available = $methods->get_available_methods();
2447 // read current password entry for $dn, to detect the encryption Method
2448 $ldap = $config->get_ldap_link();
2449 $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2450 $attrs = $ldap->fetch ();
2452 // Check if user account was deactivated, indicated by ! after } ... {crypt}!###
2453 if(isset($attrs['userPassword'][0]) && preg_match("/^[^\}]*+\}!/",$attrs['userPassword'][0])){
2454 $deactivated = TRUE;
2455 }else{
2456 $deactivated = FALSE;
2457 }
2459 /* Is ensure that clear passwords will stay clear */
2460 if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2461 $hash = "clear";
2462 }
2464 // Detect the encryption Method
2465 if ( (isset($attrs['userPassword'][0]) && preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) || $hash != ""){
2467 /* Check for supported algorithm */
2468 mt_srand((double) microtime()*1000000);
2470 /* Extract used hash */
2471 if ($hash == ""){
2472 $test = passwordMethod::get_method($attrs['userPassword'][0],$dn);
2473 } else {
2474 $test = new $available[$hash]($config,$dn);
2475 $test->set_hash($hash);
2476 }
2478 } else {
2479 // User MD5 by default
2480 $hash= "md5";
2481 $test = new $available['md5']($config);
2482 }
2484 /* Feed password backends with information */
2485 $test->dn= $dn;
2486 $test->attrs= $attrs;
2487 $newpass= $test->generate_hash($password);
2489 // Update shadow timestamp?
2490 if (isset($attrs["shadowLastChange"][0])){
2491 $shadow= (int)(date("U") / 86400);
2492 } else {
2493 $shadow= 0;
2494 }
2496 // Write back modified entry
2497 $ldap->cd($dn);
2498 $attrs= array();
2500 // Not for groups
2501 if ($mode == 0){
2503 if ($shadow != 0){
2504 $attrs['shadowLastChange']= $shadow;
2505 }
2507 // Create SMB Password
2508 $attrs= generate_smb_nt_hash($password);
2509 }
2511 /* Read ! if user was deactivated */
2512 if($deactivated){
2513 $newpass = preg_replace("/(^[^\}]+\})(.*$)/","\\1!\\2",$newpass);
2514 }
2516 $attrs['userPassword']= array();
2517 $attrs['userPassword']= $newpass;
2519 $ldap->modify($attrs);
2521 new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2523 if (!$ldap->success()) {
2524 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, ERROR_DIALOG));
2525 } else {
2527 /* Run backend method for change/create */
2528 if(!$test->set_password($password)){
2529 return(FALSE);
2530 }
2532 /* Find postmodify entries for this class */
2533 $command= $config->search("password", "POSTMODIFY",array('menu'));
2535 if ($command != ""){
2536 /* Walk through attribute list */
2537 $command= preg_replace("/%userPassword/", $password, $command);
2538 $command= preg_replace("/%dn/", $dn, $command);
2540 if (check_command($command)){
2541 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2542 exec($command);
2543 } else {
2544 $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2545 msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2546 }
2547 }
2548 }
2549 return(TRUE);
2550 }
2553 // Return something like array['sambaLMPassword']= "lalla..."
2554 function generate_smb_nt_hash($password)
2555 {
2556 global $config;
2558 # Try to use gosa-si?
2559 if (isset($config->current['GOSA_SI'])){
2560 $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
2561 if (isset($res['XML']['HASH'])){
2562 $hash= $res['XML']['HASH'];
2563 } else {
2564 $hash= "";
2565 }
2566 } else {
2567 $tmp= $config->data['MAIN']['SMBHASH']." ".escapeshellarg($password);
2568 @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2570 exec($tmp, $ar);
2571 flush();
2572 reset($ar);
2573 $hash= current($ar);
2574 }
2576 if ($hash == "") {
2577 msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
2578 return ("");
2579 }
2581 list($lm,$nt)= split (":", trim($hash));
2583 if ($config->current['SAMBAVERSION'] == 3) {
2584 $attrs['sambaLMPassword']= $lm;
2585 $attrs['sambaNTPassword']= $nt;
2586 $attrs['sambaPwdLastSet']= date('U');
2587 $attrs['sambaBadPasswordCount']= "0";
2588 $attrs['sambaBadPasswordTime']= "0";
2589 } else {
2590 $attrs['lmPassword']= $lm;
2591 $attrs['ntPassword']= $nt;
2592 $attrs['pwdLastSet']= date('U');
2593 }
2594 return($attrs);
2595 }
2598 function getEntryCSN($dn)
2599 {
2600 global $config;
2601 if(empty($dn) || !is_object($config)){
2602 return("");
2603 }
2605 /* Get attribute that we should use as serial number */
2606 if(isset($config->current['UNIQ_IDENTIFIER'])){
2607 $attr = $config->current['UNIQ_IDENTIFIER'];
2608 }elseif(isset($config->data['MAIN']['UNIQ_IDENTIFIER'])){
2609 $attr = $config->data['MAIN']['UNIQ_IDENTIFIER'];
2610 }
2611 if(!empty($attr)){
2612 $ldap = $config->get_ldap_link();
2613 $ldap->cat($dn,array($attr));
2614 $csn = $ldap->fetch();
2615 if(isset($csn[$attr][0])){
2616 return($csn[$attr][0]);
2617 }
2618 }
2619 return("");
2620 }
2623 /* Add a given objectClass to an attrs entry */
2624 function add_objectClass($classes, &$attrs)
2625 {
2626 if (is_array($classes)){
2627 $list= $classes;
2628 } else {
2629 $list= array($classes);
2630 }
2632 foreach ($list as $class){
2633 $attrs['objectClass'][]= $class;
2634 }
2635 }
2638 /* Removes a given objectClass from the attrs entry */
2639 function remove_objectClass($classes, &$attrs)
2640 {
2641 if (isset($attrs['objectClass'])){
2642 /* Array? */
2643 if (is_array($classes)){
2644 $list= $classes;
2645 } else {
2646 $list= array($classes);
2647 }
2649 $tmp= array();
2650 foreach ($attrs['objectClass'] as $oc) {
2651 foreach ($list as $class){
2652 if ($oc != $class){
2653 $tmp[]= $oc;
2654 }
2655 }
2656 }
2657 $attrs['objectClass']= $tmp;
2658 }
2659 }
2661 /*! \brief Initialize a file download with given content, name and data type.
2662 * @param data String The content to send.
2663 * @param name String The name of the file.
2664 * @param type String The content identifier, default value is "application/octet-stream";
2665 */
2666 function send_binary_content($data,$name,$type = "application/octet-stream")
2667 {
2668 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
2669 header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
2670 header("Cache-Control: no-cache");
2671 header("Pragma: no-cache");
2672 header("Cache-Control: post-check=0, pre-check=0");
2673 header("Content-type: ".$type."");
2675 /* force download dialog */
2676 if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
2677 header('Content-Disposition: filename="'.$name.'"');
2678 } else {
2679 header('Content-Disposition: attachment; filename="'.$name.'"');
2680 }
2682 echo $data;
2683 exit();
2684 }
2687 /*! \brief Encode special string characters so we can use the string in \
2688 HTML output, without breaking quotes.
2689 @param The String we want to encode.
2690 @return The encoded String
2691 */
2692 function xmlentities($str)
2693 {
2694 if(is_string($str)){
2695 return(htmlentities($str,ENT_QUOTES));
2696 }elseif(is_array($str)){
2697 foreach($str as $name => $value){
2698 $str[$name] = xmlentities($value);
2699 }
2700 }
2701 return($str);
2702 }
2705 /*! \brief Updates all accessTo attributes from a given value to a new one.
2706 For example if a host is renamed.
2707 @param String $from The source accessTo name.
2708 @param String $to The destination accessTo name.
2709 */
2710 function update_accessTo($from,$to)
2711 {
2712 global $config;
2713 $ldap = $config->get_ldap_link();
2714 $ldap->cd($config->current['BASE']);
2715 $ldap->search("(&(objectClass=trustAccount)(accessTo=".$from."))",array("objectClass","accessTo"));
2716 while($attrs = $ldap->fetch()){
2717 $new_attrs = array("accessTo" => array());
2718 $dn = $attrs['dn'];
2719 for($i = 0 ; $i < $attrs['objectClass']['count']; $i++){
2720 $new_attrs['objectClass'][] = $attrs['objectClass'][$i];
2721 }
2722 for($i = 0 ; $i < $attrs['accessTo']['count']; $i++){
2723 if($attrs['accessTo'][$i] == $from){
2724 if(!empty($to)){
2725 $new_attrs['accessTo'][] = $to;
2726 }
2727 }else{
2728 $new_attrs['accessTo'][] = $attrs['accessTo'][$i];
2729 }
2730 }
2731 $ldap->cd($dn);
2732 $ldap->modify($new_attrs);
2733 if (!$ldap->success()){
2734 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, "update_accessTo($from,$to)"));
2735 }
2736 new log("modify","update_accessTo($from,$to)",$dn,array_keys($new_attrs),$ldap->get_error());
2737 }
2738 }
2741 function get_random_char () {
2742 $randno = rand (0, 63);
2743 if ($randno < 12) {
2744 return (chr ($randno + 46)); // Digits, '/' and '.'
2745 } else if ($randno < 38) {
2746 return (chr ($randno + 53)); // Uppercase
2747 } else {
2748 return (chr ($randno + 59)); // Lowercase
2749 }
2750 }
2753 function cred_encrypt($input, $password) {
2755 $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2756 $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2758 return bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $password, $input, MCRYPT_MODE_ECB, $iv));
2760 }
2762 function cred_decrypt($input,$password) {
2763 $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2764 $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2766 return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $password, pack("H*", $input), MCRYPT_MODE_ECB, $iv);
2767 }
2770 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2771 ?>