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 global $config;
1097 $dn = preg_replace("/".normalizePreg($config->current['BASE'])."$/i","",$dn);
1098 if(empty($dn)) return("/");
1100 foreach (split(',', $dn) as $rdn){
1102 /* We're only interested in organizational units... */
1103 if (substr($rdn,0,3) == 'ou='){
1104 $dep= substr($rdn,3)."/$dep";
1105 }
1107 /* ... and location objects */
1108 if (substr($rdn,0,2) == 'l='){
1109 $dep= substr($rdn,2)."/$dep";
1110 }
1111 }
1113 /* Return and remove accidently trailing slashes */
1114 return rtrim($dep, "/");
1115 }
1118 /* Strip off the last sub department part of a '/level1/level2/.../'
1119 * style value. It removes the trailing '/', too. */
1120 function get_sub_department($value)
1121 {
1122 return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1123 }
1126 function get_ou($name)
1127 {
1128 global $config;
1130 $map = array(
1131 "ogroupou" => "ou=groups,",
1132 "applicationou" => "ou=apps,",
1133 "systemsou" => "ou=systems,",
1134 "serverou" => "ou=servers,ou=systems,",
1135 "terminalou" => "ou=terminals,ou=systems,",
1136 "workstationou" => "ou=workstations,ou=systems,",
1137 "printerou" => "ou=printers,ou=systems,",
1138 "phoneou" => "ou=phones,ou=systems,",
1139 "componentou" => "ou=netdevices,ou=systems,",
1140 "blocklistou" => "ou=gofax,ou=systems,",
1141 "incomingou" => "ou=incoming,",
1142 "aclroleou" => "ou=aclroles,",
1143 "macroou" => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1144 "conferenceou" => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1146 "faiou" => "ou=fai,ou=configs,ou=systems,",
1147 "faiscriptou" => "ou=scripts,",
1148 "faihookou" => "ou=hooks,",
1149 "faitemplateou" => "ou=templates,",
1150 "faivariableou" => "ou=variables,",
1151 "faiprofileou" => "ou=profiles,",
1152 "faipackageou" => "ou=packages,",
1153 "faipartitionou"=> "ou=disk,",
1155 "deviceou" => "ou=devices,",
1156 "mimetypeou" => "ou=mime,");
1158 /* Preset ou... */
1159 if (isset($config->current[strtoupper($name)])){
1160 $ou= $config->current[strtoupper($name)];
1161 } elseif (isset($map[$name])) {
1162 $ou = $map[$name];
1163 return($ou);
1164 } else {
1165 trigger_error("No department mapping found for type ".$name);
1166 return "";
1167 }
1170 if ($ou != ""){
1171 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1172 $ou = @LDAP::convert("ou=$ou");
1173 } else {
1174 $ou = @LDAP::convert("$ou");
1175 }
1177 if(preg_match("/".normalizePreg($config->current['BASE'])."$/",$ou)){
1178 return($ou);
1179 }else{
1180 return("$ou,");
1181 }
1183 } else {
1184 return "";
1185 }
1186 }
1189 function get_people_ou()
1190 {
1191 return (get_ou("PEOPLE"));
1192 }
1195 function get_groups_ou()
1196 {
1197 return (get_ou("GROUPS"));
1198 }
1201 function get_winstations_ou()
1202 {
1203 return (get_ou("WINSTATIONS"));
1204 }
1207 function get_base_from_people($dn)
1208 {
1209 global $config;
1211 $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
1212 $base= preg_replace($pattern, '', $dn);
1214 /* Set to base, if we're not on a correct subtree */
1215 if (!isset($config->idepartments[$base])){
1216 $base= $config->current['BASE'];
1217 }
1219 return ($base);
1220 }
1223 function strict_uid_mode()
1224 {
1225 global $config;
1227 return !(isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT']));
1228 }
1231 function get_uid_regexp()
1232 {
1233 /* STRICT adds spaces and case insenstivity to the uid check.
1234 This is dangerous and should not be used. */
1235 if (strict_uid_mode()){
1236 return "^[a-z0-9_-]+$";
1237 } else {
1238 return "^[a-zA-Z0-9 _.-]+$";
1239 }
1240 }
1243 function gen_locked_message($user, $dn)
1244 {
1245 global $plug, $config;
1247 session::set('dn', $dn);
1248 $remove= false;
1250 /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1251 if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1253 $LOCK_VARS_USED = array();
1254 $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1256 foreach($LOCK_VARS_TO_USE as $name){
1258 if(empty($name)){
1259 continue;
1260 }
1262 foreach($_POST as $Pname => $Pvalue){
1263 if(preg_match($name,$Pname)){
1264 $LOCK_VARS_USED[$Pname] = $_POST[$Pname];
1265 }
1266 }
1268 foreach($_GET as $Pname => $Pvalue){
1269 if(preg_match($name,$Pname)){
1270 $LOCK_VARS_USED[$Pname] = $_GET[$Pname];
1271 }
1272 }
1273 }
1274 session::set('LOCK_VARS_TO_USE',array());
1275 session::set('LOCK_VARS_USED' , $LOCK_VARS_USED);
1276 }
1278 /* Prepare and show template */
1279 $smarty= get_smarty();
1281 if(is_array($dn)){
1282 $msg = "<pre>";
1283 foreach($dn as $sub_dn){
1284 $msg .= "\n".$sub_dn.", ";
1285 }
1286 $msg = preg_replace("/, $/","</pre>",$msg);
1287 }else{
1288 $msg = $dn;
1289 }
1291 $smarty->assign ("dn", $msg);
1292 if ($remove){
1293 $smarty->assign ("action", _("Continue anyway"));
1294 } else {
1295 $smarty->assign ("action", _("Edit anyway"));
1296 }
1297 $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries %s"), "<b>".$msg."</b>", ""));
1299 return ($smarty->fetch (get_template_path('islocked.tpl')));
1300 }
1303 function to_string ($value)
1304 {
1305 /* If this is an array, generate a text blob */
1306 if (is_array($value)){
1307 $ret= "";
1308 foreach ($value as $line){
1309 $ret.= $line."<br>\n";
1310 }
1311 return ($ret);
1312 } else {
1313 return ($value);
1314 }
1315 }
1318 function get_printer_list()
1319 {
1320 global $config;
1321 $res = array();
1322 $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1323 foreach($data as $attrs ){
1324 $res[$attrs['cn'][0]] = $attrs['cn'][0];
1325 }
1326 return $res;
1327 }
1330 function rewrite($s)
1331 {
1332 global $REWRITE;
1334 foreach ($REWRITE as $key => $val){
1335 $s= preg_replace("/$key/", "$val", $s);
1336 }
1338 return ($s);
1339 }
1342 function dn2base($dn)
1343 {
1344 global $config;
1346 if (get_people_ou() != ""){
1347 $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1348 }
1349 if (get_groups_ou() != ""){
1350 $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1351 }
1352 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1354 return ($base);
1355 }
1359 function check_command($cmdline)
1360 {
1361 $cmd= preg_replace("/ .*$/", "", $cmdline);
1363 /* Check if command exists in filesystem */
1364 if (!file_exists($cmd)){
1365 return (FALSE);
1366 }
1368 /* Check if command is executable */
1369 if (!is_executable($cmd)){
1370 return (FALSE);
1371 }
1373 return (TRUE);
1374 }
1377 function print_header($image, $headline, $info= "")
1378 {
1379 $display= "<div class=\"plugtop\">\n";
1380 $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";
1381 $display.= "</div>\n";
1383 if ($info != ""){
1384 $display.= "<div class=\"pluginfo\">\n";
1385 $display.= "$info";
1386 $display.= "</div>\n";
1387 } else {
1388 $display.= "<div style=\"height:5px;\">\n";
1389 $display.= " ";
1390 $display.= "</div>\n";
1391 }
1392 return ($display);
1393 }
1396 function range_selector($dcnt,$start,$range=25,$post_var=false)
1397 {
1399 /* Entries shown left and right from the selected entry */
1400 $max_entries= 10;
1402 /* Initialize and take care that max_entries is even */
1403 $output="";
1404 if ($max_entries & 1){
1405 $max_entries++;
1406 }
1408 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1409 $range= $_POST[$post_var];
1410 }
1412 /* Prevent output to start or end out of range */
1413 if ($start < 0 ){
1414 $start= 0 ;
1415 }
1416 if ($start >= $dcnt){
1417 $start= $range * (int)(($dcnt / $range) + 0.5);
1418 }
1420 $numpages= (($dcnt / $range));
1421 if(((int)($numpages))!=($numpages)){
1422 $numpages = (int)$numpages + 1;
1423 }
1424 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1425 return ("");
1426 }
1427 $ppage= (int)(($start / $range) + 0.5);
1430 /* Align selected page to +/- max_entries/2 */
1431 $begin= $ppage - $max_entries/2;
1432 $end= $ppage + $max_entries/2;
1434 /* Adjust begin/end, so that the selected value is somewhere in
1435 the middle and the size is max_entries if possible */
1436 if ($begin < 0){
1437 $end-= $begin + 1;
1438 $begin= 0;
1439 }
1440 if ($end > $numpages) {
1441 $end= $numpages;
1442 }
1443 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1444 $begin= $end - $max_entries;
1445 }
1447 if($post_var){
1448 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1449 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1450 }else{
1451 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1452 }
1454 /* Draw decrement */
1455 if ($start > 0 ) {
1456 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1457 (($start-$range))."\">".
1458 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1459 }
1461 /* Draw pages */
1462 for ($i= $begin; $i < $end; $i++) {
1463 if ($ppage == $i){
1464 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1465 validate($_GET['plug'])."&start=".
1466 ($i*$range)."\"> ".($i+1)." </a>";
1467 } else {
1468 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1469 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1470 }
1471 }
1473 /* Draw increment */
1474 if($start < ($dcnt-$range)) {
1475 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1476 (($start+($range)))."\">".
1477 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1478 }
1480 if(($post_var)&&($numpages)){
1481 $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()'>";
1482 foreach(array(20,50,100,200,"all") as $num){
1483 if($num == "all"){
1484 $var = 10000;
1485 }else{
1486 $var = $num;
1487 }
1488 if($var == $range){
1489 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1490 }else{
1491 $output.="\n<option value='".$var."'>".$num."</option>";
1492 }
1493 }
1494 $output.= "</select></td></tr></table></div>";
1495 }else{
1496 $output.= "</div>";
1497 }
1499 return($output);
1500 }
1503 function apply_filter()
1504 {
1505 $apply= "";
1507 $apply= ''.
1508 '<table summary="" width="100%" style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1509 '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1511 return ($apply);
1512 }
1515 function back_to_main()
1516 {
1517 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1518 msgPool::backButton().'"></p><input type="hidden" name="ignore">';
1520 return ($string);
1521 }
1524 function normalize_netmask($netmask)
1525 {
1526 /* Check for notation of netmask */
1527 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1528 $num= (int)($netmask);
1529 $netmask= "";
1531 for ($byte= 0; $byte<4; $byte++){
1532 $result=0;
1534 for ($i= 7; $i>=0; $i--){
1535 if ($num-- > 0){
1536 $result+= pow(2,$i);
1537 }
1538 }
1540 $netmask.= $result.".";
1541 }
1543 return (preg_replace('/\.$/', '', $netmask));
1544 }
1546 return ($netmask);
1547 }
1550 function netmask_to_bits($netmask)
1551 {
1552 list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1553 $res= 0;
1555 for ($n= 0; $n<4; $n++){
1556 $start= 255;
1557 $name= "nm$n";
1559 for ($i= 0; $i<8; $i++){
1560 if ($start == (int)($$name)){
1561 $res+= 8 - $i;
1562 break;
1563 }
1564 $start-= pow(2,$i);
1565 }
1566 }
1568 return ($res);
1569 }
1572 function recurse($rule, $variables)
1573 {
1574 $result= array();
1576 if (!count($variables)){
1577 return array($rule);
1578 }
1580 reset($variables);
1581 $key= key($variables);
1582 $val= current($variables);
1583 unset ($variables[$key]);
1585 foreach($val as $possibility){
1586 $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1587 $result= array_merge($result, recurse($nrule, $variables));
1588 }
1590 return ($result);
1591 }
1594 function expand_id($rule, $attributes)
1595 {
1596 /* Check for id rule */
1597 if(preg_match('/^id(:|#)\d+$/',$rule)){
1598 return (array("\{$rule}"));
1599 }
1601 /* Check for clean attribute */
1602 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1603 $rule= preg_replace('/^%/', '', $rule);
1604 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1605 return (array($val));
1606 }
1608 /* Check for attribute with parameters */
1609 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1610 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1611 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1612 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1613 $start= preg_replace ('/-.*$/', '', $param);
1614 $stop = preg_replace ('/^[^-]+-/', '', $param);
1616 /* Assemble results */
1617 $result= array();
1618 for ($i= $start; $i<= $stop; $i++){
1619 $result[]= substr($val, 0, $i);
1620 }
1621 return ($result);
1622 }
1624 echo "Error in idgen string: don't know how to handle rule $rule.\n";
1625 return (array($rule));
1626 }
1629 function gen_uids($rule, $attributes)
1630 {
1631 global $config;
1633 /* Search for keys and fill the variables array with all
1634 possible values for that key. */
1635 $part= "";
1636 $trigger= false;
1637 $stripped= "";
1638 $variables= array();
1640 for ($pos= 0; $pos < strlen($rule); $pos++){
1642 if ($rule[$pos] == "{" ){
1643 $trigger= true;
1644 $part= "";
1645 continue;
1646 }
1648 if ($rule[$pos] == "}" ){
1649 $variables[$pos]= expand_id($part, $attributes);
1650 $stripped.= "{".$pos."}";
1651 $trigger= false;
1652 continue;
1653 }
1655 if ($trigger){
1656 $part.= $rule[$pos];
1657 } else {
1658 $stripped.= $rule[$pos];
1659 }
1660 }
1662 /* Recurse through all possible combinations */
1663 $proposed= recurse($stripped, $variables);
1665 /* Get list of used ID's */
1666 $used= array();
1667 $ldap= $config->get_ldap_link();
1668 $ldap->cd($config->current['BASE']);
1669 $ldap->search('(uid=*)');
1671 while($attrs= $ldap->fetch()){
1672 $used[]= $attrs['uid'][0];
1673 }
1675 /* Remove used uids and watch out for id tags */
1676 $ret= array();
1677 foreach($proposed as $uid){
1679 /* Check for id tag and modify uid if needed */
1680 if(preg_match('/\{id:\d+}/',$uid)){
1681 $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1683 for ($i= 0; $i < pow(10,$size); $i++){
1684 $number= sprintf("%0".$size."d", $i);
1685 $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1686 if (!in_array($res, $used)){
1687 $uid= $res;
1688 break;
1689 }
1690 }
1691 }
1693 if(preg_match('/\{id#\d+}/',$uid)){
1694 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1696 while (true){
1697 mt_srand((double) microtime()*1000000);
1698 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1699 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1700 if (!in_array($res, $used)){
1701 $uid= $res;
1702 break;
1703 }
1704 }
1705 }
1707 /* Don't assign used ones */
1708 if (!in_array($uid, $used)){
1709 $ret[]= $uid;
1710 }
1711 }
1713 return(array_unique($ret));
1714 }
1717 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1718 Need to convert... */
1719 function to_byte($value) {
1720 $value= strtolower(trim($value));
1722 if(!is_numeric(substr($value, -1))) {
1724 switch(substr($value, -1)) {
1725 case 'g':
1726 $mult= 1073741824;
1727 break;
1728 case 'm':
1729 $mult= 1048576;
1730 break;
1731 case 'k':
1732 $mult= 1024;
1733 break;
1734 }
1736 return ($mult * (int)substr($value, 0, -1));
1737 } else {
1738 return $value;
1739 }
1740 }
1743 function in_array_ics($value, $items)
1744 {
1745 if (!is_array($items)){
1746 return (FALSE);
1747 }
1749 foreach ($items as $item){
1750 if (strcasecmp($item, $value) == 0) {
1751 return (TRUE);
1752 }
1753 }
1755 return (FALSE);
1756 }
1759 function generate_alphabet($count= 10)
1760 {
1761 $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1762 $alphabet= "";
1763 $c= 0;
1765 /* Fill cells with charaters */
1766 for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1767 if ($c == 0){
1768 $alphabet.= "<tr>";
1769 }
1771 $ch = mb_substr($characters, $i, 1, "UTF8");
1772 $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1773 validate($_GET['plug'])."&search=".$ch."\"> ".$ch." </a></td>";
1775 if ($c++ == $count){
1776 $alphabet.= "</tr>";
1777 $c= 0;
1778 }
1779 }
1781 /* Fill remaining cells */
1782 while ($c++ <= $count){
1783 $alphabet.= "<td> </td>";
1784 }
1786 return ($alphabet);
1787 }
1790 function validate($string)
1791 {
1792 return (strip_tags(preg_replace('/\0/', '', $string)));
1793 }
1796 function get_gosa_version()
1797 {
1798 global $svn_revision, $svn_path;
1800 /* Extract informations */
1801 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1803 /* Release or development? */
1804 if (preg_match('%/gosa/trunk/%', $svn_path)){
1805 return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1806 } else {
1807 $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1808 return (sprintf(_("GOsa $release"), $revision));
1809 }
1810 }
1813 function rmdirRecursive($path, $followLinks=false) {
1814 $dir= opendir($path);
1815 while($entry= readdir($dir)) {
1816 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1817 unlink($path."/".$entry);
1818 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1819 rmdirRecursive($path."/".$entry);
1820 }
1821 }
1822 closedir($dir);
1823 return rmdir($path);
1824 }
1827 function scan_directory($path,$sort_desc=false)
1828 {
1829 $ret = false;
1831 /* is this a dir ? */
1832 if(is_dir($path)) {
1834 /* is this path a readable one */
1835 if(is_readable($path)){
1837 /* Get contents and write it into an array */
1838 $ret = array();
1840 $dir = opendir($path);
1842 /* Is this a correct result ?*/
1843 if($dir){
1844 while($fp = readdir($dir))
1845 $ret[]= $fp;
1846 }
1847 }
1848 }
1849 /* Sort array ascending , like scandir */
1850 sort($ret);
1852 /* Sort descending if parameter is sort_desc is set */
1853 if($sort_desc) {
1854 $ret = array_reverse($ret);
1855 }
1857 return($ret);
1858 }
1861 function clean_smarty_compile_dir($directory)
1862 {
1863 global $svn_revision;
1865 if(is_dir($directory) && is_readable($directory)) {
1866 // Set revision filename to REVISION
1867 $revision_file= $directory."/REVISION";
1869 /* Is there a stamp containing the current revision? */
1870 if(!file_exists($revision_file)) {
1871 // create revision file
1872 create_revision($revision_file, $svn_revision);
1873 } else {
1874 # check for "$config->...['CONFIG']/revision" and the
1875 # contents should match the revision number
1876 if(!compare_revision($revision_file, $svn_revision)){
1877 // If revision differs, clean compile directory
1878 foreach(scan_directory($directory) as $file) {
1879 if(($file==".")||($file=="..")) continue;
1880 if( is_file($directory."/".$file) &&
1881 is_writable($directory."/".$file)) {
1882 // delete file
1883 if(!unlink($directory."/".$file)) {
1884 msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
1885 // This should never be reached
1886 }
1887 } elseif(is_dir($directory."/".$file) &&
1888 is_writable($directory."/".$file)) {
1889 // Just recursively delete it
1890 rmdirRecursive($directory."/".$file);
1891 }
1892 }
1893 // We should now create a fresh revision file
1894 clean_smarty_compile_dir($directory);
1895 } else {
1896 // Revision matches, nothing to do
1897 }
1898 }
1899 } else {
1900 // Smarty compile dir is not accessible
1901 // (Smarty will warn about this)
1902 }
1903 }
1906 function create_revision($revision_file, $revision)
1907 {
1908 $result= false;
1910 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1911 if($fh= fopen($revision_file, "w")) {
1912 if(fwrite($fh, $revision)) {
1913 $result= true;
1914 }
1915 }
1916 fclose($fh);
1917 } else {
1918 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1919 }
1921 return $result;
1922 }
1925 function compare_revision($revision_file, $revision)
1926 {
1927 // false means revision differs
1928 $result= false;
1930 if(file_exists($revision_file) && is_readable($revision_file)) {
1931 // Open file
1932 if($fh= fopen($revision_file, "r")) {
1933 // Compare File contents with current revision
1934 if($revision == fread($fh, filesize($revision_file))) {
1935 $result= true;
1936 }
1937 } else {
1938 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1939 }
1940 // Close file
1941 fclose($fh);
1942 }
1944 return $result;
1945 }
1948 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1949 {
1950 $str = ""; // Our return value will be saved in this var
1952 $color = dechex($percentage+150);
1953 $color2 = dechex(150 - $percentage);
1954 $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1956 $progress = (int)(($percentage /100)*$width);
1958 /* Abort printing out percentage, if divs are to small */
1961 /* If theres a better solution for this, use it... */
1962 $str = "
1963 <div style=\" width:".($width)."px;
1964 height:".($height)."px;
1965 background-color:#000000;
1966 padding:1px;\">
1968 <div style=\" width:".($width)."px;
1969 background-color:#$bgcolor;
1970 height:".($height)."px;\">
1972 <div style=\" width:".$progress."px;
1973 height:".$height."px;
1974 background-color:#".$color2.$color2.$color."; \">";
1977 if(($height >10)&&($showvalue)){
1978 $str.= "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1979 <b>".$percentage."%</b>
1980 </font>";
1981 }
1983 $str.= "</div></div></div>";
1985 return($str);
1986 }
1989 function array_key_ics($ikey, $items)
1990 {
1991 /* Gather keys, make them lowercase */
1992 $tmp= array();
1993 foreach ($items as $key => $value){
1994 $tmp[strtolower($key)]= $key;
1995 }
1997 if (isset($tmp[strtolower($ikey)])){
1998 return($tmp[strtolower($ikey)]);
1999 }
2001 return ("");
2002 }
2005 function array_differs($src, $dst)
2006 {
2007 /* If the count is differing, the arrays differ */
2008 if (count ($src) != count ($dst)){
2009 return (TRUE);
2010 }
2012 /* So the count is the same - lets check the contents */
2013 $differs= FALSE;
2014 foreach($src as $value){
2015 if (!in_array($value, $dst)){
2016 $differs= TRUE;
2017 }
2018 }
2020 return ($differs);
2021 }
2024 function saveFilter($a_filter, $values)
2025 {
2026 if (isset($_POST['regexit'])){
2027 $a_filter["regex"]= $_POST['regexit'];
2029 foreach($values as $type){
2030 if (isset($_POST[$type])) {
2031 $a_filter[$type]= "checked";
2032 } else {
2033 $a_filter[$type]= "";
2034 }
2035 }
2036 }
2038 /* React on alphabet links if needed */
2039 if (isset($_GET['search'])){
2040 $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2041 if ($s == "**"){
2042 $s= "*";
2043 }
2044 $a_filter['regex']= $s;
2045 }
2047 return ($a_filter);
2048 }
2051 /* Escape all preg_* relevant characters */
2052 function normalizePreg($input)
2053 {
2054 return (addcslashes($input, '[]()|/.*+-'));
2055 }
2058 /* Escape all LDAP filter relevant characters */
2059 function normalizeLdap($input)
2060 {
2061 return (addcslashes($input, '()|'));
2062 }
2065 /* Resturns the difference between to microtime() results in float */
2066 function get_MicroTimeDiff($start , $stop)
2067 {
2068 $a = split("\ ",$start);
2069 $b = split("\ ",$stop);
2071 $secs = $b[1] - $a[1];
2072 $msecs= $b[0] - $a[0];
2074 $ret = (float) ($secs+ $msecs);
2075 return($ret);
2076 }
2079 function get_base_dir()
2080 {
2081 global $BASE_DIR;
2083 return $BASE_DIR;
2084 }
2087 function obj_is_readable($dn, $object, $attribute)
2088 {
2089 global $ui;
2091 return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2092 }
2095 function obj_is_writable($dn, $object, $attribute)
2096 {
2097 global $ui;
2099 return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2100 }
2103 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2104 {
2105 /* Initialize variables */
2106 $ret = array("count" => 0); // Set count to 0
2107 $next = true; // if false, then skip next loops and return
2108 $cnt = 0; // Current number of loops
2109 $max = 100; // Just for security, prevent looops
2110 $ldap = NULL; // To check if created result a valid
2111 $keep = ""; // save last failed parse string
2113 /* Check each parsed dn in ldap ? */
2114 if($config!==NULL && $verify_in_ldap){
2115 $ldap = $config->get_ldap_link();
2116 }
2118 /* Lets start */
2119 $called = false;
2120 while(preg_match("/,/",$dn) && $next && $cnt < $max){
2122 $cnt ++;
2123 if(!preg_match("/,/",$dn)){
2124 $next = false;
2125 }
2126 $object = preg_replace("/[,].*$/","",$dn);
2127 $dn = preg_replace("/^[^,]+,/","",$dn);
2129 $called = true;
2131 /* Check if current dn is valid */
2132 if($ldap!==NULL){
2133 $ldap->cd($dn);
2134 $ldap->cat($dn,array("dn"));
2135 if($ldap->count()){
2136 $ret[] = $keep.$object;
2137 $keep = "";
2138 }else{
2139 $keep .= $object.",";
2140 }
2141 }else{
2142 $ret[] = $keep.$object;
2143 $keep = "";
2144 }
2145 }
2147 /* No dn was posted */
2148 if($cnt == 0 && !empty($dn)){
2149 $ret[] = $dn;
2150 }
2152 /* Append the rest */
2153 $test = $keep.$dn;
2154 if($called && !empty($test)){
2155 $ret[] = $keep.$dn;
2156 }
2157 $ret['count'] = count($ret) - 1;
2159 return($ret);
2160 }
2163 function get_base_from_hook($dn, $attrib)
2164 {
2165 global $config;
2167 if (isset($config->current['BASE_HOOK'])){
2169 /* Call hook script - if present */
2170 $command= $config->current['BASE_HOOK'];
2172 if ($command != ""){
2173 $command.= " '".LDAP::fix($dn)."' $attrib";
2174 if (check_command($command)){
2175 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2176 exec($command, $output);
2177 if (preg_match("/^[0-9]+$/", $output[0])){
2178 return ($output[0]);
2179 } else {
2180 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base!"), WARNING_DIALOG);
2181 return ($config->current['UIDBASE']);
2182 }
2183 } else {
2184 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base!"), WARNING_DIALOG);
2185 return ($config->current['UIDBASE']);
2186 }
2188 } else {
2190 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base!"), WARNING_DIALOG);
2191 return ($config->current['UIDBASE']);
2193 }
2194 }
2195 }
2198 function check_schema_version($class, $version)
2199 {
2200 return preg_match("/\(v$version\)/", $class['DESC']);
2201 }
2204 function check_schema($cfg,$rfc2307bis = FALSE)
2205 {
2206 $messages= array();
2208 /* Get objectclasses */
2209 $ldap = new ldapMultiplexer(new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']));
2210 $objectclasses = $ldap->get_objectclasses();
2211 if(count($objectclasses) == 0){
2212 msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2213 }
2215 /* This is the default block used for each entry.
2216 * to avoid unset indexes.
2217 */
2218 $def_check = array("REQUIRED_VERSION" => "0",
2219 "SCHEMA_FILES" => array(),
2220 "CLASSES_REQUIRED" => array(),
2221 "STATUS" => FALSE,
2222 "IS_MUST_HAVE" => FALSE,
2223 "MSG" => "",
2224 "INFO" => "");#_("There is currently no information specified for this schema extension."));
2226 /* The gosa base schema */
2227 $checks['gosaObject'] = $def_check;
2228 $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2229 $checks['gosaObject']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2230 $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2231 $checks['gosaObject']['IS_MUST_HAVE'] = TRUE;
2233 /* GOsa Account class */
2234 $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2235 $checks["gosaAccount"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2236 $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2237 $checks["gosaAccount"]["IS_MUST_HAVE"] = TRUE;
2238 $checks["gosaAccount"]["INFO"] = _("Used to store account specific informations.");
2240 /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2241 $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2242 $checks["gosaLockEntry"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2243 $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2244 $checks["gosaLockEntry"]["IS_MUST_HAVE"] = TRUE;
2245 $checks["gosaLockEntry"]["INFO"] = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2247 /* Some other checks */
2248 foreach(array(
2249 "gosaCacheEntry" => array("version" => "2.4"),
2250 "gosaDepartment" => array("version" => "2.4"),
2251 "goFaxAccount" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2252 "goFaxSBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2253 "goFaxRBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2254 "gosaUserTemplate" => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2255 "gosaMailAccount" => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2256 "gosaProxyAccount" => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2257 "gosaApplication" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2258 "gosaApplicationGroup" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2259 "GOhard" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2260 "gotoTerminal" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2261 "goServer" => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2262 "goTerminalServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2263 "goShareServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2264 "goNtpServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2265 "goSyslogServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2266 "goLdapServer" => array("version" => "2.4"),
2267 "goCupsServer" => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2268 "goImapServer" => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3. schema"),
2269 "goKrbServer" => array("version" => "2.4"),
2270 "goFaxServer" => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2271 ) as $name => $values){
2273 $checks[$name] = $def_check;
2274 if(isset($values['version'])){
2275 $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2276 }
2277 if(isset($values['file'])){
2278 $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2279 }
2280 $checks[$name]["CLASSES_REQUIRED"] = array($name);
2281 }
2282 foreach($checks as $name => $value){
2283 foreach($value['CLASSES_REQUIRED'] as $class){
2285 if(!isset($objectclasses[$name])){
2286 $checks[$name]['STATUS'] = FALSE;
2287 if($value['IS_MUST_HAVE']){
2288 $checks[$name]['MSG'] = sprintf(_("Missing required object class '%s'!"),$class);
2289 }else{
2290 $checks[$name]['MSG'] = sprintf(_("Missing optional object class '%s'!"),$class);
2291 }
2292 }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2293 $checks[$name]['STATUS'] = FALSE;
2295 if($value['IS_MUST_HAVE']){
2296 $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2297 }else{
2298 $checks[$name]['MSG'] = sprintf(_("Version mismatch for optional object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2299 }
2300 }else{
2301 $checks[$name]['STATUS'] = TRUE;
2302 $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2303 }
2304 }
2305 }
2307 $tmp = $objectclasses;
2309 /* The gosa base schema */
2310 $checks['posixGroup'] = $def_check;
2311 $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2312 $checks['posixGroup']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2313 $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2314 $checks['posixGroup']['STATUS'] = TRUE;
2315 $checks['posixGroup']['IS_MUST_HAVE'] = TRUE;
2316 $checks['posixGroup']['MSG'] = "";
2317 $checks['posixGroup']['INFO'] = "";
2319 /* Depending on selected rfc2307bis mode, we need different schema configurations */
2320 if(isset($tmp['posixGroup'])){
2322 if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2323 $checks['posixGroup']['STATUS'] = FALSE;
2324 $checks['posixGroup']['MSG'] = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema configuration do not support this option.");
2325 $checks['posixGroup']['INFO'] = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be AUXILIARY");
2326 }
2327 if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2328 $checks['posixGroup']['STATUS'] = FALSE;
2329 $checks['posixGroup']['MSG'] = _("Your schema is configured to support the rfc2307bis group, but you have disabled this option on the 'ldap setup' step.");
2330 $checks['posixGroup']['INFO'] = _("The objectClass 'posixGroup' must be STRUCTURAL");
2331 }
2332 }
2334 return($checks);
2335 }
2338 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2339 {
2340 $tmp = array(
2341 "de_DE" => "German",
2342 "fr_FR" => "French",
2343 "it_IT" => "Italian",
2344 "es_ES" => "Spanish",
2345 "en_US" => "English",
2346 "nl_NL" => "Dutch",
2347 "pl_PL" => "Polish",
2348 "sv_SE" => "Swedish",
2349 "zh_CN" => "Chinese",
2350 "ru_RU" => "Russian");
2352 $tmp2= array(
2353 "de_DE" => _("German"),
2354 "fr_FR" => _("French"),
2355 "it_IT" => _("Italian"),
2356 "es_ES" => _("Spanish"),
2357 "en_US" => _("English"),
2358 "nl_NL" => _("Dutch"),
2359 "pl_PL" => _("Polish"),
2360 "sv_SE" => _("Swedish"),
2361 "zh_CN" => _("Chinese"),
2362 "ru_RU" => _("Russian"));
2364 $ret = array();
2365 if($languages_in_own_language){
2367 $old_lang = setlocale(LC_ALL, 0);
2368 foreach($tmp as $key => $name){
2369 $lang = $key.".UTF-8";
2370 setlocale(LC_ALL, $lang);
2371 if($strip_region_tag){
2372 $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2373 }else{
2374 $ret[$key] = _($name)." (".$tmp2[$key].")";
2375 }
2376 }
2377 setlocale(LC_ALL, $old_lang);
2378 }else{
2379 foreach($tmp as $key => $name){
2380 if($strip_region_tag){
2381 $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2382 }else{
2383 $ret[$key] = _($name);
2384 }
2385 }
2386 }
2387 return($ret);
2388 }
2391 /* Returns contents of the given POST variable and check magic quotes settings */
2392 function get_post($name)
2393 {
2394 if(!isset($_POST[$name])){
2395 trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2396 return(FALSE);
2397 }
2398 if(get_magic_quotes_gpc()){
2399 return(stripcslashes($_POST[$name]));
2400 }else{
2401 return($_POST[$name]);
2402 }
2403 }
2406 /* Return class name in correct case */
2407 function get_correct_class_name($cls)
2408 {
2409 global $class_mapping;
2410 if(isset($class_mapping) && is_array($class_mapping)){
2411 foreach($class_mapping as $class => $file){
2412 if(preg_match("/^".$cls."$/i",$class)){
2413 return($class);
2414 }
2415 }
2416 }
2417 return(FALSE);
2418 }
2421 // change_password, changes the Password, of the given dn
2422 function change_password ($dn, $password, $mode=0, $hash= "")
2423 {
2424 global $config;
2425 $newpass= "";
2427 /* Convert to lower. Methods are lowercase */
2428 $hash= strtolower($hash);
2430 // Get all available encryption Methods
2432 // NON STATIC CALL :)
2433 $methods = new passwordMethod(session::get('config'));
2434 $available = $methods->get_available_methods();
2436 // read current password entry for $dn, to detect the encryption Method
2437 $ldap = $config->get_ldap_link();
2438 $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2439 $attrs = $ldap->fetch ();
2441 // Check if user account was deactivated, indicated by ! after } ... {crypt}!###
2442 if(isset($attrs['userPassword'][0]) && preg_match("/^[^\}]*+\}!/",$attrs['userPassword'][0])){
2443 $deactivated = TRUE;
2444 }else{
2445 $deactivated = FALSE;
2446 }
2448 /* Is ensure that clear passwords will stay clear */
2449 if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2450 $hash = "clear";
2451 }
2453 // Detect the encryption Method
2454 if ( (isset($attrs['userPassword'][0]) && preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) || $hash != ""){
2456 /* Check for supported algorithm */
2457 mt_srand((double) microtime()*1000000);
2459 /* Extract used hash */
2460 if ($hash == ""){
2461 $test = passwordMethod::get_method($attrs['userPassword'][0]);
2462 } else {
2463 $test = new $available[$hash]($config);
2464 $test->set_hash($hash);
2465 }
2467 } else {
2468 // User MD5 by default
2469 $hash= "md5";
2470 $test = new $available['md5']($config);
2471 }
2473 /* Feed password backends with information */
2474 $test->dn= $dn;
2475 $test->attrs= $attrs;
2476 $newpass= $test->generate_hash($password);
2478 // Update shadow timestamp?
2479 if (isset($attrs["shadowLastChange"][0])){
2480 $shadow= (int)(date("U") / 86400);
2481 } else {
2482 $shadow= 0;
2483 }
2485 // Write back modified entry
2486 $ldap->cd($dn);
2487 $attrs= array();
2489 // Not for groups
2490 if ($mode == 0){
2492 if ($shadow != 0){
2493 $attrs['shadowLastChange']= $shadow;
2494 }
2496 // Create SMB Password
2497 $attrs= generate_smb_nt_hash($password);
2498 }
2500 /* Read ! if user was deactivated */
2501 if($deactivated){
2502 $newpass = preg_replace("/(^[^\}]+\})(.*$)/","\\1!\\2",$newpass);
2503 }
2505 $attrs['userPassword']= array();
2506 $attrs['userPassword']= $newpass;
2508 $ldap->modify($attrs);
2510 new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2512 if (!$ldap->success()) {
2513 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, ERROR_DIALOG));
2514 } else {
2516 /* Run backend method for change/create */
2517 $test->set_password($password);
2519 /* Find postmodify entries for this class */
2520 $command= $config->search("password", "POSTMODIFY",array('menu'));
2522 if ($command != ""){
2523 /* Walk through attribute list */
2524 $command= preg_replace("/%userPassword/", $password, $command);
2525 $command= preg_replace("/%dn/", $dn, $command);
2527 if (check_command($command)){
2528 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2529 exec($command);
2530 } else {
2531 $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2532 msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2533 }
2534 }
2535 }
2536 }
2539 // Return something like array['sambaLMPassword']= "lalla..."
2540 function generate_smb_nt_hash($password)
2541 {
2542 global $config;
2544 # Try to use gosa-si?
2545 if (isset($config->current['GOSA_SI'])){
2546 $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
2547 if (isset($res['XML']['HASH'])){
2548 $hash= $res['XML']['HASH'];
2549 } else {
2550 $hash= "";
2551 }
2552 } else {
2553 $tmp= $config->data['MAIN']['SMBHASH']." ".escapeshellarg($password);
2554 @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2556 exec($tmp, $ar);
2557 flush();
2558 reset($ar);
2559 $hash= current($ar);
2560 }
2562 if ($hash == "") {
2563 msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
2564 return ("");
2565 }
2567 list($lm,$nt)= split (":", trim($hash));
2569 if ($config->current['SAMBAVERSION'] == 3) {
2570 $attrs['sambaLMPassword']= $lm;
2571 $attrs['sambaNTPassword']= $nt;
2572 $attrs['sambaPwdLastSet']= date('U');
2573 $attrs['sambaBadPasswordCount']= "0";
2574 $attrs['sambaBadPasswordTime']= "0";
2575 } else {
2576 $attrs['lmPassword']= $lm;
2577 $attrs['ntPassword']= $nt;
2578 $attrs['pwdLastSet']= date('U');
2579 }
2580 return($attrs);
2581 }
2584 function getEntryCSN($dn)
2585 {
2586 global $config;
2587 if(empty($dn) || !is_object($config)){
2588 return("");
2589 }
2591 /* Get attribute that we should use as serial number */
2592 if(isset($config->current['UNIQ_IDENTIFIER'])){
2593 $attr = $config->current['UNIQ_IDENTIFIER'];
2594 }elseif(isset($config->data['MAIN']['UNIQ_IDENTIFIER'])){
2595 $attr = $config->data['MAIN']['UNIQ_IDENTIFIER'];
2596 }
2597 if(!empty($attr)){
2598 $ldap = $config->get_ldap_link();
2599 $ldap->cat($dn,array($attr));
2600 $csn = $ldap->fetch();
2601 if(isset($csn[$attr][0])){
2602 return($csn[$attr][0]);
2603 }
2604 }
2605 return("");
2606 }
2609 /* Add a given objectClass to an attrs entry */
2610 function add_objectClass($classes, &$attrs)
2611 {
2612 if (is_array($classes)){
2613 $list= $classes;
2614 } else {
2615 $list= array($classes);
2616 }
2618 foreach ($list as $class){
2619 $attrs['objectClass'][]= $class;
2620 }
2621 }
2624 /* Removes a given objectClass from the attrs entry */
2625 function remove_objectClass($classes, &$attrs)
2626 {
2627 if (isset($attrs['objectClass'])){
2628 /* Array? */
2629 if (is_array($classes)){
2630 $list= $classes;
2631 } else {
2632 $list= array($classes);
2633 }
2635 $tmp= array();
2636 foreach ($attrs['objectClass'] as $oc) {
2637 foreach ($list as $class){
2638 if ($oc != $class){
2639 $tmp[]= $oc;
2640 }
2641 }
2642 }
2643 $attrs['objectClass']= $tmp;
2644 }
2645 }
2647 /*! \brief Initialize a file download with given content, name and data type.
2648 * @param data String The content to send.
2649 * @param name String The name of the file.
2650 * @param type String The content identifier, default value is "application/octet-stream";
2651 */
2652 function send_binary_content($data,$name,$type = "application/octet-stream")
2653 {
2654 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
2655 header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
2656 header("Cache-Control: no-cache");
2657 header("Pragma: no-cache");
2658 header("Cache-Control: post-check=0, pre-check=0");
2659 header("Content-type: ".$type."");
2661 /* force download dialog */
2662 if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
2663 header('Content-Disposition: filename="'.$name.'"');
2664 } else {
2665 header('Content-Disposition: attachment; filename="'.$name.'"');
2666 }
2668 echo $data;
2669 exit();
2670 }
2673 /*! \brief Encode special string characters so we can use the string in \
2674 HTML output, without breaking quotes.
2675 @param The String we want to encode.
2676 @return The encoded String
2677 */
2678 function xmlentities($str)
2679 {
2680 if(is_string($str)){
2681 return(htmlentities($str,ENT_QUOTES));
2682 }elseif(is_array($str)){
2683 foreach($str as $name => $value){
2684 $str[$name] = xmlentities($value);
2685 }
2686 }
2687 return($str);
2688 }
2691 /*! \brief Updates all accessTo attributes from a given value to a new one.
2692 For example if a host is renamed.
2693 @param String $from The source accessTo name.
2694 @param String $to The destination accessTo name.
2695 */
2696 function update_accessTo($from,$to)
2697 {
2698 global $config;
2699 $ldap = $config->get_ldap_link();
2700 $ldap->cd($config->current['BASE']);
2701 $ldap->search("(&(objectClass=trustAccount)(accessTo=".$from."))",array("objectClass","accessTo"));
2702 while($attrs = $ldap->fetch()){
2703 $new_attrs = array("accessTo" => array());
2704 $dn = $attrs['dn'];
2705 for($i = 0 ; $i < $attrs['objectClass']['count']; $i++){
2706 $new_attrs['objectClass'][] = $attrs['objectClass'][$i];
2707 }
2708 for($i = 0 ; $i < $attrs['accessTo']['count']; $i++){
2709 if($attrs['accessTo'][$i] == $from){
2710 if(!empty($to)){
2711 $new_attrs['accessTo'][] = $to;
2712 }
2713 }else{
2714 $new_attrs['accessTo'][] = $attrs['accessTo'][$i];
2715 }
2716 }
2717 $ldap->cd($dn);
2718 $ldap->modify($new_attrs);
2719 if (!$ldap->success()){
2720 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, "update_accessTo($from,$to)"));
2721 }
2722 new log("modify","update_accessTo($from,$to)",$dn,array_keys($new_attrs),$ldap->get_error());
2723 }
2724 }
2727 function get_random_char () {
2728 $randno = rand (0, 63);
2729 if ($randno < 12) {
2730 return (chr ($randno + 46)); // Digits, '/' and '.'
2731 } else if ($randno < 38) {
2732 return (chr ($randno + 53)); // Uppercase
2733 } else {
2734 return (chr ($randno + 59)); // Lowercase
2735 }
2736 }
2738 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2739 ?>