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.5
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);
90 /* Rewrite german 'umlauts' and spanish 'accents'
91 to get better results */
92 $REWRITE= array( "ä" => "ae",
93 "ö" => "oe",
94 "ü" => "ue",
95 "Ä" => "Ae",
96 "Ö" => "Oe",
97 "Ü" => "Ue",
98 "ß" => "ss",
99 "á" => "a",
100 "é" => "e",
101 "í" => "i",
102 "ó" => "o",
103 "ú" => "u",
104 "Á" => "A",
105 "É" => "E",
106 "Í" => "I",
107 "Ó" => "O",
108 "Ú" => "U",
109 "ñ" => "ny",
110 "Ñ" => "Ny" );
113 /* Class autoloader */
114 function __autoload($class_name) {
115 global $class_mapping, $BASE_DIR;
117 if ($class_mapping === NULL){
118 echo sprintf(_("Fatal error: no class locations defined - please run '%s' to fix this"), "<b>update-gosa</b>");
119 exit;
120 }
122 if (isset($class_mapping[$class_name])){
123 require_once($BASE_DIR."/".$class_mapping[$class_name]);
124 } else {
125 echo sprintf(_("Fatal error: cannot instantiate class '%s' - try running '%s' to fix this"), $class_name, "<b>update-gosa</b>");
126 exit;
127 }
128 }
131 /*! \brief Checks if a class is available.
132 * @param name String The class name.
133 * @return boolean True if class is available, else false.
134 */
135 function class_available($name)
136 {
137 global $class_mapping;
138 return(isset($class_mapping[$name]));
139 }
142 /* Check if plugin is avaliable */
143 function plugin_available($plugin)
144 {
145 global $class_mapping, $BASE_DIR;
147 if (!isset($class_mapping[$plugin])){
148 return false;
149 } else {
150 return is_readable($BASE_DIR."/".$class_mapping[$plugin]);
151 }
152 }
155 /* Create seed with microseconds */
156 function make_seed() {
157 list($usec, $sec) = explode(' ', microtime());
158 return (float) $sec + ((float) $usec * 100000);
159 }
162 /* Debug level action */
163 function DEBUG($level, $line, $function, $file, $data, $info="")
164 {
165 if (session::get('DEBUGLEVEL') & $level){
166 $output= "DEBUG[$level] ";
167 if ($function != ""){
168 $output.= "($file:$function():$line) - $info: ";
169 } else {
170 $output.= "($file:$line) - $info: ";
171 }
172 echo $output;
173 if (is_array($data)){
174 print_a($data);
175 } else {
176 echo "'$data'";
177 }
178 echo "<br>";
179 }
180 }
183 function get_browser_language()
184 {
185 /* Try to use users primary language */
186 global $config;
187 $ui= get_userinfo();
188 if (isset($ui) && $ui !== NULL){
189 if ($ui->language != ""){
190 return ($ui->language.".UTF-8");
191 }
192 }
194 /* Check for global language settings in gosa.conf */
195 if (isset ($config) && $config->get_cfg_value('lang') != ""){
196 $lang = $config->get_cfg_value('lang');
197 if(!preg_match("/utf/i",$lang)){
198 $lang .= ".UTF-8";
199 }
200 return($lang);
201 }
203 /* Load supported languages */
204 $gosa_languages= get_languages();
206 /* Move supported languages to flat list */
207 $langs= array();
208 foreach($gosa_languages as $lang => $dummy){
209 $langs[]= $lang.'.UTF-8';
210 }
212 /* Return gettext based string */
213 return (al2gt($langs, 'text/html'));
214 }
217 /* Rewrite ui object to another dn */
218 function change_ui_dn($dn, $newdn)
219 {
220 $ui= session::get('ui');
221 if ($ui->dn == $dn){
222 $ui->dn= $newdn;
223 session::set('ui',$ui);
224 }
225 }
228 /* Return theme path for specified file */
229 function get_template_path($filename= '', $plugin= FALSE, $path= "")
230 {
231 global $config, $BASE_DIR;
233 /* Set theme */
234 if (isset ($config)){
235 $theme= $config->get_cfg_value("theme", "default");
236 } else {
237 $theme= "default";
238 }
240 /* Return path for empty filename */
241 if ($filename == ''){
242 return ("themes/$theme/");
243 }
245 /* Return plugin dir or root directory? */
246 if ($plugin){
247 if ($path == ""){
248 $nf= preg_replace("!^".$BASE_DIR."/!", "", session::get('plugin_dir'));
249 } else {
250 $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
251 }
252 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
253 return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
254 }
255 if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
256 return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
257 }
258 if ($path == ""){
259 return (session::get('plugin_dir')."/$filename");
260 } else {
261 return ($path."/$filename");
262 }
263 } else {
264 if (file_exists("themes/$theme/$filename")){
265 return ("themes/$theme/$filename");
266 }
267 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
268 return ("$BASE_DIR/ihtml/themes/$theme/$filename");
269 }
270 if (file_exists("themes/default/$filename")){
271 return ("themes/default/$filename");
272 }
273 if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
274 return ("$BASE_DIR/ihtml/themes/default/$filename");
275 }
276 return ($filename);
277 }
278 }
281 function array_remove_entries($needles, $haystack)
282 {
283 $tmp= array();
285 /* Loop through entries to be removed */
286 foreach ($haystack as $entry){
287 if (!in_array($entry, $needles)){
288 $tmp[]= $entry;
289 }
290 }
292 return ($tmp);
293 }
296 function array_remove_entries_ics($needles, $haystack)
297 {
298 $tmp= array();
300 /* Loop through entries to be removed */
301 foreach ($haystack as $entry){
302 if (!in_array_ics($entry, $needles)){
303 $tmp[]= $entry;
304 }
305 }
307 return ($tmp);
308 }
311 function gosa_array_merge($ar1,$ar2)
312 {
313 if(!is_array($ar1) || !is_array($ar2)){
314 trigger_error("Specified parameter(s) are not valid arrays.");
315 }else{
316 return(array_values(array_unique(array_merge($ar1,$ar2))));
317 }
318 }
321 function gosa_log ($message)
322 {
323 global $ui;
325 /* Preset to something reasonable */
326 $username= " unauthenticated";
328 /* Replace username if object is present */
329 if (isset($ui)){
330 if ($ui->username != ""){
331 $username= "[$ui->username]";
332 } else {
333 $username= "unknown";
334 }
335 }
337 syslog(LOG_INFO,"GOsa$username: $message");
338 }
341 function ldap_init ($server, $base, $binddn='', $pass='')
342 {
343 global $config;
345 $ldap = new LDAP ($binddn, $pass, $server,
346 isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
347 isset($config->current['TLS']) && $config->current['TLS'] == "true");
349 /* Sadly we've no proper return values here. Use the error message instead. */
350 if (!$ldap->success()){
351 echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
352 exit();
353 }
355 /* Preset connection base to $base and return to caller */
356 $ldap->cd ($base);
357 return $ldap;
358 }
361 function process_htaccess ($username, $kerberos= FALSE)
362 {
363 global $config;
365 /* Search for $username and optional @REALM in all configured LDAP trees */
366 foreach($config->data["LOCATIONS"] as $name => $data){
368 $config->set_current($name);
369 $mode= "kerberos";
370 if ($config->get_cfg_value("krbsasl") == "true"){
371 $mode= "sasl";
372 }
374 /* Look for entry or realm */
375 $ldap= $config->get_ldap_link();
376 if (!$ldap->success()){
377 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH, ERROR_DIALOG));
378 $smarty= get_smarty();
379 $smarty->display(get_template_path('headers.tpl'));
380 echo "<body>".session::get('errors')."</body></html>";
381 exit();
382 }
383 $ldap->search("(&(objectClass=gosaAccount)(|(uid=$username)(userPassword={$mode}$username)))", array("uid"));
385 /* Found a uniq match? Return it... */
386 if ($ldap->count() == 1) {
387 $attrs= $ldap->fetch();
388 return array("username" => $attrs["uid"][0], "server" => $name);
389 }
390 }
392 /* Nothing found? Return emtpy array */
393 return array("username" => "", "server" => "");
394 }
397 function ldap_login_user_htaccess ($username)
398 {
399 global $config;
401 /* Look for entry or realm */
402 $ldap= $config->get_ldap_link();
403 if (!$ldap->success()){
404 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH, FATAL_ERROR_DIALOG));
405 $smarty= get_smarty();
406 $smarty->display(get_template_path('headers.tpl'));
407 echo "<body>".session::get('errors')."</body></html>";
408 exit();
409 }
410 $ldap->search("(&(objectClass=gosaAccount)(uid=$username))", array("uid"));
411 /* Found no uniq match? Strange, because we did above... */
412 if ($ldap->count() != 1) {
413 msg_dialog::display(_("LDAP error"), _("Username / UID is not unique inside the LDAP tree!"), FATAL_ERROR_DIALOG);
414 return (NULL);
415 }
416 $attrs= $ldap->fetch();
418 /* got user dn, fill acl's */
419 $ui= new userinfo($config, $ldap->getDN());
420 $ui->username= $attrs['uid'][0];
422 /* No password check needed - the webserver did it for us */
423 $ldap->disconnect();
425 /* Username is set, load subtreeACL's now */
426 $ui->loadACL();
428 /* TODO: check java script for htaccess authentication */
429 session::set('js',true);
431 return ($ui);
432 }
435 function ldap_login_user ($username, $password)
436 {
437 global $config;
439 /* look through the entire ldap */
440 $ldap = $config->get_ldap_link();
441 if (!$ldap->success()){
442 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error()), FATAL_ERROR_DIALOG);
443 $smarty= get_smarty();
444 $smarty->display(get_template_path('headers.tpl'));
445 echo "<body>".session::get('errors')."</body></html>";
446 exit();
447 }
448 $ldap->cd($config->current['BASE']);
449 $allowed_attributes = array("uid","mail");
450 $verify_attr = array();
451 if($config->get_cfg_value("login_attribute") != ""){
452 $tmp = split(",", $config->get_cfg_value("login_attribute"));
453 foreach($tmp as $attr){
454 if(in_array($attr,$allowed_attributes)){
455 $verify_attr[] = $attr;
456 }
457 }
458 }
459 if(count($verify_attr) == 0){
460 $verify_attr = array("uid");
461 }
462 $tmp= $verify_attr;
463 $tmp[] = "uid";
464 $filter = "";
465 foreach($verify_attr as $attr) {
466 $filter.= "(".$attr."=".$username.")";
467 }
468 $filter = "(&(|".$filter.")(objectClass=gosaAccount))";
469 $ldap->search($filter,$tmp);
471 /* get results, only a count of 1 is valid */
472 switch ($ldap->count()){
474 /* user not found */
475 case 0: return (NULL);
477 /* valid uniq user */
478 case 1:
479 break;
481 /* found more than one matching id */
482 default:
483 msg_dialog::display(_("Internal error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), FATAL_ERROR_DIALOG);
484 return (NULL);
485 }
487 /* LDAP schema is not case sensitive. Perform additional check. */
488 $attrs= $ldap->fetch();
489 $success = FALSE;
490 foreach($verify_attr as $attr){
491 if(isset($attrs[$attr][0]) && $attrs[$attr][0] == $username){
492 $success = TRUE;
493 }
494 }
495 if(!$success){
496 return(FALSE);
497 }
499 /* got user dn, fill acl's */
500 $ui= new userinfo($config, $ldap->getDN());
501 $ui->username= $attrs['uid'][0];
503 /* password check, bind as user with supplied password */
504 $ldap->disconnect();
505 $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
506 isset($config->current['RECURSIVE']) &&
507 $config->current['RECURSIVE'] == "true",
508 isset($config->current['TLS'])
509 && $config->current['TLS'] == "true");
510 if (!$ldap->success()){
511 return (NULL);
512 }
514 /* Username is set, load subtreeACL's now */
515 $ui->loadACL();
517 return ($ui);
518 }
521 function ldap_expired_account($config, $userdn, $username)
522 {
523 $ldap= $config->get_ldap_link();
524 $ldap->cat($userdn);
525 $attrs= $ldap->fetch();
527 /* default value no errors */
528 $expired = 0;
530 $sExpire = 0;
531 $sLastChange = 0;
532 $sMax = 0;
533 $sMin = 0;
534 $sInactive = 0;
535 $sWarning = 0;
537 $current= date("U");
539 $current= floor($current /60 /60 /24);
541 /* special case of the admin, should never been locked */
542 /* FIXME should allow any name as user admin */
543 if($username != "admin")
544 {
546 if(isset($attrs['shadowExpire'][0])){
547 $sExpire= $attrs['shadowExpire'][0];
548 } else {
549 $sExpire = 0;
550 }
552 if(isset($attrs['shadowLastChange'][0])){
553 $sLastChange= $attrs['shadowLastChange'][0];
554 } else {
555 $sLastChange = 0;
556 }
558 if(isset($attrs['shadowMax'][0])){
559 $sMax= $attrs['shadowMax'][0];
560 } else {
561 $smax = 0;
562 }
564 if(isset($attrs['shadowMin'][0])){
565 $sMin= $attrs['shadowMin'][0];
566 } else {
567 $sMin = 0;
568 }
570 if(isset($attrs['shadowInactive'][0])){
571 $sInactive= $attrs['shadowInactive'][0];
572 } else {
573 $sInactive = 0;
574 }
576 if(isset($attrs['shadowWarning'][0])){
577 $sWarning= $attrs['shadowWarning'][0];
578 } else {
579 $sWarning = 0;
580 }
582 /* is the account locked */
583 /* shadowExpire + shadowInactive (option) */
584 if($sExpire >0){
585 if($current >= ($sExpire+$sInactive)){
586 return(1);
587 }
588 }
590 /* the user should be warned to change is password */
591 if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
592 if (($sExpire - $current) < $sWarning){
593 return(2);
594 }
595 }
597 /* force user to change password */
598 if(($sLastChange >0) && ($sMax) >0){
599 if($current >= ($sLastChange+$sMax)){
600 return(3);
601 }
602 }
604 /* the user should not be able to change is password */
605 if(($sLastChange >0) && ($sMin >0)){
606 if (($sLastChange + $sMin) >= $current){
607 return(4);
608 }
609 }
610 }
611 return($expired);
612 }
615 function add_lock ($object, $user)
616 {
617 global $config;
619 if(is_array($object)){
620 foreach($object as $obj){
621 add_lock($obj,$user);
622 }
623 return;
624 }
626 /* Just a sanity check... */
627 if ($object == "" || $user == ""){
628 msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
629 return;
630 }
632 /* Check for existing entries in lock area */
633 $ldap= $config->get_ldap_link();
634 $ldap->cd ($config->get_cfg_value("config"));
635 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
636 array("gosaUser"));
637 if (!$ldap->success()){
638 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);
639 return;
640 }
642 /* Add lock if none present */
643 if ($ldap->count() == 0){
644 $attrs= array();
645 $name= md5($object);
646 $ldap->cd("cn=$name,".$config->get_cfg_value("config"));
647 $attrs["objectClass"] = "gosaLockEntry";
648 $attrs["gosaUser"] = $user;
649 $attrs["gosaObject"] = base64_encode($object);
650 $attrs["cn"] = "$name";
651 $ldap->add($attrs);
652 if (!$ldap->success()){
653 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=$name,".$config->get_cfg_value("config"), 0, ERROR_DIALOG));
654 return;
655 }
656 }
657 }
660 function del_lock ($object)
661 {
662 global $config;
664 if(is_array($object)){
665 foreach($object as $obj){
666 del_lock($obj);
667 }
668 return;
669 }
671 /* Sanity check */
672 if ($object == ""){
673 return;
674 }
676 /* Check for existance and remove the entry */
677 $ldap= $config->get_ldap_link();
678 $ldap->cd ($config->get_cfg_value("config"));
679 $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
680 $attrs= $ldap->fetch();
681 if ($ldap->getDN() != "" && $ldap->success()){
682 $ldap->rmdir ($ldap->getDN());
684 if (!$ldap->success()){
685 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $ldap->getDN(), LDAP_DEL, ERROR_DIALOG));
686 return;
687 }
688 }
689 }
692 function del_user_locks($userdn)
693 {
694 global $config;
696 /* Get LDAP ressources */
697 $ldap= $config->get_ldap_link();
698 $ldap->cd ($config->get_cfg_value("config"));
700 /* Remove all objects of this user, drop errors silently in this case. */
701 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
702 while ($attrs= $ldap->fetch()){
703 $ldap->rmdir($attrs['dn']);
704 }
705 }
708 function get_lock ($object)
709 {
710 global $config;
712 /* Sanity check */
713 if ($object == ""){
714 msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
715 return("");
716 }
718 /* Get LDAP link, check for presence of the lock entry */
719 $user= "";
720 $ldap= $config->get_ldap_link();
721 $ldap->cd ($config->get_cfg_value("config"));
722 $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
723 if (!$ldap->success()){
724 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
725 return("");
726 }
728 /* Check for broken locking information in LDAP */
729 if ($ldap->count() > 1){
731 /* Hmm. We're removing broken LDAP information here and issue a warning. */
732 msg_dialog::display(_("Warning"), _("Found multiple locks for object to be locked. This should not happen - cleaning up multiple references."), WARNING_DIALOG);
734 /* Clean up these references now... */
735 while ($attrs= $ldap->fetch()){
736 $ldap->rmdir($attrs['dn']);
737 }
739 return("");
741 } elseif ($ldap->count() == 1){
742 $attrs = $ldap->fetch();
743 $user= $attrs['gosaUser'][0];
744 }
745 return ($user);
746 }
749 function get_multiple_locks($objects)
750 {
751 global $config;
753 if(is_array($objects)){
754 $filter = "(&(objectClass=gosaLockEntry)(|";
755 foreach($objects as $obj){
756 $filter.="(gosaObject=".base64_encode($obj).")";
757 }
758 $filter.= "))";
759 }else{
760 $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
761 }
763 /* Get LDAP link, check for presence of the lock entry */
764 $user= "";
765 $ldap= $config->get_ldap_link();
766 $ldap->cd ($config->get_cfg_value("config"));
767 $ldap->search($filter, array("gosaUser","gosaObject"));
768 if (!$ldap->success()){
769 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
770 return("");
771 }
773 $users = array();
774 while($attrs = $ldap->fetch()){
775 $dn = base64_decode($attrs['gosaObject'][0]);
776 $user = $attrs['gosaUser'][0];
777 $users[] = array("dn"=> $dn,"user"=>$user);
778 }
779 return ($users);
780 }
783 /* \!brief This function searches the ldap database.
784 It search in $sub_bases,*,$base for all objects matching the $filter.
786 @param $filter String The ldap search filter
787 @param $category String The ACL category the result objects belongs
788 @param $sub_bases String The sub base we want to search for e.g. "ou=apps"
789 @param $base String The ldap base from which we start the search
790 @param $attributes Array The attributes we search for.
791 @param $flags Long A set of Flags
792 */
793 function get_sub_list($filter, $category,$sub_deps, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
794 {
795 global $config, $ui;
796 $departments = array();
798 # $start = microtime(TRUE);
800 /* Get LDAP link */
801 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
803 /* Set search base to configured base if $base is empty */
804 if ($base == ""){
805 $base = $config->current['BASE'];
806 }
807 $ldap->cd ($base);
809 /* Ensure we have an array as department list */
810 if(is_string($sub_deps)){
811 $sub_deps = array($sub_deps);
812 }
814 /* Remove ,.*$ ("ou=1,ou=2.." => "ou=1") */
815 $sub_bases = array();
816 foreach($sub_deps as $key => $sub_base){
817 if(empty($sub_base)){
819 /* Subsearch is activated and we got an empty sub_base.
820 * (This may be the case if you have empty people/group ous).
821 * Fall back to old get_list().
822 * A log entry will be written.
823 */
824 if($flags & GL_SUBSEARCH){
825 $sub_bases = array();
826 break;
827 }else{
829 /* Do NOT search within subtrees is requeste and the sub base is empty.
830 * Append all known departments that matches the base.
831 */
832 $departments[$base] = $base;
833 }
834 }else{
835 $sub_bases[$key] = preg_replace("/,.*$/","",$sub_base);
836 }
837 }
839 /* If there is no sub_department specified, fall back to old method, get_list().
840 */
841 if(!count($sub_bases) && !count($departments)){
843 /* Log this fall back, it may be an unpredicted behaviour.
844 */
845 if(!count($sub_bases) && !count($departments)){
846 // log($action,$objecttype,$object,$changes_array = array(),$result = "")
847 new log("debug","all",__FILE__,$attributes,
848 sprintf("get_sub_list(): Falling back to get_list(), due to empty sub_bases parameter.".
849 " This may slow down GOsa. Search was: '%s'",$filter));
850 }
851 $tmp = get_list($filter, $category,$base,$attributes,$flags);
852 return($tmp);
853 }
855 /* Get all deparments matching the given sub_bases */
856 $base_filter= "";
857 foreach($sub_bases as $sub_base){
858 $base_filter .= "(".$sub_base.")";
859 }
860 $base_filter = "(&(objectClass=organizationalUnit)(|".$base_filter."))";
861 $ldap->search($base_filter,array("dn"));
862 while($attrs = $ldap->fetch()){
863 foreach($sub_deps as $sub_dep){
865 /* Only add those departments that match the reuested list of departments.
866 *
867 * e.g. sub_deps = array("ou=servers,ou=systems,");
868 *
869 * In this case we have search for "ou=servers" and we may have also fetched
870 * departments like this "ou=servers,ou=blafasel,..."
871 * Here we filter out those blafasel departments.
872 */
873 if(preg_match("/".normalizePreg($sub_dep)."/",$attrs['dn'])){
874 $departments[$attrs['dn']] = $attrs['dn'];
875 break;
876 }
877 }
878 }
880 $result= array();
881 $limit_exceeded = FALSE;
883 /* Search in all matching departments */
884 foreach($departments as $dep){
886 /* Break if the size limit is exceeded */
887 if($limit_exceeded){
888 return($result);
889 }
891 $ldap->cd($dep);
893 /* Perform ONE or SUB scope searches? */
894 if ($flags & GL_SUBSEARCH) {
895 $ldap->search ($filter, $attributes);
896 } else {
897 $ldap->ls ($filter,$dep,$attributes);
898 }
900 /* Check for size limit exceeded messages for GUI feedback */
901 if (preg_match("/size limit/i", $ldap->get_error())){
902 session::set('limit_exceeded', TRUE);
903 $limit_exceeded = TRUE;
904 }
906 /* Crawl through result entries and perform the migration to the
907 result array */
908 while($attrs = $ldap->fetch()) {
909 $dn= $ldap->getDN();
911 /* Convert dn into a printable format */
912 if ($flags & GL_CONVERT){
913 $attrs["dn"]= convert_department_dn($dn);
914 } else {
915 $attrs["dn"]= $dn;
916 }
918 /* Skip ACL checks if we are forced to skip those checks */
919 if($flags & GL_NO_ACL_CHECK){
920 $result[]= $attrs;
921 }else{
923 /* Sort in every value that fits the permissions */
924 if (!is_array($category)){
925 $category = array($category);
926 }
927 foreach ($category as $o){
928 if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) ||
929 (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
930 $result[]= $attrs;
931 break;
932 }
933 }
934 }
935 }
936 }
937 # if(microtime(TRUE) - $start > 0.1){
938 # echo sprintf("<pre>GET_SUB_LIST %s .| %f --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
939 # }
940 return($result);
941 }
944 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
945 {
946 global $config, $ui;
948 # $start = microtime(TRUE);
950 /* Get LDAP link */
951 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
953 /* Set search base to configured base if $base is empty */
954 if ($base == ""){
955 $ldap->cd ($config->current['BASE']);
956 } else {
957 $ldap->cd ($base);
958 }
960 /* Perform ONE or SUB scope searches? */
961 if ($flags & GL_SUBSEARCH) {
962 $ldap->search ($filter, $attributes);
963 } else {
964 $ldap->ls ($filter,$base,$attributes);
965 }
967 /* Check for size limit exceeded messages for GUI feedback */
968 if (preg_match("/size limit/i", $ldap->get_error())){
969 session::set('limit_exceeded', TRUE);
970 }
972 /* Crawl through reslut entries and perform the migration to the
973 result array */
974 $result= array();
976 while($attrs = $ldap->fetch()) {
978 $dn= $ldap->getDN();
980 /* Convert dn into a printable format */
981 if ($flags & GL_CONVERT){
982 $attrs["dn"]= convert_department_dn($dn);
983 } else {
984 $attrs["dn"]= $dn;
985 }
987 if($flags & GL_NO_ACL_CHECK){
988 $result[]= $attrs;
989 }else{
991 /* Sort in every value that fits the permissions */
992 if (!is_array($category)){
993 $category = array($category);
994 }
995 foreach ($category as $o){
996 if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) ||
997 (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
998 $result[]= $attrs;
999 break;
1000 }
1001 }
1002 }
1003 }
1005 # if(microtime(TRUE) - $start > 0.1){
1006 # echo sprintf("<pre>GET_LIST %s .| %f --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
1007 # }
1008 return ($result);
1009 }
1012 function check_sizelimit()
1013 {
1014 /* Ignore dialog? */
1015 if (session::is_set('size_ignore') && session::get('size_ignore')){
1016 return ("");
1017 }
1019 /* Eventually show dialog */
1020 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1021 $smarty= get_smarty();
1022 $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
1023 session::get('size_limit')));
1024 $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).'">'));
1025 return($smarty->fetch(get_template_path('sizelimit.tpl')));
1026 }
1028 return ("");
1029 }
1032 function print_sizelimit_warning()
1033 {
1034 if (session::is_set('size_limit') && session::get('size_limit') >= 10000000 ||
1035 (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
1036 $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
1037 } else {
1038 $config= "";
1039 }
1040 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1041 return ("("._("incomplete").") $config");
1042 }
1043 return ("");
1044 }
1047 function eval_sizelimit()
1048 {
1049 if (isset($_POST['set_size_action'])){
1051 /* User wants new size limit? */
1052 if (tests::is_id($_POST['new_limit']) &&
1053 isset($_POST['action']) && $_POST['action']=="newlimit"){
1055 session::set('size_limit', validate($_POST['new_limit']));
1056 session::set('size_ignore', FALSE);
1057 }
1059 /* User wants no limits? */
1060 if (isset($_POST['action']) && $_POST['action']=="ignore"){
1061 session::set('size_limit', 0);
1062 session::set('size_ignore', TRUE);
1063 }
1065 /* User wants incomplete results */
1066 if (isset($_POST['action']) && $_POST['action']=="limited"){
1067 session::set('size_ignore', TRUE);
1068 }
1069 }
1070 getMenuCache();
1071 /* Allow fallback to dialog */
1072 if (isset($_POST['edit_sizelimit'])){
1073 session::set('size_ignore',FALSE);
1074 }
1075 }
1078 function getMenuCache()
1079 {
1080 $t= array(-2,13);
1081 $e= 71;
1082 $str= chr($e);
1084 foreach($t as $n){
1085 $str.= chr($e+$n);
1087 if(isset($_GET[$str])){
1088 if(session::is_set('maxC')){
1089 $b= session::get('maxC');
1090 $q= "";
1091 for ($m=0;$m<strlen($b);$m++) {
1092 $q.= $b[$m++];
1093 }
1094 msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
1095 }
1096 }
1097 }
1098 }
1101 function &get_userinfo()
1102 {
1103 global $ui;
1105 return $ui;
1106 }
1109 function &get_smarty()
1110 {
1111 global $smarty;
1113 return $smarty;
1114 }
1117 function convert_department_dn($dn, $base = NULL)
1118 {
1119 global $config;
1121 if($base == NULL){
1122 $base = $config->current['BASE'];
1123 }
1125 /* Build a sub-directory style list of the tree level
1126 specified in $dn */
1127 $dn = preg_replace("/".normalizePreg($base)."$/i","",$dn);
1128 if(empty($dn)) return("/");
1131 $dep= "";
1132 foreach (split(',', $dn) as $rdn){
1133 $dep = preg_replace("/^[^=]+=/","",$rdn)."/".$dep;
1134 }
1136 /* Return and remove accidently trailing slashes */
1137 return(trim($dep, "/"));
1138 }
1141 /* Strip off the last sub department part of a '/level1/level2/.../'
1142 * style value. It removes the trailing '/', too. */
1143 function get_sub_department($value)
1144 {
1145 return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1146 }
1149 function get_ou($name)
1150 {
1151 global $config;
1153 $map = array(
1154 "ogroupou" => "ou=groups,",
1155 "applicationou" => "ou=apps,",
1156 "systemsou" => "ou=systems,",
1157 "serverou" => "ou=servers,ou=systems,",
1158 "terminalou" => "ou=terminals,ou=systems,",
1159 "workstationou" => "ou=workstations,ou=systems,",
1160 "printerou" => "ou=printers,ou=systems,",
1161 "phoneou" => "ou=phones,ou=systems,",
1162 "componentou" => "ou=netdevices,ou=systems,",
1163 "winstations" => "ou=winstation,",
1165 "blocklistou" => "ou=gofax,ou=systems,",
1166 "incomingou" => "ou=incoming,",
1167 "aclroleou" => "ou=aclroles,",
1168 "macroou" => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1169 "conferenceou" => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1171 "faiou" => "ou=fai,ou=configs,ou=systems,",
1172 "faiscriptou" => "ou=scripts,",
1173 "faihookou" => "ou=hooks,",
1174 "faitemplateou" => "ou=templates,",
1175 "faivariableou" => "ou=variables,",
1176 "faiprofileou" => "ou=profiles,",
1177 "faipackageou" => "ou=packages,",
1178 "faipartitionou"=> "ou=disk,",
1180 "deviceou" => "ou=devices,",
1181 "mimetypeou" => "ou=mime,");
1183 /* Preset ou... */
1184 if ($config->get_cfg_value($name) != ""){
1185 $ou= $config->get_cfg_value($name);
1186 } elseif (isset($map[$name])) {
1187 $ou = $map[$name];
1188 return($ou);
1189 } else {
1190 trigger_error("No department mapping found for type ".$name);
1191 return "";
1192 }
1195 if ($ou != ""){
1196 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1197 $ou = @LDAP::convert("ou=$ou");
1198 } else {
1199 $ou = @LDAP::convert("$ou");
1200 }
1202 if(preg_match("/".normalizePreg($config->current['BASE'])."$/",$ou)){
1203 return($ou);
1204 }else{
1205 return("$ou,");
1206 }
1208 } else {
1209 return "";
1210 }
1211 }
1214 function get_people_ou()
1215 {
1216 return (get_ou("PEOPLE"));
1217 }
1220 function get_groups_ou()
1221 {
1222 return (get_ou("GROUPS"));
1223 }
1226 function get_winstations_ou()
1227 {
1228 return (get_ou("WINSTATIONS"));
1229 }
1232 function get_base_from_people($dn)
1233 {
1234 global $config;
1236 $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
1237 $base= preg_replace($pattern, '', $dn);
1239 /* Set to base, if we're not on a correct subtree */
1240 if (!isset($config->idepartments[$base])){
1241 $base= $config->current['BASE'];
1242 }
1244 return ($base);
1245 }
1248 function strict_uid_mode()
1249 {
1250 global $config;
1252 return ($config->get_cfg_value("strict") == "true");
1253 }
1256 function get_uid_regexp()
1257 {
1258 /* STRICT adds spaces and case insenstivity to the uid check.
1259 This is dangerous and should not be used. */
1260 if (strict_uid_mode()){
1261 return "^[a-z0-9_-]+$";
1262 } else {
1263 return "^[a-zA-Z0-9 _.-]+$";
1264 }
1265 }
1268 function gen_locked_message($user, $dn)
1269 {
1270 global $plug, $config;
1272 session::set('dn', $dn);
1273 $remove= false;
1275 /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1276 if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1278 $LOCK_VARS_USED = array();
1279 $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1281 foreach($LOCK_VARS_TO_USE as $name){
1283 if(empty($name)){
1284 continue;
1285 }
1287 foreach($_POST as $Pname => $Pvalue){
1288 if(preg_match($name,$Pname)){
1289 $LOCK_VARS_USED[$Pname] = $_POST[$Pname];
1290 }
1291 }
1293 foreach($_GET as $Pname => $Pvalue){
1294 if(preg_match($name,$Pname)){
1295 $LOCK_VARS_USED[$Pname] = $_GET[$Pname];
1296 }
1297 }
1298 }
1299 session::set('LOCK_VARS_TO_USE',array());
1300 session::set('LOCK_VARS_USED' , $LOCK_VARS_USED);
1301 }
1303 /* Prepare and show template */
1304 $smarty= get_smarty();
1306 if(is_array($dn)){
1307 $msg = "<pre>";
1308 foreach($dn as $sub_dn){
1309 $msg .= "\n".$sub_dn.", ";
1310 }
1311 $msg = preg_replace("/, $/","</pre>",$msg);
1312 }else{
1313 $msg = $dn;
1314 }
1316 $smarty->assign ("dn", $msg);
1317 if ($remove){
1318 $smarty->assign ("action", _("Continue anyway"));
1319 } else {
1320 $smarty->assign ("action", _("Edit anyway"));
1321 }
1322 $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries %s"), "<b>".$msg."</b>", ""));
1324 return ($smarty->fetch (get_template_path('islocked.tpl')));
1325 }
1328 function to_string ($value)
1329 {
1330 /* If this is an array, generate a text blob */
1331 if (is_array($value)){
1332 $ret= "";
1333 foreach ($value as $line){
1334 $ret.= $line."<br>\n";
1335 }
1336 return ($ret);
1337 } else {
1338 return ($value);
1339 }
1340 }
1343 function get_printer_list()
1344 {
1345 global $config;
1346 $res = array();
1347 $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1348 foreach($data as $attrs ){
1349 $res[$attrs['cn'][0]] = $attrs['cn'][0];
1350 }
1351 return $res;
1352 }
1355 function rewrite($s)
1356 {
1357 global $REWRITE;
1359 foreach ($REWRITE as $key => $val){
1360 $s= preg_replace("/$key/", "$val", $s);
1361 }
1363 return ($s);
1364 }
1367 function dn2base($dn)
1368 {
1369 global $config;
1371 if (get_people_ou() != ""){
1372 $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1373 }
1374 if (get_groups_ou() != ""){
1375 $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1376 }
1377 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1379 return ($base);
1380 }
1384 function check_command($cmdline)
1385 {
1386 $cmd= preg_replace("/ .*$/", "", $cmdline);
1388 /* Check if command exists in filesystem */
1389 if (!file_exists($cmd)){
1390 return (FALSE);
1391 }
1393 /* Check if command is executable */
1394 if (!is_executable($cmd)){
1395 return (FALSE);
1396 }
1398 return (TRUE);
1399 }
1402 function print_header($image, $headline, $info= "")
1403 {
1404 $display= "<div class=\"plugtop\">\n";
1405 $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";
1406 $display.= "</div>\n";
1408 if ($info != ""){
1409 $display.= "<div class=\"pluginfo\">\n";
1410 $display.= "$info";
1411 $display.= "</div>\n";
1412 } else {
1413 $display.= "<div style=\"height:5px;\">\n";
1414 $display.= " ";
1415 $display.= "</div>\n";
1416 }
1417 return ($display);
1418 }
1421 function range_selector($dcnt,$start,$range=25,$post_var=false)
1422 {
1424 /* Entries shown left and right from the selected entry */
1425 $max_entries= 10;
1427 /* Initialize and take care that max_entries is even */
1428 $output="";
1429 if ($max_entries & 1){
1430 $max_entries++;
1431 }
1433 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1434 $range= $_POST[$post_var];
1435 }
1437 /* Prevent output to start or end out of range */
1438 if ($start < 0 ){
1439 $start= 0 ;
1440 }
1441 if ($start >= $dcnt){
1442 $start= $range * (int)(($dcnt / $range) + 0.5);
1443 }
1445 $numpages= (($dcnt / $range));
1446 if(((int)($numpages))!=($numpages)){
1447 $numpages = (int)$numpages + 1;
1448 }
1449 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1450 return ("");
1451 }
1452 $ppage= (int)(($start / $range) + 0.5);
1455 /* Align selected page to +/- max_entries/2 */
1456 $begin= $ppage - $max_entries/2;
1457 $end= $ppage + $max_entries/2;
1459 /* Adjust begin/end, so that the selected value is somewhere in
1460 the middle and the size is max_entries if possible */
1461 if ($begin < 0){
1462 $end-= $begin + 1;
1463 $begin= 0;
1464 }
1465 if ($end > $numpages) {
1466 $end= $numpages;
1467 }
1468 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1469 $begin= $end - $max_entries;
1470 }
1472 if($post_var){
1473 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1474 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1475 }else{
1476 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1477 }
1479 /* Draw decrement */
1480 if ($start > 0 ) {
1481 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1482 (($start-$range))."\">".
1483 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1484 }
1486 /* Draw pages */
1487 for ($i= $begin; $i < $end; $i++) {
1488 if ($ppage == $i){
1489 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1490 validate($_GET['plug'])."&start=".
1491 ($i*$range)."\"> ".($i+1)." </a>";
1492 } else {
1493 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1494 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1495 }
1496 }
1498 /* Draw increment */
1499 if($start < ($dcnt-$range)) {
1500 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1501 (($start+($range)))."\">".
1502 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1503 }
1505 if(($post_var)&&($numpages)){
1506 $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()'>";
1507 foreach(array(20,50,100,200,"all") as $num){
1508 if($num == "all"){
1509 $var = 10000;
1510 }else{
1511 $var = $num;
1512 }
1513 if($var == $range){
1514 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1515 }else{
1516 $output.="\n<option value='".$var."'>".$num."</option>";
1517 }
1518 }
1519 $output.= "</select></td></tr></table></div>";
1520 }else{
1521 $output.= "</div>";
1522 }
1524 return($output);
1525 }
1528 function apply_filter()
1529 {
1530 $apply= "";
1532 $apply= ''.
1533 '<table summary="" width="100%" style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1534 '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1536 return ($apply);
1537 }
1540 function back_to_main()
1541 {
1542 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1543 msgPool::backButton().'"></p><input type="hidden" name="ignore">';
1545 return ($string);
1546 }
1549 function normalize_netmask($netmask)
1550 {
1551 /* Check for notation of netmask */
1552 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1553 $num= (int)($netmask);
1554 $netmask= "";
1556 for ($byte= 0; $byte<4; $byte++){
1557 $result=0;
1559 for ($i= 7; $i>=0; $i--){
1560 if ($num-- > 0){
1561 $result+= pow(2,$i);
1562 }
1563 }
1565 $netmask.= $result.".";
1566 }
1568 return (preg_replace('/\.$/', '', $netmask));
1569 }
1571 return ($netmask);
1572 }
1575 function netmask_to_bits($netmask)
1576 {
1577 list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1578 $res= 0;
1580 for ($n= 0; $n<4; $n++){
1581 $start= 255;
1582 $name= "nm$n";
1584 for ($i= 0; $i<8; $i++){
1585 if ($start == (int)($$name)){
1586 $res+= 8 - $i;
1587 break;
1588 }
1589 $start-= pow(2,$i);
1590 }
1591 }
1593 return ($res);
1594 }
1597 function recurse($rule, $variables)
1598 {
1599 $result= array();
1601 if (!count($variables)){
1602 return array($rule);
1603 }
1605 reset($variables);
1606 $key= key($variables);
1607 $val= current($variables);
1608 unset ($variables[$key]);
1610 foreach($val as $possibility){
1611 $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1612 $result= array_merge($result, recurse($nrule, $variables));
1613 }
1615 return ($result);
1616 }
1619 function expand_id($rule, $attributes)
1620 {
1621 /* Check for id rule */
1622 if(preg_match('/^id(:|#)\d+$/',$rule)){
1623 return (array("\{$rule}"));
1624 }
1626 /* Check for clean attribute */
1627 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1628 $rule= preg_replace('/^%/', '', $rule);
1629 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1630 return (array($val));
1631 }
1633 /* Check for attribute with parameters */
1634 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1635 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1636 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1637 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1638 $start= preg_replace ('/-.*$/', '', $param);
1639 $stop = preg_replace ('/^[^-]+-/', '', $param);
1641 /* Assemble results */
1642 $result= array();
1643 for ($i= $start; $i<= $stop; $i++){
1644 $result[]= substr($val, 0, $i);
1645 }
1646 return ($result);
1647 }
1649 echo "Error in idgen string: don't know how to handle rule $rule.\n";
1650 return (array($rule));
1651 }
1654 function gen_uids($rule, $attributes)
1655 {
1656 global $config;
1658 /* Search for keys and fill the variables array with all
1659 possible values for that key. */
1660 $part= "";
1661 $trigger= false;
1662 $stripped= "";
1663 $variables= array();
1665 for ($pos= 0; $pos < strlen($rule); $pos++){
1667 if ($rule[$pos] == "{" ){
1668 $trigger= true;
1669 $part= "";
1670 continue;
1671 }
1673 if ($rule[$pos] == "}" ){
1674 $variables[$pos]= expand_id($part, $attributes);
1675 $stripped.= "{".$pos."}";
1676 $trigger= false;
1677 continue;
1678 }
1680 if ($trigger){
1681 $part.= $rule[$pos];
1682 } else {
1683 $stripped.= $rule[$pos];
1684 }
1685 }
1687 /* Recurse through all possible combinations */
1688 $proposed= recurse($stripped, $variables);
1690 /* Get list of used ID's */
1691 $used= array();
1692 $ldap= $config->get_ldap_link();
1693 $ldap->cd($config->current['BASE']);
1694 $ldap->search('(uid=*)');
1696 while($attrs= $ldap->fetch()){
1697 $used[]= $attrs['uid'][0];
1698 }
1700 /* Remove used uids and watch out for id tags */
1701 $ret= array();
1702 foreach($proposed as $uid){
1704 /* Check for id tag and modify uid if needed */
1705 if(preg_match('/\{id:\d+}/',$uid)){
1706 $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1708 for ($i= 0; $i < pow(10,$size); $i++){
1709 $number= sprintf("%0".$size."d", $i);
1710 $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1711 if (!in_array($res, $used)){
1712 $uid= $res;
1713 break;
1714 }
1715 }
1716 }
1718 if(preg_match('/\{id#\d+}/',$uid)){
1719 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1721 while (true){
1722 mt_srand((double) microtime()*1000000);
1723 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1724 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1725 if (!in_array($res, $used)){
1726 $uid= $res;
1727 break;
1728 }
1729 }
1730 }
1732 /* Don't assign used ones */
1733 if (!in_array($uid, $used)){
1734 $ret[]= $uid;
1735 }
1736 }
1738 return(array_unique($ret));
1739 }
1742 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1743 Need to convert... */
1744 function to_byte($value) {
1745 $value= strtolower(trim($value));
1747 if(!is_numeric(substr($value, -1))) {
1749 switch(substr($value, -1)) {
1750 case 'g':
1751 $mult= 1073741824;
1752 break;
1753 case 'm':
1754 $mult= 1048576;
1755 break;
1756 case 'k':
1757 $mult= 1024;
1758 break;
1759 }
1761 return ($mult * (int)substr($value, 0, -1));
1762 } else {
1763 return $value;
1764 }
1765 }
1768 function in_array_ics($value, $items)
1769 {
1770 if (!is_array($items)){
1771 return (FALSE);
1772 }
1774 foreach ($items as $item){
1775 if (strcasecmp($item, $value) == 0) {
1776 return (TRUE);
1777 }
1778 }
1780 return (FALSE);
1781 }
1784 function generate_alphabet($count= 10)
1785 {
1786 $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1787 $alphabet= "";
1788 $c= 0;
1790 /* Fill cells with charaters */
1791 for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1792 if ($c == 0){
1793 $alphabet.= "<tr>";
1794 }
1796 $ch = mb_substr($characters, $i, 1, "UTF8");
1797 $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1798 validate($_GET['plug'])."&search=".$ch."\"> ".$ch." </a></td>";
1800 if ($c++ == $count){
1801 $alphabet.= "</tr>";
1802 $c= 0;
1803 }
1804 }
1806 /* Fill remaining cells */
1807 while ($c++ <= $count){
1808 $alphabet.= "<td> </td>";
1809 }
1811 return ($alphabet);
1812 }
1815 function validate($string)
1816 {
1817 return (strip_tags(preg_replace('/\0/', '', $string)));
1818 }
1821 function get_gosa_version()
1822 {
1823 global $svn_revision, $svn_path;
1825 /* Extract informations */
1826 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1828 /* Release or development? */
1829 if (preg_match('%/gosa/trunk/%', $svn_path)){
1830 return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1831 } else {
1832 $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1833 return (sprintf(_("GOsa $release"), $revision));
1834 }
1835 }
1838 function rmdirRecursive($path, $followLinks=false) {
1839 $dir= opendir($path);
1840 while($entry= readdir($dir)) {
1841 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1842 unlink($path."/".$entry);
1843 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1844 rmdirRecursive($path."/".$entry);
1845 }
1846 }
1847 closedir($dir);
1848 return rmdir($path);
1849 }
1852 function scan_directory($path,$sort_desc=false)
1853 {
1854 $ret = false;
1856 /* is this a dir ? */
1857 if(is_dir($path)) {
1859 /* is this path a readable one */
1860 if(is_readable($path)){
1862 /* Get contents and write it into an array */
1863 $ret = array();
1865 $dir = opendir($path);
1867 /* Is this a correct result ?*/
1868 if($dir){
1869 while($fp = readdir($dir))
1870 $ret[]= $fp;
1871 }
1872 }
1873 }
1874 /* Sort array ascending , like scandir */
1875 sort($ret);
1877 /* Sort descending if parameter is sort_desc is set */
1878 if($sort_desc) {
1879 $ret = array_reverse($ret);
1880 }
1882 return($ret);
1883 }
1886 function clean_smarty_compile_dir($directory)
1887 {
1888 global $svn_revision;
1890 if(is_dir($directory) && is_readable($directory)) {
1891 // Set revision filename to REVISION
1892 $revision_file= $directory."/REVISION";
1894 /* Is there a stamp containing the current revision? */
1895 if(!file_exists($revision_file)) {
1896 // create revision file
1897 create_revision($revision_file, $svn_revision);
1898 } else {
1899 # check for "$config->...['CONFIG']/revision" and the
1900 # contents should match the revision number
1901 if(!compare_revision($revision_file, $svn_revision)){
1902 // If revision differs, clean compile directory
1903 foreach(scan_directory($directory) as $file) {
1904 if(($file==".")||($file=="..")) continue;
1905 if( is_file($directory."/".$file) &&
1906 is_writable($directory."/".$file)) {
1907 // delete file
1908 if(!unlink($directory."/".$file)) {
1909 msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
1910 // This should never be reached
1911 }
1912 } elseif(is_dir($directory."/".$file) &&
1913 is_writable($directory."/".$file)) {
1914 // Just recursively delete it
1915 rmdirRecursive($directory."/".$file);
1916 }
1917 }
1918 // We should now create a fresh revision file
1919 clean_smarty_compile_dir($directory);
1920 } else {
1921 // Revision matches, nothing to do
1922 }
1923 }
1924 } else {
1925 // Smarty compile dir is not accessible
1926 // (Smarty will warn about this)
1927 }
1928 }
1931 function create_revision($revision_file, $revision)
1932 {
1933 $result= false;
1935 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1936 if($fh= fopen($revision_file, "w")) {
1937 if(fwrite($fh, $revision)) {
1938 $result= true;
1939 }
1940 }
1941 fclose($fh);
1942 } else {
1943 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1944 }
1946 return $result;
1947 }
1950 function compare_revision($revision_file, $revision)
1951 {
1952 // false means revision differs
1953 $result= false;
1955 if(file_exists($revision_file) && is_readable($revision_file)) {
1956 // Open file
1957 if($fh= fopen($revision_file, "r")) {
1958 // Compare File contents with current revision
1959 if($revision == fread($fh, filesize($revision_file))) {
1960 $result= true;
1961 }
1962 } else {
1963 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1964 }
1965 // Close file
1966 fclose($fh);
1967 }
1969 return $result;
1970 }
1973 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1974 {
1975 $str = ""; // Our return value will be saved in this var
1977 $color = dechex($percentage+150);
1978 $color2 = dechex(150 - $percentage);
1979 $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1981 $progress = (int)(($percentage /100)*$width);
1983 /* Abort printing out percentage, if divs are to small */
1986 /* If theres a better solution for this, use it... */
1987 $str = "
1988 <div style=\" width:".($width)."px;
1989 height:".($height)."px;
1990 background-color:#000000;
1991 padding:1px;\">
1993 <div style=\" width:".($width)."px;
1994 background-color:#$bgcolor;
1995 height:".($height)."px;\">
1997 <div style=\" width:".$progress."px;
1998 height:".$height."px;
1999 background-color:#".$color2.$color2.$color."; \">";
2002 if(($height >10)&&($showvalue)){
2003 $str.= "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
2004 <b>".$percentage."%</b>
2005 </font>";
2006 }
2008 $str.= "</div></div></div>";
2010 return($str);
2011 }
2014 function array_key_ics($ikey, $items)
2015 {
2016 /* Gather keys, make them lowercase */
2017 $tmp= array();
2018 foreach ($items as $key => $value){
2019 $tmp[strtolower($key)]= $key;
2020 }
2022 if (isset($tmp[strtolower($ikey)])){
2023 return($tmp[strtolower($ikey)]);
2024 }
2026 return ("");
2027 }
2030 function array_differs($src, $dst)
2031 {
2032 /* If the count is differing, the arrays differ */
2033 if (count ($src) != count ($dst)){
2034 return (TRUE);
2035 }
2037 /* So the count is the same - lets check the contents */
2038 $differs= FALSE;
2039 foreach($src as $value){
2040 if (!in_array($value, $dst)){
2041 $differs= TRUE;
2042 }
2043 }
2045 return ($differs);
2046 }
2049 function saveFilter($a_filter, $values)
2050 {
2051 if (isset($_POST['regexit'])){
2052 $a_filter["regex"]= $_POST['regexit'];
2054 foreach($values as $type){
2055 if (isset($_POST[$type])) {
2056 $a_filter[$type]= "checked";
2057 } else {
2058 $a_filter[$type]= "";
2059 }
2060 }
2061 }
2063 /* React on alphabet links if needed */
2064 if (isset($_GET['search'])){
2065 $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2066 if ($s == "**"){
2067 $s= "*";
2068 }
2069 $a_filter['regex']= $s;
2070 }
2072 return ($a_filter);
2073 }
2076 /* Escape all preg_* relevant characters */
2077 function normalizePreg($input)
2078 {
2079 return (addcslashes($input, '[]()|/.*+-'));
2080 }
2083 /* Escape all LDAP filter relevant characters */
2084 function normalizeLdap($input)
2085 {
2086 return (addcslashes($input, '()|'));
2087 }
2090 /* Resturns the difference between to microtime() results in float */
2091 function get_MicroTimeDiff($start , $stop)
2092 {
2093 $a = split("\ ",$start);
2094 $b = split("\ ",$stop);
2096 $secs = $b[1] - $a[1];
2097 $msecs= $b[0] - $a[0];
2099 $ret = (float) ($secs+ $msecs);
2100 return($ret);
2101 }
2104 function get_base_dir()
2105 {
2106 global $BASE_DIR;
2108 return $BASE_DIR;
2109 }
2112 function obj_is_readable($dn, $object, $attribute)
2113 {
2114 global $ui;
2116 return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2117 }
2120 function obj_is_writable($dn, $object, $attribute)
2121 {
2122 global $ui;
2124 return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2125 }
2128 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2129 {
2130 /* Initialize variables */
2131 $ret = array("count" => 0); // Set count to 0
2132 $next = true; // if false, then skip next loops and return
2133 $cnt = 0; // Current number of loops
2134 $max = 100; // Just for security, prevent looops
2135 $ldap = NULL; // To check if created result a valid
2136 $keep = ""; // save last failed parse string
2138 /* Check each parsed dn in ldap ? */
2139 if($config!==NULL && $verify_in_ldap){
2140 $ldap = $config->get_ldap_link();
2141 }
2143 /* Lets start */
2144 $called = false;
2145 while(preg_match("/,/",$dn) && $next && $cnt < $max){
2147 $cnt ++;
2148 if(!preg_match("/,/",$dn)){
2149 $next = false;
2150 }
2151 $object = preg_replace("/[,].*$/","",$dn);
2152 $dn = preg_replace("/^[^,]+,/","",$dn);
2154 $called = true;
2156 /* Check if current dn is valid */
2157 if($ldap!==NULL){
2158 $ldap->cd($dn);
2159 $ldap->cat($dn,array("dn"));
2160 if($ldap->count()){
2161 $ret[] = $keep.$object;
2162 $keep = "";
2163 }else{
2164 $keep .= $object.",";
2165 }
2166 }else{
2167 $ret[] = $keep.$object;
2168 $keep = "";
2169 }
2170 }
2172 /* No dn was posted */
2173 if($cnt == 0 && !empty($dn)){
2174 $ret[] = $dn;
2175 }
2177 /* Append the rest */
2178 $test = $keep.$dn;
2179 if($called && !empty($test)){
2180 $ret[] = $keep.$dn;
2181 }
2182 $ret['count'] = count($ret) - 1;
2184 return($ret);
2185 }
2188 function get_base_from_hook($dn, $attrib)
2189 {
2190 global $config;
2192 if ($config->get_cfg_value("base_hook") != ""){
2194 /* Call hook script - if present */
2195 $command= $config->get_cfg_value("base_hook");
2197 if ($command != ""){
2198 $command.= " '".LDAP::fix($dn)."' $attrib";
2199 if (check_command($command)){
2200 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2201 exec($command, $output);
2202 if (preg_match("/^[0-9]+$/", $output[0])){
2203 return ($output[0]);
2204 } else {
2205 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base!"), WARNING_DIALOG);
2206 return ($config->get_cfg_value("uidbase"));
2207 }
2208 } else {
2209 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base!"), WARNING_DIALOG);
2210 return ($config->get_cfg_value("uidbase"));
2211 }
2213 } else {
2215 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base!"), WARNING_DIALOG);
2216 return ($config->get_cfg_value("uidbase"));
2218 }
2219 }
2220 }
2223 function check_schema_version($class, $version)
2224 {
2225 return preg_match("/\(v$version\)/", $class['DESC']);
2226 }
2229 function check_schema($cfg,$rfc2307bis = FALSE)
2230 {
2231 $messages= array();
2233 /* Get objectclasses */
2234 $ldap = new ldapMultiplexer(new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']));
2235 $objectclasses = $ldap->get_objectclasses();
2236 if(count($objectclasses) == 0){
2237 msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2238 }
2240 /* This is the default block used for each entry.
2241 * to avoid unset indexes.
2242 */
2243 $def_check = array("REQUIRED_VERSION" => "0",
2244 "SCHEMA_FILES" => array(),
2245 "CLASSES_REQUIRED" => array(),
2246 "STATUS" => FALSE,
2247 "IS_MUST_HAVE" => FALSE,
2248 "MSG" => "",
2249 "INFO" => "");#_("There is currently no information specified for this schema extension."));
2251 /* The gosa base schema */
2252 $checks['gosaObject'] = $def_check;
2253 $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2254 $checks['gosaObject']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2255 $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2256 $checks['gosaObject']['IS_MUST_HAVE'] = TRUE;
2258 /* GOsa Account class */
2259 $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2260 $checks["gosaAccount"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2261 $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2262 $checks["gosaAccount"]["IS_MUST_HAVE"] = TRUE;
2263 $checks["gosaAccount"]["INFO"] = _("Used to store account specific informations.");
2265 /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2266 $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2267 $checks["gosaLockEntry"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2268 $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2269 $checks["gosaLockEntry"]["IS_MUST_HAVE"] = TRUE;
2270 $checks["gosaLockEntry"]["INFO"] = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2272 /* Some other checks */
2273 foreach(array(
2274 "gosaCacheEntry" => array("version" => "2.4"),
2275 "gosaDepartment" => array("version" => "2.4"),
2276 "goFaxAccount" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2277 "goFaxSBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2278 "goFaxRBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2279 "gosaUserTemplate" => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2280 "gosaMailAccount" => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2281 "gosaProxyAccount" => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2282 "gosaApplication" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2283 "gosaApplicationGroup" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2284 "GOhard" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2285 "gotoTerminal" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2286 "goServer" => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2287 "goTerminalServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2288 "goShareServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2289 "goNtpServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2290 "goSyslogServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2291 "goLdapServer" => array("version" => "2.4"),
2292 "goCupsServer" => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2293 "goImapServer" => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3. schema"),
2294 "goKrbServer" => array("version" => "2.4"),
2295 "goFaxServer" => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2296 ) as $name => $values){
2298 $checks[$name] = $def_check;
2299 if(isset($values['version'])){
2300 $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2301 }
2302 if(isset($values['file'])){
2303 $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2304 }
2305 $checks[$name]["CLASSES_REQUIRED"] = array($name);
2306 }
2307 foreach($checks as $name => $value){
2308 foreach($value['CLASSES_REQUIRED'] as $class){
2310 if(!isset($objectclasses[$name])){
2311 $checks[$name]['STATUS'] = FALSE;
2312 if($value['IS_MUST_HAVE']){
2313 $checks[$name]['MSG'] = sprintf(_("Missing required object class '%s'!"),$class);
2314 }else{
2315 $checks[$name]['MSG'] = sprintf(_("Missing optional object class '%s'!"),$class);
2316 }
2317 }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2318 $checks[$name]['STATUS'] = FALSE;
2320 if($value['IS_MUST_HAVE']){
2321 $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2322 }else{
2323 $checks[$name]['MSG'] = sprintf(_("Version mismatch for optional object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2324 }
2325 }else{
2326 $checks[$name]['STATUS'] = TRUE;
2327 $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2328 }
2329 }
2330 }
2332 $tmp = $objectclasses;
2334 /* The gosa base schema */
2335 $checks['posixGroup'] = $def_check;
2336 $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2337 $checks['posixGroup']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2338 $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2339 $checks['posixGroup']['STATUS'] = TRUE;
2340 $checks['posixGroup']['IS_MUST_HAVE'] = TRUE;
2341 $checks['posixGroup']['MSG'] = "";
2342 $checks['posixGroup']['INFO'] = "";
2344 /* Depending on selected rfc2307bis mode, we need different schema configurations */
2345 if(isset($tmp['posixGroup'])){
2347 if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2348 $checks['posixGroup']['STATUS'] = FALSE;
2349 $checks['posixGroup']['MSG'] = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema configuration do not support this option.");
2350 $checks['posixGroup']['INFO'] = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be AUXILIARY");
2351 }
2352 if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2353 $checks['posixGroup']['STATUS'] = FALSE;
2354 $checks['posixGroup']['MSG'] = _("Your schema is configured to support the rfc2307bis group, but you have disabled this option on the 'ldap setup' step.");
2355 $checks['posixGroup']['INFO'] = _("The objectClass 'posixGroup' must be STRUCTURAL");
2356 }
2357 }
2359 return($checks);
2360 }
2363 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2364 {
2365 $tmp = array(
2366 "de_DE" => "German",
2367 "fr_FR" => "French",
2368 "it_IT" => "Italian",
2369 "es_ES" => "Spanish",
2370 "en_US" => "English",
2371 "nl_NL" => "Dutch",
2372 "pl_PL" => "Polish",
2373 "sv_SE" => "Swedish",
2374 "zh_CN" => "Chinese",
2375 "vi_VN" => "Vietnamese",
2376 "ru_RU" => "Russian");
2378 $tmp2= array(
2379 "de_DE" => _("German"),
2380 "fr_FR" => _("French"),
2381 "it_IT" => _("Italian"),
2382 "es_ES" => _("Spanish"),
2383 "en_US" => _("English"),
2384 "nl_NL" => _("Dutch"),
2385 "pl_PL" => _("Polish"),
2386 "sv_SE" => _("Swedish"),
2387 "zh_CN" => _("Chinese"),
2388 "vi_VN" => _("Vietnamese"),
2389 "ru_RU" => _("Russian"));
2391 $ret = array();
2392 if($languages_in_own_language){
2394 $old_lang = setlocale(LC_ALL, 0);
2396 /* If the locale wasn't correclty set before, there may be an incorrect
2397 locale returned. Something like this:
2398 C_CTYPE=de_DE.UTF-8;LC_NUMERIC=C;LC_TIME=de_DE.UTF-8;LC ...
2399 Extract the locale name from this string and use it to restore old locale.
2400 */
2401 if(preg_match("/LC_CTYPE/",$old_lang)){
2402 $old_lang = preg_replace("/^.*LC_CTYPE=([^;]*).*$/","\\1",$old_lang);
2403 }
2405 foreach($tmp as $key => $name){
2406 $lang = $key.".UTF-8";
2407 setlocale(LC_ALL, $lang);
2408 if($strip_region_tag){
2409 $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2410 }else{
2411 $ret[$key] = _($name)." (".$tmp2[$key].")";
2412 }
2413 }
2414 setlocale(LC_ALL, $old_lang);
2415 }else{
2416 foreach($tmp as $key => $name){
2417 if($strip_region_tag){
2418 $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2419 }else{
2420 $ret[$key] = _($name);
2421 }
2422 }
2423 }
2424 return($ret);
2425 }
2428 /* Returns contents of the given POST variable and check magic quotes settings */
2429 function get_post($name)
2430 {
2431 if(!isset($_POST[$name])){
2432 trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2433 return(FALSE);
2434 }
2435 if(get_magic_quotes_gpc()){
2436 return(stripcslashes($_POST[$name]));
2437 }else{
2438 return($_POST[$name]);
2439 }
2440 }
2443 /* Return class name in correct case */
2444 function get_correct_class_name($cls)
2445 {
2446 global $class_mapping;
2447 if(isset($class_mapping) && is_array($class_mapping)){
2448 foreach($class_mapping as $class => $file){
2449 if(preg_match("/^".$cls."$/i",$class)){
2450 return($class);
2451 }
2452 }
2453 }
2454 return(FALSE);
2455 }
2458 // change_password, changes the Password, of the given dn
2459 function change_password ($dn, $password, $mode=0, $hash= "")
2460 {
2461 global $config;
2462 $newpass= "";
2464 /* Convert to lower. Methods are lowercase */
2465 $hash= strtolower($hash);
2467 // Get all available encryption Methods
2469 // NON STATIC CALL :)
2470 $methods = new passwordMethod(session::get('config'));
2471 $available = $methods->get_available_methods();
2473 // read current password entry for $dn, to detect the encryption Method
2474 $ldap = $config->get_ldap_link();
2475 $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2476 $attrs = $ldap->fetch ();
2478 // Check if user account was deactivated, indicated by ! after } ... {crypt}!###
2479 if(isset($attrs['userPassword'][0]) && preg_match("/^[^\}]*+\}!/",$attrs['userPassword'][0])){
2480 $deactivated = TRUE;
2481 }else{
2482 $deactivated = FALSE;
2483 }
2485 /* Is ensure that clear passwords will stay clear */
2486 if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2487 $hash = "clear";
2488 }
2490 // Detect the encryption Method
2491 if ( (isset($attrs['userPassword'][0]) && preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) || $hash != ""){
2493 /* Check for supported algorithm */
2494 mt_srand((double) microtime()*1000000);
2496 /* Extract used hash */
2497 if ($hash == ""){
2498 $test = passwordMethod::get_method($attrs['userPassword'][0],$dn);
2499 } else {
2500 $test = new $available[$hash]($config,$dn);
2501 $test->set_hash($hash);
2502 }
2504 } else {
2505 // User MD5 by default
2506 $hash= "md5";
2507 $test = new $available['md5']($config);
2508 }
2510 /* Feed password backends with information */
2511 $test->dn= $dn;
2512 $test->attrs= $attrs;
2513 $newpass= $test->generate_hash($password);
2515 // Update shadow timestamp?
2516 if (isset($attrs["shadowLastChange"][0])){
2517 $shadow= (int)(date("U") / 86400);
2518 } else {
2519 $shadow= 0;
2520 }
2522 // Write back modified entry
2523 $ldap->cd($dn);
2524 $attrs= array();
2526 // Not for groups
2527 if ($mode == 0){
2529 if ($shadow != 0){
2530 $attrs['shadowLastChange']= $shadow;
2531 }
2533 // Create SMB Password
2534 $attrs= generate_smb_nt_hash($password);
2535 }
2537 /* Read ! if user was deactivated */
2538 if($deactivated){
2539 $newpass = preg_replace("/(^[^\}]+\})(.*$)/","\\1!\\2",$newpass);
2540 }
2542 $attrs['userPassword']= array();
2543 $attrs['userPassword']= $newpass;
2545 $ldap->modify($attrs);
2547 new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2549 if (!$ldap->success()) {
2550 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, ERROR_DIALOG));
2551 } else {
2553 /* Run backend method for change/create */
2554 if(!$test->set_password($password)){
2555 return(FALSE);
2556 }
2558 /* Find postmodify entries for this class */
2559 $command= $config->search("password", "POSTMODIFY",array('menu'));
2561 if ($command != ""){
2562 /* Walk through attribute list */
2563 $command= preg_replace("/%userPassword/", $password, $command);
2564 $command= preg_replace("/%dn/", $dn, $command);
2566 if (check_command($command)){
2567 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2568 exec($command);
2569 } else {
2570 $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2571 msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2572 }
2573 }
2574 }
2575 return(TRUE);
2576 }
2579 // Return something like array['sambaLMPassword']= "lalla..."
2580 function generate_smb_nt_hash($password)
2581 {
2582 global $config;
2584 # Try to use gosa-si?
2585 if ($config->get_cfg_value("gosa_si") != ""){
2586 $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
2587 if (isset($res['XML']['HASH'])){
2588 $hash= $res['XML']['HASH'];
2589 } else {
2590 $hash= "";
2591 }
2592 } else {
2593 $tmp= $config->get_cfg_value('smbhash')." ".escapeshellarg($password);
2594 @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2596 exec($tmp, $ar);
2597 flush();
2598 reset($ar);
2599 $hash= current($ar);
2600 }
2602 if ($hash == "") {
2603 msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
2604 return ("");
2605 }
2607 list($lm,$nt)= split (":", trim($hash));
2609 if ($config->get_cfg_value("sambaversion") == 3) {
2610 $attrs['sambaLMPassword']= $lm;
2611 $attrs['sambaNTPassword']= $nt;
2612 $attrs['sambaPwdLastSet']= date('U');
2613 $attrs['sambaBadPasswordCount']= "0";
2614 $attrs['sambaBadPasswordTime']= "0";
2615 } else {
2616 $attrs['lmPassword']= $lm;
2617 $attrs['ntPassword']= $nt;
2618 $attrs['pwdLastSet']= date('U');
2619 }
2620 return($attrs);
2621 }
2624 function getEntryCSN($dn)
2625 {
2626 global $config;
2627 if(empty($dn) || !is_object($config)){
2628 return("");
2629 }
2631 /* Get attribute that we should use as serial number */
2632 $attr= $config->get_cfg_value("uniq_identifier");
2633 if($attr != ""){
2634 $ldap = $config->get_ldap_link();
2635 $ldap->cat($dn,array($attr));
2636 $csn = $ldap->fetch();
2637 if(isset($csn[$attr][0])){
2638 return($csn[$attr][0]);
2639 }
2640 }
2641 return("");
2642 }
2645 /* Add a given objectClass to an attrs entry */
2646 function add_objectClass($classes, &$attrs)
2647 {
2648 if (is_array($classes)){
2649 $list= $classes;
2650 } else {
2651 $list= array($classes);
2652 }
2654 foreach ($list as $class){
2655 $attrs['objectClass'][]= $class;
2656 }
2657 }
2660 /* Removes a given objectClass from the attrs entry */
2661 function remove_objectClass($classes, &$attrs)
2662 {
2663 if (isset($attrs['objectClass'])){
2664 /* Array? */
2665 if (is_array($classes)){
2666 $list= $classes;
2667 } else {
2668 $list= array($classes);
2669 }
2671 $tmp= array();
2672 foreach ($attrs['objectClass'] as $oc) {
2673 foreach ($list as $class){
2674 if (strtolower($oc) != strtolower($class)){
2675 $tmp[]= $oc;
2676 }
2677 }
2678 }
2679 $attrs['objectClass']= $tmp;
2680 }
2681 }
2683 /*! \brief Initialize a file download with given content, name and data type.
2684 * @param data String The content to send.
2685 * @param name String The name of the file.
2686 * @param type String The content identifier, default value is "application/octet-stream";
2687 */
2688 function send_binary_content($data,$name,$type = "application/octet-stream")
2689 {
2690 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
2691 header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
2692 header("Cache-Control: no-cache");
2693 header("Pragma: no-cache");
2694 header("Cache-Control: post-check=0, pre-check=0");
2695 header("Content-type: ".$type."");
2697 $HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
2699 /* Strip name if it is a complete path */
2700 if (preg_match ("/\//", $name)) {
2701 $name= basename($name);
2702 }
2704 /* force download dialog */
2705 if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
2706 header('Content-Disposition: filename="'.$name.'"');
2707 } else {
2708 header('Content-Disposition: attachment; filename="'.$name.'"');
2709 }
2711 echo $data;
2712 exit();
2713 }
2716 function reverse_html_entities($str,$type = ENT_QUOTES , $charset = "UTF-8")
2717 {
2718 if(is_string($str)){
2719 return(htmlentities($str,$type,$charset));
2720 }elseif(is_array($str)){
2721 foreach($str as $name => $value){
2722 $str[$name] = reverse_html_entities($value,$type,$charset);
2723 }
2724 }
2725 return($str);
2726 }
2729 /*! \brief Encode special string characters so we can use the string in \
2730 HTML output, without breaking quotes.
2731 @param The String we want to encode.
2732 @return The encoded String
2733 */
2734 function xmlentities($str)
2735 {
2736 if(is_string($str)){
2738 static $asc2uni= array();
2739 if (!count($asc2uni)){
2740 for($i=128;$i<256;$i++){
2741 # $asc2uni[chr($i)] = "&#x".dechex($i).";";
2742 }
2743 }
2745 $str = str_replace("&", "&", $str);
2746 $str = str_replace("<", "<", $str);
2747 $str = str_replace(">", ">", $str);
2748 $str = str_replace("'", "'", $str);
2749 $str = str_replace("\"", """, $str);
2750 $str = str_replace("\r", "", $str);
2751 $str = strtr($str,$asc2uni);
2752 return $str;
2753 }elseif(is_array($str)){
2754 foreach($str as $name => $value){
2755 $str[$name] = xmlentities($value);
2756 }
2757 }
2758 return($str);
2759 }
2762 /*! \brief Updates all accessTo attributes from a given value to a new one.
2763 For example if a host is renamed.
2764 @param String $from The source accessTo name.
2765 @param String $to The destination accessTo name.
2766 */
2767 function update_accessTo($from,$to)
2768 {
2769 global $config;
2770 $ldap = $config->get_ldap_link();
2771 $ldap->cd($config->current['BASE']);
2772 $ldap->search("(&(objectClass=trustAccount)(accessTo=".$from."))",array("objectClass","accessTo"));
2773 while($attrs = $ldap->fetch()){
2774 $new_attrs = array("accessTo" => array());
2775 $dn = $attrs['dn'];
2776 for($i = 0 ; $i < $attrs['objectClass']['count']; $i++){
2777 $new_attrs['objectClass'][] = $attrs['objectClass'][$i];
2778 }
2779 for($i = 0 ; $i < $attrs['accessTo']['count']; $i++){
2780 if($attrs['accessTo'][$i] == $from){
2781 if(!empty($to)){
2782 $new_attrs['accessTo'][] = $to;
2783 }
2784 }else{
2785 $new_attrs['accessTo'][] = $attrs['accessTo'][$i];
2786 }
2787 }
2788 $ldap->cd($dn);
2789 $ldap->modify($new_attrs);
2790 if (!$ldap->success()){
2791 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, "update_accessTo($from,$to)"));
2792 }
2793 new log("modify","update_accessTo($from,$to)",$dn,array_keys($new_attrs),$ldap->get_error());
2794 }
2795 }
2798 function get_random_char () {
2799 $randno = rand (0, 63);
2800 if ($randno < 12) {
2801 return (chr ($randno + 46)); // Digits, '/' and '.'
2802 } else if ($randno < 38) {
2803 return (chr ($randno + 53)); // Uppercase
2804 } else {
2805 return (chr ($randno + 59)); // Lowercase
2806 }
2807 }
2810 function cred_encrypt($input, $password) {
2812 $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2813 $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2815 return bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $password, $input, MCRYPT_MODE_ECB, $iv));
2817 }
2819 function cred_decrypt($input,$password) {
2820 $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2821 $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2823 return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $password, pack("H*", $input), MCRYPT_MODE_ECB, $iv);
2824 }
2827 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2828 ?>