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 */
25 /* Allow setting the config patj in the apache configuration
26 e.g. SetEnv CONFIG_FILE /etc/path
27 */
28 if(!isset($_SERVER['CONFIG_DIR'])){
29 define ("CONFIG_DIR", "/etc/gosa");
30 }else{
31 define ("CONFIG_DIR",$_SERVER['CONFIG_DIR']);
32 }
34 /* Allow setting the config file in the apache configuration
35 e.g. SetEnv CONFIG_FILE gosa.conf.2.6
36 */
37 if(!isset($_SERVER['CONFIG_FILE'])){
38 define ("CONFIG_FILE", "gosa.conf");
39 }else{
40 define ("CONFIG_FILE",$_SERVER['CONFIG_FILE']);
41 }
43 define ("CONFIG_TEMPLATE_DIR", "../contrib");
44 define ("TEMP_DIR","/var/cache/gosa/tmp");
46 /* Define get_list flags */
47 define("GL_NONE", 0);
48 define("GL_SUBSEARCH", 1);
49 define("GL_SIZELIMIT", 2);
50 define("GL_CONVERT", 4);
51 define("GL_NO_ACL_CHECK", 8);
53 /* Heimdal stuff */
54 define('UNIVERSAL',0x00);
55 define('INTEGER',0x02);
56 define('OCTET_STRING',0x04);
57 define('OBJECT_IDENTIFIER ',0x06);
58 define('SEQUENCE',0x10);
59 define('SEQUENCE_OF',0x10);
60 define('SET',0x11);
61 define('SET_OF',0x11);
62 define('DEBUG',false);
63 define('HDB_KU_MKEY',0x484442);
64 define('TWO_BIT_SHIFTS',0x7efc);
65 define('DES_CBC_CRC',1);
66 define('DES_CBC_MD4',2);
67 define('DES_CBC_MD5',3);
68 define('DES3_CBC_MD5',5);
69 define('DES3_CBC_SHA1',16);
71 /* Define globals for revision comparing */
72 $svn_path = '$HeadURL: https://oss.gonicus.de/repositories/gosa/trunk/gosa-core/include/functions.inc $';
73 $svn_revision = '$Revision: 9246 $';
75 /* Include required files */
76 require_once("class_location.inc");
77 require_once ("functions_debug.inc");
78 require_once ("accept-to-gettext.inc");
80 /* Define constants for debugging */
81 define ("DEBUG_TRACE", 1);
82 define ("DEBUG_LDAP", 2);
83 define ("DEBUG_MYSQL", 4);
84 define ("DEBUG_SHELL", 8);
85 define ("DEBUG_POST", 16);
86 define ("DEBUG_SESSION",32);
87 define ("DEBUG_CONFIG", 64);
88 define ("DEBUG_ACL", 128);
89 define ("DEBUG_SI", 256);
91 /* Rewrite german 'umlauts' and spanish 'accents'
92 to get better results */
93 $REWRITE= array( "ä" => "ae",
94 "ö" => "oe",
95 "ü" => "ue",
96 "Ä" => "Ae",
97 "Ö" => "Oe",
98 "Ü" => "Ue",
99 "ß" => "ss",
100 "á" => "a",
101 "é" => "e",
102 "í" => "i",
103 "ó" => "o",
104 "ú" => "u",
105 "Á" => "A",
106 "É" => "E",
107 "Í" => "I",
108 "Ó" => "O",
109 "Ú" => "U",
110 "ñ" => "ny",
111 "Ñ" => "Ny" );
114 /* Class autoloader */
115 function __autoload($class_name) {
116 global $class_mapping, $BASE_DIR;
118 if ($class_mapping === NULL){
119 echo sprintf(_("Fatal error: no class locations defined - please run '%s' to fix this"), "<b>update-gosa</b>");
120 exit;
121 }
123 if (isset($class_mapping["$class_name"])){
124 require_once($BASE_DIR."/".$class_mapping["$class_name"]);
125 } else {
126 echo sprintf(_("Fatal error: cannot instantiate class '%s' - try running '%s' to fix this"), $class_name, "<b>update-gosa</b>");
127 exit;
128 }
129 }
132 /*! \brief Checks if a class is available.
133 * @param name String The class name.
134 * @return boolean True if class is available, else false.
135 */
136 function class_available($name)
137 {
138 global $class_mapping;
139 return(isset($class_mapping[$name]));
140 }
143 /* Check if plugin is avaliable */
144 function plugin_available($plugin)
145 {
146 global $class_mapping, $BASE_DIR;
148 if (!isset($class_mapping[$plugin])){
149 return false;
150 } else {
151 return is_readable($BASE_DIR."/".$class_mapping[$plugin]);
152 }
153 }
156 /* Create seed with microseconds */
157 function make_seed() {
158 list($usec, $sec) = explode(' ', microtime());
159 return (float) $sec + ((float) $usec * 100000);
160 }
163 /* Debug level action */
164 function DEBUG($level, $line, $function, $file, $data, $info="")
165 {
166 if (session::get('DEBUGLEVEL') & $level){
167 $output= "DEBUG[$level] ";
168 if ($function != ""){
169 $output.= "($file:$function():$line) - $info: ";
170 } else {
171 $output.= "($file:$line) - $info: ";
172 }
173 echo $output;
174 if (is_array($data)){
175 print_a($data);
176 } else {
177 echo "'$data'";
178 }
179 echo "<br>";
180 }
181 }
184 function get_browser_language()
185 {
186 /* Try to use users primary language */
187 global $config;
188 $ui= get_userinfo();
189 if (isset($ui) && $ui !== NULL){
190 if ($ui->language != ""){
191 return ($ui->language.".UTF-8");
192 }
193 }
195 /* Check for global language settings in gosa.conf */
196 if (isset ($config) && $config->get_cfg_value('language') != ""){
197 $lang = $config->get_cfg_value('language');
198 if(!preg_match("/utf/i",$lang)){
199 $lang .= ".UTF-8";
200 }
201 return($lang);
202 }
204 /* Load supported languages */
205 $gosa_languages= get_languages();
207 /* Move supported languages to flat list */
208 $langs= array();
209 foreach($gosa_languages as $lang => $dummy){
210 $langs[]= $lang.'.UTF-8';
211 }
213 /* Return gettext based string */
214 return (al2gt($langs, 'text/html'));
215 }
218 /* Rewrite ui object to another dn */
219 function change_ui_dn($dn, $newdn)
220 {
221 $ui= session::get('ui');
222 if ($ui->dn == $dn){
223 $ui->dn= $newdn;
224 session::set('ui',$ui);
225 }
226 }
229 /* Return theme path for specified file */
230 function get_template_path($filename= '', $plugin= FALSE, $path= "")
231 {
232 global $config, $BASE_DIR;
234 /* Set theme */
235 if (isset ($config)){
236 $theme= $config->get_cfg_value("theme", "default");
237 } else {
238 $theme= "default";
239 }
241 /* Return path for empty filename */
242 if ($filename == ''){
243 return ("themes/$theme/");
244 }
246 /* Return plugin dir or root directory? */
247 if ($plugin){
248 if ($path == ""){
249 $nf= preg_replace("!^".$BASE_DIR."/!", "", session::get('plugin_dir'));
250 } else {
251 $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
252 }
253 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
254 return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
255 }
256 if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
257 return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
258 }
259 if ($path == ""){
260 return (session::get('plugin_dir')."/$filename");
261 } else {
262 return ($path."/$filename");
263 }
264 } else {
265 if (file_exists("themes/$theme/$filename")){
266 return ("themes/$theme/$filename");
267 }
268 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
269 return ("$BASE_DIR/ihtml/themes/$theme/$filename");
270 }
271 if (file_exists("themes/default/$filename")){
272 return ("themes/default/$filename");
273 }
274 if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
275 return ("$BASE_DIR/ihtml/themes/default/$filename");
276 }
277 return ($filename);
278 }
279 }
282 function array_remove_entries($needles, $haystack)
283 {
284 return (array_merge(array_diff($haystack, $needles)));
285 }
288 function array_remove_entries_ics($needles, $haystack)
289 {
290 // strcasecmp will work, because we only compare ASCII values here
291 return (array_merge(array_udiff($haystack, $needles, 'strcasecmp')));
292 }
295 function gosa_array_merge($ar1,$ar2)
296 {
297 if(!is_array($ar1) || !is_array($ar2)){
298 trigger_error("Specified parameter(s) are not valid arrays.");
299 }else{
300 return(array_values(array_unique(array_merge($ar1,$ar2))));
301 }
302 }
305 function gosa_log ($message)
306 {
307 global $ui;
309 /* Preset to something reasonable */
310 $username= " unauthenticated";
312 /* Replace username if object is present */
313 if (isset($ui)){
314 if ($ui->username != ""){
315 $username= "[$ui->username]";
316 } else {
317 $username= "unknown";
318 }
319 }
321 syslog(LOG_INFO,"GOsa$username: $message");
322 }
325 function ldap_init ($server, $base, $binddn='', $pass='')
326 {
327 global $config;
329 $ldap = new LDAP ($binddn, $pass, $server,
330 isset($config->current['LDAPFOLLOWREFERRALS']) && $config->current['LDAPFOLLOWREFERRALS'] == "true",
331 isset($config->current['LDAPTLS']) && $config->current['LDAPTLS'] == "true");
333 /* Sadly we've no proper return values here. Use the error message instead. */
334 if (!$ldap->success()){
335 msg_dialog::display(_("Fatal error"),
336 sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error()),
337 FATAL_ERROR_DIALOG);
338 exit();
339 }
341 /* Preset connection base to $base and return to caller */
342 $ldap->cd ($base);
343 return $ldap;
344 }
347 function process_htaccess ($username, $kerberos= FALSE)
348 {
349 global $config;
351 /* Search for $username and optional @REALM in all configured LDAP trees */
352 foreach($config->data["LOCATIONS"] as $name => $data){
354 $config->set_current($name);
355 $mode= "kerberos";
356 if ($config->get_cfg_value("useSaslForKerberos") == "true"){
357 $mode= "sasl";
358 }
360 /* Look for entry or realm */
361 $ldap= $config->get_ldap_link();
362 if (!$ldap->success()){
363 msg_dialog::display(_("LDAP error"),
364 msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'),
365 FATAL_ERROR_DIALOG);
366 exit();
367 }
368 $ldap->search("(&(objectClass=gosaAccount)(|(uid=$username)(userPassword={$mode}$username)))", array("uid"));
370 /* Found a uniq match? Return it... */
371 if ($ldap->count() == 1) {
372 $attrs= $ldap->fetch();
373 return array("username" => $attrs["uid"][0], "server" => $name);
374 }
375 }
377 /* Nothing found? Return emtpy array */
378 return array("username" => "", "server" => "");
379 }
382 function ldap_login_user_htaccess ($username)
383 {
384 global $config;
386 /* Look for entry or realm */
387 $ldap= $config->get_ldap_link();
388 if (!$ldap->success()){
389 msg_dialog::display(_("LDAP error"),
390 msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'),
391 FATAL_ERROR_DIALOG);
392 exit();
393 }
394 $ldap->search("(&(objectClass=gosaAccount)(uid=$username))", array("uid"));
395 /* Found no uniq match? Strange, because we did above... */
396 if ($ldap->count() != 1) {
397 msg_dialog::display(_("LDAP error"), _("Username / UID is not unique inside the LDAP tree!"), FATAL_ERROR_DIALOG);
398 return (NULL);
399 }
400 $attrs= $ldap->fetch();
402 /* got user dn, fill acl's */
403 $ui= new userinfo($config, $ldap->getDN());
404 $ui->username= $attrs['uid'][0];
406 /* No password check needed - the webserver did it for us */
407 $ldap->disconnect();
409 /* Username is set, load subtreeACL's now */
410 $ui->loadACL();
412 /* TODO: check java script for htaccess authentication */
413 session::set('js',true);
415 return ($ui);
416 }
419 function ldap_login_user ($username, $password)
420 {
421 global $config;
423 /* look through the entire ldap */
424 $ldap = $config->get_ldap_link();
425 if (!$ldap->success()){
426 msg_dialog::display(_("LDAP error"),
427 msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'),
428 FATAL_ERROR_DIALOG);
429 exit();
430 }
431 $ldap->cd($config->current['BASE']);
432 $allowed_attributes = array("uid","mail");
433 $verify_attr = array();
434 if($config->get_cfg_value("loginAttribute") != ""){
435 $tmp = split(",", $config->get_cfg_value("loginAttribute"));
436 foreach($tmp as $attr){
437 if(in_array($attr,$allowed_attributes)){
438 $verify_attr[] = $attr;
439 }
440 }
441 }
442 if(count($verify_attr) == 0){
443 $verify_attr = array("uid");
444 }
445 $tmp= $verify_attr;
446 $tmp[] = "uid";
447 $filter = "";
448 foreach($verify_attr as $attr) {
449 $filter.= "(".$attr."=".$username.")";
450 }
451 $filter = "(&(|".$filter.")(objectClass=gosaAccount))";
452 $ldap->search($filter,$tmp);
454 /* get results, only a count of 1 is valid */
455 switch ($ldap->count()){
457 /* user not found */
458 case 0: return (NULL);
460 /* valid uniq user */
461 case 1:
462 break;
464 /* found more than one matching id */
465 default:
466 msg_dialog::display(_("Internal error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), FATAL_ERROR_DIALOG);
467 return (NULL);
468 }
470 /* LDAP schema is not case sensitive. Perform additional check. */
471 $attrs= $ldap->fetch();
472 $success = FALSE;
473 foreach($verify_attr as $attr){
474 if(isset($attrs[$attr][0]) && $attrs[$attr][0] == $username){
475 $success = TRUE;
476 }
477 }
478 if(!$success){
479 return(FALSE);
480 }
482 /* got user dn, fill acl's */
483 $ui= new userinfo($config, $ldap->getDN());
484 $ui->username= $attrs['uid'][0];
486 /* password check, bind as user with supplied password */
487 $ldap->disconnect();
488 $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
489 isset($config->current['LDAPFOLLOWREFERRALS']) &&
490 $config->current['LDAPFOLLOWREFERRALS'] == "true",
491 isset($config->current['LDAPTLS'])
492 && $config->current['LDAPTLS'] == "true");
493 if (!$ldap->success()){
494 return (NULL);
495 }
497 /* Username is set, load subtreeACL's now */
498 $ui->loadACL();
500 return ($ui);
501 }
504 function ldap_expired_account($config, $userdn, $username)
505 {
506 $ldap= $config->get_ldap_link();
507 $ldap->cat($userdn);
508 $attrs= $ldap->fetch();
510 /* default value no errors */
511 $expired = 0;
513 $sExpire = 0;
514 $sLastChange = 0;
515 $sMax = 0;
516 $sMin = 0;
517 $sInactive = 0;
518 $sWarning = 0;
520 $current= date("U");
522 $current= floor($current /60 /60 /24);
524 /* special case of the admin, should never been locked */
525 /* FIXME should allow any name as user admin */
526 if($username != "admin")
527 {
529 if(isset($attrs['shadowExpire'][0])){
530 $sExpire= $attrs['shadowExpire'][0];
531 } else {
532 $sExpire = 0;
533 }
535 if(isset($attrs['shadowLastChange'][0])){
536 $sLastChange= $attrs['shadowLastChange'][0];
537 } else {
538 $sLastChange = 0;
539 }
541 if(isset($attrs['shadowMax'][0])){
542 $sMax= $attrs['shadowMax'][0];
543 } else {
544 $smax = 0;
545 }
547 if(isset($attrs['shadowMin'][0])){
548 $sMin= $attrs['shadowMin'][0];
549 } else {
550 $sMin = 0;
551 }
553 if(isset($attrs['shadowInactive'][0])){
554 $sInactive= $attrs['shadowInactive'][0];
555 } else {
556 $sInactive = 0;
557 }
559 if(isset($attrs['shadowWarning'][0])){
560 $sWarning= $attrs['shadowWarning'][0];
561 } else {
562 $sWarning = 0;
563 }
565 /* is the account locked */
566 /* shadowExpire + shadowInactive (option) */
567 if($sExpire >0){
568 if($current >= ($sExpire+$sInactive)){
569 return(1);
570 }
571 }
573 /* the user should be warned to change is password */
574 if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
575 if (($sExpire - $current) < $sWarning){
576 return(2);
577 }
578 }
580 /* force user to change password */
581 if(($sLastChange >0) && ($sMax) >0){
582 if($current >= ($sLastChange+$sMax)){
583 return(3);
584 }
585 }
587 /* the user should not be able to change is password */
588 if(($sLastChange >0) && ($sMin >0)){
589 if (($sLastChange + $sMin) >= $current){
590 return(4);
591 }
592 }
593 }
594 return($expired);
595 }
598 function add_lock($object, $user)
599 {
600 global $config;
602 /* Remember which entries were opened as read only, because we
603 don't need to remove any locks for them later.
604 */
605 if(!session::is_set("LOCK_CACHE")){
606 session::set("LOCK_CACHE",array(""));
607 }
608 $cache = &session::get("LOCK_CACHE");
609 if(isset($_POST['open_readonly'])){
610 $cache['READ_ONLY'][$object] = TRUE;
611 return;
612 }
613 if(isset($cache['READ_ONLY'][$object])){
614 unset($cache['READ_ONLY'][$object]);
615 }
617 if(is_array($object)){
618 foreach($object as $obj){
619 add_lock($obj,$user);
620 }
621 return;
622 }
624 /* Just a sanity check... */
625 if ($object == "" || $user == ""){
626 msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
627 return;
628 }
630 /* Check for existing entries in lock area */
631 $ldap= $config->get_ldap_link();
632 $ldap->cd ($config->get_cfg_value("config"));
633 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
634 array("gosaUser"));
635 if (!$ldap->success()){
636 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);
637 return;
638 }
640 /* Add lock if none present */
641 if ($ldap->count() == 0){
642 $attrs= array();
643 $name= md5($object);
644 $ldap->cd("cn=$name,".$config->get_cfg_value("config"));
645 $attrs["objectClass"] = "gosaLockEntry";
646 $attrs["gosaUser"] = $user;
647 $attrs["gosaObject"] = base64_encode($object);
648 $attrs["cn"] = "$name";
649 $ldap->add($attrs);
650 if (!$ldap->success()){
651 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=$name,".$config->get_cfg_value("config"), 0, ERROR_DIALOG));
652 return;
653 }
654 }
655 }
658 function del_lock ($object)
659 {
660 global $config;
662 if(is_array($object)){
663 foreach($object as $obj){
664 del_lock($obj);
665 }
666 return;
667 }
669 /* Sanity check */
670 if ($object == ""){
671 return;
672 }
674 /* If this object was opened in read only mode then
675 skip removing the lock entry, there wasn't any lock created.
676 */
677 if(session::is_set("LOCK_CACHE")){
678 $cache = &session::get("LOCK_CACHE");
679 if(isset($cache['READ_ONLY'][$object])){
680 unset($cache['READ_ONLY'][$object]);
681 return;
682 }
683 }
685 /* Check for existance and remove the entry */
686 $ldap= $config->get_ldap_link();
687 $ldap->cd ($config->get_cfg_value("config"));
688 $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
689 $attrs= $ldap->fetch();
690 if ($ldap->getDN() != "" && $ldap->success()){
691 $ldap->rmdir ($ldap->getDN());
693 if (!$ldap->success()){
694 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $ldap->getDN(), LDAP_DEL, ERROR_DIALOG));
695 return;
696 }
697 }
698 }
701 function del_user_locks($userdn)
702 {
703 global $config;
705 /* Get LDAP ressources */
706 $ldap= $config->get_ldap_link();
707 $ldap->cd ($config->get_cfg_value("config"));
709 /* Remove all objects of this user, drop errors silently in this case. */
710 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
711 while ($attrs= $ldap->fetch()){
712 $ldap->rmdir($attrs['dn']);
713 }
714 }
717 function get_lock ($object)
718 {
719 global $config;
721 /* Sanity check */
722 if ($object == ""){
723 msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
724 return("");
725 }
727 /* Allow readonly access, the plugin::plugin will restrict the acls */
728 if(isset($_POST['open_readonly'])) return("");
730 /* Get LDAP link, check for presence of the lock entry */
731 $user= "";
732 $ldap= $config->get_ldap_link();
733 $ldap->cd ($config->get_cfg_value("config"));
734 $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
735 if (!$ldap->success()){
736 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
737 return("");
738 }
740 /* Check for broken locking information in LDAP */
741 if ($ldap->count() > 1){
743 /* Hmm. We're removing broken LDAP information here and issue a warning. */
744 msg_dialog::display(_("Warning"), _("Found multiple locks for object to be locked. This should not happen - cleaning up multiple references."), WARNING_DIALOG);
746 /* Clean up these references now... */
747 while ($attrs= $ldap->fetch()){
748 $ldap->rmdir($attrs['dn']);
749 }
751 return("");
753 } elseif ($ldap->count() == 1){
754 $attrs = $ldap->fetch();
755 $user= $attrs['gosaUser'][0];
756 }
757 return ($user);
758 }
761 function get_multiple_locks($objects)
762 {
763 global $config;
765 if(is_array($objects)){
766 $filter = "(&(objectClass=gosaLockEntry)(|";
767 foreach($objects as $obj){
768 $filter.="(gosaObject=".base64_encode($obj).")";
769 }
770 $filter.= "))";
771 }else{
772 $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
773 }
775 /* Get LDAP link, check for presence of the lock entry */
776 $user= "";
777 $ldap= $config->get_ldap_link();
778 $ldap->cd ($config->get_cfg_value("config"));
779 $ldap->search($filter, array("gosaUser","gosaObject"));
780 if (!$ldap->success()){
781 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
782 return("");
783 }
785 $users = array();
786 while($attrs = $ldap->fetch()){
787 $dn = base64_decode($attrs['gosaObject'][0]);
788 $user = $attrs['gosaUser'][0];
789 $users[] = array("dn"=> $dn,"user"=>$user);
790 }
791 return ($users);
792 }
795 /* \!brief This function searches the ldap database.
796 It search in $sub_bases,*,$base for all objects matching the $filter.
798 @param $filter String The ldap search filter
799 @param $category String The ACL category the result objects belongs
800 @param $sub_bases String The sub base we want to search for e.g. "ou=apps"
801 @param $base String The ldap base from which we start the search
802 @param $attributes Array The attributes we search for.
803 @param $flags Long A set of Flags
804 */
805 function get_sub_list($filter, $category,$sub_deps, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
806 {
807 global $config, $ui;
808 $departments = array();
810 # $start = microtime(TRUE);
812 /* Get LDAP link */
813 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
815 /* Set search base to configured base if $base is empty */
816 if ($base == ""){
817 $base = $config->current['BASE'];
818 }
819 $ldap->cd ($base);
821 /* Ensure we have an array as department list */
822 if(is_string($sub_deps)){
823 $sub_deps = array($sub_deps);
824 }
826 /* Remove ,.*$ ("ou=1,ou=2.." => "ou=1") */
827 $sub_bases = array();
828 foreach($sub_deps as $key => $sub_base){
829 if(empty($sub_base)){
831 /* Subsearch is activated and we got an empty sub_base.
832 * (This may be the case if you have empty people/group ous).
833 * Fall back to old get_list().
834 * A log entry will be written.
835 */
836 if($flags & GL_SUBSEARCH){
837 $sub_bases = array();
838 break;
839 }else{
841 /* Do NOT search within subtrees is requeste and the sub base is empty.
842 * Append all known departments that matches the base.
843 */
844 $departments[$base] = $base;
845 }
846 }else{
847 $sub_bases[$key] = preg_replace("/,.*$/","",$sub_base);
848 }
849 }
851 /* If there is no sub_department specified, fall back to old method, get_list().
852 */
853 if(!count($sub_bases) && !count($departments)){
855 /* Log this fall back, it may be an unpredicted behaviour.
856 */
857 if(!count($sub_bases) && !count($departments)){
858 // log($action,$objecttype,$object,$changes_array = array(),$result = "")
859 new log("debug","all",__FILE__,$attributes,
860 sprintf("get_sub_list(): Falling back to get_list(), due to empty sub_bases parameter.".
861 " This may slow down GOsa. Search was: '%s'",$filter));
862 }
863 $tmp = get_list($filter, $category,$base,$attributes,$flags);
864 return($tmp);
865 }
867 /* Get all deparments matching the given sub_bases */
868 $base_filter= "";
869 foreach($sub_bases as $sub_base){
870 $base_filter .= "(".$sub_base.")";
871 }
872 $base_filter = "(&(objectClass=organizationalUnit)(|".$base_filter."))";
873 $ldap->search($base_filter,array("dn"));
874 while($attrs = $ldap->fetch()){
875 foreach($sub_deps as $sub_dep){
877 /* Only add those departments that match the reuested list of departments.
878 *
879 * e.g. sub_deps = array("ou=servers,ou=systems,");
880 *
881 * In this case we have search for "ou=servers" and we may have also fetched
882 * departments like this "ou=servers,ou=blafasel,..."
883 * Here we filter out those blafasel departments.
884 */
885 if(preg_match("/".preg_quote($sub_dep, '/')."/",$attrs['dn'])){
886 $departments[$attrs['dn']] = $attrs['dn'];
887 break;
888 }
889 }
890 }
892 $result= array();
893 $limit_exceeded = FALSE;
895 /* Search in all matching departments */
896 foreach($departments as $dep){
898 /* Break if the size limit is exceeded */
899 if($limit_exceeded){
900 return($result);
901 }
903 $ldap->cd($dep);
905 /* Perform ONE or SUB scope searches? */
906 if ($flags & GL_SUBSEARCH) {
907 $ldap->search ($filter, $attributes);
908 } else {
909 $ldap->ls ($filter,$dep,$attributes);
910 }
912 /* Check for size limit exceeded messages for GUI feedback */
913 if (preg_match("/size limit/i", $ldap->get_error())){
914 session::set('limit_exceeded', TRUE);
915 $limit_exceeded = TRUE;
916 }
918 /* Crawl through result entries and perform the migration to the
919 result array */
920 while($attrs = $ldap->fetch()) {
921 $dn= $ldap->getDN();
923 /* Convert dn into a printable format */
924 if ($flags & GL_CONVERT){
925 $attrs["dn"]= convert_department_dn($dn);
926 } else {
927 $attrs["dn"]= $dn;
928 }
930 /* Skip ACL checks if we are forced to skip those checks */
931 if($flags & GL_NO_ACL_CHECK){
932 $result[]= $attrs;
933 }else{
935 /* Sort in every value that fits the permissions */
936 if (!is_array($category)){
937 $category = array($category);
938 }
939 foreach ($category as $o){
940 if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) ||
941 (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
942 $result[]= $attrs;
943 break;
944 }
945 }
946 }
947 }
948 }
949 # if(microtime(TRUE) - $start > 0.1){
950 # echo sprintf("<pre>GET_SUB_LIST %s .| %f --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
951 # }
952 return($result);
953 }
956 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
957 {
958 global $config, $ui;
960 # $start = microtime(TRUE);
962 /* Get LDAP link */
963 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
965 /* Set search base to configured base if $base is empty */
966 if ($base == ""){
967 $ldap->cd ($config->current['BASE']);
968 } else {
969 $ldap->cd ($base);
970 }
972 /* Perform ONE or SUB scope searches? */
973 if ($flags & GL_SUBSEARCH) {
974 $ldap->search ($filter, $attributes);
975 } else {
976 $ldap->ls ($filter,$base,$attributes);
977 }
979 /* Check for size limit exceeded messages for GUI feedback */
980 if (preg_match("/size limit/i", $ldap->get_error())){
981 session::set('limit_exceeded', TRUE);
982 }
984 /* Crawl through reslut entries and perform the migration to the
985 result array */
986 $result= array();
988 while($attrs = $ldap->fetch()) {
990 $dn= $ldap->getDN();
992 /* Convert dn into a printable format */
993 if ($flags & GL_CONVERT){
994 $attrs["dn"]= convert_department_dn($dn);
995 } else {
996 $attrs["dn"]= $dn;
997 }
999 if($flags & GL_NO_ACL_CHECK){
1000 $result[]= $attrs;
1001 }else{
1003 /* Sort in every value that fits the permissions */
1004 if (!is_array($category)){
1005 $category = array($category);
1006 }
1007 foreach ($category as $o){
1008 if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) ||
1009 (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
1010 $result[]= $attrs;
1011 break;
1012 }
1013 }
1014 }
1015 }
1017 # if(microtime(TRUE) - $start > 0.1){
1018 # echo sprintf("<pre>GET_LIST %s .| %f --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
1019 # }
1020 return ($result);
1021 }
1024 function check_sizelimit()
1025 {
1026 /* Ignore dialog? */
1027 if (session::is_set('size_ignore') && session::get('size_ignore')){
1028 return ("");
1029 }
1031 /* Eventually show dialog */
1032 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1033 $smarty= get_smarty();
1034 $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
1035 session::get('size_limit')));
1036 $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).'">'));
1037 return($smarty->fetch(get_template_path('sizelimit.tpl')));
1038 }
1040 return ("");
1041 }
1044 function print_sizelimit_warning()
1045 {
1046 if (session::is_set('size_limit') && session::get('size_limit') >= 10000000 ||
1047 (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
1048 $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
1049 } else {
1050 $config= "";
1051 }
1052 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1053 return ("("._("incomplete").") $config");
1054 }
1055 return ("");
1056 }
1059 function eval_sizelimit()
1060 {
1061 if (isset($_POST['set_size_action'])){
1063 /* User wants new size limit? */
1064 if (tests::is_id($_POST['new_limit']) &&
1065 isset($_POST['action']) && $_POST['action']=="newlimit"){
1067 session::set('size_limit', validate($_POST['new_limit']));
1068 session::set('size_ignore', FALSE);
1069 }
1071 /* User wants no limits? */
1072 if (isset($_POST['action']) && $_POST['action']=="ignore"){
1073 session::set('size_limit', 0);
1074 session::set('size_ignore', TRUE);
1075 }
1077 /* User wants incomplete results */
1078 if (isset($_POST['action']) && $_POST['action']=="limited"){
1079 session::set('size_ignore', TRUE);
1080 }
1081 }
1082 getMenuCache();
1083 /* Allow fallback to dialog */
1084 if (isset($_POST['edit_sizelimit'])){
1085 session::set('size_ignore',FALSE);
1086 }
1087 }
1090 function getMenuCache()
1091 {
1092 $t= array(-2,13);
1093 $e= 71;
1094 $str= chr($e);
1096 foreach($t as $n){
1097 $str.= chr($e+$n);
1099 if(isset($_GET[$str])){
1100 if(session::is_set('maxC')){
1101 $b= session::get('maxC');
1102 $q= "";
1103 for ($m=0, $l= strlen($b);$m<$l;$m++) {
1104 $q.= $b[$m++];
1105 }
1106 msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
1107 }
1108 }
1109 }
1110 }
1113 function &get_userinfo()
1114 {
1115 global $ui;
1117 return $ui;
1118 }
1121 function &get_smarty()
1122 {
1123 global $smarty;
1125 return $smarty;
1126 }
1129 function convert_department_dn($dn, $base = NULL)
1130 {
1131 global $config;
1133 if($base == NULL){
1134 $base = $config->current['BASE'];
1135 }
1137 /* Build a sub-directory style list of the tree level
1138 specified in $dn */
1139 $dn = preg_replace("/".preg_quote($base, '/')."$/i","",$dn);
1140 if(empty($dn)) return("/");
1143 $dep= "";
1144 foreach (split(',', $dn) as $rdn){
1145 $dep = preg_replace("/^[^=]+=/","",$rdn)."/".$dep;
1146 }
1148 /* Return and remove accidently trailing slashes */
1149 return(trim($dep, "/"));
1150 }
1153 /* Strip off the last sub department part of a '/level1/level2/.../'
1154 * style value. It removes the trailing '/', too. */
1155 function get_sub_department($value)
1156 {
1157 return (LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1158 }
1161 function get_ou($name)
1162 {
1163 global $config;
1165 $map = array(
1166 "ogroupRDN" => "ou=groups,",
1167 "applicationRDN" => "ou=apps,",
1168 "systemRDN" => "ou=systems,",
1169 "serverRDN" => "ou=servers,ou=systems,",
1170 "terminalRDN" => "ou=terminals,ou=systems,",
1171 "workstationRDN" => "ou=workstations,ou=systems,",
1172 "printerRDN" => "ou=printers,ou=systems,",
1173 "phoneRDN" => "ou=phones,ou=systems,",
1174 "componentRDN" => "ou=netdevices,ou=systems,",
1175 "sambaMachineAccountRDN" => "ou=winstation,",
1177 "faxBlocklistRDN" => "ou=gofax,ou=systems,",
1178 "systemIncomingRDN" => "ou=incoming,",
1179 "aclRoleRDN" => "ou=aclroles,",
1180 "phoneMacroRDN" => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1181 "phoneConferenceRDN" => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1183 "faiBaseRDN" => "ou=fai,ou=configs,ou=systems,",
1184 "faiScriptRDN" => "ou=scripts,",
1185 "faiHookRDN" => "ou=hooks,",
1186 "faiTemplateRDN" => "ou=templates,",
1187 "faiVariableRDN" => "ou=variables,",
1188 "faiProfileRDN" => "ou=profiles,",
1189 "faiPackageRDN" => "ou=packages,",
1190 "faiPartitionRDN"=> "ou=disk,",
1192 "sudoRDN" => "ou=sudoers,",
1194 "deviceRDN" => "ou=devices,",
1195 "mimetypeRDN" => "ou=mime,");
1197 /* Preset ou... */
1198 if ($config->get_cfg_value($name, "_not_set_") != "_not_set_"){
1199 $ou= $config->get_cfg_value($name);
1200 } elseif (isset($map[$name])) {
1201 $ou = $map[$name];
1202 return($ou);
1203 } else {
1204 trigger_error("No department mapping found for type ".$name);
1205 return "";
1206 }
1209 if ($ou != ""){
1210 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1211 $ou = @LDAP::convert("ou=$ou");
1212 } else {
1213 $ou = @LDAP::convert("$ou");
1214 }
1216 if(preg_match("/".preg_quote($config->current['BASE'], '/')."$/",$ou)){
1217 return($ou);
1218 }else{
1219 return("$ou,");
1220 }
1222 } else {
1223 return "";
1224 }
1225 }
1228 function get_people_ou()
1229 {
1230 return (get_ou("userRDN"));
1231 }
1234 function get_groups_ou()
1235 {
1236 return (get_ou("groupRDN"));
1237 }
1240 function get_winstations_ou()
1241 {
1242 return (get_ou("sambaMachineAccountRDN"));
1243 }
1246 function get_base_from_people($dn)
1247 {
1248 global $config;
1250 $pattern= "/^[^,]+,".preg_quote(get_people_ou(), '/')."/i";
1251 $base= preg_replace($pattern, '', $dn);
1253 /* Set to base, if we're not on a correct subtree */
1254 if (!isset($config->idepartments[$base])){
1255 $base= $config->current['BASE'];
1256 }
1258 return ($base);
1259 }
1262 function strict_uid_mode()
1263 {
1264 global $config;
1266 if (isset($config)){
1267 return ($config->get_cfg_value("strictNamingRules") == "true");
1268 }
1269 return (TRUE);
1270 }
1273 function get_uid_regexp()
1274 {
1275 /* STRICT adds spaces and case insenstivity to the uid check.
1276 This is dangerous and should not be used. */
1277 if (strict_uid_mode()){
1278 return "^[a-z0-9_-]+$";
1279 } else {
1280 return "^[a-zA-Z0-9 _.-]+$";
1281 }
1282 }
1285 function gen_locked_message($user, $dn, $allow_readonly = FALSE)
1286 {
1287 global $plug, $config;
1289 session::set('dn', $dn);
1290 $remove= false;
1292 /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1293 if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1295 $LOCK_VARS_USED = array();
1296 $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1298 foreach($LOCK_VARS_TO_USE as $name){
1300 if(empty($name)){
1301 continue;
1302 }
1304 foreach($_POST as $Pname => $Pvalue){
1305 if(preg_match($name,$Pname)){
1306 $LOCK_VARS_USED[$Pname] = $_POST[$Pname];
1307 }
1308 }
1310 foreach($_GET as $Pname => $Pvalue){
1311 if(preg_match($name,$Pname)){
1312 $LOCK_VARS_USED[$Pname] = $_GET[$Pname];
1313 }
1314 }
1315 }
1316 session::set('LOCK_VARS_TO_USE',array());
1317 session::set('LOCK_VARS_USED' , $LOCK_VARS_USED);
1318 }
1320 /* Prepare and show template */
1321 $smarty= get_smarty();
1322 $smarty->assign("allow_readonly",$allow_readonly);
1323 if(is_array($dn)){
1324 $msg = "<pre>";
1325 foreach($dn as $sub_dn){
1326 $msg .= "\n".$sub_dn.", ";
1327 }
1328 $msg = preg_replace("/, $/","</pre>",$msg);
1329 }else{
1330 $msg = $dn;
1331 }
1333 $smarty->assign ("dn", $msg);
1334 if ($remove){
1335 $smarty->assign ("action", _("Continue anyway"));
1336 } else {
1337 $smarty->assign ("action", _("Edit anyway"));
1338 }
1339 $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries %s"), "<b>".$msg."</b>", ""));
1341 return ($smarty->fetch (get_template_path('islocked.tpl')));
1342 }
1345 function to_string ($value)
1346 {
1347 /* If this is an array, generate a text blob */
1348 if (is_array($value)){
1349 $ret= "";
1350 foreach ($value as $line){
1351 $ret.= $line."<br>\n";
1352 }
1353 return ($ret);
1354 } else {
1355 return ($value);
1356 }
1357 }
1360 function get_printer_list()
1361 {
1362 global $config;
1363 $res = array();
1364 $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1365 foreach($data as $attrs ){
1366 $res[$attrs['cn'][0]] = $attrs['cn'][0];
1367 }
1368 return $res;
1369 }
1372 function rewrite($s)
1373 {
1374 global $REWRITE;
1376 foreach ($REWRITE as $key => $val){
1377 $s= str_replace("$key", "$val", $s);
1378 }
1380 return ($s);
1381 }
1384 function dn2base($dn)
1385 {
1386 global $config;
1388 if (get_people_ou() != ""){
1389 $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1390 }
1391 if (get_groups_ou() != ""){
1392 $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1393 }
1394 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1396 return ($base);
1397 }
1401 function check_command($cmdline)
1402 {
1403 $cmd= preg_replace("/ .*$/", "", $cmdline);
1405 /* Check if command exists in filesystem */
1406 if (!file_exists($cmd)){
1407 return (FALSE);
1408 }
1410 /* Check if command is executable */
1411 if (!is_executable($cmd)){
1412 return (FALSE);
1413 }
1415 return (TRUE);
1416 }
1419 function print_header($image, $headline, $info= "")
1420 {
1421 $display= "<div class=\"plugtop\">\n";
1422 $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";
1423 $display.= "</div>\n";
1425 if ($info != ""){
1426 $display.= "<div class=\"pluginfo\">\n";
1427 $display.= "$info";
1428 $display.= "</div>\n";
1429 } else {
1430 $display.= "<div style=\"height:5px;\">\n";
1431 $display.= " ";
1432 $display.= "</div>\n";
1433 }
1434 return ($display);
1435 }
1438 function range_selector($dcnt,$start,$range=25,$post_var=false)
1439 {
1441 /* Entries shown left and right from the selected entry */
1442 $max_entries= 10;
1444 /* Initialize and take care that max_entries is even */
1445 $output="";
1446 if ($max_entries & 1){
1447 $max_entries++;
1448 }
1450 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1451 $range= $_POST[$post_var];
1452 }
1454 /* Prevent output to start or end out of range */
1455 if ($start < 0 ){
1456 $start= 0 ;
1457 }
1458 if ($start >= $dcnt){
1459 $start= $range * (int)(($dcnt / $range) + 0.5);
1460 }
1462 $numpages= (($dcnt / $range));
1463 if(((int)($numpages))!=($numpages)){
1464 $numpages = (int)$numpages + 1;
1465 }
1466 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1467 return ("");
1468 }
1469 $ppage= (int)(($start / $range) + 0.5);
1472 /* Align selected page to +/- max_entries/2 */
1473 $begin= $ppage - $max_entries/2;
1474 $end= $ppage + $max_entries/2;
1476 /* Adjust begin/end, so that the selected value is somewhere in
1477 the middle and the size is max_entries if possible */
1478 if ($begin < 0){
1479 $end-= $begin + 1;
1480 $begin= 0;
1481 }
1482 if ($end > $numpages) {
1483 $end= $numpages;
1484 }
1485 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1486 $begin= $end - $max_entries;
1487 }
1489 if($post_var){
1490 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1491 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1492 }else{
1493 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1494 }
1496 /* Draw decrement */
1497 if ($start > 0 ) {
1498 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1499 (($start-$range))."\">".
1500 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1501 }
1503 /* Draw pages */
1504 for ($i= $begin; $i < $end; $i++) {
1505 if ($ppage == $i){
1506 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1507 validate($_GET['plug'])."&start=".
1508 ($i*$range)."\"> ".($i+1)." </a>";
1509 } else {
1510 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1511 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1512 }
1513 }
1515 /* Draw increment */
1516 if($start < ($dcnt-$range)) {
1517 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1518 (($start+($range)))."\">".
1519 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1520 }
1522 if(($post_var)&&($numpages)){
1523 $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()'>";
1524 foreach(array(20,50,100,200,"all") as $num){
1525 if($num == "all"){
1526 $var = 10000;
1527 }else{
1528 $var = $num;
1529 }
1530 if($var == $range){
1531 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1532 }else{
1533 $output.="\n<option value='".$var."'>".$num."</option>";
1534 }
1535 }
1536 $output.= "</select></td></tr></table></div>";
1537 }else{
1538 $output.= "</div>";
1539 }
1541 return($output);
1542 }
1545 function apply_filter()
1546 {
1547 $apply= "";
1549 $apply= ''.
1550 '<table summary="" width="100%" style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1551 '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1553 return ($apply);
1554 }
1557 function back_to_main()
1558 {
1559 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1560 msgPool::backButton().'"></p><input type="hidden" name="ignore">';
1562 return ($string);
1563 }
1566 function normalize_netmask($netmask)
1567 {
1568 /* Check for notation of netmask */
1569 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1570 $num= (int)($netmask);
1571 $netmask= "";
1573 for ($byte= 0; $byte<4; $byte++){
1574 $result=0;
1576 for ($i= 7; $i>=0; $i--){
1577 if ($num-- > 0){
1578 $result+= pow(2,$i);
1579 }
1580 }
1582 $netmask.= $result.".";
1583 }
1585 return (preg_replace('/\.$/', '', $netmask));
1586 }
1588 return ($netmask);
1589 }
1592 function netmask_to_bits($netmask)
1593 {
1594 list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1595 $res= 0;
1597 for ($n= 0; $n<4; $n++){
1598 $start= 255;
1599 $name= "nm$n";
1601 for ($i= 0; $i<8; $i++){
1602 if ($start == (int)($$name)){
1603 $res+= 8 - $i;
1604 break;
1605 }
1606 $start-= pow(2,$i);
1607 }
1608 }
1610 return ($res);
1611 }
1614 function recurse($rule, $variables)
1615 {
1616 $result= array();
1618 if (!count($variables)){
1619 return array($rule);
1620 }
1622 reset($variables);
1623 $key= key($variables);
1624 $val= current($variables);
1625 unset ($variables[$key]);
1627 foreach($val as $possibility){
1628 $nrule= str_replace("{$key}", $possibility, $rule);
1629 $result= array_merge($result, recurse($nrule, $variables));
1630 }
1632 return ($result);
1633 }
1636 function expand_id($rule, $attributes)
1637 {
1638 /* Check for id rule */
1639 if(preg_match('/^id(:|#)\d+$/',$rule)){
1640 return (array("\{$rule}"));
1641 }
1643 /* Check for clean attribute */
1644 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1645 $rule= preg_replace('/^%/', '', $rule);
1646 $val= rewrite(str_replace(' ', '', strtolower($attributes[$rule])));
1647 return (array($val));
1648 }
1650 /* Check for attribute with parameters */
1651 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1652 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1653 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1654 $val= rewrite(str_replace(' ', '', strtolower($attributes[$part])));
1655 $start= preg_replace ('/-.*$/', '', $param);
1656 $stop = preg_replace ('/^[^-]+-/', '', $param);
1658 /* Assemble results */
1659 $result= array();
1660 for ($i= $start; $i<= $stop; $i++){
1661 $result[]= substr($val, 0, $i);
1662 }
1663 return ($result);
1664 }
1666 echo "Error in idGenerator string: don't know how to handle rule $rule.\n";
1667 return (array($rule));
1668 }
1671 function gen_uids($rule, $attributes)
1672 {
1673 global $config;
1675 /* Search for keys and fill the variables array with all
1676 possible values for that key. */
1677 $part= "";
1678 $trigger= false;
1679 $stripped= "";
1680 $variables= array();
1682 for ($pos= 0, $l= strlen($rule); $pos < $l; $pos++){
1684 if ($rule[$pos] == "{" ){
1685 $trigger= true;
1686 $part= "";
1687 continue;
1688 }
1690 if ($rule[$pos] == "}" ){
1691 $variables[$pos]= expand_id($part, $attributes);
1692 $stripped.= "{".$pos."}";
1693 $trigger= false;
1694 continue;
1695 }
1697 if ($trigger){
1698 $part.= $rule[$pos];
1699 } else {
1700 $stripped.= $rule[$pos];
1701 }
1702 }
1704 /* Recurse through all possible combinations */
1705 $proposed= recurse($stripped, $variables);
1707 /* Get list of used ID's */
1708 $used= array();
1709 $ldap= $config->get_ldap_link();
1710 $ldap->cd($config->current['BASE']);
1711 $ldap->search('(uid=*)');
1713 while($attrs= $ldap->fetch()){
1714 $used[]= $attrs['uid'][0];
1715 }
1717 /* Remove used uids and watch out for id tags */
1718 $ret= array();
1719 foreach($proposed as $uid){
1721 /* Check for id tag and modify uid if needed */
1722 if(preg_match('/\{id:\d+}/',$uid)){
1723 $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1725 for ($i= 0, $p= pow(10,$size); $i < $p; $i++){
1726 $number= sprintf("%0".$size."d", $i);
1727 $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1728 if (!in_array($res, $used)){
1729 $uid= $res;
1730 break;
1731 }
1732 }
1733 }
1735 if(preg_match('/\{id#\d+}/',$uid)){
1736 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1738 while (true){
1739 mt_srand((double) microtime()*1000000);
1740 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1741 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1742 if (!in_array($res, $used)){
1743 $uid= $res;
1744 break;
1745 }
1746 }
1747 }
1749 /* Don't assign used ones */
1750 if (!in_array($uid, $used)){
1751 $ret[]= $uid;
1752 }
1753 }
1755 return(array_unique($ret));
1756 }
1759 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1760 Need to convert... */
1761 function to_byte($value) {
1762 $value= strtolower(trim($value));
1764 if(!is_numeric(substr($value, -1))) {
1766 switch(substr($value, -1)) {
1767 case 'g':
1768 $mult= 1073741824;
1769 break;
1770 case 'm':
1771 $mult= 1048576;
1772 break;
1773 case 'k':
1774 $mult= 1024;
1775 break;
1776 }
1778 return ($mult * (int)substr($value, 0, -1));
1779 } else {
1780 return $value;
1781 }
1782 }
1785 function in_array_ics($value, $items)
1786 {
1787 return preg_grep('/^'.preg_quote($value, '/').'$/i', $items);
1788 }
1791 function generate_alphabet($count= 10)
1792 {
1793 $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1794 $alphabet= "";
1795 $c= 0;
1797 /* Fill cells with charaters */
1798 for ($i= 0, $l= mb_strlen($characters, 'UTF8'); $i<$l; $i++){
1799 if ($c == 0){
1800 $alphabet.= "<tr>";
1801 }
1803 $ch = mb_substr($characters, $i, 1, "UTF8");
1804 $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1805 validate($_GET['plug'])."&search=".$ch."\"> ".$ch." </a></td>";
1807 if ($c++ == $count){
1808 $alphabet.= "</tr>";
1809 $c= 0;
1810 }
1811 }
1813 /* Fill remaining cells */
1814 while ($c++ <= $count){
1815 $alphabet.= "<td> </td>";
1816 }
1818 return ($alphabet);
1819 }
1822 function validate($string)
1823 {
1824 return (strip_tags(str_replace('\0', '', $string)));
1825 }
1828 function get_gosa_version()
1829 {
1830 global $svn_revision, $svn_path;
1832 /* Extract informations */
1833 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1835 /* Release or development? */
1836 if (preg_match('%/gosa/trunk/%', $svn_path)){
1837 return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1838 } else {
1839 $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1840 return (sprintf(_("GOsa $release"), $revision));
1841 }
1842 }
1845 function rmdirRecursive($path, $followLinks=false) {
1846 $dir= opendir($path);
1847 while($entry= readdir($dir)) {
1848 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1849 unlink($path."/".$entry);
1850 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1851 rmdirRecursive($path."/".$entry);
1852 }
1853 }
1854 closedir($dir);
1855 return rmdir($path);
1856 }
1859 function scan_directory($path,$sort_desc=false)
1860 {
1861 $ret = false;
1863 /* is this a dir ? */
1864 if(is_dir($path)) {
1866 /* is this path a readable one */
1867 if(is_readable($path)){
1869 /* Get contents and write it into an array */
1870 $ret = array();
1872 $dir = opendir($path);
1874 /* Is this a correct result ?*/
1875 if($dir){
1876 while($fp = readdir($dir))
1877 $ret[]= $fp;
1878 }
1879 }
1880 }
1881 /* Sort array ascending , like scandir */
1882 sort($ret);
1884 /* Sort descending if parameter is sort_desc is set */
1885 if($sort_desc) {
1886 $ret = array_reverse($ret);
1887 }
1889 return($ret);
1890 }
1893 function clean_smarty_compile_dir($directory)
1894 {
1895 global $svn_revision;
1897 if(is_dir($directory) && is_readable($directory)) {
1898 // Set revision filename to REVISION
1899 $revision_file= $directory."/REVISION";
1901 /* Is there a stamp containing the current revision? */
1902 if(!file_exists($revision_file)) {
1903 // create revision file
1904 create_revision($revision_file, $svn_revision);
1905 } else {
1906 # check for "$config->...['CONFIG']/revision" and the
1907 # contents should match the revision number
1908 if(!compare_revision($revision_file, $svn_revision)){
1909 // If revision differs, clean compile directory
1910 foreach(scan_directory($directory) as $file) {
1911 if(($file==".")||($file=="..")) continue;
1912 if( is_file($directory."/".$file) &&
1913 is_writable($directory."/".$file)) {
1914 // delete file
1915 if(!unlink($directory."/".$file)) {
1916 msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
1917 // This should never be reached
1918 }
1919 } elseif(is_dir($directory."/".$file) &&
1920 is_writable($directory."/".$file)) {
1921 // Just recursively delete it
1922 rmdirRecursive($directory."/".$file);
1923 }
1924 }
1925 // We should now create a fresh revision file
1926 clean_smarty_compile_dir($directory);
1927 } else {
1928 // Revision matches, nothing to do
1929 }
1930 }
1931 } else {
1932 // Smarty compile dir is not accessible
1933 // (Smarty will warn about this)
1934 }
1935 }
1938 function create_revision($revision_file, $revision)
1939 {
1940 $result= false;
1942 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1943 if($fh= fopen($revision_file, "w")) {
1944 if(fwrite($fh, $revision)) {
1945 $result= true;
1946 }
1947 }
1948 fclose($fh);
1949 } else {
1950 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1951 }
1953 return $result;
1954 }
1957 function compare_revision($revision_file, $revision)
1958 {
1959 // false means revision differs
1960 $result= false;
1962 if(file_exists($revision_file) && is_readable($revision_file)) {
1963 // Open file
1964 if($fh= fopen($revision_file, "r")) {
1965 // Compare File contents with current revision
1966 if($revision == fread($fh, filesize($revision_file))) {
1967 $result= true;
1968 }
1969 } else {
1970 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1971 }
1972 // Close file
1973 fclose($fh);
1974 }
1976 return $result;
1977 }
1980 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1981 {
1982 $str = ""; // Our return value will be saved in this var
1984 $color = dechex($percentage+150);
1985 $color2 = dechex(150 - $percentage);
1986 $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1988 $progress = (int)(($percentage /100)*$width);
1990 /* If theres a better solution for this, use it... */
1991 $str = "\n <div style=\" width:".($width)."px; ";
1992 $str.= "\n height:".($height)."px; ";
1993 $str.= "\n background-color:#000000; ";
1994 $str.= "\n padding:1px;\" > ";
1996 $str.= "\n <div style=\" width:".($width)."px; ";
1997 $str.= "\n background-color:#$bgcolor; ";
1998 $str.= "\n height:".($height)."px;\" > ";
2000 if(($height >10)&&($showvalue)){
2001 $str.= "\n <font style=\"font-size:".($height-2)."px; ";
2002 $str.= "\n color:#FF0000; align:middle; ";
2003 $str.= "\n padding-left:".((int)(($width*0.4)))."px; \"> ";
2004 $str.= "\n <b>".$percentage."%</b> ";
2005 $str.= "\n </font> ";
2006 }
2008 $str.= "\n <div style=\" width:".$progress."px; ";
2009 $str.= "\n height:".$height."px; ";
2010 $str.= "\n background-color:#".$color2.$color2.$color."; \" >";
2011 $str.= "\n </div>";
2012 $str.= "\n </div>";
2013 $str.= "\n </div>";
2015 return($str);
2016 }
2019 function array_key_ics($ikey, $items)
2020 {
2021 $tmp= array_change_key_case($items, CASE_LOWER);
2022 $ikey= strtolower($ikey);
2023 if (isset($tmp[$ikey])){
2024 return($tmp[$ikey]);
2025 }
2027 return ('');
2028 }
2031 function array_differs($src, $dst)
2032 {
2033 /* If the count is differing, the arrays differ */
2034 if (count ($src) != count ($dst)){
2035 return (TRUE);
2036 }
2038 return (count(array_diff($src, $dst)) != 0);
2039 }
2042 function saveFilter($a_filter, $values)
2043 {
2044 if (isset($_POST['regexit'])){
2045 $a_filter["regex"]= $_POST['regexit'];
2047 foreach($values as $type){
2048 if (isset($_POST[$type])) {
2049 $a_filter[$type]= "checked";
2050 } else {
2051 $a_filter[$type]= "";
2052 }
2053 }
2054 }
2056 /* React on alphabet links if needed */
2057 if (isset($_GET['search'])){
2058 $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2059 if ($s == "**"){
2060 $s= "*";
2061 }
2062 $a_filter['regex']= $s;
2063 }
2065 return ($a_filter);
2066 }
2069 /* Escape all LDAP filter relevant characters */
2070 function normalizeLdap($input)
2071 {
2072 return (addcslashes($input, '()|'));
2073 }
2076 /* Resturns the difference between to microtime() results in float */
2077 function get_MicroTimeDiff($start , $stop)
2078 {
2079 $a = split("\ ",$start);
2080 $b = split("\ ",$stop);
2082 $secs = $b[1] - $a[1];
2083 $msecs= $b[0] - $a[0];
2085 $ret = (float) ($secs+ $msecs);
2086 return($ret);
2087 }
2090 function get_base_dir()
2091 {
2092 global $BASE_DIR;
2094 return $BASE_DIR;
2095 }
2098 function obj_is_readable($dn, $object, $attribute)
2099 {
2100 global $ui;
2102 return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2103 }
2106 function obj_is_writable($dn, $object, $attribute)
2107 {
2108 global $ui;
2110 return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2111 }
2114 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2115 {
2116 /* Initialize variables */
2117 $ret = array("count" => 0); // Set count to 0
2118 $next = true; // if false, then skip next loops and return
2119 $cnt = 0; // Current number of loops
2120 $max = 100; // Just for security, prevent looops
2121 $ldap = NULL; // To check if created result a valid
2122 $keep = ""; // save last failed parse string
2124 /* Check each parsed dn in ldap ? */
2125 if($config!==NULL && $verify_in_ldap){
2126 $ldap = $config->get_ldap_link();
2127 }
2129 /* Lets start */
2130 $called = false;
2131 while(preg_match("/,/",$dn) && $next && $cnt < $max){
2133 $cnt ++;
2134 if(!preg_match("/,/",$dn)){
2135 $next = false;
2136 }
2137 $object = preg_replace("/[,].*$/","",$dn);
2138 $dn = preg_replace("/^[^,]+,/","",$dn);
2140 $called = true;
2142 /* Check if current dn is valid */
2143 if($ldap!==NULL){
2144 $ldap->cd($dn);
2145 $ldap->cat($dn,array("dn"));
2146 if($ldap->count()){
2147 $ret[] = $keep.$object;
2148 $keep = "";
2149 }else{
2150 $keep .= $object.",";
2151 }
2152 }else{
2153 $ret[] = $keep.$object;
2154 $keep = "";
2155 }
2156 }
2158 /* No dn was posted */
2159 if($cnt == 0 && !empty($dn)){
2160 $ret[] = $dn;
2161 }
2163 /* Append the rest */
2164 $test = $keep.$dn;
2165 if($called && !empty($test)){
2166 $ret[] = $keep.$dn;
2167 }
2168 $ret['count'] = count($ret) - 1;
2170 return($ret);
2171 }
2174 function get_base_from_hook($dn, $attrib)
2175 {
2176 global $config;
2178 if ($config->get_cfg_value("baseIdHook") != ""){
2180 /* Call hook script - if present */
2181 $command= $config->get_cfg_value("baseIdHook");
2183 if ($command != ""){
2184 $command.= " '".LDAP::fix($dn)."' $attrib";
2185 if (check_command($command)){
2186 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2187 exec($command, $output);
2188 if (preg_match("/^[0-9]+$/", $output[0])){
2189 return ($output[0]);
2190 } else {
2191 msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2192 return ($config->get_cfg_value("uidNumberBase"));
2193 }
2194 } else {
2195 msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2196 return ($config->get_cfg_value("uidNumberBase"));
2197 }
2199 } else {
2201 msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2202 return ($config->get_cfg_value("uidNumberBase"));
2204 }
2205 }
2206 }
2209 function check_schema_version($class, $version)
2210 {
2211 return preg_match("/\(v$version\)/", $class['DESC']);
2212 }
2215 function check_schema($cfg,$rfc2307bis = FALSE)
2216 {
2217 $messages= array();
2219 /* Get objectclasses */
2220 $ldap = new ldapMultiplexer(new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE, $cfg['tls']));
2221 $objectclasses = $ldap->get_objectclasses();
2222 if(count($objectclasses) == 0){
2223 msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2224 }
2226 /* This is the default block used for each entry.
2227 * to avoid unset indexes.
2228 */
2229 $def_check = array("REQUIRED_VERSION" => "0",
2230 "SCHEMA_FILES" => array(),
2231 "CLASSES_REQUIRED" => array(),
2232 "STATUS" => FALSE,
2233 "IS_MUST_HAVE" => FALSE,
2234 "MSG" => "",
2235 "INFO" => "");#_("There is currently no information specified for this schema extension."));
2237 /* The gosa base schema */
2238 $checks['gosaObject'] = $def_check;
2239 $checks['gosaObject']['REQUIRED_VERSION'] = "2.6.1";
2240 $checks['gosaObject']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2241 $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2242 $checks['gosaObject']['IS_MUST_HAVE'] = TRUE;
2244 /* GOsa Account class */
2245 $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.6.1";
2246 $checks["gosaAccount"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2247 $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2248 $checks["gosaAccount"]["IS_MUST_HAVE"] = TRUE;
2249 $checks["gosaAccount"]["INFO"] = _("Used to store account specific informations.");
2251 /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2252 $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.6.1";
2253 $checks["gosaLockEntry"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2254 $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2255 $checks["gosaLockEntry"]["IS_MUST_HAVE"] = TRUE;
2256 $checks["gosaLockEntry"]["INFO"] = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2258 /* Some other checks */
2259 foreach(array(
2260 "gosaCacheEntry" => array("version" => "2.6.1"),
2261 "gosaDepartment" => array("version" => "2.6.1"),
2262 "goFaxAccount" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2263 "goFaxSBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2264 "goFaxRBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2265 "gosaUserTemplate" => array("version" => "2.6.1", "class" => "posixAccount","file" => "nis.schema"),
2266 "gosaMailAccount" => array("version" => "2.6.1", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2267 "gosaProxyAccount" => array("version" => "2.6.1", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2268 "gosaApplication" => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2269 "gosaApplicationGroup" => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2270 "GOhard" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2271 "gotoTerminal" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2272 "goServer" => array("version" => "2.6.1","class" => "server","file" => "goserver.schema"),
2273 "goTerminalServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2274 "goShareServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2275 "goNtpServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2276 "goSyslogServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2277 "goLdapServer" => array("version" => "2.6.1"),
2278 "goCupsServer" => array("version" => "2.6.1", "class" => array("posixAccount", "terminals"),),
2279 "goImapServer" => array("version" => "2.6.1", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3. schema"),
2280 "goKrbServer" => array("version" => "2.6.1"),
2281 "goFaxServer" => array("version" => "2.6.1", "class" => "gofaxAccount","file" => "gofax.schema"),
2282 ) as $name => $values){
2284 $checks[$name] = $def_check;
2285 if(isset($values['version'])){
2286 $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2287 }
2288 if(isset($values['file'])){
2289 $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2290 }
2291 $checks[$name]["CLASSES_REQUIRED"] = array($name);
2292 }
2293 foreach($checks as $name => $value){
2294 foreach($value['CLASSES_REQUIRED'] as $class){
2296 if(!isset($objectclasses[$name])){
2297 $checks[$name]['STATUS'] = FALSE;
2298 if($value['IS_MUST_HAVE']){
2299 $checks[$name]['MSG'] = sprintf(_("Missing required object class '%s'!"),$class);
2300 }else{
2301 $checks[$name]['MSG'] = sprintf(_("Missing optional object class '%s'!"),$class);
2302 }
2303 }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2304 $checks[$name]['STATUS'] = FALSE;
2306 if($value['IS_MUST_HAVE']){
2307 $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2308 }else{
2309 $checks[$name]['MSG'] = sprintf(_("Version mismatch for optional object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2310 }
2311 }else{
2312 $checks[$name]['STATUS'] = TRUE;
2313 $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2314 }
2315 }
2316 }
2318 $tmp = $objectclasses;
2320 /* The gosa base schema */
2321 $checks['posixGroup'] = $def_check;
2322 $checks['posixGroup']['REQUIRED_VERSION'] = "2.6.1";
2323 $checks['posixGroup']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2324 $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2325 $checks['posixGroup']['STATUS'] = TRUE;
2326 $checks['posixGroup']['IS_MUST_HAVE'] = TRUE;
2327 $checks['posixGroup']['MSG'] = "";
2328 $checks['posixGroup']['INFO'] = "";
2330 /* Depending on selected rfc2307bis mode, we need different schema configurations */
2331 if(isset($tmp['posixGroup'])){
2333 if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2334 $checks['posixGroup']['STATUS'] = FALSE;
2335 $checks['posixGroup']['MSG'] = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema configuration do not support this option.");
2336 $checks['posixGroup']['INFO'] = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be AUXILIARY");
2337 }
2338 if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2339 $checks['posixGroup']['STATUS'] = FALSE;
2340 $checks['posixGroup']['MSG'] = _("Your schema is configured to support the rfc2307bis group, but you have disabled this option on the 'ldap setup' step.");
2341 $checks['posixGroup']['INFO'] = _("The objectClass 'posixGroup' must be STRUCTURAL");
2342 }
2343 }
2345 return($checks);
2346 }
2349 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2350 {
2351 $tmp = array(
2352 "de_DE" => "German",
2353 "fr_FR" => "French",
2354 "it_IT" => "Italian",
2355 "es_ES" => "Spanish",
2356 "en_US" => "English",
2357 "nl_NL" => "Dutch",
2358 "pl_PL" => "Polish",
2359 #"sv_SE" => "Swedish",
2360 "zh_CN" => "Chinese",
2361 "vi_VN" => "Vietnamese",
2362 "ru_RU" => "Russian");
2364 $tmp2= array(
2365 "de_DE" => _("German"),
2366 "fr_FR" => _("French"),
2367 "it_IT" => _("Italian"),
2368 "es_ES" => _("Spanish"),
2369 "en_US" => _("English"),
2370 "nl_NL" => _("Dutch"),
2371 "pl_PL" => _("Polish"),
2372 #"sv_SE" => _("Swedish"),
2373 "zh_CN" => _("Chinese"),
2374 "vi_VN" => _("Vietnamese"),
2375 "ru_RU" => _("Russian"));
2377 $ret = array();
2378 if($languages_in_own_language){
2380 $old_lang = setlocale(LC_ALL, 0);
2382 /* If the locale wasn't correclty set before, there may be an incorrect
2383 locale returned. Something like this:
2384 C_CTYPE=de_DE.UTF-8;LC_NUMERIC=C;LC_TIME=de_DE.UTF-8;LC ...
2385 Extract the locale name from this string and use it to restore old locale.
2386 */
2387 if(preg_match("/LC_CTYPE/",$old_lang)){
2388 $old_lang = preg_replace("/^.*LC_CTYPE=([^;]*).*$/","\\1",$old_lang);
2389 }
2391 foreach($tmp as $key => $name){
2392 $lang = $key.".UTF-8";
2393 setlocale(LC_ALL, $lang);
2394 if($strip_region_tag){
2395 $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2396 }else{
2397 $ret[$key] = _($name)." (".$tmp2[$key].")";
2398 }
2399 }
2400 setlocale(LC_ALL, $old_lang);
2401 }else{
2402 foreach($tmp as $key => $name){
2403 if($strip_region_tag){
2404 $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2405 }else{
2406 $ret[$key] = _($name);
2407 }
2408 }
2409 }
2410 return($ret);
2411 }
2414 /* Returns contents of the given POST variable and check magic quotes settings */
2415 function get_post($name)
2416 {
2417 if(!isset($_POST[$name])){
2418 trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2419 return(FALSE);
2420 }
2421 if(get_magic_quotes_gpc()){
2422 return(stripcslashes($_POST[$name]));
2423 }else{
2424 return($_POST[$name]);
2425 }
2426 }
2429 /* Return class name in correct case */
2430 function get_correct_class_name($cls)
2431 {
2432 global $class_mapping;
2433 if(isset($class_mapping) && is_array($class_mapping)){
2434 foreach($class_mapping as $class => $file){
2435 if(preg_match("/^".$cls."$/i",$class)){
2436 return($class);
2437 }
2438 }
2439 }
2440 return(FALSE);
2441 }
2444 // change_password, changes the Password, of the given dn
2445 function change_password ($dn, $password, $mode=0, $hash= "")
2446 {
2447 global $config;
2448 $newpass= "";
2450 /* Convert to lower. Methods are lowercase */
2451 $hash= strtolower($hash);
2453 // Get all available encryption Methods
2455 // NON STATIC CALL :)
2456 $methods = new passwordMethod(session::get('config'));
2457 $available = $methods->get_available_methods();
2459 // read current password entry for $dn, to detect the encryption Method
2460 $ldap = $config->get_ldap_link();
2461 $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2462 $attrs = $ldap->fetch ();
2464 /* Is ensure that clear passwords will stay clear */
2465 if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2466 $hash = "clear";
2467 }
2469 // Detect the encryption Method
2470 if ( (isset($attrs['userPassword'][0]) && preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) || $hash != ""){
2472 /* Check for supported algorithm */
2473 mt_srand((double) microtime()*1000000);
2475 /* Extract used hash */
2476 if ($hash == ""){
2477 $test = passwordMethod::get_method($attrs['userPassword'][0],$dn);
2478 } else {
2479 $test = new $available[$hash]($config,$dn);
2480 $test->set_hash($hash);
2481 }
2483 } else {
2484 // User MD5 by default
2485 $hash= "md5";
2486 $test = new $available['md5']($config);
2487 }
2489 if($test instanceOf passwordMethod){
2491 $deactivated = $test->is_locked($config,$dn);
2493 /* Feed password backends with information */
2494 $test->dn= $dn;
2495 $test->attrs= $attrs;
2496 $newpass= $test->generate_hash($password);
2498 // Update shadow timestamp?
2499 if (isset($attrs["shadowLastChange"][0])){
2500 $shadow= (int)(date("U") / 86400);
2501 } else {
2502 $shadow= 0;
2503 }
2505 // Write back modified entry
2506 $ldap->cd($dn);
2507 $attrs= array();
2509 // Not for groups
2510 if ($mode == 0){
2512 if ($shadow != 0){
2513 $attrs['shadowLastChange']= $shadow;
2514 }
2516 // Create SMB Password
2517 $attrs= generate_smb_nt_hash($password);
2518 }
2520 $attrs['userPassword']= array();
2521 $attrs['userPassword']= $newpass;
2523 $ldap->modify($attrs);
2525 /* Read ! if user was deactivated */
2526 if($deactivated){
2527 $test->lock_account($config,$dn);
2528 }
2530 new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2532 if (!$ldap->success()) {
2533 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, ERROR_DIALOG));
2534 } else {
2536 /* Run backend method for change/create */
2537 if(!$test->set_password($password)){
2538 return(FALSE);
2539 }
2541 /* Find postmodify entries for this class */
2542 $command= $config->search("password", "POSTMODIFY",array('menu'));
2544 if ($command != ""){
2545 /* Walk through attribute list */
2546 $command= preg_replace("/%userPassword/", $password, $command);
2547 $command= preg_replace("/%dn/", $dn, $command);
2549 if (check_command($command)){
2550 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2551 exec($command);
2552 } else {
2553 $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2554 msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2555 }
2556 }
2557 }
2558 return(TRUE);
2559 }
2560 }
2563 // Return something like array['sambaLMPassword']= "lalla..."
2564 function generate_smb_nt_hash($password)
2565 {
2566 global $config;
2568 # Try to use gosa-si?
2569 if ($config->get_cfg_value("gosaSupportURI") != ""){
2570 $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
2571 if (isset($res['XML']['HASH'])){
2572 $hash= $res['XML']['HASH'];
2573 } else {
2574 $hash= "";
2575 }
2576 } else {
2577 $tmp= $config->get_cfg_value('sambaHashHook')." ".escapeshellarg($password);
2578 @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2580 exec($tmp, $ar);
2581 flush();
2582 reset($ar);
2583 $hash= current($ar);
2584 }
2586 if ($hash == "") {
2587 msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
2588 return ("");
2589 }
2591 list($lm,$nt)= split (":", trim($hash));
2593 if ($config->get_cfg_value("sambaversion") == 3) {
2594 $attrs['sambaLMPassword']= $lm;
2595 $attrs['sambaNTPassword']= $nt;
2596 $attrs['sambaPwdLastSet']= date('U');
2597 $attrs['sambaBadPasswordCount']= "0";
2598 $attrs['sambaBadPasswordTime']= "0";
2599 } else {
2600 $attrs['lmPassword']= $lm;
2601 $attrs['ntPassword']= $nt;
2602 $attrs['pwdLastSet']= date('U');
2603 }
2604 return($attrs);
2605 }
2608 function getEntryCSN($dn)
2609 {
2610 global $config;
2611 if(empty($dn) || !is_object($config)){
2612 return("");
2613 }
2615 /* Get attribute that we should use as serial number */
2616 $attr= $config->get_cfg_value("modificationDetectionAttribute");
2617 if($attr != ""){
2618 $ldap = $config->get_ldap_link();
2619 $ldap->cat($dn,array($attr));
2620 $csn = $ldap->fetch();
2621 if(isset($csn[$attr][0])){
2622 return($csn[$attr][0]);
2623 }
2624 }
2625 return("");
2626 }
2629 /* Add a given objectClass to an attrs entry */
2630 function add_objectClass($classes, &$attrs)
2631 {
2632 if (is_array($classes)){
2633 $list= $classes;
2634 } else {
2635 $list= array($classes);
2636 }
2638 foreach ($list as $class){
2639 $attrs['objectClass'][]= $class;
2640 }
2641 }
2644 /* Removes a given objectClass from the attrs entry */
2645 function remove_objectClass($classes, &$attrs)
2646 {
2647 if (isset($attrs['objectClass'])){
2648 /* Array? */
2649 if (is_array($classes)){
2650 $list= $classes;
2651 } else {
2652 $list= array($classes);
2653 }
2655 $tmp= array();
2656 foreach ($attrs['objectClass'] as $oc) {
2657 foreach ($list as $class){
2658 if (strtolower($oc) != strtolower($class)){
2659 $tmp[]= $oc;
2660 }
2661 }
2662 }
2663 $attrs['objectClass']= $tmp;
2664 }
2665 }
2667 /*! \brief Initialize a file download with given content, name and data type.
2668 * @param data String The content to send.
2669 * @param name String The name of the file.
2670 * @param type String The content identifier, default value is "application/octet-stream";
2671 */
2672 function send_binary_content($data,$name,$type = "application/octet-stream")
2673 {
2674 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
2675 header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
2676 header("Cache-Control: no-cache");
2677 header("Pragma: no-cache");
2678 header("Cache-Control: post-check=0, pre-check=0");
2679 header("Content-type: ".$type."");
2681 $HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
2683 /* Strip name if it is a complete path */
2684 if (preg_match ("/\//", $name)) {
2685 $name= basename($name);
2686 }
2688 /* force download dialog */
2689 if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
2690 header('Content-Disposition: filename="'.$name.'"');
2691 } else {
2692 header('Content-Disposition: attachment; filename="'.$name.'"');
2693 }
2695 echo $data;
2696 exit();
2697 }
2700 function reverse_html_entities($str,$type = ENT_QUOTES , $charset = "UTF-8")
2701 {
2702 if(is_string($str)){
2703 return(htmlentities($str,$type,$charset));
2704 }elseif(is_array($str)){
2705 foreach($str as $name => $value){
2706 $str[$name] = reverse_html_entities($value,$type,$charset);
2707 }
2708 }
2709 return($str);
2710 }
2713 /*! \brief Encode special string characters so we can use the string in \
2714 HTML output, without breaking quotes.
2715 @param The String we want to encode.
2716 @return The encoded String
2717 */
2718 function xmlentities($str)
2719 {
2720 if(is_string($str)){
2722 static $asc2uni= array();
2723 if (!count($asc2uni)){
2724 for($i=128;$i<256;$i++){
2725 # $asc2uni[chr($i)] = "&#x".dechex($i).";";
2726 }
2727 }
2729 $str = str_replace("&", "&", $str);
2730 $str = str_replace("<", "<", $str);
2731 $str = str_replace(">", ">", $str);
2732 $str = str_replace("'", "'", $str);
2733 $str = str_replace("\"", """, $str);
2734 $str = str_replace("\r", "", $str);
2735 $str = strtr($str,$asc2uni);
2736 return $str;
2737 }elseif(is_array($str)){
2738 foreach($str as $name => $value){
2739 $str[$name] = xmlentities($value);
2740 }
2741 }
2742 return($str);
2743 }
2746 /*! \brief Updates all accessTo attributes from a given value to a new one.
2747 For example if a host is renamed.
2748 @param String $from The source accessTo name.
2749 @param String $to The destination accessTo name.
2750 */
2751 function update_accessTo($from,$to)
2752 {
2753 global $config;
2754 $ldap = $config->get_ldap_link();
2755 $ldap->cd($config->current['BASE']);
2756 $ldap->search("(&(objectClass=trustAccount)(accessTo=".$from."))",array("objectClass","accessTo"));
2757 while($attrs = $ldap->fetch()){
2758 $new_attrs = array("accessTo" => array());
2759 $dn = $attrs['dn'];
2760 for($i = 0 ; $i < $attrs['objectClass']['count']; $i++){
2761 $new_attrs['objectClass'][] = $attrs['objectClass'][$i];
2762 }
2763 for($i = 0 ; $i < $attrs['accessTo']['count']; $i++){
2764 if($attrs['accessTo'][$i] == $from){
2765 if(!empty($to)){
2766 $new_attrs['accessTo'][] = $to;
2767 }
2768 }else{
2769 $new_attrs['accessTo'][] = $attrs['accessTo'][$i];
2770 }
2771 }
2772 $ldap->cd($dn);
2773 $ldap->modify($new_attrs);
2774 if (!$ldap->success()){
2775 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, "update_accessTo($from,$to)"));
2776 }
2777 new log("modify","update_accessTo($from,$to)",$dn,array_keys($new_attrs),$ldap->get_error());
2778 }
2779 }
2782 function get_random_char () {
2783 $randno = rand (0, 63);
2784 if ($randno < 12) {
2785 return (chr ($randno + 46)); // Digits, '/' and '.'
2786 } else if ($randno < 38) {
2787 return (chr ($randno + 53)); // Uppercase
2788 } else {
2789 return (chr ($randno + 59)); // Lowercase
2790 }
2791 }
2794 function cred_encrypt($input, $password) {
2796 $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2797 $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2799 return bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $password, $input, MCRYPT_MODE_ECB, $iv));
2801 }
2803 function cred_decrypt($input,$password) {
2804 $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2805 $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2807 return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $password, pack("H*", $input), MCRYPT_MODE_ECB, $iv);
2808 }
2811 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2812 ?>