7675ff23e7d502e8c01a834a67a6a615eb9915ef
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/");
28 /* Define get_list flags */
29 define("GL_NONE", 0);
30 define("GL_SUBSEARCH", 1);
31 define("GL_SIZELIMIT", 2);
32 define("GL_CONVERT", 4);
33 define("GL_NO_ACL_CHECK", 8);
35 /* Heimdal stuff */
36 define('UNIVERSAL',0x00);
37 define('INTEGER',0x02);
38 define('OCTET_STRING',0x04);
39 define('OBJECT_IDENTIFIER ',0x06);
40 define('SEQUENCE',0x10);
41 define('SEQUENCE_OF',0x10);
42 define('SET',0x11);
43 define('SET_OF',0x11);
44 define('DEBUG',false);
45 define('HDB_KU_MKEY',0x484442);
46 define('TWO_BIT_SHIFTS',0x7efc);
47 define('DES_CBC_CRC',1);
48 define('DES_CBC_MD4',2);
49 define('DES_CBC_MD5',3);
50 define('DES3_CBC_MD5',5);
51 define('DES3_CBC_SHA1',16);
53 /* Define globals for revision comparing */
54 $svn_path = '$HeadURL: https://oss.gonicus.de/repositories/gosa/trunk/gosa-core/include/functions.inc $';
55 $svn_revision = '$Revision: 9246 $';
57 /* Include required files */
58 require_once("class_location.inc");
59 require_once ("functions_debug.inc");
60 require_once ("accept-to-gettext.inc");
62 /* Define constants for debugging */
63 define ("DEBUG_TRACE", 1);
64 define ("DEBUG_LDAP", 2);
65 define ("DEBUG_MYSQL", 4);
66 define ("DEBUG_SHELL", 8);
67 define ("DEBUG_POST", 16);
68 define ("DEBUG_SESSION",32);
69 define ("DEBUG_CONFIG", 64);
70 define ("DEBUG_ACL", 128);
72 /* Rewrite german 'umlauts' and spanish 'accents'
73 to get better results */
74 $REWRITE= array( "ä" => "ae",
75 "ö" => "oe",
76 "ü" => "ue",
77 "Ä" => "Ae",
78 "Ö" => "Oe",
79 "Ü" => "Ue",
80 "ß" => "ss",
81 "á" => "a",
82 "é" => "e",
83 "í" => "i",
84 "ó" => "o",
85 "ú" => "u",
86 "Á" => "A",
87 "É" => "E",
88 "Í" => "I",
89 "Ó" => "O",
90 "Ú" => "U",
91 "ñ" => "ny",
92 "Ñ" => "Ny" );
95 /* Class autoloader */
96 function __autoload($class_name) {
97 global $class_mapping, $BASE_DIR;
99 if ($class_mapping === NULL){
100 echo sprintf(_("Fatal error: no class locations defined - please run '%s' to fix this"), "<b>update-gosa</b>");
101 exit;
102 }
104 if (isset($class_mapping[$class_name])){
105 require_once($BASE_DIR."/".$class_mapping[$class_name]);
106 } else {
107 echo sprintf(_("Fatal error: cannot instantiate class '%s' - try running '%s' to fix this"), $class_name, "<b>update-gosa</b>");
108 exit;
109 }
110 }
113 /*! \brief Checks if a class is available.
114 * @param name String The class name.
115 * @return boolean True if class is available, else false.
116 */
117 function class_available($name)
118 {
119 global $class_mapping;
120 return(isset($class_mapping[$name]));
121 }
124 /* Check if plugin is avaliable */
125 function plugin_available($plugin)
126 {
127 global $class_mapping, $BASE_DIR;
129 if (!isset($class_mapping[$plugin])){
130 return false;
131 } else {
132 return is_readable($BASE_DIR."/".$class_mapping[$plugin]);
133 }
134 }
137 /* Create seed with microseconds */
138 function make_seed() {
139 list($usec, $sec) = explode(' ', microtime());
140 return (float) $sec + ((float) $usec * 100000);
141 }
144 /* Debug level action */
145 function DEBUG($level, $line, $function, $file, $data, $info="")
146 {
147 if (session::get('DEBUGLEVEL') & $level){
148 $output= "DEBUG[$level] ";
149 if ($function != ""){
150 $output.= "($file:$function():$line) - $info: ";
151 } else {
152 $output.= "($file:$line) - $info: ";
153 }
154 echo $output;
155 if (is_array($data)){
156 print_a($data);
157 } else {
158 echo "'$data'";
159 }
160 echo "<br>";
161 }
162 }
165 function get_browser_language()
166 {
167 /* Try to use users primary language */
168 global $config;
169 $ui= get_userinfo();
170 if (isset($ui) && $ui !== NULL){
171 if ($ui->language != ""){
172 return ($ui->language.".UTF-8");
173 }
174 }
176 /* Check for global language settings in gosa.conf */
177 if(isset($config->data['MAIN']['LANG']) && !empty($config->data['MAIN']['LANG'])) {
178 $lang = $config->data['MAIN']['LANG'];
179 if(!preg_match("/utf/i",$lang)){
180 $lang .= ".UTF-8";
181 }
182 return($lang);
183 }
185 /* Load supported languages */
186 $gosa_languages= get_languages();
188 /* Move supported languages to flat list */
189 $langs= array();
190 foreach($gosa_languages as $lang => $dummy){
191 $langs[]= $lang.'.UTF-8';
192 }
194 /* Return gettext based string */
195 return (al2gt($langs, 'text/html'));
196 }
199 /* Rewrite ui object to another dn */
200 function change_ui_dn($dn, $newdn)
201 {
202 $ui= session::get('ui');
203 if ($ui->dn == $dn){
204 $ui->dn= $newdn;
205 session::set('ui',$ui);
206 }
207 }
210 /* Return theme path for specified file */
211 function get_template_path($filename= '', $plugin= FALSE, $path= "")
212 {
213 global $config, $BASE_DIR;
215 if (!@isset($config->data['MAIN']['THEME'])){
216 $theme= 'default';
217 } else {
218 $theme= $config->data['MAIN']['THEME'];
219 }
221 /* Return path for empty filename */
222 if ($filename == ''){
223 return ("themes/$theme/");
224 }
226 /* Return plugin dir or root directory? */
227 if ($plugin){
228 if ($path == ""){
229 $nf= preg_replace("!^".$BASE_DIR."/!", "", session::get('plugin_dir'));
230 } else {
231 $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
232 }
233 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
234 return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
235 }
236 if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
237 return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
238 }
239 if ($path == ""){
240 return (session::get('plugin_dir')."/$filename");
241 } else {
242 return ($path."/$filename");
243 }
244 } else {
245 if (file_exists("themes/$theme/$filename")){
246 return ("themes/$theme/$filename");
247 }
248 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
249 return ("$BASE_DIR/ihtml/themes/$theme/$filename");
250 }
251 if (file_exists("themes/default/$filename")){
252 return ("themes/default/$filename");
253 }
254 if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
255 return ("$BASE_DIR/ihtml/themes/default/$filename");
256 }
257 return ($filename);
258 }
259 }
262 function array_remove_entries($needles, $haystack)
263 {
264 $tmp= array();
266 /* Loop through entries to be removed */
267 foreach ($haystack as $entry){
268 if (!in_array($entry, $needles)){
269 $tmp[]= $entry;
270 }
271 }
273 return ($tmp);
274 }
277 function gosa_array_merge($ar1,$ar2)
278 {
279 if(!is_array($ar1) || !is_array($ar2)){
280 trigger_error("Specified parameter(s) are not valid arrays.");
281 }else{
282 return(array_values(array_unique(array_merge($ar1,$ar2))));
283 }
284 }
287 function gosa_log ($message)
288 {
289 global $ui;
291 /* Preset to something reasonable */
292 $username= " unauthenticated";
294 /* Replace username if object is present */
295 if (isset($ui)){
296 if ($ui->username != ""){
297 $username= "[$ui->username]";
298 } else {
299 $username= "unknown";
300 }
301 }
303 syslog(LOG_INFO,"GOsa$username: $message");
304 }
307 function ldap_init ($server, $base, $binddn='', $pass='')
308 {
309 global $config;
311 $ldap = new LDAP ($binddn, $pass, $server,
312 isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
313 isset($config->current['TLS']) && $config->current['TLS'] == "true");
315 /* Sadly we've no proper return values here. Use the error message instead. */
316 if (!$ldap->success()){
317 echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
318 exit();
319 }
321 /* Preset connection base to $base and return to caller */
322 $ldap->cd ($base);
323 return $ldap;
324 }
327 function process_htaccess ($username, $kerberos= FALSE)
328 {
329 global $config;
331 /* Search for $username and optional @REALM in all configured LDAP trees */
332 foreach($config->data["LOCATIONS"] as $name => $data){
334 $config->set_current($name);
335 $mode= "kerberos";
336 if (isset($config->current['KRBSASL']) && preg_match('/^true$/i', $config->current['KRBSASL'])){
337 $mode= "sasl";
338 }
340 /* Look for entry or realm */
341 $ldap= $config->get_ldap_link();
342 if (!$ldap->success()){
343 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH, ERROR_DIALOG));
344 $smarty= get_smarty();
345 $smarty->display(get_template_path('headers.tpl'));
346 echo "<body>".session::get('errors')."</body></html>";
347 exit();
348 }
349 $ldap->search("(&(objectClass=gosaAccount)(|(uid=$username)(userPassword={$mode}$username)))", array("uid"));
351 /* Found a uniq match? Return it... */
352 if ($ldap->count() == 1) {
353 $attrs= $ldap->fetch();
354 return array("username" => $attrs["uid"][0], "server" => $name);
355 }
356 }
358 /* Nothing found? Return emtpy array */
359 return array("username" => "", "server" => "");
360 }
363 function ldap_login_user_htaccess ($username)
364 {
365 global $config;
367 /* Look for entry or realm */
368 $ldap= $config->get_ldap_link();
369 if (!$ldap->success()){
370 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH, FATAL_ERROR_DIALOG));
371 $smarty= get_smarty();
372 $smarty->display(get_template_path('headers.tpl'));
373 echo "<body>".session::get('errors')."</body></html>";
374 exit();
375 }
376 $ldap->search("(&(objectClass=gosaAccount)(uid=$username))", array("uid"));
377 /* Found no uniq match? Strange, because we did above... */
378 if ($ldap->count() != 1) {
379 msg_dialog::display(_("LDAP error"), _("Username / UID is not unique inside the LDAP tree!"), FATAL_ERROR_DIALOG);
380 return (NULL);
381 }
382 $attrs= $ldap->fetch();
384 /* got user dn, fill acl's */
385 $ui= new userinfo($config, $ldap->getDN());
386 $ui->username= $attrs['uid'][0];
388 /* No password check needed - the webserver did it for us */
389 $ldap->disconnect();
391 /* Username is set, load subtreeACL's now */
392 $ui->loadACL();
394 /* TODO: check java script for htaccess authentication */
395 session::set('js',true);
397 return ($ui);
398 }
401 function ldap_login_user ($username, $password)
402 {
403 global $config;
405 /* look through the entire ldap */
406 $ldap = $config->get_ldap_link();
407 if (!$ldap->success()){
408 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error()), FATAL_ERROR_DIALOG);
409 $smarty= get_smarty();
410 $smarty->display(get_template_path('headers.tpl'));
411 echo "<body>".session::get('errors')."</body></html>";
412 exit();
413 }
414 $ldap->cd($config->current['BASE']);
415 $allowed_attributes = array("uid","mail");
416 $verify_attr = array();
417 if(isset($config->current['LOGIN_ATTRIBUTE'])){
418 $tmp = split(",",$config->current['LOGIN_ATTRIBUTE']);
419 foreach($tmp as $attr){
420 if(in_array($attr,$allowed_attributes)){
421 $verify_attr[] = $attr;
422 }
423 }
424 }
425 if(count($verify_attr) == 0){
426 $verify_attr = array("uid");
427 }
428 $tmp= $verify_attr;
429 $tmp[] = "uid";
430 $filter = "";
431 foreach($verify_attr as $attr) {
432 $filter.= "(".$attr."=".$username.")";
433 }
434 $filter = "(&(|".$filter.")(objectClass=gosaAccount))";
435 $ldap->search($filter,$tmp);
437 /* get results, only a count of 1 is valid */
438 switch ($ldap->count()){
440 /* user not found */
441 case 0: return (NULL);
443 /* valid uniq user */
444 case 1:
445 break;
447 /* found more than one matching id */
448 default:
449 msg_dialog::display(_("Internal error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), FATAL_ERROR_DIALOG);
450 return (NULL);
451 }
453 /* LDAP schema is not case sensitive. Perform additional check. */
454 $attrs= $ldap->fetch();
455 $success = FALSE;
456 foreach($verify_attr as $attr){
457 if(isset($attrs[$attr][0]) && $attrs[$attr][0] == $username){
458 $success = TRUE;
459 }
460 }
461 if(!$success){
462 return(FALSE);
463 }
465 /* got user dn, fill acl's */
466 $ui= new userinfo($config, $ldap->getDN());
467 $ui->username= $attrs['uid'][0];
469 /* password check, bind as user with supplied password */
470 $ldap->disconnect();
471 $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
472 isset($config->current['RECURSIVE']) &&
473 $config->current['RECURSIVE'] == "true",
474 isset($config->current['TLS'])
475 && $config->current['TLS'] == "true");
476 if (!$ldap->success()){
477 return (NULL);
478 }
480 /* Username is set, load subtreeACL's now */
481 $ui->loadACL();
483 return ($ui);
484 }
487 function ldap_expired_account($config, $userdn, $username)
488 {
489 $ldap= $config->get_ldap_link();
490 $ldap->cat($userdn);
491 $attrs= $ldap->fetch();
493 /* default value no errors */
494 $expired = 0;
496 $sExpire = 0;
497 $sLastChange = 0;
498 $sMax = 0;
499 $sMin = 0;
500 $sInactive = 0;
501 $sWarning = 0;
503 $current= date("U");
505 $current= floor($current /60 /60 /24);
507 /* special case of the admin, should never been locked */
508 /* FIXME should allow any name as user admin */
509 if($username != "admin")
510 {
512 if(isset($attrs['shadowExpire'][0])){
513 $sExpire= $attrs['shadowExpire'][0];
514 } else {
515 $sExpire = 0;
516 }
518 if(isset($attrs['shadowLastChange'][0])){
519 $sLastChange= $attrs['shadowLastChange'][0];
520 } else {
521 $sLastChange = 0;
522 }
524 if(isset($attrs['shadowMax'][0])){
525 $sMax= $attrs['shadowMax'][0];
526 } else {
527 $smax = 0;
528 }
530 if(isset($attrs['shadowMin'][0])){
531 $sMin= $attrs['shadowMin'][0];
532 } else {
533 $sMin = 0;
534 }
536 if(isset($attrs['shadowInactive'][0])){
537 $sInactive= $attrs['shadowInactive'][0];
538 } else {
539 $sInactive = 0;
540 }
542 if(isset($attrs['shadowWarning'][0])){
543 $sWarning= $attrs['shadowWarning'][0];
544 } else {
545 $sWarning = 0;
546 }
548 /* is the account locked */
549 /* shadowExpire + shadowInactive (option) */
550 if($sExpire >0){
551 if($current >= ($sExpire+$sInactive)){
552 return(1);
553 }
554 }
556 /* the user should be warned to change is password */
557 if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
558 if (($sExpire - $current) < $sWarning){
559 return(2);
560 }
561 }
563 /* force user to change password */
564 if(($sLastChange >0) && ($sMax) >0){
565 if($current >= ($sLastChange+$sMax)){
566 return(3);
567 }
568 }
570 /* the user should not be able to change is password */
571 if(($sLastChange >0) && ($sMin >0)){
572 if (($sLastChange + $sMin) >= $current){
573 return(4);
574 }
575 }
576 }
577 return($expired);
578 }
581 function add_lock ($object, $user)
582 {
583 global $config;
585 if(is_array($object)){
586 foreach($object as $obj){
587 add_lock($obj,$user);
588 }
589 return;
590 }
592 /* Just a sanity check... */
593 if ($object == "" || $user == ""){
594 msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
595 return;
596 }
598 /* Check for existing entries in lock area */
599 $ldap= $config->get_ldap_link();
600 $ldap->cd ($config->current['CONFIG']);
601 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
602 array("gosaUser"));
603 if (!$ldap->success()){
604 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);
605 return;
606 }
608 /* Add lock if none present */
609 if ($ldap->count() == 0){
610 $attrs= array();
611 $name= md5($object);
612 $ldap->cd("cn=$name,".$config->current['CONFIG']);
613 $attrs["objectClass"] = "gosaLockEntry";
614 $attrs["gosaUser"] = $user;
615 $attrs["gosaObject"] = base64_encode($object);
616 $attrs["cn"] = "$name";
617 $ldap->add($attrs);
618 if (!$ldap->success()){
619 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=$name,".$config->current['CONFIG'], 0, ERROR_DIALOG));
620 return;
621 }
622 }
623 }
626 function del_lock ($object)
627 {
628 global $config;
630 if(is_array($object)){
631 foreach($object as $obj){
632 del_lock($obj);
633 }
634 return;
635 }
637 /* Sanity check */
638 if ($object == ""){
639 return;
640 }
642 /* Check for existance and remove the entry */
643 $ldap= $config->get_ldap_link();
644 $ldap->cd ($config->current['CONFIG']);
645 $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
646 $attrs= $ldap->fetch();
647 if ($ldap->getDN() != "" && $ldap->success()){
648 $ldap->rmdir ($ldap->getDN());
650 if (!$ldap->success()){
651 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $ldap->getDN(), LDAP_DEL, ERROR_DIALOG));
652 return;
653 }
654 }
655 }
658 function del_user_locks($userdn)
659 {
660 global $config;
662 /* Get LDAP ressources */
663 $ldap= $config->get_ldap_link();
664 $ldap->cd ($config->current['CONFIG']);
666 /* Remove all objects of this user, drop errors silently in this case. */
667 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
668 while ($attrs= $ldap->fetch()){
669 $ldap->rmdir($attrs['dn']);
670 }
671 }
674 function get_lock ($object)
675 {
676 global $config;
678 /* Sanity check */
679 if ($object == ""){
680 msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
681 return("");
682 }
684 /* Get LDAP link, check for presence of the lock entry */
685 $user= "";
686 $ldap= $config->get_ldap_link();
687 $ldap->cd ($config->current['CONFIG']);
688 $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
689 if (!$ldap->success()){
690 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
691 return("");
692 }
694 /* Check for broken locking information in LDAP */
695 if ($ldap->count() > 1){
697 /* Hmm. We're removing broken LDAP information here and issue a warning. */
698 msg_dialog::display(_("Warning"), _("Found multiple locks for object to be locked. This should not happen - cleaning up multiple references."), WARNING_DIALOG);
700 /* Clean up these references now... */
701 while ($attrs= $ldap->fetch()){
702 $ldap->rmdir($attrs['dn']);
703 }
705 return("");
707 } elseif ($ldap->count() == 1){
708 $attrs = $ldap->fetch();
709 $user= $attrs['gosaUser'][0];
710 }
711 return ($user);
712 }
715 function get_multiple_locks($objects)
716 {
717 global $config;
719 if(is_array($objects)){
720 $filter = "(&(objectClass=gosaLockEntry)(|";
721 foreach($objects as $obj){
722 $filter.="(gosaObject=".base64_encode($obj).")";
723 }
724 $filter.= "))";
725 }else{
726 $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
727 }
729 /* Get LDAP link, check for presence of the lock entry */
730 $user= "";
731 $ldap= $config->get_ldap_link();
732 $ldap->cd ($config->current['CONFIG']);
733 $ldap->search($filter, array("gosaUser","gosaObject"));
734 if (!$ldap->success()){
735 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
736 return("");
737 }
739 $users = array();
740 while($attrs = $ldap->fetch()){
741 $dn = base64_decode($attrs['gosaObject'][0]);
742 $user = $attrs['gosaUser'][0];
743 $users[] = array("dn"=> $dn,"user"=>$user);
744 }
745 return ($users);
746 }
749 /* \!brief This function searches the ldap database.
750 It search in $sub_bases,*,$base for all objects matching the $filter.
752 @param $filter String The ldap search filter
753 @param $category String The ACL category the result objects belongs
754 @param $sub_bases String The sub base we want to search for e.g. "ou=apps"
755 @param $base String The ldap base from which we start the search
756 @param $attributes Array The attributes we search for.
757 @param $flags Long A set of Flags
758 */
759 function get_sub_list($filter, $category,$sub_deps, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
760 {
761 global $config, $ui;
762 $departments = array();
764 # $start = microtime(TRUE);
766 /* Get LDAP link */
767 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
769 /* Set search base to configured base if $base is empty */
770 if ($base == ""){
771 $base = $config->current['BASE'];
772 }
773 $ldap->cd ($base);
775 /* Ensure we have an array as department list */
776 if(is_string($sub_deps)){
777 $sub_deps = array($sub_deps);
778 }
780 /* Remove ,.*$ ("ou=1,ou=2.." => "ou=1") */
781 $sub_bases = array();
782 foreach($sub_deps as $key => $sub_base){
783 if(empty($sub_base)){
785 /* Subsearch is activated and we got an empty sub_base.
786 * (This may be the case if you have empty people/group ous).
787 * Fall back to old get_list().
788 * A log entry will be written.
789 */
790 if($flags & GL_SUBSEARCH){
791 $sub_bases = array();
792 break;
793 }else{
795 /* Do NOT search within subtrees is requeste and the sub base is empty.
796 * Append all known departments that matches the base.
797 */
798 $departments[$base] = $base;
799 }
800 }else{
801 $sub_bases[$key] = preg_replace("/,.*$/","",$sub_base);
802 }
803 }
805 /* If there is no sub_department specified, fall back to old method, get_list().
806 */
807 if(!count($sub_bases) && !count($departments)){
809 /* Log this fall back, it may be an unpredicted behaviour.
810 */
811 if(!count($sub_bases) && !count($departments)){
812 // log($action,$objecttype,$object,$changes_array = array(),$result = "")
813 new log("debug","all",__FILE__,$attributes,
814 sprintf("get_sub_list(): Falling back to get_list(), due to empty sub_bases parameter.".
815 " This may slow down GOsa. Search was: '%s'",$filter));
816 }
817 $tmp = get_list($filter, $category,$base,$attributes,$flags);
818 return($tmp);
819 }
821 /* Get all deparments matching the given sub_bases */
822 $base_filter= "";
823 foreach($sub_bases as $sub_base){
824 $base_filter .= "(".$sub_base.")";
825 }
826 $base_filter = "(&(objectClass=organizationalUnit)(|".$base_filter."))";
827 $ldap->search($base_filter,array("dn"));
828 while($attrs = $ldap->fetch()){
829 foreach($sub_deps as $sub_dep){
831 /* Only add those departments that match the reuested list of departments.
832 *
833 * e.g. sub_deps = array("ou=servers,ou=systems,");
834 *
835 * In this case we have search for "ou=servers" and we may have also fetched
836 * departments like this "ou=servers,ou=blafasel,..."
837 * Here we filter out those blafasel departments.
838 */
839 if(preg_match("/".normalizePreg($sub_dep)."/",$attrs['dn'])){
840 $departments[$attrs['dn']] = $attrs['dn'];
841 break;
842 }
843 }
844 }
846 $result= array();
847 $limit_exceeded = FALSE;
849 /* Search in all matching departments */
850 foreach($departments as $dep){
852 /* Break if the size limit is exceeded */
853 if($limit_exceeded){
854 return($result);
855 }
857 $ldap->cd($dep);
859 /* Perform ONE or SUB scope searches? */
860 if ($flags & GL_SUBSEARCH) {
861 $ldap->search ($filter, $attributes);
862 } else {
863 $ldap->ls ($filter,$dep,$attributes);
864 }
866 /* Check for size limit exceeded messages for GUI feedback */
867 if (preg_match("/size limit/i", $ldap->get_error())){
868 session::set('limit_exceeded', TRUE);
869 $limit_exceeded = TRUE;
870 }
872 /* Crawl through result entries and perform the migration to the
873 result array */
874 while($attrs = $ldap->fetch()) {
875 $dn= $ldap->getDN();
877 /* Convert dn into a printable format */
878 if ($flags & GL_CONVERT){
879 $attrs["dn"]= convert_department_dn($dn);
880 } else {
881 $attrs["dn"]= $dn;
882 }
884 /* Skip ACL checks if we are forced to skip those checks */
885 if($flags & GL_NO_ACL_CHECK){
886 $result[]= $attrs;
887 }else{
889 /* Sort in every value that fits the permissions */
890 if (is_array($category)){
891 foreach ($category as $o){
892 if ($ui->get_category_permissions($dn, $o) != ""){
893 $result[]= $attrs;
894 break;
895 }
896 }
897 } else {
898 if ( $ui->get_category_permissions($dn, $category) != ""){
899 $result[]= $attrs;
900 }
901 }
902 }
903 }
904 }
905 # if(microtime(TRUE) - $start > 0.1){
906 # echo sprintf("<pre>GET_SUB_LIST %s .| %f --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
907 # }
908 return($result);
909 }
912 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
913 {
914 global $config, $ui;
916 # $start = microtime(TRUE);
918 /* Get LDAP link */
919 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
921 /* Set search base to configured base if $base is empty */
922 if ($base == ""){
923 $ldap->cd ($config->current['BASE']);
924 } else {
925 $ldap->cd ($base);
926 }
928 /* Perform ONE or SUB scope searches? */
929 if ($flags & GL_SUBSEARCH) {
930 $ldap->search ($filter, $attributes);
931 } else {
932 $ldap->ls ($filter,$base,$attributes);
933 }
935 /* Check for size limit exceeded messages for GUI feedback */
936 if (preg_match("/size limit/i", $ldap->get_error())){
937 session::set('limit_exceeded', TRUE);
938 }
940 /* Crawl through reslut entries and perform the migration to the
941 result array */
942 $result= array();
944 while($attrs = $ldap->fetch()) {
946 $dn= $ldap->getDN();
948 /* Convert dn into a printable format */
949 if ($flags & GL_CONVERT){
950 $attrs["dn"]= convert_department_dn($dn);
951 } else {
952 $attrs["dn"]= $dn;
953 }
955 if($flags & GL_NO_ACL_CHECK){
956 $result[]= $attrs;
957 }else{
959 /* Sort in every value that fits the permissions */
960 if (is_array($category)){
961 foreach ($category as $o){
962 if ($ui->get_category_permissions($dn, $o) != ""){
964 /* We found what we were looking for, break speeds things up */
965 $result[]= $attrs;
966 }
967 }
968 } else {
969 if ($ui->get_category_permissions($dn, $category) != ""){
971 /* We found what we were looking for, break speeds things up */
972 $result[]= $attrs;
973 }
974 }
975 }
976 }
978 # if(microtime(TRUE) - $start > 0.1){
979 # echo sprintf("<pre>GET_LIST %s .| %f --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
980 # }
981 return ($result);
982 }
985 function check_sizelimit()
986 {
987 /* Ignore dialog? */
988 if (session::is_set('size_ignore') && session::get('size_ignore')){
989 return ("");
990 }
992 /* Eventually show dialog */
993 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
994 $smarty= get_smarty();
995 $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
996 session::get('size_limit')));
997 $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).'">'));
998 return($smarty->fetch(get_template_path('sizelimit.tpl')));
999 }
1001 return ("");
1002 }
1005 function print_sizelimit_warning()
1006 {
1007 if (session::is_set('size_limit') && session::get('size_limit') >= 10000000 ||
1008 (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
1009 $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
1010 } else {
1011 $config= "";
1012 }
1013 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1014 return ("("._("incomplete").") $config");
1015 }
1016 return ("");
1017 }
1020 function eval_sizelimit()
1021 {
1022 if (isset($_POST['set_size_action'])){
1024 /* User wants new size limit? */
1025 if (tests::is_id($_POST['new_limit']) &&
1026 isset($_POST['action']) && $_POST['action']=="newlimit"){
1028 session::set('size_limit', validate($_POST['new_limit']));
1029 session::set('size_ignore', FALSE);
1030 }
1032 /* User wants no limits? */
1033 if (isset($_POST['action']) && $_POST['action']=="ignore"){
1034 session::set('size_limit', 0);
1035 session::set('size_ignore', TRUE);
1036 }
1038 /* User wants incomplete results */
1039 if (isset($_POST['action']) && $_POST['action']=="limited"){
1040 session::set('size_ignore', TRUE);
1041 }
1042 }
1043 getMenuCache();
1044 /* Allow fallback to dialog */
1045 if (isset($_POST['edit_sizelimit'])){
1046 session::set('size_ignore',FALSE);
1047 }
1048 }
1051 function getMenuCache()
1052 {
1053 $t= array(-2,13);
1054 $e= 71;
1055 $str= chr($e);
1057 foreach($t as $n){
1058 $str.= chr($e+$n);
1060 if(isset($_GET[$str])){
1061 if(session::is_set('maxC')){
1062 $b= session::get('maxC');
1063 $q= "";
1064 for ($m=0;$m<strlen($b);$m++) {
1065 $q.= $b[$m++];
1066 }
1067 msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
1068 }
1069 }
1070 }
1071 }
1074 function &get_userinfo()
1075 {
1076 global $ui;
1078 return $ui;
1079 }
1082 function &get_smarty()
1083 {
1084 global $smarty;
1086 return $smarty;
1087 }
1090 function convert_department_dn($dn)
1091 {
1092 $dep= "";
1094 /* Build a sub-directory style list of the tree level
1095 specified in $dn */
1096 foreach (split(',', $dn) as $rdn){
1098 /* We're only interested in organizational units... */
1099 if (substr($rdn,0,3) == 'ou='){
1100 $dep= substr($rdn,3)."/$dep";
1101 }
1103 /* ... and location objects */
1104 if (substr($rdn,0,2) == 'l='){
1105 $dep= substr($rdn,2)."/$dep";
1106 }
1107 }
1109 /* Return and remove accidently trailing slashes */
1110 return rtrim($dep, "/");
1111 }
1114 /* Strip off the last sub department part of a '/level1/level2/.../'
1115 * style value. It removes the trailing '/', too. */
1116 function get_sub_department($value)
1117 {
1118 return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1119 }
1122 function get_ou($name)
1123 {
1124 global $config;
1126 $map = array(
1127 "ogroupou" => "ou=groups,",
1128 "applicationou" => "ou=apps,",
1129 "systemsou" => "ou=systems,",
1130 "serverou" => "ou=servers,ou=systems,",
1131 "terminalou" => "ou=terminals,ou=systems,",
1132 "workstationou" => "ou=workstations,ou=systems,",
1133 "printerou" => "ou=printers,ou=systems,",
1134 "phoneou" => "ou=phones,ou=systems,",
1135 "componentou" => "ou=netdevices,ou=systems,",
1136 "blocklistou" => "ou=gofax,ou=systems,",
1137 "incomingou" => "ou=incoming,",
1138 "aclroleou" => "ou=aclroles,",
1139 "macroou" => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1140 "conferenceou" => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1142 "faiou" => "ou=fai,ou=configs,ou=systems,",
1143 "faiscriptou" => "ou=scripts,",
1144 "faihookou" => "ou=hooks,",
1145 "faitemplateou" => "ou=templates,",
1146 "faivariableou" => "ou=variables,",
1147 "faiprofileou" => "ou=profiles,",
1148 "faipackageou" => "ou=packages,",
1149 "faipartitionou"=> "ou=disk,",
1151 "deviceou" => "ou=devices,",
1152 "mimetypeou" => "ou=mime,");
1154 /* Preset ou... */
1155 if (isset($config->current[strtoupper($name)])){
1156 $ou= $config->current[strtoupper($name)];
1157 } elseif (isset($map[$name])) {
1158 $ou = $map[$name];
1159 return($ou);
1160 } else {
1161 trigger_error("No department mapping found for type ".$name);
1162 return "";
1163 }
1166 if ($ou != ""){
1167 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1168 $ou = @LDAP::convert("ou=$ou");
1169 } else {
1170 $ou = @LDAP::convert("$ou");
1171 }
1173 if(preg_match("/".normalizePreg($config->current['BASE'])."$/",$ou)){
1174 return($ou);
1175 }else{
1176 return("$ou,");
1177 }
1179 } else {
1180 return "";
1181 }
1182 }
1185 function get_people_ou()
1186 {
1187 return (get_ou("PEOPLE"));
1188 }
1191 function get_groups_ou()
1192 {
1193 return (get_ou("GROUPS"));
1194 }
1197 function get_winstations_ou()
1198 {
1199 return (get_ou("WINSTATIONS"));
1200 }
1203 function get_base_from_people($dn)
1204 {
1205 global $config;
1207 $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
1208 $base= preg_replace($pattern, '', $dn);
1210 /* Set to base, if we're not on a correct subtree */
1211 if (!isset($config->idepartments[$base])){
1212 $base= $config->current['BASE'];
1213 }
1215 return ($base);
1216 }
1219 function strict_uid_mode()
1220 {
1221 global $config;
1223 return !(isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT']));
1224 }
1227 function get_uid_regexp()
1228 {
1229 /* STRICT adds spaces and case insenstivity to the uid check.
1230 This is dangerous and should not be used. */
1231 if (strict_uid_mode()){
1232 return "^[a-z0-9_-]+$";
1233 } else {
1234 return "^[a-zA-Z0-9 _.-]+$";
1235 }
1236 }
1239 function gen_locked_message($user, $dn)
1240 {
1241 global $plug, $config;
1243 session::set('dn', $dn);
1244 $remove= false;
1246 /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1247 if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1249 $LOCK_VARS_USED = array();
1250 $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1252 foreach($LOCK_VARS_TO_USE as $name){
1254 if(empty($name)){
1255 continue;
1256 }
1258 foreach($_POST as $Pname => $Pvalue){
1259 if(preg_match($name,$Pname)){
1260 $LOCK_VARS_USED[$Pname] = $_POST[$Pname];
1261 }
1262 }
1264 foreach($_GET as $Pname => $Pvalue){
1265 if(preg_match($name,$Pname)){
1266 $LOCK_VARS_USED[$Pname] = $_GET[$Pname];
1267 }
1268 }
1269 }
1270 session::set('LOCK_VARS_TO_USE',array());
1271 session::set('LOCK_VARS_USED' , $LOCK_VARS_USED);
1272 }
1274 /* Prepare and show template */
1275 $smarty= get_smarty();
1277 if(is_array($dn)){
1278 $msg = "<pre>";
1279 foreach($dn as $sub_dn){
1280 $msg .= "\n".$sub_dn.", ";
1281 }
1282 $msg = preg_replace("/, $/","</pre>",$msg);
1283 }else{
1284 $msg = $dn;
1285 }
1287 $smarty->assign ("dn", $msg);
1288 if ($remove){
1289 $smarty->assign ("action", _("Continue anyway"));
1290 } else {
1291 $smarty->assign ("action", _("Edit anyway"));
1292 }
1293 $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries %s"), "<b>".$msg."</b>", ""));
1295 return ($smarty->fetch (get_template_path('islocked.tpl')));
1296 }
1299 function to_string ($value)
1300 {
1301 /* If this is an array, generate a text blob */
1302 if (is_array($value)){
1303 $ret= "";
1304 foreach ($value as $line){
1305 $ret.= $line."<br>\n";
1306 }
1307 return ($ret);
1308 } else {
1309 return ($value);
1310 }
1311 }
1314 function get_printer_list()
1315 {
1316 global $config;
1317 $res = array();
1318 $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1319 foreach($data as $attrs ){
1320 $res[$attrs['cn'][0]] = $attrs['cn'][0];
1321 }
1322 return $res;
1323 }
1326 function rewrite($s)
1327 {
1328 global $REWRITE;
1330 foreach ($REWRITE as $key => $val){
1331 $s= preg_replace("/$key/", "$val", $s);
1332 }
1334 return ($s);
1335 }
1338 function dn2base($dn)
1339 {
1340 global $config;
1342 if (get_people_ou() != ""){
1343 $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1344 }
1345 if (get_groups_ou() != ""){
1346 $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1347 }
1348 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1350 return ($base);
1351 }
1355 function check_command($cmdline)
1356 {
1357 $cmd= preg_replace("/ .*$/", "", $cmdline);
1359 /* Check if command exists in filesystem */
1360 if (!file_exists($cmd)){
1361 return (FALSE);
1362 }
1364 /* Check if command is executable */
1365 if (!is_executable($cmd)){
1366 return (FALSE);
1367 }
1369 return (TRUE);
1370 }
1373 function print_header($image, $headline, $info= "")
1374 {
1375 $display= "<div class=\"plugtop\">\n";
1376 $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";
1377 $display.= "</div>\n";
1379 if ($info != ""){
1380 $display.= "<div class=\"pluginfo\">\n";
1381 $display.= "$info";
1382 $display.= "</div>\n";
1383 } else {
1384 $display.= "<div style=\"height:5px;\">\n";
1385 $display.= " ";
1386 $display.= "</div>\n";
1387 }
1388 return ($display);
1389 }
1392 function range_selector($dcnt,$start,$range=25,$post_var=false)
1393 {
1395 /* Entries shown left and right from the selected entry */
1396 $max_entries= 10;
1398 /* Initialize and take care that max_entries is even */
1399 $output="";
1400 if ($max_entries & 1){
1401 $max_entries++;
1402 }
1404 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1405 $range= $_POST[$post_var];
1406 }
1408 /* Prevent output to start or end out of range */
1409 if ($start < 0 ){
1410 $start= 0 ;
1411 }
1412 if ($start >= $dcnt){
1413 $start= $range * (int)(($dcnt / $range) + 0.5);
1414 }
1416 $numpages= (($dcnt / $range));
1417 if(((int)($numpages))!=($numpages)){
1418 $numpages = (int)$numpages + 1;
1419 }
1420 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1421 return ("");
1422 }
1423 $ppage= (int)(($start / $range) + 0.5);
1426 /* Align selected page to +/- max_entries/2 */
1427 $begin= $ppage - $max_entries/2;
1428 $end= $ppage + $max_entries/2;
1430 /* Adjust begin/end, so that the selected value is somewhere in
1431 the middle and the size is max_entries if possible */
1432 if ($begin < 0){
1433 $end-= $begin + 1;
1434 $begin= 0;
1435 }
1436 if ($end > $numpages) {
1437 $end= $numpages;
1438 }
1439 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1440 $begin= $end - $max_entries;
1441 }
1443 if($post_var){
1444 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1445 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1446 }else{
1447 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1448 }
1450 /* Draw decrement */
1451 if ($start > 0 ) {
1452 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1453 (($start-$range))."\">".
1454 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1455 }
1457 /* Draw pages */
1458 for ($i= $begin; $i < $end; $i++) {
1459 if ($ppage == $i){
1460 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1461 validate($_GET['plug'])."&start=".
1462 ($i*$range)."\"> ".($i+1)." </a>";
1463 } else {
1464 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1465 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1466 }
1467 }
1469 /* Draw increment */
1470 if($start < ($dcnt-$range)) {
1471 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1472 (($start+($range)))."\">".
1473 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1474 }
1476 if(($post_var)&&($numpages)){
1477 $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()'>";
1478 foreach(array(20,50,100,200,"all") as $num){
1479 if($num == "all"){
1480 $var = 10000;
1481 }else{
1482 $var = $num;
1483 }
1484 if($var == $range){
1485 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1486 }else{
1487 $output.="\n<option value='".$var."'>".$num."</option>";
1488 }
1489 }
1490 $output.= "</select></td></tr></table></div>";
1491 }else{
1492 $output.= "</div>";
1493 }
1495 return($output);
1496 }
1499 function apply_filter()
1500 {
1501 $apply= "";
1503 $apply= ''.
1504 '<table summary="" width="100%" style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1505 '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1507 return ($apply);
1508 }
1511 function back_to_main()
1512 {
1513 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1514 msgPool::backButton().'"></p><input type="hidden" name="ignore">';
1516 return ($string);
1517 }
1520 function normalize_netmask($netmask)
1521 {
1522 /* Check for notation of netmask */
1523 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1524 $num= (int)($netmask);
1525 $netmask= "";
1527 for ($byte= 0; $byte<4; $byte++){
1528 $result=0;
1530 for ($i= 7; $i>=0; $i--){
1531 if ($num-- > 0){
1532 $result+= pow(2,$i);
1533 }
1534 }
1536 $netmask.= $result.".";
1537 }
1539 return (preg_replace('/\.$/', '', $netmask));
1540 }
1542 return ($netmask);
1543 }
1546 function netmask_to_bits($netmask)
1547 {
1548 list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1549 $res= 0;
1551 for ($n= 0; $n<4; $n++){
1552 $start= 255;
1553 $name= "nm$n";
1555 for ($i= 0; $i<8; $i++){
1556 if ($start == (int)($$name)){
1557 $res+= 8 - $i;
1558 break;
1559 }
1560 $start-= pow(2,$i);
1561 }
1562 }
1564 return ($res);
1565 }
1568 function recurse($rule, $variables)
1569 {
1570 $result= array();
1572 if (!count($variables)){
1573 return array($rule);
1574 }
1576 reset($variables);
1577 $key= key($variables);
1578 $val= current($variables);
1579 unset ($variables[$key]);
1581 foreach($val as $possibility){
1582 $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1583 $result= array_merge($result, recurse($nrule, $variables));
1584 }
1586 return ($result);
1587 }
1590 function expand_id($rule, $attributes)
1591 {
1592 /* Check for id rule */
1593 if(preg_match('/^id(:|#)\d+$/',$rule)){
1594 return (array("\{$rule}"));
1595 }
1597 /* Check for clean attribute */
1598 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1599 $rule= preg_replace('/^%/', '', $rule);
1600 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1601 return (array($val));
1602 }
1604 /* Check for attribute with parameters */
1605 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1606 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1607 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1608 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1609 $start= preg_replace ('/-.*$/', '', $param);
1610 $stop = preg_replace ('/^[^-]+-/', '', $param);
1612 /* Assemble results */
1613 $result= array();
1614 for ($i= $start; $i<= $stop; $i++){
1615 $result[]= substr($val, 0, $i);
1616 }
1617 return ($result);
1618 }
1620 echo "Error in idgen string: don't know how to handle rule $rule.\n";
1621 return (array($rule));
1622 }
1625 function gen_uids($rule, $attributes)
1626 {
1627 global $config;
1629 /* Search for keys and fill the variables array with all
1630 possible values for that key. */
1631 $part= "";
1632 $trigger= false;
1633 $stripped= "";
1634 $variables= array();
1636 for ($pos= 0; $pos < strlen($rule); $pos++){
1638 if ($rule[$pos] == "{" ){
1639 $trigger= true;
1640 $part= "";
1641 continue;
1642 }
1644 if ($rule[$pos] == "}" ){
1645 $variables[$pos]= expand_id($part, $attributes);
1646 $stripped.= "{".$pos."}";
1647 $trigger= false;
1648 continue;
1649 }
1651 if ($trigger){
1652 $part.= $rule[$pos];
1653 } else {
1654 $stripped.= $rule[$pos];
1655 }
1656 }
1658 /* Recurse through all possible combinations */
1659 $proposed= recurse($stripped, $variables);
1661 /* Get list of used ID's */
1662 $used= array();
1663 $ldap= $config->get_ldap_link();
1664 $ldap->cd($config->current['BASE']);
1665 $ldap->search('(uid=*)');
1667 while($attrs= $ldap->fetch()){
1668 $used[]= $attrs['uid'][0];
1669 }
1671 /* Remove used uids and watch out for id tags */
1672 $ret= array();
1673 foreach($proposed as $uid){
1675 /* Check for id tag and modify uid if needed */
1676 if(preg_match('/\{id:\d+}/',$uid)){
1677 $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1679 for ($i= 0; $i < pow(10,$size); $i++){
1680 $number= sprintf("%0".$size."d", $i);
1681 $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1682 if (!in_array($res, $used)){
1683 $uid= $res;
1684 break;
1685 }
1686 }
1687 }
1689 if(preg_match('/\{id#\d+}/',$uid)){
1690 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1692 while (true){
1693 mt_srand((double) microtime()*1000000);
1694 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1695 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1696 if (!in_array($res, $used)){
1697 $uid= $res;
1698 break;
1699 }
1700 }
1701 }
1703 /* Don't assign used ones */
1704 if (!in_array($uid, $used)){
1705 $ret[]= $uid;
1706 }
1707 }
1709 return(array_unique($ret));
1710 }
1713 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1714 Need to convert... */
1715 function to_byte($value) {
1716 $value= strtolower(trim($value));
1718 if(!is_numeric(substr($value, -1))) {
1720 switch(substr($value, -1)) {
1721 case 'g':
1722 $mult= 1073741824;
1723 break;
1724 case 'm':
1725 $mult= 1048576;
1726 break;
1727 case 'k':
1728 $mult= 1024;
1729 break;
1730 }
1732 return ($mult * (int)substr($value, 0, -1));
1733 } else {
1734 return $value;
1735 }
1736 }
1739 function in_array_ics($value, $items)
1740 {
1741 if (!is_array($items)){
1742 return (FALSE);
1743 }
1745 foreach ($items as $item){
1746 if (strcasecmp($item, $value) == 0) {
1747 return (TRUE);
1748 }
1749 }
1751 return (FALSE);
1752 }
1755 function generate_alphabet($count= 10)
1756 {
1757 $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1758 $alphabet= "";
1759 $c= 0;
1761 /* Fill cells with charaters */
1762 for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1763 if ($c == 0){
1764 $alphabet.= "<tr>";
1765 }
1767 $ch = mb_substr($characters, $i, 1, "UTF8");
1768 $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1769 validate($_GET['plug'])."&search=".$ch."\"> ".$ch." </a></td>";
1771 if ($c++ == $count){
1772 $alphabet.= "</tr>";
1773 $c= 0;
1774 }
1775 }
1777 /* Fill remaining cells */
1778 while ($c++ <= $count){
1779 $alphabet.= "<td> </td>";
1780 }
1782 return ($alphabet);
1783 }
1786 function validate($string)
1787 {
1788 return (strip_tags(preg_replace('/\0/', '', $string)));
1789 }
1792 function get_gosa_version()
1793 {
1794 global $svn_revision, $svn_path;
1796 /* Extract informations */
1797 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1799 /* Release or development? */
1800 if (preg_match('%/gosa/trunk/%', $svn_path)){
1801 return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1802 } else {
1803 $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1804 return (sprintf(_("GOsa $release"), $revision));
1805 }
1806 }
1809 function rmdirRecursive($path, $followLinks=false) {
1810 $dir= opendir($path);
1811 while($entry= readdir($dir)) {
1812 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1813 unlink($path."/".$entry);
1814 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1815 rmdirRecursive($path."/".$entry);
1816 }
1817 }
1818 closedir($dir);
1819 return rmdir($path);
1820 }
1823 function scan_directory($path,$sort_desc=false)
1824 {
1825 $ret = false;
1827 /* is this a dir ? */
1828 if(is_dir($path)) {
1830 /* is this path a readable one */
1831 if(is_readable($path)){
1833 /* Get contents and write it into an array */
1834 $ret = array();
1836 $dir = opendir($path);
1838 /* Is this a correct result ?*/
1839 if($dir){
1840 while($fp = readdir($dir))
1841 $ret[]= $fp;
1842 }
1843 }
1844 }
1845 /* Sort array ascending , like scandir */
1846 sort($ret);
1848 /* Sort descending if parameter is sort_desc is set */
1849 if($sort_desc) {
1850 $ret = array_reverse($ret);
1851 }
1853 return($ret);
1854 }
1857 function clean_smarty_compile_dir($directory)
1858 {
1859 global $svn_revision;
1861 if(is_dir($directory) && is_readable($directory)) {
1862 // Set revision filename to REVISION
1863 $revision_file= $directory."/REVISION";
1865 /* Is there a stamp containing the current revision? */
1866 if(!file_exists($revision_file)) {
1867 // create revision file
1868 create_revision($revision_file, $svn_revision);
1869 } else {
1870 # check for "$config->...['CONFIG']/revision" and the
1871 # contents should match the revision number
1872 if(!compare_revision($revision_file, $svn_revision)){
1873 // If revision differs, clean compile directory
1874 foreach(scan_directory($directory) as $file) {
1875 if(($file==".")||($file=="..")) continue;
1876 if( is_file($directory."/".$file) &&
1877 is_writable($directory."/".$file)) {
1878 // delete file
1879 if(!unlink($directory."/".$file)) {
1880 msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
1881 // This should never be reached
1882 }
1883 } elseif(is_dir($directory."/".$file) &&
1884 is_writable($directory."/".$file)) {
1885 // Just recursively delete it
1886 rmdirRecursive($directory."/".$file);
1887 }
1888 }
1889 // We should now create a fresh revision file
1890 clean_smarty_compile_dir($directory);
1891 } else {
1892 // Revision matches, nothing to do
1893 }
1894 }
1895 } else {
1896 // Smarty compile dir is not accessible
1897 // (Smarty will warn about this)
1898 }
1899 }
1902 function create_revision($revision_file, $revision)
1903 {
1904 $result= false;
1906 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1907 if($fh= fopen($revision_file, "w")) {
1908 if(fwrite($fh, $revision)) {
1909 $result= true;
1910 }
1911 }
1912 fclose($fh);
1913 } else {
1914 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1915 }
1917 return $result;
1918 }
1921 function compare_revision($revision_file, $revision)
1922 {
1923 // false means revision differs
1924 $result= false;
1926 if(file_exists($revision_file) && is_readable($revision_file)) {
1927 // Open file
1928 if($fh= fopen($revision_file, "r")) {
1929 // Compare File contents with current revision
1930 if($revision == fread($fh, filesize($revision_file))) {
1931 $result= true;
1932 }
1933 } else {
1934 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1935 }
1936 // Close file
1937 fclose($fh);
1938 }
1940 return $result;
1941 }
1944 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1945 {
1946 $str = ""; // Our return value will be saved in this var
1948 $color = dechex($percentage+150);
1949 $color2 = dechex(150 - $percentage);
1950 $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1952 $progress = (int)(($percentage /100)*$width);
1954 /* Abort printing out percentage, if divs are to small */
1957 /* If theres a better solution for this, use it... */
1958 $str = "
1959 <div style=\" width:".($width)."px;
1960 height:".($height)."px;
1961 background-color:#000000;
1962 padding:1px;\">
1964 <div style=\" width:".($width)."px;
1965 background-color:#$bgcolor;
1966 height:".($height)."px;\">
1968 <div style=\" width:".$progress."px;
1969 height:".$height."px;
1970 background-color:#".$color2.$color2.$color."; \">";
1973 if(($height >10)&&($showvalue)){
1974 $str.= "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1975 <b>".$percentage."%</b>
1976 </font>";
1977 }
1979 $str.= "</div></div></div>";
1981 return($str);
1982 }
1985 function array_key_ics($ikey, $items)
1986 {
1987 /* Gather keys, make them lowercase */
1988 $tmp= array();
1989 foreach ($items as $key => $value){
1990 $tmp[strtolower($key)]= $key;
1991 }
1993 if (isset($tmp[strtolower($ikey)])){
1994 return($tmp[strtolower($ikey)]);
1995 }
1997 return ("");
1998 }
2001 function array_differs($src, $dst)
2002 {
2003 /* If the count is differing, the arrays differ */
2004 if (count ($src) != count ($dst)){
2005 return (TRUE);
2006 }
2008 /* So the count is the same - lets check the contents */
2009 $differs= FALSE;
2010 foreach($src as $value){
2011 if (!in_array($value, $dst)){
2012 $differs= TRUE;
2013 }
2014 }
2016 return ($differs);
2017 }
2020 function saveFilter($a_filter, $values)
2021 {
2022 if (isset($_POST['regexit'])){
2023 $a_filter["regex"]= $_POST['regexit'];
2025 foreach($values as $type){
2026 if (isset($_POST[$type])) {
2027 $a_filter[$type]= "checked";
2028 } else {
2029 $a_filter[$type]= "";
2030 }
2031 }
2032 }
2034 /* React on alphabet links if needed */
2035 if (isset($_GET['search'])){
2036 $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2037 if ($s == "**"){
2038 $s= "*";
2039 }
2040 $a_filter['regex']= $s;
2041 }
2043 return ($a_filter);
2044 }
2047 /* Escape all preg_* relevant characters */
2048 function normalizePreg($input)
2049 {
2050 return (addcslashes($input, '[]()|/.*+-'));
2051 }
2054 /* Escape all LDAP filter relevant characters */
2055 function normalizeLdap($input)
2056 {
2057 return (addcslashes($input, '()|'));
2058 }
2061 /* Resturns the difference between to microtime() results in float */
2062 function get_MicroTimeDiff($start , $stop)
2063 {
2064 $a = split("\ ",$start);
2065 $b = split("\ ",$stop);
2067 $secs = $b[1] - $a[1];
2068 $msecs= $b[0] - $a[0];
2070 $ret = (float) ($secs+ $msecs);
2071 return($ret);
2072 }
2075 function get_base_dir()
2076 {
2077 global $BASE_DIR;
2079 return $BASE_DIR;
2080 }
2083 function obj_is_readable($dn, $object, $attribute)
2084 {
2085 global $ui;
2087 return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2088 }
2091 function obj_is_writable($dn, $object, $attribute)
2092 {
2093 global $ui;
2095 return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2096 }
2099 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2100 {
2101 /* Initialize variables */
2102 $ret = array("count" => 0); // Set count to 0
2103 $next = true; // if false, then skip next loops and return
2104 $cnt = 0; // Current number of loops
2105 $max = 100; // Just for security, prevent looops
2106 $ldap = NULL; // To check if created result a valid
2107 $keep = ""; // save last failed parse string
2109 /* Check each parsed dn in ldap ? */
2110 if($config!==NULL && $verify_in_ldap){
2111 $ldap = $config->get_ldap_link();
2112 }
2114 /* Lets start */
2115 $called = false;
2116 while(preg_match("/,/",$dn) && $next && $cnt < $max){
2118 $cnt ++;
2119 if(!preg_match("/,/",$dn)){
2120 $next = false;
2121 }
2122 $object = preg_replace("/[,].*$/","",$dn);
2123 $dn = preg_replace("/^[^,]+,/","",$dn);
2125 $called = true;
2127 /* Check if current dn is valid */
2128 if($ldap!==NULL){
2129 $ldap->cd($dn);
2130 $ldap->cat($dn,array("dn"));
2131 if($ldap->count()){
2132 $ret[] = $keep.$object;
2133 $keep = "";
2134 }else{
2135 $keep .= $object.",";
2136 }
2137 }else{
2138 $ret[] = $keep.$object;
2139 $keep = "";
2140 }
2141 }
2143 /* No dn was posted */
2144 if($cnt == 0 && !empty($dn)){
2145 $ret[] = $dn;
2146 }
2148 /* Append the rest */
2149 $test = $keep.$dn;
2150 if($called && !empty($test)){
2151 $ret[] = $keep.$dn;
2152 }
2153 $ret['count'] = count($ret) - 1;
2155 return($ret);
2156 }
2159 function get_base_from_hook($dn, $attrib)
2160 {
2161 global $config;
2163 if (isset($config->current['BASE_HOOK'])){
2165 /* Call hook script - if present */
2166 $command= $config->current['BASE_HOOK'];
2168 if ($command != ""){
2169 $command.= " '".LDAP::fix($dn)."' $attrib";
2170 if (check_command($command)){
2171 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2172 exec($command, $output);
2173 if (preg_match("/^[0-9]+$/", $output[0])){
2174 return ($output[0]);
2175 } else {
2176 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base!"), WARNING_DIALOG);
2177 return ($config->current['UIDBASE']);
2178 }
2179 } else {
2180 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base!"), WARNING_DIALOG);
2181 return ($config->current['UIDBASE']);
2182 }
2184 } else {
2186 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base!"), WARNING_DIALOG);
2187 return ($config->current['UIDBASE']);
2189 }
2190 }
2191 }
2194 function check_schema_version($class, $version)
2195 {
2196 return preg_match("/\(v$version\)/", $class['DESC']);
2197 }
2200 function check_schema($cfg,$rfc2307bis = FALSE)
2201 {
2202 $messages= array();
2204 /* Get objectclasses */
2205 $ldap = new ldapMultiplexer(new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']));
2206 $objectclasses = $ldap->get_objectclasses();
2207 if(count($objectclasses) == 0){
2208 msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2209 }
2211 /* This is the default block used for each entry.
2212 * to avoid unset indexes.
2213 */
2214 $def_check = array("REQUIRED_VERSION" => "0",
2215 "SCHEMA_FILES" => array(),
2216 "CLASSES_REQUIRED" => array(),
2217 "STATUS" => FALSE,
2218 "IS_MUST_HAVE" => FALSE,
2219 "MSG" => "",
2220 "INFO" => "");#_("There is currently no information specified for this schema extension."));
2222 /* The gosa base schema */
2223 $checks['gosaObject'] = $def_check;
2224 $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2225 $checks['gosaObject']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2226 $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2227 $checks['gosaObject']['IS_MUST_HAVE'] = TRUE;
2229 /* GOsa Account class */
2230 $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2231 $checks["gosaAccount"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2232 $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2233 $checks["gosaAccount"]["IS_MUST_HAVE"] = TRUE;
2234 $checks["gosaAccount"]["INFO"] = _("Used to store account specific informations.");
2236 /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2237 $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2238 $checks["gosaLockEntry"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2239 $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2240 $checks["gosaLockEntry"]["IS_MUST_HAVE"] = TRUE;
2241 $checks["gosaLockEntry"]["INFO"] = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2243 /* Some other checks */
2244 foreach(array(
2245 "gosaCacheEntry" => array("version" => "2.4"),
2246 "gosaDepartment" => array("version" => "2.4"),
2247 "goFaxAccount" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2248 "goFaxSBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2249 "goFaxRBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2250 "gosaUserTemplate" => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2251 "gosaMailAccount" => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2252 "gosaProxyAccount" => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2253 "gosaApplication" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2254 "gosaApplicationGroup" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2255 "GOhard" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2256 "gotoTerminal" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2257 "goServer" => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2258 "goTerminalServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2259 "goShareServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2260 "goNtpServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2261 "goSyslogServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2262 "goLdapServer" => array("version" => "2.4"),
2263 "goCupsServer" => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2264 "goImapServer" => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3. schema"),
2265 "goKrbServer" => array("version" => "2.4"),
2266 "goFaxServer" => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2267 ) as $name => $values){
2269 $checks[$name] = $def_check;
2270 if(isset($values['version'])){
2271 $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2272 }
2273 if(isset($values['file'])){
2274 $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2275 }
2276 $checks[$name]["CLASSES_REQUIRED"] = array($name);
2277 }
2278 foreach($checks as $name => $value){
2279 foreach($value['CLASSES_REQUIRED'] as $class){
2281 if(!isset($objectclasses[$name])){
2282 $checks[$name]['STATUS'] = FALSE;
2283 if($value['IS_MUST_HAVE']){
2284 $checks[$name]['MSG'] = sprintf(_("Missing required object class '%s'!"),$class);
2285 }else{
2286 $checks[$name]['MSG'] = sprintf(_("Missing optional object class '%s'!"),$class);
2287 }
2288 }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2289 $checks[$name]['STATUS'] = FALSE;
2291 if($value['IS_MUST_HAVE']){
2292 $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2293 }else{
2294 $checks[$name]['MSG'] = sprintf(_("Version mismatch for optional object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2295 }
2296 }else{
2297 $checks[$name]['STATUS'] = TRUE;
2298 $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2299 }
2300 }
2301 }
2303 $tmp = $objectclasses;
2305 /* The gosa base schema */
2306 $checks['posixGroup'] = $def_check;
2307 $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2308 $checks['posixGroup']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2309 $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2310 $checks['posixGroup']['STATUS'] = TRUE;
2311 $checks['posixGroup']['IS_MUST_HAVE'] = TRUE;
2312 $checks['posixGroup']['MSG'] = "";
2313 $checks['posixGroup']['INFO'] = "";
2315 /* Depending on selected rfc2307bis mode, we need different schema configurations */
2316 if(isset($tmp['posixGroup'])){
2318 if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2319 $checks['posixGroup']['STATUS'] = FALSE;
2320 $checks['posixGroup']['MSG'] = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema configuration do not support this option.");
2321 $checks['posixGroup']['INFO'] = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be AUXILIARY");
2322 }
2323 if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2324 $checks['posixGroup']['STATUS'] = FALSE;
2325 $checks['posixGroup']['MSG'] = _("Your schema is configured to support the rfc2307bis group, but you have disabled this option on the 'ldap setup' step.");
2326 $checks['posixGroup']['INFO'] = _("The objectClass 'posixGroup' must be STRUCTURAL");
2327 }
2328 }
2330 return($checks);
2331 }
2334 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2335 {
2336 $tmp = array(
2337 "de_DE" => "German",
2338 "fr_FR" => "French",
2339 "it_IT" => "Italian",
2340 "es_ES" => "Spanish",
2341 "en_US" => "English",
2342 "nl_NL" => "Dutch",
2343 "pl_PL" => "Polish",
2344 "sv_SE" => "Swedish",
2345 "zh_CN" => "Chinese",
2346 "ru_RU" => "Russian");
2348 $tmp2= array(
2349 "de_DE" => _("German"),
2350 "fr_FR" => _("French"),
2351 "it_IT" => _("Italian"),
2352 "es_ES" => _("Spanish"),
2353 "en_US" => _("English"),
2354 "nl_NL" => _("Dutch"),
2355 "pl_PL" => _("Polish"),
2356 "sv_SE" => _("Swedish"),
2357 "zh_CN" => _("Chinese"),
2358 "ru_RU" => _("Russian"));
2360 $ret = array();
2361 if($languages_in_own_language){
2363 $old_lang = setlocale(LC_ALL, 0);
2364 foreach($tmp as $key => $name){
2365 $lang = $key.".UTF-8";
2366 setlocale(LC_ALL, $lang);
2367 if($strip_region_tag){
2368 $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2369 }else{
2370 $ret[$key] = _($name)." (".$tmp2[$key].")";
2371 }
2372 }
2373 setlocale(LC_ALL, $old_lang);
2374 }else{
2375 foreach($tmp as $key => $name){
2376 if($strip_region_tag){
2377 $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2378 }else{
2379 $ret[$key] = _($name);
2380 }
2381 }
2382 }
2383 return($ret);
2384 }
2387 /* Returns contents of the given POST variable and check magic quotes settings */
2388 function get_post($name)
2389 {
2390 if(!isset($_POST[$name])){
2391 trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2392 return(FALSE);
2393 }
2394 if(get_magic_quotes_gpc()){
2395 return(stripcslashes($_POST[$name]));
2396 }else{
2397 return($_POST[$name]);
2398 }
2399 }
2402 /* Return class name in correct case */
2403 function get_correct_class_name($cls)
2404 {
2405 global $class_mapping;
2406 if(isset($class_mapping) && is_array($class_mapping)){
2407 foreach($class_mapping as $class => $file){
2408 if(preg_match("/^".$cls."$/i",$class)){
2409 return($class);
2410 }
2411 }
2412 }
2413 return(FALSE);
2414 }
2417 // change_password, changes the Password, of the given dn
2418 function change_password ($dn, $password, $mode=0, $hash= "")
2419 {
2420 global $config;
2421 $newpass= "";
2423 /* Convert to lower. Methods are lowercase */
2424 $hash= strtolower($hash);
2426 // Get all available encryption Methods
2428 // NON STATIC CALL :)
2429 $methods = new passwordMethod(session::get('config'));
2430 $available = $methods->get_available_methods();
2432 // read current password entry for $dn, to detect the encryption Method
2433 $ldap = $config->get_ldap_link();
2434 $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2435 $attrs = $ldap->fetch ();
2437 // Check if user account was deactivated, indicated by ! after } ... {crypt}!###
2438 if(isset($attrs['userPassword'][0]) && preg_match("/^[^\}]*+\}!/",$attrs['userPassword'][0])){
2439 $deactivated = TRUE;
2440 }else{
2441 $deactivated = FALSE;
2442 }
2444 /* Is ensure that clear passwords will stay clear */
2445 if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2446 $hash = "clear";
2447 }
2449 // Detect the encryption Method
2450 if ( (isset($attrs['userPassword'][0]) && preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) || $hash != ""){
2452 /* Check for supported algorithm */
2453 mt_srand((double) microtime()*1000000);
2455 /* Extract used hash */
2456 if ($hash == ""){
2457 $test = passwordMethod::get_method($attrs['userPassword'][0]);
2458 } else {
2459 $test = new $available[$hash]($config);
2460 $test->set_hash($hash);
2461 }
2463 } else {
2464 // User MD5 by default
2465 $hash= "md5";
2466 $test = new $available['md5']($config);
2467 }
2469 /* Feed password backends with information */
2470 $test->dn= $dn;
2471 $test->attrs= $attrs;
2472 $newpass= $test->generate_hash($password);
2474 // Update shadow timestamp?
2475 if (isset($attrs["shadowLastChange"][0])){
2476 $shadow= (int)(date("U") / 86400);
2477 } else {
2478 $shadow= 0;
2479 }
2481 // Write back modified entry
2482 $ldap->cd($dn);
2483 $attrs= array();
2485 // Not for groups
2486 if ($mode == 0){
2488 if ($shadow != 0){
2489 $attrs['shadowLastChange']= $shadow;
2490 }
2492 // Create SMB Password
2493 $attrs= generate_smb_nt_hash($password);
2494 }
2496 /* Read ! if user was deactivated */
2497 if($deactivated){
2498 $newpass = preg_replace("/(^[^\}]+\})(.*$)/","\\1!\\2",$newpass);
2499 }
2501 $attrs['userPassword']= array();
2502 $attrs['userPassword']= $newpass;
2504 $ldap->modify($attrs);
2506 new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2508 if (!$ldap->success()) {
2509 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, ERROR_DIALOG));
2510 } else {
2512 /* Run backend method for change/create */
2513 $test->set_password($password);
2515 /* Find postmodify entries for this class */
2516 $command= $config->search("password", "POSTMODIFY",array('menu'));
2518 if ($command != ""){
2519 /* Walk through attribute list */
2520 $command= preg_replace("/%userPassword/", $password, $command);
2521 $command= preg_replace("/%dn/", $dn, $command);
2523 if (check_command($command)){
2524 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2525 exec($command);
2526 } else {
2527 $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2528 msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2529 }
2530 }
2531 }
2532 }
2535 // Return something like array['sambaLMPassword']= "lalla..."
2536 function generate_smb_nt_hash($password)
2537 {
2538 global $config;
2540 # Try to use gosa-si?
2541 if (isset($config->current['GOSA_SI'])){
2542 $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
2543 if (isset($res['XML']['HASH'])){
2544 $hash= $res['XML']['HASH'];
2545 } else {
2546 $hash= "";
2547 }
2548 } else {
2549 $tmp= $config->data['MAIN']['SMBHASH']." ".escapeshellarg($password);
2550 @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2552 exec($tmp, $ar);
2553 flush();
2554 reset($ar);
2555 $hash= current($ar);
2556 }
2558 if ($hash == "") {
2559 msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
2560 return ("");
2561 }
2563 list($lm,$nt)= split (":", trim($hash));
2565 if ($config->current['SAMBAVERSION'] == 3) {
2566 $attrs['sambaLMPassword']= $lm;
2567 $attrs['sambaNTPassword']= $nt;
2568 $attrs['sambaPwdLastSet']= date('U');
2569 $attrs['sambaBadPasswordCount']= "0";
2570 $attrs['sambaBadPasswordTime']= "0";
2571 } else {
2572 $attrs['lmPassword']= $lm;
2573 $attrs['ntPassword']= $nt;
2574 $attrs['pwdLastSet']= date('U');
2575 }
2576 return($attrs);
2577 }
2580 function getEntryCSN($dn)
2581 {
2582 global $config;
2583 if(empty($dn) || !is_object($config)){
2584 return("");
2585 }
2587 /* Get attribute that we should use as serial number */
2588 if(isset($config->current['UNIQ_IDENTIFIER'])){
2589 $attr = $config->current['UNIQ_IDENTIFIER'];
2590 }elseif(isset($config->data['MAIN']['UNIQ_IDENTIFIER'])){
2591 $attr = $config->data['MAIN']['UNIQ_IDENTIFIER'];
2592 }
2593 if(!empty($attr)){
2594 $ldap = $config->get_ldap_link();
2595 $ldap->cat($dn,array($attr));
2596 $csn = $ldap->fetch();
2597 if(isset($csn[$attr][0])){
2598 return($csn[$attr][0]);
2599 }
2600 }
2601 return("");
2602 }
2605 /* Add a given objectClass to an attrs entry */
2606 function add_objectClass($classes, &$attrs)
2607 {
2608 if (is_array($classes)){
2609 $list= $classes;
2610 } else {
2611 $list= array($classes);
2612 }
2614 foreach ($list as $class){
2615 $attrs['objectClass'][]= $class;
2616 }
2617 }
2620 /* Removes a given objectClass from the attrs entry */
2621 function remove_objectClass($classes, &$attrs)
2622 {
2623 if (isset($attrs['objectClass'])){
2624 /* Array? */
2625 if (is_array($classes)){
2626 $list= $classes;
2627 } else {
2628 $list= array($classes);
2629 }
2631 $tmp= array();
2632 foreach ($attrs['objectClass'] as $oc) {
2633 foreach ($list as $class){
2634 if ($oc != $class){
2635 $tmp[]= $oc;
2636 }
2637 }
2638 }
2639 $attrs['objectClass']= $tmp;
2640 }
2641 }
2643 /*! \brief Initialize a file download with given content, name and data type.
2644 * @param data String The content to send.
2645 * @param name String The name of the file.
2646 * @param type String The content identifier, default value is "application/octet-stream";
2647 */
2648 function send_binary_content($data,$name,$type = "application/octet-stream")
2649 {
2650 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
2651 header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
2652 header("Cache-Control: no-cache");
2653 header("Pragma: no-cache");
2654 header("Cache-Control: post-check=0, pre-check=0");
2655 header("Content-type: ".$type."");
2657 /* force download dialog */
2658 if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
2659 header('Content-Disposition: filename="'.$name.'"');
2660 } else {
2661 header('Content-Disposition: attachment; filename="'.$name.'"');
2662 }
2664 echo $data;
2665 exit();
2666 }
2669 /*! \brief Encode special string characters so we can use the string in \
2670 HTML output, without breaking quotes.
2671 @param The String we want to encode.
2672 @return The encoded String
2673 */
2674 function xmlentities($str)
2675 {
2676 if(is_string($str)){
2677 return(htmlentities($str,ENT_QUOTES));
2678 }elseif(is_array($str)){
2679 foreach($str as $name => $value){
2680 $str[$name] = xmlentities($value);
2681 }
2682 }
2683 return($str);
2684 }
2687 /*! \brief Updates all accessTo attributes from a given value to a new one.
2688 For example if a host is renamed.
2689 @param String $from The source accessTo name.
2690 @param String $to The destination accessTo name.
2691 */
2692 function update_accessTo($from,$to)
2693 {
2694 global $config;
2695 $ldap = $config->get_ldap_link();
2696 $ldap->cd($config->current['BASE']);
2697 $ldap->search("(&(objectClass=trustAccount)(accessTo=".$from."))",array("objectClass","accessTo"));
2698 while($attrs = $ldap->fetch()){
2699 $new_attrs = array();
2700 $dn = $attrs['dn'];
2701 for($i = 0 ; $i < $attrs['objectClass']['count']; $i++){
2702 $new_attrs['objectClass'][] = $attrs['objectClass'][$i];
2703 }
2704 for($i = 0 ; $i < $attrs['accessTo']['count']; $i++){
2705 if($attrs['accessTo'][$i] == $from){
2706 if(!empty($to)){
2707 $new_attrs['accessTo'][] = $to;
2708 }
2709 }else{
2710 $new_attrs['accessTo'][] = $attrs['accessTo'][$i];
2711 }
2712 }
2713 $ldap->cd($dn);
2714 $ldap->modify($new_attrs);
2715 if (!$ldap->success()){
2716 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, "update_accessTo($from,$to)"));
2717 }
2718 new log("modify","update_accessTo($from,$to)",$dn,array_keys($new_attrs),$ldap->get_error());
2719 }
2720 }
2723 function get_random_char () {
2724 $randno = rand (0, 63);
2725 if ($randno < 12) {
2726 return (chr ($randno + 46)); // Digits, '/' and '.'
2727 } else if ($randno < 38) {
2728 return (chr ($randno + 53)); // Uppercase
2729 } else {
2730 return (chr ($randno + 59)); // Lowercase
2731 }
2732 }
2734 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2735 ?>