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 msg_dialog::display(_("Fatal error"),
352 sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error()),
353 FATAL_ERROR_DIALOG);
354 exit();
355 }
357 /* Preset connection base to $base and return to caller */
358 $ldap->cd ($base);
359 return $ldap;
360 }
363 function process_htaccess ($username, $kerberos= FALSE)
364 {
365 global $config;
367 /* Search for $username and optional @REALM in all configured LDAP trees */
368 foreach($config->data["LOCATIONS"] as $name => $data){
370 $config->set_current($name);
371 $mode= "kerberos";
372 if ($config->get_cfg_value("krbsasl") == "true"){
373 $mode= "sasl";
374 }
376 /* Look for entry or realm */
377 $ldap= $config->get_ldap_link();
378 if (!$ldap->success()){
379 msg_dialog::display(_("LDAP error"),
380 msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'),
381 FATAL_ERROR_DIALOG);
382 exit();
383 }
384 $ldap->search("(&(objectClass=gosaAccount)(|(uid=$username)(userPassword={$mode}$username)))", array("uid"));
386 /* Found a uniq match? Return it... */
387 if ($ldap->count() == 1) {
388 $attrs= $ldap->fetch();
389 return array("username" => $attrs["uid"][0], "server" => $name);
390 }
391 }
393 /* Nothing found? Return emtpy array */
394 return array("username" => "", "server" => "");
395 }
398 function ldap_login_user_htaccess ($username)
399 {
400 global $config;
402 /* Look for entry or realm */
403 $ldap= $config->get_ldap_link();
404 if (!$ldap->success()){
405 msg_dialog::display(_("LDAP error"),
406 msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'),
407 FATAL_ERROR_DIALOG);
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"),
443 msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'),
444 FATAL_ERROR_DIALOG);
445 exit();
446 }
447 $ldap->cd($config->current['BASE']);
448 $allowed_attributes = array("uid","mail");
449 $verify_attr = array();
450 if($config->get_cfg_value("login_attribute") != ""){
451 $tmp = split(",", $config->get_cfg_value("login_attribute"));
452 foreach($tmp as $attr){
453 if(in_array($attr,$allowed_attributes)){
454 $verify_attr[] = $attr;
455 }
456 }
457 }
458 if(count($verify_attr) == 0){
459 $verify_attr = array("uid");
460 }
461 $tmp= $verify_attr;
462 $tmp[] = "uid";
463 $filter = "";
464 foreach($verify_attr as $attr) {
465 $filter.= "(".$attr."=".$username.")";
466 }
467 $filter = "(&(|".$filter.")(objectClass=gosaAccount))";
468 $ldap->search($filter,$tmp);
470 /* get results, only a count of 1 is valid */
471 switch ($ldap->count()){
473 /* user not found */
474 case 0: return (NULL);
476 /* valid uniq user */
477 case 1:
478 break;
480 /* found more than one matching id */
481 default:
482 msg_dialog::display(_("Internal error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), FATAL_ERROR_DIALOG);
483 return (NULL);
484 }
486 /* LDAP schema is not case sensitive. Perform additional check. */
487 $attrs= $ldap->fetch();
488 $success = FALSE;
489 foreach($verify_attr as $attr){
490 if(isset($attrs[$attr][0]) && $attrs[$attr][0] == $username){
491 $success = TRUE;
492 }
493 }
494 if(!$success){
495 return(FALSE);
496 }
498 /* got user dn, fill acl's */
499 $ui= new userinfo($config, $ldap->getDN());
500 $ui->username= $attrs['uid'][0];
502 /* password check, bind as user with supplied password */
503 $ldap->disconnect();
504 $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
505 isset($config->current['RECURSIVE']) &&
506 $config->current['RECURSIVE'] == "true",
507 isset($config->current['TLS'])
508 && $config->current['TLS'] == "true");
509 if (!$ldap->success()){
510 return (NULL);
511 }
513 /* Username is set, load subtreeACL's now */
514 $ui->loadACL();
516 return ($ui);
517 }
520 function ldap_expired_account($config, $userdn, $username)
521 {
522 $ldap= $config->get_ldap_link();
523 $ldap->cat($userdn);
524 $attrs= $ldap->fetch();
526 /* default value no errors */
527 $expired = 0;
529 $sExpire = 0;
530 $sLastChange = 0;
531 $sMax = 0;
532 $sMin = 0;
533 $sInactive = 0;
534 $sWarning = 0;
536 $current= date("U");
538 $current= floor($current /60 /60 /24);
540 /* special case of the admin, should never been locked */
541 /* FIXME should allow any name as user admin */
542 if($username != "admin")
543 {
545 if(isset($attrs['shadowExpire'][0])){
546 $sExpire= $attrs['shadowExpire'][0];
547 } else {
548 $sExpire = 0;
549 }
551 if(isset($attrs['shadowLastChange'][0])){
552 $sLastChange= $attrs['shadowLastChange'][0];
553 } else {
554 $sLastChange = 0;
555 }
557 if(isset($attrs['shadowMax'][0])){
558 $sMax= $attrs['shadowMax'][0];
559 } else {
560 $smax = 0;
561 }
563 if(isset($attrs['shadowMin'][0])){
564 $sMin= $attrs['shadowMin'][0];
565 } else {
566 $sMin = 0;
567 }
569 if(isset($attrs['shadowInactive'][0])){
570 $sInactive= $attrs['shadowInactive'][0];
571 } else {
572 $sInactive = 0;
573 }
575 if(isset($attrs['shadowWarning'][0])){
576 $sWarning= $attrs['shadowWarning'][0];
577 } else {
578 $sWarning = 0;
579 }
581 /* is the account locked */
582 /* shadowExpire + shadowInactive (option) */
583 if($sExpire >0){
584 if($current >= ($sExpire+$sInactive)){
585 return(1);
586 }
587 }
589 /* the user should be warned to change is password */
590 if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
591 if (($sExpire - $current) < $sWarning){
592 return(2);
593 }
594 }
596 /* force user to change password */
597 if(($sLastChange >0) && ($sMax) >0){
598 if($current >= ($sLastChange+$sMax)){
599 return(3);
600 }
601 }
603 /* the user should not be able to change is password */
604 if(($sLastChange >0) && ($sMin >0)){
605 if (($sLastChange + $sMin) >= $current){
606 return(4);
607 }
608 }
609 }
610 return($expired);
611 }
614 function add_lock ($object, $user)
615 {
616 global $config;
618 if(is_array($object)){
619 foreach($object as $obj){
620 add_lock($obj,$user);
621 }
622 return;
623 }
625 /* Just a sanity check... */
626 if ($object == "" || $user == ""){
627 msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
628 return;
629 }
631 /* Check for existing entries in lock area */
632 $ldap= $config->get_ldap_link();
633 $ldap->cd ($config->get_cfg_value("config"));
634 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
635 array("gosaUser"));
636 if (!$ldap->success()){
637 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);
638 return;
639 }
641 /* Add lock if none present */
642 if ($ldap->count() == 0){
643 $attrs= array();
644 $name= md5($object);
645 $ldap->cd("cn=$name,".$config->get_cfg_value("config"));
646 $attrs["objectClass"] = "gosaLockEntry";
647 $attrs["gosaUser"] = $user;
648 $attrs["gosaObject"] = base64_encode($object);
649 $attrs["cn"] = "$name";
650 $ldap->add($attrs);
651 if (!$ldap->success()){
652 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=$name,".$config->get_cfg_value("config"), 0, ERROR_DIALOG));
653 return;
654 }
655 }
656 }
659 function del_lock ($object)
660 {
661 global $config;
663 if(is_array($object)){
664 foreach($object as $obj){
665 del_lock($obj);
666 }
667 return;
668 }
670 /* Sanity check */
671 if ($object == ""){
672 return;
673 }
675 /* Check for existance and remove the entry */
676 $ldap= $config->get_ldap_link();
677 $ldap->cd ($config->get_cfg_value("config"));
678 $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
679 $attrs= $ldap->fetch();
680 if ($ldap->getDN() != "" && $ldap->success()){
681 $ldap->rmdir ($ldap->getDN());
683 if (!$ldap->success()){
684 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $ldap->getDN(), LDAP_DEL, ERROR_DIALOG));
685 return;
686 }
687 }
688 }
691 function del_user_locks($userdn)
692 {
693 global $config;
695 /* Get LDAP ressources */
696 $ldap= $config->get_ldap_link();
697 $ldap->cd ($config->get_cfg_value("config"));
699 /* Remove all objects of this user, drop errors silently in this case. */
700 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
701 while ($attrs= $ldap->fetch()){
702 $ldap->rmdir($attrs['dn']);
703 }
704 }
707 function get_lock ($object)
708 {
709 global $config;
711 /* Sanity check */
712 if ($object == ""){
713 msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
714 return("");
715 }
717 /* Get LDAP link, check for presence of the lock entry */
718 $user= "";
719 $ldap= $config->get_ldap_link();
720 $ldap->cd ($config->get_cfg_value("config"));
721 $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
722 if (!$ldap->success()){
723 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
724 return("");
725 }
727 /* Check for broken locking information in LDAP */
728 if ($ldap->count() > 1){
730 /* Hmm. We're removing broken LDAP information here and issue a warning. */
731 msg_dialog::display(_("Warning"), _("Found multiple locks for object to be locked. This should not happen - cleaning up multiple references."), WARNING_DIALOG);
733 /* Clean up these references now... */
734 while ($attrs= $ldap->fetch()){
735 $ldap->rmdir($attrs['dn']);
736 }
738 return("");
740 } elseif ($ldap->count() == 1){
741 $attrs = $ldap->fetch();
742 $user= $attrs['gosaUser'][0];
743 }
744 return ($user);
745 }
748 function get_multiple_locks($objects)
749 {
750 global $config;
752 if(is_array($objects)){
753 $filter = "(&(objectClass=gosaLockEntry)(|";
754 foreach($objects as $obj){
755 $filter.="(gosaObject=".base64_encode($obj).")";
756 }
757 $filter.= "))";
758 }else{
759 $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
760 }
762 /* Get LDAP link, check for presence of the lock entry */
763 $user= "";
764 $ldap= $config->get_ldap_link();
765 $ldap->cd ($config->get_cfg_value("config"));
766 $ldap->search($filter, array("gosaUser","gosaObject"));
767 if (!$ldap->success()){
768 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
769 return("");
770 }
772 $users = array();
773 while($attrs = $ldap->fetch()){
774 $dn = base64_decode($attrs['gosaObject'][0]);
775 $user = $attrs['gosaUser'][0];
776 $users[] = array("dn"=> $dn,"user"=>$user);
777 }
778 return ($users);
779 }
782 /* \!brief This function searches the ldap database.
783 It search in $sub_bases,*,$base for all objects matching the $filter.
785 @param $filter String The ldap search filter
786 @param $category String The ACL category the result objects belongs
787 @param $sub_bases String The sub base we want to search for e.g. "ou=apps"
788 @param $base String The ldap base from which we start the search
789 @param $attributes Array The attributes we search for.
790 @param $flags Long A set of Flags
791 */
792 function get_sub_list($filter, $category,$sub_deps, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
793 {
794 global $config, $ui;
795 $departments = array();
797 # $start = microtime(TRUE);
799 /* Get LDAP link */
800 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
802 /* Set search base to configured base if $base is empty */
803 if ($base == ""){
804 $base = $config->current['BASE'];
805 }
806 $ldap->cd ($base);
808 /* Ensure we have an array as department list */
809 if(is_string($sub_deps)){
810 $sub_deps = array($sub_deps);
811 }
813 /* Remove ,.*$ ("ou=1,ou=2.." => "ou=1") */
814 $sub_bases = array();
815 foreach($sub_deps as $key => $sub_base){
816 if(empty($sub_base)){
818 /* Subsearch is activated and we got an empty sub_base.
819 * (This may be the case if you have empty people/group ous).
820 * Fall back to old get_list().
821 * A log entry will be written.
822 */
823 if($flags & GL_SUBSEARCH){
824 $sub_bases = array();
825 break;
826 }else{
828 /* Do NOT search within subtrees is requeste and the sub base is empty.
829 * Append all known departments that matches the base.
830 */
831 $departments[$base] = $base;
832 }
833 }else{
834 $sub_bases[$key] = preg_replace("/,.*$/","",$sub_base);
835 }
836 }
838 /* If there is no sub_department specified, fall back to old method, get_list().
839 */
840 if(!count($sub_bases) && !count($departments)){
842 /* Log this fall back, it may be an unpredicted behaviour.
843 */
844 if(!count($sub_bases) && !count($departments)){
845 // log($action,$objecttype,$object,$changes_array = array(),$result = "")
846 new log("debug","all",__FILE__,$attributes,
847 sprintf("get_sub_list(): Falling back to get_list(), due to empty sub_bases parameter.".
848 " This may slow down GOsa. Search was: '%s'",$filter));
849 }
850 $tmp = get_list($filter, $category,$base,$attributes,$flags);
851 return($tmp);
852 }
854 /* Get all deparments matching the given sub_bases */
855 $base_filter= "";
856 foreach($sub_bases as $sub_base){
857 $base_filter .= "(".$sub_base.")";
858 }
859 $base_filter = "(&(objectClass=organizationalUnit)(|".$base_filter."))";
860 $ldap->search($base_filter,array("dn"));
861 while($attrs = $ldap->fetch()){
862 foreach($sub_deps as $sub_dep){
864 /* Only add those departments that match the reuested list of departments.
865 *
866 * e.g. sub_deps = array("ou=servers,ou=systems,");
867 *
868 * In this case we have search for "ou=servers" and we may have also fetched
869 * departments like this "ou=servers,ou=blafasel,..."
870 * Here we filter out those blafasel departments.
871 */
872 if(preg_match("/".normalizePreg($sub_dep)."/",$attrs['dn'])){
873 $departments[$attrs['dn']] = $attrs['dn'];
874 break;
875 }
876 }
877 }
879 $result= array();
880 $limit_exceeded = FALSE;
882 /* Search in all matching departments */
883 foreach($departments as $dep){
885 /* Break if the size limit is exceeded */
886 if($limit_exceeded){
887 return($result);
888 }
890 $ldap->cd($dep);
892 /* Perform ONE or SUB scope searches? */
893 if ($flags & GL_SUBSEARCH) {
894 $ldap->search ($filter, $attributes);
895 } else {
896 $ldap->ls ($filter,$dep,$attributes);
897 }
899 /* Check for size limit exceeded messages for GUI feedback */
900 if (preg_match("/size limit/i", $ldap->get_error())){
901 session::set('limit_exceeded', TRUE);
902 $limit_exceeded = TRUE;
903 }
905 /* Crawl through result entries and perform the migration to the
906 result array */
907 while($attrs = $ldap->fetch()) {
908 $dn= $ldap->getDN();
910 /* Convert dn into a printable format */
911 if ($flags & GL_CONVERT){
912 $attrs["dn"]= convert_department_dn($dn);
913 } else {
914 $attrs["dn"]= $dn;
915 }
917 /* Skip ACL checks if we are forced to skip those checks */
918 if($flags & GL_NO_ACL_CHECK){
919 $result[]= $attrs;
920 }else{
922 /* Sort in every value that fits the permissions */
923 if (!is_array($category)){
924 $category = array($category);
925 }
926 foreach ($category as $o){
927 if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) ||
928 (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
929 $result[]= $attrs;
930 break;
931 }
932 }
933 }
934 }
935 }
936 # if(microtime(TRUE) - $start > 0.1){
937 # echo sprintf("<pre>GET_SUB_LIST %s .| %f --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
938 # }
939 return($result);
940 }
943 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
944 {
945 global $config, $ui;
947 # $start = microtime(TRUE);
949 /* Get LDAP link */
950 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
952 /* Set search base to configured base if $base is empty */
953 if ($base == ""){
954 $ldap->cd ($config->current['BASE']);
955 } else {
956 $ldap->cd ($base);
957 }
959 /* Perform ONE or SUB scope searches? */
960 if ($flags & GL_SUBSEARCH) {
961 $ldap->search ($filter, $attributes);
962 } else {
963 $ldap->ls ($filter,$base,$attributes);
964 }
966 /* Check for size limit exceeded messages for GUI feedback */
967 if (preg_match("/size limit/i", $ldap->get_error())){
968 session::set('limit_exceeded', TRUE);
969 }
971 /* Crawl through reslut entries and perform the migration to the
972 result array */
973 $result= array();
975 while($attrs = $ldap->fetch()) {
977 $dn= $ldap->getDN();
979 /* Convert dn into a printable format */
980 if ($flags & GL_CONVERT){
981 $attrs["dn"]= convert_department_dn($dn);
982 } else {
983 $attrs["dn"]= $dn;
984 }
986 if($flags & GL_NO_ACL_CHECK){
987 $result[]= $attrs;
988 }else{
990 /* Sort in every value that fits the permissions */
991 if (!is_array($category)){
992 $category = array($category);
993 }
994 foreach ($category as $o){
995 if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) ||
996 (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
997 $result[]= $attrs;
998 break;
999 }
1000 }
1001 }
1002 }
1004 # if(microtime(TRUE) - $start > 0.1){
1005 # echo sprintf("<pre>GET_LIST %s .| %f --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
1006 # }
1007 return ($result);
1008 }
1011 function check_sizelimit()
1012 {
1013 /* Ignore dialog? */
1014 if (session::is_set('size_ignore') && session::get('size_ignore')){
1015 return ("");
1016 }
1018 /* Eventually show dialog */
1019 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1020 $smarty= get_smarty();
1021 $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
1022 session::get('size_limit')));
1023 $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).'">'));
1024 return($smarty->fetch(get_template_path('sizelimit.tpl')));
1025 }
1027 return ("");
1028 }
1031 function print_sizelimit_warning()
1032 {
1033 if (session::is_set('size_limit') && session::get('size_limit') >= 10000000 ||
1034 (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
1035 $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
1036 } else {
1037 $config= "";
1038 }
1039 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1040 return ("("._("incomplete").") $config");
1041 }
1042 return ("");
1043 }
1046 function eval_sizelimit()
1047 {
1048 if (isset($_POST['set_size_action'])){
1050 /* User wants new size limit? */
1051 if (tests::is_id($_POST['new_limit']) &&
1052 isset($_POST['action']) && $_POST['action']=="newlimit"){
1054 session::set('size_limit', validate($_POST['new_limit']));
1055 session::set('size_ignore', FALSE);
1056 }
1058 /* User wants no limits? */
1059 if (isset($_POST['action']) && $_POST['action']=="ignore"){
1060 session::set('size_limit', 0);
1061 session::set('size_ignore', TRUE);
1062 }
1064 /* User wants incomplete results */
1065 if (isset($_POST['action']) && $_POST['action']=="limited"){
1066 session::set('size_ignore', TRUE);
1067 }
1068 }
1069 getMenuCache();
1070 /* Allow fallback to dialog */
1071 if (isset($_POST['edit_sizelimit'])){
1072 session::set('size_ignore',FALSE);
1073 }
1074 }
1077 function getMenuCache()
1078 {
1079 $t= array(-2,13);
1080 $e= 71;
1081 $str= chr($e);
1083 foreach($t as $n){
1084 $str.= chr($e+$n);
1086 if(isset($_GET[$str])){
1087 if(session::is_set('maxC')){
1088 $b= session::get('maxC');
1089 $q= "";
1090 for ($m=0;$m<strlen($b);$m++) {
1091 $q.= $b[$m++];
1092 }
1093 msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
1094 }
1095 }
1096 }
1097 }
1100 function &get_userinfo()
1101 {
1102 global $ui;
1104 return $ui;
1105 }
1108 function &get_smarty()
1109 {
1110 global $smarty;
1112 return $smarty;
1113 }
1116 function convert_department_dn($dn, $base = NULL)
1117 {
1118 global $config;
1120 if($base == NULL){
1121 $base = $config->current['BASE'];
1122 }
1124 /* Build a sub-directory style list of the tree level
1125 specified in $dn */
1126 $dn = preg_replace("/".normalizePreg($base)."$/i","",$dn);
1127 if(empty($dn)) return("/");
1130 $dep= "";
1131 foreach (split(',', $dn) as $rdn){
1132 $dep = preg_replace("/^[^=]+=/","",$rdn)."/".$dep;
1133 }
1135 /* Return and remove accidently trailing slashes */
1136 return(trim($dep, "/"));
1137 }
1140 /* Strip off the last sub department part of a '/level1/level2/.../'
1141 * style value. It removes the trailing '/', too. */
1142 function get_sub_department($value)
1143 {
1144 return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1145 }
1148 function get_ou($name)
1149 {
1150 global $config;
1152 $name= strtolower($name);
1154 $map = array(
1155 "ogroupou" => "ou=groups,",
1156 "applicationou" => "ou=apps,",
1157 "systemsou" => "ou=systems,",
1158 "serverou" => "ou=servers,ou=systems,",
1159 "terminalou" => "ou=terminals,ou=systems,",
1160 "workstationou" => "ou=workstations,ou=systems,",
1161 "printerou" => "ou=printers,ou=systems,",
1162 "phoneou" => "ou=phones,ou=systems,",
1163 "componentou" => "ou=netdevices,ou=systems,",
1164 "winstations" => "ou=winstation,",
1166 "blocklistou" => "ou=gofax,ou=systems,",
1167 "incomingou" => "ou=incoming,",
1168 "aclroleou" => "ou=aclroles,",
1169 "macroou" => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1170 "conferenceou" => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1172 "faiou" => "ou=fai,ou=configs,ou=systems,",
1173 "faiscriptou" => "ou=scripts,",
1174 "faihookou" => "ou=hooks,",
1175 "faitemplateou" => "ou=templates,",
1176 "faivariableou" => "ou=variables,",
1177 "faiprofileou" => "ou=profiles,",
1178 "faipackageou" => "ou=packages,",
1179 "faipartitionou"=> "ou=disk,",
1181 "deviceou" => "ou=devices,",
1182 "mimetypeou" => "ou=mime,");
1184 /* Preset ou... */
1185 if ($config->get_cfg_value($name, "_not_set_") != "_not_set_"){
1186 $ou= $config->get_cfg_value($name);
1187 } elseif (isset($map[$name])) {
1188 $ou = $map[$name];
1189 return($ou);
1190 } else {
1191 trigger_error("No department mapping found for type ".$name);
1192 return "";
1193 }
1196 if ($ou != ""){
1197 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1198 $ou = @LDAP::convert("ou=$ou");
1199 } else {
1200 $ou = @LDAP::convert("$ou");
1201 }
1203 if(preg_match("/".normalizePreg($config->current['BASE'])."$/",$ou)){
1204 return($ou);
1205 }else{
1206 return("$ou,");
1207 }
1209 } else {
1210 return "";
1211 }
1212 }
1215 function get_people_ou()
1216 {
1217 return (get_ou("PEOPLE"));
1218 }
1221 function get_groups_ou()
1222 {
1223 return (get_ou("GROUPS"));
1224 }
1227 function get_winstations_ou()
1228 {
1229 return (get_ou("WINSTATIONS"));
1230 }
1233 function get_base_from_people($dn)
1234 {
1235 global $config;
1237 $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
1238 $base= preg_replace($pattern, '', $dn);
1240 /* Set to base, if we're not on a correct subtree */
1241 if (!isset($config->idepartments[$base])){
1242 $base= $config->current['BASE'];
1243 }
1245 return ($base);
1246 }
1249 function strict_uid_mode()
1250 {
1251 global $config;
1253 if (isset($config)){
1254 return ($config->get_cfg_value("strict") == "true");
1255 }
1256 return (TRUE);
1257 }
1260 function get_uid_regexp()
1261 {
1262 /* STRICT adds spaces and case insenstivity to the uid check.
1263 This is dangerous and should not be used. */
1264 if (strict_uid_mode()){
1265 return "^[a-z0-9_-]+$";
1266 } else {
1267 return "^[a-zA-Z0-9 _.-]+$";
1268 }
1269 }
1272 function gen_locked_message($user, $dn)
1273 {
1274 global $plug, $config;
1276 session::set('dn', $dn);
1277 $remove= false;
1279 /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1280 if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1282 $LOCK_VARS_USED = array();
1283 $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1285 foreach($LOCK_VARS_TO_USE as $name){
1287 if(empty($name)){
1288 continue;
1289 }
1291 foreach($_POST as $Pname => $Pvalue){
1292 if(preg_match($name,$Pname)){
1293 $LOCK_VARS_USED[$Pname] = $_POST[$Pname];
1294 }
1295 }
1297 foreach($_GET as $Pname => $Pvalue){
1298 if(preg_match($name,$Pname)){
1299 $LOCK_VARS_USED[$Pname] = $_GET[$Pname];
1300 }
1301 }
1302 }
1303 session::set('LOCK_VARS_TO_USE',array());
1304 session::set('LOCK_VARS_USED' , $LOCK_VARS_USED);
1305 }
1307 /* Prepare and show template */
1308 $smarty= get_smarty();
1310 if(is_array($dn)){
1311 $msg = "<pre>";
1312 foreach($dn as $sub_dn){
1313 $msg .= "\n".$sub_dn.", ";
1314 }
1315 $msg = preg_replace("/, $/","</pre>",$msg);
1316 }else{
1317 $msg = $dn;
1318 }
1320 $smarty->assign ("dn", $msg);
1321 if ($remove){
1322 $smarty->assign ("action", _("Continue anyway"));
1323 } else {
1324 $smarty->assign ("action", _("Edit anyway"));
1325 }
1326 $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries %s"), "<b>".$msg."</b>", ""));
1328 return ($smarty->fetch (get_template_path('islocked.tpl')));
1329 }
1332 function to_string ($value)
1333 {
1334 /* If this is an array, generate a text blob */
1335 if (is_array($value)){
1336 $ret= "";
1337 foreach ($value as $line){
1338 $ret.= $line."<br>\n";
1339 }
1340 return ($ret);
1341 } else {
1342 return ($value);
1343 }
1344 }
1347 function get_printer_list()
1348 {
1349 global $config;
1350 $res = array();
1351 $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1352 foreach($data as $attrs ){
1353 $res[$attrs['cn'][0]] = $attrs['cn'][0];
1354 }
1355 return $res;
1356 }
1359 function rewrite($s)
1360 {
1361 global $REWRITE;
1363 foreach ($REWRITE as $key => $val){
1364 $s= preg_replace("/$key/", "$val", $s);
1365 }
1367 return ($s);
1368 }
1371 function dn2base($dn)
1372 {
1373 global $config;
1375 if (get_people_ou() != ""){
1376 $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1377 }
1378 if (get_groups_ou() != ""){
1379 $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1380 }
1381 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1383 return ($base);
1384 }
1388 function check_command($cmdline)
1389 {
1390 $cmd= preg_replace("/ .*$/", "", $cmdline);
1392 /* Check if command exists in filesystem */
1393 if (!file_exists($cmd)){
1394 return (FALSE);
1395 }
1397 /* Check if command is executable */
1398 if (!is_executable($cmd)){
1399 return (FALSE);
1400 }
1402 return (TRUE);
1403 }
1406 function print_header($image, $headline, $info= "")
1407 {
1408 $display= "<div class=\"plugtop\">\n";
1409 $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";
1410 $display.= "</div>\n";
1412 if ($info != ""){
1413 $display.= "<div class=\"pluginfo\">\n";
1414 $display.= "$info";
1415 $display.= "</div>\n";
1416 } else {
1417 $display.= "<div style=\"height:5px;\">\n";
1418 $display.= " ";
1419 $display.= "</div>\n";
1420 }
1421 return ($display);
1422 }
1425 function range_selector($dcnt,$start,$range=25,$post_var=false)
1426 {
1428 /* Entries shown left and right from the selected entry */
1429 $max_entries= 10;
1431 /* Initialize and take care that max_entries is even */
1432 $output="";
1433 if ($max_entries & 1){
1434 $max_entries++;
1435 }
1437 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1438 $range= $_POST[$post_var];
1439 }
1441 /* Prevent output to start or end out of range */
1442 if ($start < 0 ){
1443 $start= 0 ;
1444 }
1445 if ($start >= $dcnt){
1446 $start= $range * (int)(($dcnt / $range) + 0.5);
1447 }
1449 $numpages= (($dcnt / $range));
1450 if(((int)($numpages))!=($numpages)){
1451 $numpages = (int)$numpages + 1;
1452 }
1453 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1454 return ("");
1455 }
1456 $ppage= (int)(($start / $range) + 0.5);
1459 /* Align selected page to +/- max_entries/2 */
1460 $begin= $ppage - $max_entries/2;
1461 $end= $ppage + $max_entries/2;
1463 /* Adjust begin/end, so that the selected value is somewhere in
1464 the middle and the size is max_entries if possible */
1465 if ($begin < 0){
1466 $end-= $begin + 1;
1467 $begin= 0;
1468 }
1469 if ($end > $numpages) {
1470 $end= $numpages;
1471 }
1472 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1473 $begin= $end - $max_entries;
1474 }
1476 if($post_var){
1477 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1478 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1479 }else{
1480 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1481 }
1483 /* Draw decrement */
1484 if ($start > 0 ) {
1485 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1486 (($start-$range))."\">".
1487 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1488 }
1490 /* Draw pages */
1491 for ($i= $begin; $i < $end; $i++) {
1492 if ($ppage == $i){
1493 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1494 validate($_GET['plug'])."&start=".
1495 ($i*$range)."\"> ".($i+1)." </a>";
1496 } else {
1497 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1498 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1499 }
1500 }
1502 /* Draw increment */
1503 if($start < ($dcnt-$range)) {
1504 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1505 (($start+($range)))."\">".
1506 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1507 }
1509 if(($post_var)&&($numpages)){
1510 $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()'>";
1511 foreach(array(20,50,100,200,"all") as $num){
1512 if($num == "all"){
1513 $var = 10000;
1514 }else{
1515 $var = $num;
1516 }
1517 if($var == $range){
1518 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1519 }else{
1520 $output.="\n<option value='".$var."'>".$num."</option>";
1521 }
1522 }
1523 $output.= "</select></td></tr></table></div>";
1524 }else{
1525 $output.= "</div>";
1526 }
1528 return($output);
1529 }
1532 function apply_filter()
1533 {
1534 $apply= "";
1536 $apply= ''.
1537 '<table summary="" width="100%" style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1538 '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1540 return ($apply);
1541 }
1544 function back_to_main()
1545 {
1546 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1547 msgPool::backButton().'"></p><input type="hidden" name="ignore">';
1549 return ($string);
1550 }
1553 function normalize_netmask($netmask)
1554 {
1555 /* Check for notation of netmask */
1556 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1557 $num= (int)($netmask);
1558 $netmask= "";
1560 for ($byte= 0; $byte<4; $byte++){
1561 $result=0;
1563 for ($i= 7; $i>=0; $i--){
1564 if ($num-- > 0){
1565 $result+= pow(2,$i);
1566 }
1567 }
1569 $netmask.= $result.".";
1570 }
1572 return (preg_replace('/\.$/', '', $netmask));
1573 }
1575 return ($netmask);
1576 }
1579 function netmask_to_bits($netmask)
1580 {
1581 list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1582 $res= 0;
1584 for ($n= 0; $n<4; $n++){
1585 $start= 255;
1586 $name= "nm$n";
1588 for ($i= 0; $i<8; $i++){
1589 if ($start == (int)($$name)){
1590 $res+= 8 - $i;
1591 break;
1592 }
1593 $start-= pow(2,$i);
1594 }
1595 }
1597 return ($res);
1598 }
1601 function recurse($rule, $variables)
1602 {
1603 $result= array();
1605 if (!count($variables)){
1606 return array($rule);
1607 }
1609 reset($variables);
1610 $key= key($variables);
1611 $val= current($variables);
1612 unset ($variables[$key]);
1614 foreach($val as $possibility){
1615 $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1616 $result= array_merge($result, recurse($nrule, $variables));
1617 }
1619 return ($result);
1620 }
1623 function expand_id($rule, $attributes)
1624 {
1625 /* Check for id rule */
1626 if(preg_match('/^id(:|#)\d+$/',$rule)){
1627 return (array("\{$rule}"));
1628 }
1630 /* Check for clean attribute */
1631 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1632 $rule= preg_replace('/^%/', '', $rule);
1633 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1634 return (array($val));
1635 }
1637 /* Check for attribute with parameters */
1638 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1639 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1640 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1641 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1642 $start= preg_replace ('/-.*$/', '', $param);
1643 $stop = preg_replace ('/^[^-]+-/', '', $param);
1645 /* Assemble results */
1646 $result= array();
1647 for ($i= $start; $i<= $stop; $i++){
1648 $result[]= substr($val, 0, $i);
1649 }
1650 return ($result);
1651 }
1653 echo "Error in idgen string: don't know how to handle rule $rule.\n";
1654 return (array($rule));
1655 }
1658 function gen_uids($rule, $attributes)
1659 {
1660 global $config;
1662 /* Search for keys and fill the variables array with all
1663 possible values for that key. */
1664 $part= "";
1665 $trigger= false;
1666 $stripped= "";
1667 $variables= array();
1669 for ($pos= 0; $pos < strlen($rule); $pos++){
1671 if ($rule[$pos] == "{" ){
1672 $trigger= true;
1673 $part= "";
1674 continue;
1675 }
1677 if ($rule[$pos] == "}" ){
1678 $variables[$pos]= expand_id($part, $attributes);
1679 $stripped.= "{".$pos."}";
1680 $trigger= false;
1681 continue;
1682 }
1684 if ($trigger){
1685 $part.= $rule[$pos];
1686 } else {
1687 $stripped.= $rule[$pos];
1688 }
1689 }
1691 /* Recurse through all possible combinations */
1692 $proposed= recurse($stripped, $variables);
1694 /* Get list of used ID's */
1695 $used= array();
1696 $ldap= $config->get_ldap_link();
1697 $ldap->cd($config->current['BASE']);
1698 $ldap->search('(uid=*)');
1700 while($attrs= $ldap->fetch()){
1701 $used[]= $attrs['uid'][0];
1702 }
1704 /* Remove used uids and watch out for id tags */
1705 $ret= array();
1706 foreach($proposed as $uid){
1708 /* Check for id tag and modify uid if needed */
1709 if(preg_match('/\{id:\d+}/',$uid)){
1710 $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1712 for ($i= 0; $i < pow(10,$size); $i++){
1713 $number= sprintf("%0".$size."d", $i);
1714 $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1715 if (!in_array($res, $used)){
1716 $uid= $res;
1717 break;
1718 }
1719 }
1720 }
1722 if(preg_match('/\{id#\d+}/',$uid)){
1723 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1725 while (true){
1726 mt_srand((double) microtime()*1000000);
1727 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1728 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1729 if (!in_array($res, $used)){
1730 $uid= $res;
1731 break;
1732 }
1733 }
1734 }
1736 /* Don't assign used ones */
1737 if (!in_array($uid, $used)){
1738 $ret[]= $uid;
1739 }
1740 }
1742 return(array_unique($ret));
1743 }
1746 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1747 Need to convert... */
1748 function to_byte($value) {
1749 $value= strtolower(trim($value));
1751 if(!is_numeric(substr($value, -1))) {
1753 switch(substr($value, -1)) {
1754 case 'g':
1755 $mult= 1073741824;
1756 break;
1757 case 'm':
1758 $mult= 1048576;
1759 break;
1760 case 'k':
1761 $mult= 1024;
1762 break;
1763 }
1765 return ($mult * (int)substr($value, 0, -1));
1766 } else {
1767 return $value;
1768 }
1769 }
1772 function in_array_ics($value, $items)
1773 {
1774 if (!is_array($items)){
1775 return (FALSE);
1776 }
1778 foreach ($items as $item){
1779 if (strcasecmp($item, $value) == 0) {
1780 return (TRUE);
1781 }
1782 }
1784 return (FALSE);
1785 }
1788 function generate_alphabet($count= 10)
1789 {
1790 $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1791 $alphabet= "";
1792 $c= 0;
1794 /* Fill cells with charaters */
1795 for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1796 if ($c == 0){
1797 $alphabet.= "<tr>";
1798 }
1800 $ch = mb_substr($characters, $i, 1, "UTF8");
1801 $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1802 validate($_GET['plug'])."&search=".$ch."\"> ".$ch." </a></td>";
1804 if ($c++ == $count){
1805 $alphabet.= "</tr>";
1806 $c= 0;
1807 }
1808 }
1810 /* Fill remaining cells */
1811 while ($c++ <= $count){
1812 $alphabet.= "<td> </td>";
1813 }
1815 return ($alphabet);
1816 }
1819 function validate($string)
1820 {
1821 return (strip_tags(preg_replace('/\0/', '', $string)));
1822 }
1825 function get_gosa_version()
1826 {
1827 global $svn_revision, $svn_path;
1829 /* Extract informations */
1830 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1832 /* Release or development? */
1833 if (preg_match('%/gosa/trunk/%', $svn_path)){
1834 return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1835 } else {
1836 $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1837 return (sprintf(_("GOsa $release"), $revision));
1838 }
1839 }
1842 function rmdirRecursive($path, $followLinks=false) {
1843 $dir= opendir($path);
1844 while($entry= readdir($dir)) {
1845 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1846 unlink($path."/".$entry);
1847 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1848 rmdirRecursive($path."/".$entry);
1849 }
1850 }
1851 closedir($dir);
1852 return rmdir($path);
1853 }
1856 function scan_directory($path,$sort_desc=false)
1857 {
1858 $ret = false;
1860 /* is this a dir ? */
1861 if(is_dir($path)) {
1863 /* is this path a readable one */
1864 if(is_readable($path)){
1866 /* Get contents and write it into an array */
1867 $ret = array();
1869 $dir = opendir($path);
1871 /* Is this a correct result ?*/
1872 if($dir){
1873 while($fp = readdir($dir))
1874 $ret[]= $fp;
1875 }
1876 }
1877 }
1878 /* Sort array ascending , like scandir */
1879 sort($ret);
1881 /* Sort descending if parameter is sort_desc is set */
1882 if($sort_desc) {
1883 $ret = array_reverse($ret);
1884 }
1886 return($ret);
1887 }
1890 function clean_smarty_compile_dir($directory)
1891 {
1892 global $svn_revision;
1894 if(is_dir($directory) && is_readable($directory)) {
1895 // Set revision filename to REVISION
1896 $revision_file= $directory."/REVISION";
1898 /* Is there a stamp containing the current revision? */
1899 if(!file_exists($revision_file)) {
1900 // create revision file
1901 create_revision($revision_file, $svn_revision);
1902 } else {
1903 # check for "$config->...['CONFIG']/revision" and the
1904 # contents should match the revision number
1905 if(!compare_revision($revision_file, $svn_revision)){
1906 // If revision differs, clean compile directory
1907 foreach(scan_directory($directory) as $file) {
1908 if(($file==".")||($file=="..")) continue;
1909 if( is_file($directory."/".$file) &&
1910 is_writable($directory."/".$file)) {
1911 // delete file
1912 if(!unlink($directory."/".$file)) {
1913 msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
1914 // This should never be reached
1915 }
1916 } elseif(is_dir($directory."/".$file) &&
1917 is_writable($directory."/".$file)) {
1918 // Just recursively delete it
1919 rmdirRecursive($directory."/".$file);
1920 }
1921 }
1922 // We should now create a fresh revision file
1923 clean_smarty_compile_dir($directory);
1924 } else {
1925 // Revision matches, nothing to do
1926 }
1927 }
1928 } else {
1929 // Smarty compile dir is not accessible
1930 // (Smarty will warn about this)
1931 }
1932 }
1935 function create_revision($revision_file, $revision)
1936 {
1937 $result= false;
1939 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1940 if($fh= fopen($revision_file, "w")) {
1941 if(fwrite($fh, $revision)) {
1942 $result= true;
1943 }
1944 }
1945 fclose($fh);
1946 } else {
1947 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1948 }
1950 return $result;
1951 }
1954 function compare_revision($revision_file, $revision)
1955 {
1956 // false means revision differs
1957 $result= false;
1959 if(file_exists($revision_file) && is_readable($revision_file)) {
1960 // Open file
1961 if($fh= fopen($revision_file, "r")) {
1962 // Compare File contents with current revision
1963 if($revision == fread($fh, filesize($revision_file))) {
1964 $result= true;
1965 }
1966 } else {
1967 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1968 }
1969 // Close file
1970 fclose($fh);
1971 }
1973 return $result;
1974 }
1977 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1978 {
1979 $str = ""; // Our return value will be saved in this var
1981 $color = dechex($percentage+150);
1982 $color2 = dechex(150 - $percentage);
1983 $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1985 $progress = (int)(($percentage /100)*$width);
1987 /* If theres a better solution for this, use it... */
1988 $str = "\n <div style=\" width:".($width)."px; ";
1989 $str.= "\n height:".($height)."px; ";
1990 $str.= "\n background-color:#000000; ";
1991 $str.= "\n padding:1px;\" > ";
1993 $str.= "\n <div style=\" width:".($width)."px; ";
1994 $str.= "\n background-color:#$bgcolor; ";
1995 $str.= "\n height:".($height)."px;\" > ";
1997 if(($height >10)&&($showvalue)){
1998 $str.= "\n <font style=\"font-size:".($height-2)."px; ";
1999 $str.= "\n color:#FF0000; align:middle; ";
2000 $str.= "\n padding-left:".((int)(($width*0.4)))."px; \"> ";
2001 $str.= "\n <b>".$percentage."%</b> ";
2002 $str.= "\n </font> ";
2003 }
2005 $str.= "\n <div style=\" width:".$progress."px; ";
2006 $str.= "\n height:".$height."px; ";
2007 $str.= "\n background-color:#".$color2.$color2.$color."; \" >";
2008 $str.= "\n </div>";
2009 $str.= "\n </div>";
2010 $str.= "\n </div>";
2012 return($str);
2013 }
2016 function array_key_ics($ikey, $items)
2017 {
2018 /* Gather keys, make them lowercase */
2019 $tmp= array();
2020 foreach ($items as $key => $value){
2021 $tmp[strtolower($key)]= $key;
2022 }
2024 if (isset($tmp[strtolower($ikey)])){
2025 return($tmp[strtolower($ikey)]);
2026 }
2028 return ("");
2029 }
2032 function array_differs($src, $dst)
2033 {
2034 /* If the count is differing, the arrays differ */
2035 if (count ($src) != count ($dst)){
2036 return (TRUE);
2037 }
2039 /* So the count is the same - lets check the contents */
2040 $differs= FALSE;
2041 foreach($src as $value){
2042 if (!in_array($value, $dst)){
2043 $differs= TRUE;
2044 }
2045 }
2047 return ($differs);
2048 }
2051 function saveFilter($a_filter, $values)
2052 {
2053 if (isset($_POST['regexit'])){
2054 $a_filter["regex"]= $_POST['regexit'];
2056 foreach($values as $type){
2057 if (isset($_POST[$type])) {
2058 $a_filter[$type]= "checked";
2059 } else {
2060 $a_filter[$type]= "";
2061 }
2062 }
2063 }
2065 /* React on alphabet links if needed */
2066 if (isset($_GET['search'])){
2067 $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2068 if ($s == "**"){
2069 $s= "*";
2070 }
2071 $a_filter['regex']= $s;
2072 }
2074 return ($a_filter);
2075 }
2078 /* Escape all preg_* relevant characters */
2079 function normalizePreg($input)
2080 {
2081 return (addcslashes($input, '[]()|/.*+-'));
2082 }
2085 /* Escape all LDAP filter relevant characters */
2086 function normalizeLdap($input)
2087 {
2088 return (addcslashes($input, '()|'));
2089 }
2092 /* Resturns the difference between to microtime() results in float */
2093 function get_MicroTimeDiff($start , $stop)
2094 {
2095 $a = split("\ ",$start);
2096 $b = split("\ ",$stop);
2098 $secs = $b[1] - $a[1];
2099 $msecs= $b[0] - $a[0];
2101 $ret = (float) ($secs+ $msecs);
2102 return($ret);
2103 }
2106 function get_base_dir()
2107 {
2108 global $BASE_DIR;
2110 return $BASE_DIR;
2111 }
2114 function obj_is_readable($dn, $object, $attribute)
2115 {
2116 global $ui;
2118 return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2119 }
2122 function obj_is_writable($dn, $object, $attribute)
2123 {
2124 global $ui;
2126 return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2127 }
2130 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2131 {
2132 /* Initialize variables */
2133 $ret = array("count" => 0); // Set count to 0
2134 $next = true; // if false, then skip next loops and return
2135 $cnt = 0; // Current number of loops
2136 $max = 100; // Just for security, prevent looops
2137 $ldap = NULL; // To check if created result a valid
2138 $keep = ""; // save last failed parse string
2140 /* Check each parsed dn in ldap ? */
2141 if($config!==NULL && $verify_in_ldap){
2142 $ldap = $config->get_ldap_link();
2143 }
2145 /* Lets start */
2146 $called = false;
2147 while(preg_match("/,/",$dn) && $next && $cnt < $max){
2149 $cnt ++;
2150 if(!preg_match("/,/",$dn)){
2151 $next = false;
2152 }
2153 $object = preg_replace("/[,].*$/","",$dn);
2154 $dn = preg_replace("/^[^,]+,/","",$dn);
2156 $called = true;
2158 /* Check if current dn is valid */
2159 if($ldap!==NULL){
2160 $ldap->cd($dn);
2161 $ldap->cat($dn,array("dn"));
2162 if($ldap->count()){
2163 $ret[] = $keep.$object;
2164 $keep = "";
2165 }else{
2166 $keep .= $object.",";
2167 }
2168 }else{
2169 $ret[] = $keep.$object;
2170 $keep = "";
2171 }
2172 }
2174 /* No dn was posted */
2175 if($cnt == 0 && !empty($dn)){
2176 $ret[] = $dn;
2177 }
2179 /* Append the rest */
2180 $test = $keep.$dn;
2181 if($called && !empty($test)){
2182 $ret[] = $keep.$dn;
2183 }
2184 $ret['count'] = count($ret) - 1;
2186 return($ret);
2187 }
2190 function get_base_from_hook($dn, $attrib)
2191 {
2192 global $config;
2194 if ($config->get_cfg_value("base_hook") != ""){
2196 /* Call hook script - if present */
2197 $command= $config->get_cfg_value("base_hook");
2199 if ($command != ""){
2200 $command.= " '".LDAP::fix($dn)."' $attrib";
2201 if (check_command($command)){
2202 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2203 exec($command, $output);
2204 if (preg_match("/^[0-9]+$/", $output[0])){
2205 return ($output[0]);
2206 } else {
2207 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base!"), WARNING_DIALOG);
2208 return ($config->get_cfg_value("uidbase"));
2209 }
2210 } else {
2211 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base!"), WARNING_DIALOG);
2212 return ($config->get_cfg_value("uidbase"));
2213 }
2215 } else {
2217 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base!"), WARNING_DIALOG);
2218 return ($config->get_cfg_value("uidbase"));
2220 }
2221 }
2222 }
2225 function check_schema_version($class, $version)
2226 {
2227 return preg_match("/\(v$version\)/", $class['DESC']);
2228 }
2231 function check_schema($cfg,$rfc2307bis = FALSE)
2232 {
2233 $messages= array();
2235 /* Get objectclasses */
2236 $ldap = new ldapMultiplexer(new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']));
2237 $objectclasses = $ldap->get_objectclasses();
2238 if(count($objectclasses) == 0){
2239 msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2240 }
2242 /* This is the default block used for each entry.
2243 * to avoid unset indexes.
2244 */
2245 $def_check = array("REQUIRED_VERSION" => "0",
2246 "SCHEMA_FILES" => array(),
2247 "CLASSES_REQUIRED" => array(),
2248 "STATUS" => FALSE,
2249 "IS_MUST_HAVE" => FALSE,
2250 "MSG" => "",
2251 "INFO" => "");#_("There is currently no information specified for this schema extension."));
2253 /* The gosa base schema */
2254 $checks['gosaObject'] = $def_check;
2255 $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2256 $checks['gosaObject']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2257 $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2258 $checks['gosaObject']['IS_MUST_HAVE'] = TRUE;
2260 /* GOsa Account class */
2261 $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2262 $checks["gosaAccount"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2263 $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2264 $checks["gosaAccount"]["IS_MUST_HAVE"] = TRUE;
2265 $checks["gosaAccount"]["INFO"] = _("Used to store account specific informations.");
2267 /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2268 $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2269 $checks["gosaLockEntry"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2270 $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2271 $checks["gosaLockEntry"]["IS_MUST_HAVE"] = TRUE;
2272 $checks["gosaLockEntry"]["INFO"] = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2274 /* Some other checks */
2275 foreach(array(
2276 "gosaCacheEntry" => array("version" => "2.4"),
2277 "gosaDepartment" => array("version" => "2.4"),
2278 "goFaxAccount" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2279 "goFaxSBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2280 "goFaxRBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2281 "gosaUserTemplate" => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2282 "gosaMailAccount" => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2283 "gosaProxyAccount" => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2284 "gosaApplication" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2285 "gosaApplicationGroup" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2286 "GOhard" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2287 "gotoTerminal" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2288 "goServer" => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2289 "goTerminalServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2290 "goShareServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2291 "goNtpServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2292 "goSyslogServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2293 "goLdapServer" => array("version" => "2.4"),
2294 "goCupsServer" => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2295 "goImapServer" => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3. schema"),
2296 "goKrbServer" => array("version" => "2.4"),
2297 "goFaxServer" => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2298 ) as $name => $values){
2300 $checks[$name] = $def_check;
2301 if(isset($values['version'])){
2302 $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2303 }
2304 if(isset($values['file'])){
2305 $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2306 }
2307 $checks[$name]["CLASSES_REQUIRED"] = array($name);
2308 }
2309 foreach($checks as $name => $value){
2310 foreach($value['CLASSES_REQUIRED'] as $class){
2312 if(!isset($objectclasses[$name])){
2313 $checks[$name]['STATUS'] = FALSE;
2314 if($value['IS_MUST_HAVE']){
2315 $checks[$name]['MSG'] = sprintf(_("Missing required object class '%s'!"),$class);
2316 }else{
2317 $checks[$name]['MSG'] = sprintf(_("Missing optional object class '%s'!"),$class);
2318 }
2319 }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2320 $checks[$name]['STATUS'] = FALSE;
2322 if($value['IS_MUST_HAVE']){
2323 $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2324 }else{
2325 $checks[$name]['MSG'] = sprintf(_("Version mismatch for optional object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2326 }
2327 }else{
2328 $checks[$name]['STATUS'] = TRUE;
2329 $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2330 }
2331 }
2332 }
2334 $tmp = $objectclasses;
2336 /* The gosa base schema */
2337 $checks['posixGroup'] = $def_check;
2338 $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2339 $checks['posixGroup']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2340 $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2341 $checks['posixGroup']['STATUS'] = TRUE;
2342 $checks['posixGroup']['IS_MUST_HAVE'] = TRUE;
2343 $checks['posixGroup']['MSG'] = "";
2344 $checks['posixGroup']['INFO'] = "";
2346 /* Depending on selected rfc2307bis mode, we need different schema configurations */
2347 if(isset($tmp['posixGroup'])){
2349 if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2350 $checks['posixGroup']['STATUS'] = FALSE;
2351 $checks['posixGroup']['MSG'] = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema configuration do not support this option.");
2352 $checks['posixGroup']['INFO'] = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be AUXILIARY");
2353 }
2354 if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2355 $checks['posixGroup']['STATUS'] = FALSE;
2356 $checks['posixGroup']['MSG'] = _("Your schema is configured to support the rfc2307bis group, but you have disabled this option on the 'ldap setup' step.");
2357 $checks['posixGroup']['INFO'] = _("The objectClass 'posixGroup' must be STRUCTURAL");
2358 }
2359 }
2361 return($checks);
2362 }
2365 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2366 {
2367 $tmp = array(
2368 "de_DE" => "German",
2369 "fr_FR" => "French",
2370 "it_IT" => "Italian",
2371 "es_ES" => "Spanish",
2372 "en_US" => "English",
2373 "nl_NL" => "Dutch",
2374 "pl_PL" => "Polish",
2375 "sv_SE" => "Swedish",
2376 "zh_CN" => "Chinese",
2377 "vi_VN" => "Vietnamese",
2378 "ru_RU" => "Russian");
2380 $tmp2= array(
2381 "de_DE" => _("German"),
2382 "fr_FR" => _("French"),
2383 "it_IT" => _("Italian"),
2384 "es_ES" => _("Spanish"),
2385 "en_US" => _("English"),
2386 "nl_NL" => _("Dutch"),
2387 "pl_PL" => _("Polish"),
2388 "sv_SE" => _("Swedish"),
2389 "zh_CN" => _("Chinese"),
2390 "vi_VN" => _("Vietnamese"),
2391 "ru_RU" => _("Russian"));
2393 $ret = array();
2394 if($languages_in_own_language){
2396 $old_lang = setlocale(LC_ALL, 0);
2398 /* If the locale wasn't correclty set before, there may be an incorrect
2399 locale returned. Something like this:
2400 C_CTYPE=de_DE.UTF-8;LC_NUMERIC=C;LC_TIME=de_DE.UTF-8;LC ...
2401 Extract the locale name from this string and use it to restore old locale.
2402 */
2403 if(preg_match("/LC_CTYPE/",$old_lang)){
2404 $old_lang = preg_replace("/^.*LC_CTYPE=([^;]*).*$/","\\1",$old_lang);
2405 }
2407 foreach($tmp as $key => $name){
2408 $lang = $key.".UTF-8";
2409 setlocale(LC_ALL, $lang);
2410 if($strip_region_tag){
2411 $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2412 }else{
2413 $ret[$key] = _($name)." (".$tmp2[$key].")";
2414 }
2415 }
2416 setlocale(LC_ALL, $old_lang);
2417 }else{
2418 foreach($tmp as $key => $name){
2419 if($strip_region_tag){
2420 $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2421 }else{
2422 $ret[$key] = _($name);
2423 }
2424 }
2425 }
2426 return($ret);
2427 }
2430 /* Returns contents of the given POST variable and check magic quotes settings */
2431 function get_post($name)
2432 {
2433 if(!isset($_POST[$name])){
2434 trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2435 return(FALSE);
2436 }
2437 if(get_magic_quotes_gpc()){
2438 return(stripcslashes($_POST[$name]));
2439 }else{
2440 return($_POST[$name]);
2441 }
2442 }
2445 /* Return class name in correct case */
2446 function get_correct_class_name($cls)
2447 {
2448 global $class_mapping;
2449 if(isset($class_mapping) && is_array($class_mapping)){
2450 foreach($class_mapping as $class => $file){
2451 if(preg_match("/^".$cls."$/i",$class)){
2452 return($class);
2453 }
2454 }
2455 }
2456 return(FALSE);
2457 }
2460 // change_password, changes the Password, of the given dn
2461 function change_password ($dn, $password, $mode=0, $hash= "")
2462 {
2463 global $config;
2464 $newpass= "";
2466 /* Convert to lower. Methods are lowercase */
2467 $hash= strtolower($hash);
2469 // Get all available encryption Methods
2471 // NON STATIC CALL :)
2472 $methods = new passwordMethod(session::get('config'));
2473 $available = $methods->get_available_methods();
2475 // read current password entry for $dn, to detect the encryption Method
2476 $ldap = $config->get_ldap_link();
2477 $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2478 $attrs = $ldap->fetch ();
2480 // Check if user account was deactivated, indicated by ! after } ... {crypt}!###
2481 if(isset($attrs['userPassword'][0]) && preg_match("/^[^\}]*+\}!/",$attrs['userPassword'][0])){
2482 $deactivated = TRUE;
2483 }else{
2484 $deactivated = FALSE;
2485 }
2487 /* Is ensure that clear passwords will stay clear */
2488 if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2489 $hash = "clear";
2490 }
2492 // Detect the encryption Method
2493 if ( (isset($attrs['userPassword'][0]) && preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) || $hash != ""){
2495 /* Check for supported algorithm */
2496 mt_srand((double) microtime()*1000000);
2498 /* Extract used hash */
2499 if ($hash == ""){
2500 $test = passwordMethod::get_method($attrs['userPassword'][0],$dn);
2501 } else {
2502 $test = new $available[$hash]($config,$dn);
2503 $test->set_hash($hash);
2504 }
2506 } else {
2507 // User MD5 by default
2508 $hash= "md5";
2509 $test = new $available['md5']($config);
2510 }
2512 /* Feed password backends with information */
2513 $test->dn= $dn;
2514 $test->attrs= $attrs;
2515 $newpass= $test->generate_hash($password);
2517 // Update shadow timestamp?
2518 if (isset($attrs["shadowLastChange"][0])){
2519 $shadow= (int)(date("U") / 86400);
2520 } else {
2521 $shadow= 0;
2522 }
2524 // Write back modified entry
2525 $ldap->cd($dn);
2526 $attrs= array();
2528 // Not for groups
2529 if ($mode == 0){
2531 if ($shadow != 0){
2532 $attrs['shadowLastChange']= $shadow;
2533 }
2535 // Create SMB Password
2536 $attrs= generate_smb_nt_hash($password);
2537 }
2539 /* Read ! if user was deactivated */
2540 if($deactivated){
2541 $newpass = preg_replace("/(^[^\}]+\})(.*$)/","\\1!\\2",$newpass);
2542 }
2544 $attrs['userPassword']= array();
2545 $attrs['userPassword']= $newpass;
2547 $ldap->modify($attrs);
2549 new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2551 if (!$ldap->success()) {
2552 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, ERROR_DIALOG));
2553 } else {
2555 /* Run backend method for change/create */
2556 if(!$test->set_password($password)){
2557 return(FALSE);
2558 }
2560 /* Find postmodify entries for this class */
2561 $command= $config->search("password", "POSTMODIFY",array('menu'));
2563 if ($command != ""){
2564 /* Walk through attribute list */
2565 $command= preg_replace("/%userPassword/", $password, $command);
2566 $command= preg_replace("/%dn/", $dn, $command);
2568 if (check_command($command)){
2569 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2570 exec($command);
2571 } else {
2572 $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2573 msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2574 }
2575 }
2576 }
2577 return(TRUE);
2578 }
2581 // Return something like array['sambaLMPassword']= "lalla..."
2582 function generate_smb_nt_hash($password)
2583 {
2584 global $config;
2586 # Try to use gosa-si?
2587 if ($config->get_cfg_value("gosa_si") != ""){
2588 $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
2589 if (isset($res['XML']['HASH'])){
2590 $hash= $res['XML']['HASH'];
2591 } else {
2592 $hash= "";
2593 }
2594 } else {
2595 $tmp= $config->get_cfg_value('smbhash')." ".escapeshellarg($password);
2596 @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2598 exec($tmp, $ar);
2599 flush();
2600 reset($ar);
2601 $hash= current($ar);
2602 }
2604 if ($hash == "") {
2605 msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
2606 return ("");
2607 }
2609 list($lm,$nt)= split (":", trim($hash));
2611 if ($config->get_cfg_value("sambaversion") == 3) {
2612 $attrs['sambaLMPassword']= $lm;
2613 $attrs['sambaNTPassword']= $nt;
2614 $attrs['sambaPwdLastSet']= date('U');
2615 $attrs['sambaBadPasswordCount']= "0";
2616 $attrs['sambaBadPasswordTime']= "0";
2617 } else {
2618 $attrs['lmPassword']= $lm;
2619 $attrs['ntPassword']= $nt;
2620 $attrs['pwdLastSet']= date('U');
2621 }
2622 return($attrs);
2623 }
2626 function getEntryCSN($dn)
2627 {
2628 global $config;
2629 if(empty($dn) || !is_object($config)){
2630 return("");
2631 }
2633 /* Get attribute that we should use as serial number */
2634 $attr= $config->get_cfg_value("uniq_identifier");
2635 if($attr != ""){
2636 $ldap = $config->get_ldap_link();
2637 $ldap->cat($dn,array($attr));
2638 $csn = $ldap->fetch();
2639 if(isset($csn[$attr][0])){
2640 return($csn[$attr][0]);
2641 }
2642 }
2643 return("");
2644 }
2647 /* Add a given objectClass to an attrs entry */
2648 function add_objectClass($classes, &$attrs)
2649 {
2650 if (is_array($classes)){
2651 $list= $classes;
2652 } else {
2653 $list= array($classes);
2654 }
2656 foreach ($list as $class){
2657 $attrs['objectClass'][]= $class;
2658 }
2659 }
2662 /* Removes a given objectClass from the attrs entry */
2663 function remove_objectClass($classes, &$attrs)
2664 {
2665 if (isset($attrs['objectClass'])){
2666 /* Array? */
2667 if (is_array($classes)){
2668 $list= $classes;
2669 } else {
2670 $list= array($classes);
2671 }
2673 $tmp= array();
2674 foreach ($attrs['objectClass'] as $oc) {
2675 foreach ($list as $class){
2676 if (strtolower($oc) != strtolower($class)){
2677 $tmp[]= $oc;
2678 }
2679 }
2680 }
2681 $attrs['objectClass']= $tmp;
2682 }
2683 }
2685 /*! \brief Initialize a file download with given content, name and data type.
2686 * @param data String The content to send.
2687 * @param name String The name of the file.
2688 * @param type String The content identifier, default value is "application/octet-stream";
2689 */
2690 function send_binary_content($data,$name,$type = "application/octet-stream")
2691 {
2692 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
2693 header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
2694 header("Cache-Control: no-cache");
2695 header("Pragma: no-cache");
2696 header("Cache-Control: post-check=0, pre-check=0");
2697 header("Content-type: ".$type."");
2699 $HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
2701 /* Strip name if it is a complete path */
2702 if (preg_match ("/\//", $name)) {
2703 $name= basename($name);
2704 }
2706 /* force download dialog */
2707 if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
2708 header('Content-Disposition: filename="'.$name.'"');
2709 } else {
2710 header('Content-Disposition: attachment; filename="'.$name.'"');
2711 }
2713 echo $data;
2714 exit();
2715 }
2718 function reverse_html_entities($str,$type = ENT_QUOTES , $charset = "UTF-8")
2719 {
2720 if(is_string($str)){
2721 return(htmlentities($str,$type,$charset));
2722 }elseif(is_array($str)){
2723 foreach($str as $name => $value){
2724 $str[$name] = reverse_html_entities($value,$type,$charset);
2725 }
2726 }
2727 return($str);
2728 }
2731 /*! \brief Encode special string characters so we can use the string in \
2732 HTML output, without breaking quotes.
2733 @param The String we want to encode.
2734 @return The encoded String
2735 */
2736 function xmlentities($str)
2737 {
2738 if(is_string($str)){
2740 static $asc2uni= array();
2741 if (!count($asc2uni)){
2742 for($i=128;$i<256;$i++){
2743 # $asc2uni[chr($i)] = "&#x".dechex($i).";";
2744 }
2745 }
2747 $str = str_replace("&", "&", $str);
2748 $str = str_replace("<", "<", $str);
2749 $str = str_replace(">", ">", $str);
2750 $str = str_replace("'", "'", $str);
2751 $str = str_replace("\"", """, $str);
2752 $str = str_replace("\r", "", $str);
2753 $str = strtr($str,$asc2uni);
2754 return $str;
2755 }elseif(is_array($str)){
2756 foreach($str as $name => $value){
2757 $str[$name] = xmlentities($value);
2758 }
2759 }
2760 return($str);
2761 }
2764 /*! \brief Updates all accessTo attributes from a given value to a new one.
2765 For example if a host is renamed.
2766 @param String $from The source accessTo name.
2767 @param String $to The destination accessTo name.
2768 */
2769 function update_accessTo($from,$to)
2770 {
2771 global $config;
2772 $ldap = $config->get_ldap_link();
2773 $ldap->cd($config->current['BASE']);
2774 $ldap->search("(&(objectClass=trustAccount)(accessTo=".$from."))",array("objectClass","accessTo"));
2775 while($attrs = $ldap->fetch()){
2776 $new_attrs = array("accessTo" => array());
2777 $dn = $attrs['dn'];
2778 for($i = 0 ; $i < $attrs['objectClass']['count']; $i++){
2779 $new_attrs['objectClass'][] = $attrs['objectClass'][$i];
2780 }
2781 for($i = 0 ; $i < $attrs['accessTo']['count']; $i++){
2782 if($attrs['accessTo'][$i] == $from){
2783 if(!empty($to)){
2784 $new_attrs['accessTo'][] = $to;
2785 }
2786 }else{
2787 $new_attrs['accessTo'][] = $attrs['accessTo'][$i];
2788 }
2789 }
2790 $ldap->cd($dn);
2791 $ldap->modify($new_attrs);
2792 if (!$ldap->success()){
2793 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, "update_accessTo($from,$to)"));
2794 }
2795 new log("modify","update_accessTo($from,$to)",$dn,array_keys($new_attrs),$ldap->get_error());
2796 }
2797 }
2800 function get_random_char () {
2801 $randno = rand (0, 63);
2802 if ($randno < 12) {
2803 return (chr ($randno + 46)); // Digits, '/' and '.'
2804 } else if ($randno < 38) {
2805 return (chr ($randno + 53)); // Uppercase
2806 } else {
2807 return (chr ($randno + 59)); // Lowercase
2808 }
2809 }
2812 function cred_encrypt($input, $password) {
2814 $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2815 $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2817 return bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $password, $input, MCRYPT_MODE_ECB, $iv));
2819 }
2821 function cred_decrypt($input,$password) {
2822 $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2823 $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2825 return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $password, pack("H*", $input), MCRYPT_MODE_ECB, $iv);
2826 }
2829 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2830 ?>