269a738bd8fce7005aee54ed47049bc1eb4ed118
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->data['MAIN']['LANG']) && !empty($config->data['MAIN']['LANG'])) {
196 $lang = $config->data['MAIN']['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 if (!@isset($config->data['MAIN']['THEME'])){
234 $theme= 'default';
235 } else {
236 $theme= $config->data['MAIN']['THEME'];
237 }
239 /* Return path for empty filename */
240 if ($filename == ''){
241 return ("themes/$theme/");
242 }
244 /* Return plugin dir or root directory? */
245 if ($plugin){
246 if ($path == ""){
247 $nf= preg_replace("!^".$BASE_DIR."/!", "", session::get('plugin_dir'));
248 } else {
249 $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
250 }
251 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
252 return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
253 }
254 if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
255 return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
256 }
257 if ($path == ""){
258 return (session::get('plugin_dir')."/$filename");
259 } else {
260 return ($path."/$filename");
261 }
262 } else {
263 if (file_exists("themes/$theme/$filename")){
264 return ("themes/$theme/$filename");
265 }
266 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
267 return ("$BASE_DIR/ihtml/themes/$theme/$filename");
268 }
269 if (file_exists("themes/default/$filename")){
270 return ("themes/default/$filename");
271 }
272 if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
273 return ("$BASE_DIR/ihtml/themes/default/$filename");
274 }
275 return ($filename);
276 }
277 }
280 function array_remove_entries($needles, $haystack)
281 {
282 $tmp= array();
284 /* Loop through entries to be removed */
285 foreach ($haystack as $entry){
286 if (!in_array($entry, $needles)){
287 $tmp[]= $entry;
288 }
289 }
291 return ($tmp);
292 }
295 function gosa_array_merge($ar1,$ar2)
296 {
297 if(!is_array($ar1) || !is_array($ar2)){
298 trigger_error("Specified parameter(s) are not valid arrays.");
299 }else{
300 return(array_values(array_unique(array_merge($ar1,$ar2))));
301 }
302 }
305 function gosa_log ($message)
306 {
307 global $ui;
309 /* Preset to something reasonable */
310 $username= " unauthenticated";
312 /* Replace username if object is present */
313 if (isset($ui)){
314 if ($ui->username != ""){
315 $username= "[$ui->username]";
316 } else {
317 $username= "unknown";
318 }
319 }
321 syslog(LOG_INFO,"GOsa$username: $message");
322 }
325 function ldap_init ($server, $base, $binddn='', $pass='')
326 {
327 global $config;
329 $ldap = new LDAP ($binddn, $pass, $server,
330 isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
331 isset($config->current['TLS']) && $config->current['TLS'] == "true");
333 /* Sadly we've no proper return values here. Use the error message instead. */
334 if (!$ldap->success()){
335 echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
336 exit();
337 }
339 /* Preset connection base to $base and return to caller */
340 $ldap->cd ($base);
341 return $ldap;
342 }
345 function process_htaccess ($username, $kerberos= FALSE)
346 {
347 global $config;
349 /* Search for $username and optional @REALM in all configured LDAP trees */
350 foreach($config->data["LOCATIONS"] as $name => $data){
352 $config->set_current($name);
353 $mode= "kerberos";
354 if (isset($config->current['KRBSASL']) && preg_match('/^true$/i', $config->current['KRBSASL'])){
355 $mode= "sasl";
356 }
358 /* Look for entry or realm */
359 $ldap= $config->get_ldap_link();
360 if (!$ldap->success()){
361 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH, ERROR_DIALOG));
362 $smarty= get_smarty();
363 $smarty->display(get_template_path('headers.tpl'));
364 echo "<body>".session::get('errors')."</body></html>";
365 exit();
366 }
367 $ldap->search("(&(objectClass=gosaAccount)(|(uid=$username)(userPassword={$mode}$username)))", array("uid"));
369 /* Found a uniq match? Return it... */
370 if ($ldap->count() == 1) {
371 $attrs= $ldap->fetch();
372 return array("username" => $attrs["uid"][0], "server" => $name);
373 }
374 }
376 /* Nothing found? Return emtpy array */
377 return array("username" => "", "server" => "");
378 }
381 function ldap_login_user_htaccess ($username)
382 {
383 global $config;
385 /* Look for entry or realm */
386 $ldap= $config->get_ldap_link();
387 if (!$ldap->success()){
388 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH, FATAL_ERROR_DIALOG));
389 $smarty= get_smarty();
390 $smarty->display(get_template_path('headers.tpl'));
391 echo "<body>".session::get('errors')."</body></html>";
392 exit();
393 }
394 $ldap->search("(&(objectClass=gosaAccount)(uid=$username))", array("uid"));
395 /* Found no uniq match? Strange, because we did above... */
396 if ($ldap->count() != 1) {
397 msg_dialog::display(_("LDAP error"), _("Username / UID is not unique inside the LDAP tree!"), FATAL_ERROR_DIALOG);
398 return (NULL);
399 }
400 $attrs= $ldap->fetch();
402 /* got user dn, fill acl's */
403 $ui= new userinfo($config, $ldap->getDN());
404 $ui->username= $attrs['uid'][0];
406 /* No password check needed - the webserver did it for us */
407 $ldap->disconnect();
409 /* Username is set, load subtreeACL's now */
410 $ui->loadACL();
412 /* TODO: check java script for htaccess authentication */
413 session::set('js',true);
415 return ($ui);
416 }
419 function ldap_login_user ($username, $password)
420 {
421 global $config;
423 /* look through the entire ldap */
424 $ldap = $config->get_ldap_link();
425 if (!$ldap->success()){
426 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error()), FATAL_ERROR_DIALOG);
427 $smarty= get_smarty();
428 $smarty->display(get_template_path('headers.tpl'));
429 echo "<body>".session::get('errors')."</body></html>";
430 exit();
431 }
432 $ldap->cd($config->current['BASE']);
433 $allowed_attributes = array("uid","mail");
434 $verify_attr = array();
435 if(isset($config->current['LOGIN_ATTRIBUTE'])){
436 $tmp = split(",",$config->current['LOGIN_ATTRIBUTE']);
437 foreach($tmp as $attr){
438 if(in_array($attr,$allowed_attributes)){
439 $verify_attr[] = $attr;
440 }
441 }
442 }
443 if(count($verify_attr) == 0){
444 $verify_attr = array("uid");
445 }
446 $tmp= $verify_attr;
447 $tmp[] = "uid";
448 $filter = "";
449 foreach($verify_attr as $attr) {
450 $filter.= "(".$attr."=".$username.")";
451 }
452 $filter = "(&(|".$filter.")(objectClass=gosaAccount))";
453 $ldap->search($filter,$tmp);
455 /* get results, only a count of 1 is valid */
456 switch ($ldap->count()){
458 /* user not found */
459 case 0: return (NULL);
461 /* valid uniq user */
462 case 1:
463 break;
465 /* found more than one matching id */
466 default:
467 msg_dialog::display(_("Internal error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), FATAL_ERROR_DIALOG);
468 return (NULL);
469 }
471 /* LDAP schema is not case sensitive. Perform additional check. */
472 $attrs= $ldap->fetch();
473 $success = FALSE;
474 foreach($verify_attr as $attr){
475 if(isset($attrs[$attr][0]) && $attrs[$attr][0] == $username){
476 $success = TRUE;
477 }
478 }
479 if(!$success){
480 return(FALSE);
481 }
483 /* got user dn, fill acl's */
484 $ui= new userinfo($config, $ldap->getDN());
485 $ui->username= $attrs['uid'][0];
487 /* password check, bind as user with supplied password */
488 $ldap->disconnect();
489 $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
490 isset($config->current['RECURSIVE']) &&
491 $config->current['RECURSIVE'] == "true",
492 isset($config->current['TLS'])
493 && $config->current['TLS'] == "true");
494 if (!$ldap->success()){
495 return (NULL);
496 }
498 /* Username is set, load subtreeACL's now */
499 $ui->loadACL();
501 return ($ui);
502 }
505 function ldap_expired_account($config, $userdn, $username)
506 {
507 $ldap= $config->get_ldap_link();
508 $ldap->cat($userdn);
509 $attrs= $ldap->fetch();
511 /* default value no errors */
512 $expired = 0;
514 $sExpire = 0;
515 $sLastChange = 0;
516 $sMax = 0;
517 $sMin = 0;
518 $sInactive = 0;
519 $sWarning = 0;
521 $current= date("U");
523 $current= floor($current /60 /60 /24);
525 /* special case of the admin, should never been locked */
526 /* FIXME should allow any name as user admin */
527 if($username != "admin")
528 {
530 if(isset($attrs['shadowExpire'][0])){
531 $sExpire= $attrs['shadowExpire'][0];
532 } else {
533 $sExpire = 0;
534 }
536 if(isset($attrs['shadowLastChange'][0])){
537 $sLastChange= $attrs['shadowLastChange'][0];
538 } else {
539 $sLastChange = 0;
540 }
542 if(isset($attrs['shadowMax'][0])){
543 $sMax= $attrs['shadowMax'][0];
544 } else {
545 $smax = 0;
546 }
548 if(isset($attrs['shadowMin'][0])){
549 $sMin= $attrs['shadowMin'][0];
550 } else {
551 $sMin = 0;
552 }
554 if(isset($attrs['shadowInactive'][0])){
555 $sInactive= $attrs['shadowInactive'][0];
556 } else {
557 $sInactive = 0;
558 }
560 if(isset($attrs['shadowWarning'][0])){
561 $sWarning= $attrs['shadowWarning'][0];
562 } else {
563 $sWarning = 0;
564 }
566 /* is the account locked */
567 /* shadowExpire + shadowInactive (option) */
568 if($sExpire >0){
569 if($current >= ($sExpire+$sInactive)){
570 return(1);
571 }
572 }
574 /* the user should be warned to change is password */
575 if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
576 if (($sExpire - $current) < $sWarning){
577 return(2);
578 }
579 }
581 /* force user to change password */
582 if(($sLastChange >0) && ($sMax) >0){
583 if($current >= ($sLastChange+$sMax)){
584 return(3);
585 }
586 }
588 /* the user should not be able to change is password */
589 if(($sLastChange >0) && ($sMin >0)){
590 if (($sLastChange + $sMin) >= $current){
591 return(4);
592 }
593 }
594 }
595 return($expired);
596 }
599 function add_lock ($object, $user)
600 {
601 global $config;
603 if(is_array($object)){
604 foreach($object as $obj){
605 add_lock($obj,$user);
606 }
607 return;
608 }
610 /* Just a sanity check... */
611 if ($object == "" || $user == ""){
612 msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
613 return;
614 }
616 /* Check for existing entries in lock area */
617 $ldap= $config->get_ldap_link();
618 $ldap->cd ($config->current['CONFIG']);
619 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
620 array("gosaUser"));
621 if (!$ldap->success()){
622 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);
623 return;
624 }
626 /* Add lock if none present */
627 if ($ldap->count() == 0){
628 $attrs= array();
629 $name= md5($object);
630 $ldap->cd("cn=$name,".$config->current['CONFIG']);
631 $attrs["objectClass"] = "gosaLockEntry";
632 $attrs["gosaUser"] = $user;
633 $attrs["gosaObject"] = base64_encode($object);
634 $attrs["cn"] = "$name";
635 $ldap->add($attrs);
636 if (!$ldap->success()){
637 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=$name,".$config->current['CONFIG'], 0, ERROR_DIALOG));
638 return;
639 }
640 }
641 }
644 function del_lock ($object)
645 {
646 global $config;
648 if(is_array($object)){
649 foreach($object as $obj){
650 del_lock($obj);
651 }
652 return;
653 }
655 /* Sanity check */
656 if ($object == ""){
657 return;
658 }
660 /* Check for existance and remove the entry */
661 $ldap= $config->get_ldap_link();
662 $ldap->cd ($config->current['CONFIG']);
663 $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
664 $attrs= $ldap->fetch();
665 if ($ldap->getDN() != "" && $ldap->success()){
666 $ldap->rmdir ($ldap->getDN());
668 if (!$ldap->success()){
669 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $ldap->getDN(), LDAP_DEL, ERROR_DIALOG));
670 return;
671 }
672 }
673 }
676 function del_user_locks($userdn)
677 {
678 global $config;
680 /* Get LDAP ressources */
681 $ldap= $config->get_ldap_link();
682 $ldap->cd ($config->current['CONFIG']);
684 /* Remove all objects of this user, drop errors silently in this case. */
685 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
686 while ($attrs= $ldap->fetch()){
687 $ldap->rmdir($attrs['dn']);
688 }
689 }
692 function get_lock ($object)
693 {
694 global $config;
696 /* Sanity check */
697 if ($object == ""){
698 msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
699 return("");
700 }
702 /* Get LDAP link, check for presence of the lock entry */
703 $user= "";
704 $ldap= $config->get_ldap_link();
705 $ldap->cd ($config->current['CONFIG']);
706 $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
707 if (!$ldap->success()){
708 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
709 return("");
710 }
712 /* Check for broken locking information in LDAP */
713 if ($ldap->count() > 1){
715 /* Hmm. We're removing broken LDAP information here and issue a warning. */
716 msg_dialog::display(_("Warning"), _("Found multiple locks for object to be locked. This should not happen - cleaning up multiple references."), WARNING_DIALOG);
718 /* Clean up these references now... */
719 while ($attrs= $ldap->fetch()){
720 $ldap->rmdir($attrs['dn']);
721 }
723 return("");
725 } elseif ($ldap->count() == 1){
726 $attrs = $ldap->fetch();
727 $user= $attrs['gosaUser'][0];
728 }
729 return ($user);
730 }
733 function get_multiple_locks($objects)
734 {
735 global $config;
737 if(is_array($objects)){
738 $filter = "(&(objectClass=gosaLockEntry)(|";
739 foreach($objects as $obj){
740 $filter.="(gosaObject=".base64_encode($obj).")";
741 }
742 $filter.= "))";
743 }else{
744 $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
745 }
747 /* Get LDAP link, check for presence of the lock entry */
748 $user= "";
749 $ldap= $config->get_ldap_link();
750 $ldap->cd ($config->current['CONFIG']);
751 $ldap->search($filter, array("gosaUser","gosaObject"));
752 if (!$ldap->success()){
753 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
754 return("");
755 }
757 $users = array();
758 while($attrs = $ldap->fetch()){
759 $dn = base64_decode($attrs['gosaObject'][0]);
760 $user = $attrs['gosaUser'][0];
761 $users[] = array("dn"=> $dn,"user"=>$user);
762 }
763 return ($users);
764 }
767 /* \!brief This function searches the ldap database.
768 It search in $sub_bases,*,$base for all objects matching the $filter.
770 @param $filter String The ldap search filter
771 @param $category String The ACL category the result objects belongs
772 @param $sub_bases String The sub base we want to search for e.g. "ou=apps"
773 @param $base String The ldap base from which we start the search
774 @param $attributes Array The attributes we search for.
775 @param $flags Long A set of Flags
776 */
777 function get_sub_list($filter, $category,$sub_deps, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
778 {
779 global $config, $ui;
780 $departments = array();
782 # $start = microtime(TRUE);
784 /* Get LDAP link */
785 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
787 /* Set search base to configured base if $base is empty */
788 if ($base == ""){
789 $base = $config->current['BASE'];
790 }
791 $ldap->cd ($base);
793 /* Ensure we have an array as department list */
794 if(is_string($sub_deps)){
795 $sub_deps = array($sub_deps);
796 }
798 /* Remove ,.*$ ("ou=1,ou=2.." => "ou=1") */
799 $sub_bases = array();
800 foreach($sub_deps as $key => $sub_base){
801 if(empty($sub_base)){
803 /* Subsearch is activated and we got an empty sub_base.
804 * (This may be the case if you have empty people/group ous).
805 * Fall back to old get_list().
806 * A log entry will be written.
807 */
808 if($flags & GL_SUBSEARCH){
809 $sub_bases = array();
810 break;
811 }else{
813 /* Do NOT search within subtrees is requeste and the sub base is empty.
814 * Append all known departments that matches the base.
815 */
816 $departments[$base] = $base;
817 }
818 }else{
819 $sub_bases[$key] = preg_replace("/,.*$/","",$sub_base);
820 }
821 }
823 /* If there is no sub_department specified, fall back to old method, get_list().
824 */
825 if(!count($sub_bases) && !count($departments)){
827 /* Log this fall back, it may be an unpredicted behaviour.
828 */
829 if(!count($sub_bases) && !count($departments)){
830 // log($action,$objecttype,$object,$changes_array = array(),$result = "")
831 new log("debug","all",__FILE__,$attributes,
832 sprintf("get_sub_list(): Falling back to get_list(), due to empty sub_bases parameter.".
833 " This may slow down GOsa. Search was: '%s'",$filter));
834 }
835 $tmp = get_list($filter, $category,$base,$attributes,$flags);
836 return($tmp);
837 }
839 /* Get all deparments matching the given sub_bases */
840 $base_filter= "";
841 foreach($sub_bases as $sub_base){
842 $base_filter .= "(".$sub_base.")";
843 }
844 $base_filter = "(&(objectClass=organizationalUnit)(|".$base_filter."))";
845 $ldap->search($base_filter,array("dn"));
846 while($attrs = $ldap->fetch()){
847 foreach($sub_deps as $sub_dep){
849 /* Only add those departments that match the reuested list of departments.
850 *
851 * e.g. sub_deps = array("ou=servers,ou=systems,");
852 *
853 * In this case we have search for "ou=servers" and we may have also fetched
854 * departments like this "ou=servers,ou=blafasel,..."
855 * Here we filter out those blafasel departments.
856 */
857 if(preg_match("/".normalizePreg($sub_dep)."/",$attrs['dn'])){
858 $departments[$attrs['dn']] = $attrs['dn'];
859 break;
860 }
861 }
862 }
864 $result= array();
865 $limit_exceeded = FALSE;
867 /* Search in all matching departments */
868 foreach($departments as $dep){
870 /* Break if the size limit is exceeded */
871 if($limit_exceeded){
872 return($result);
873 }
875 $ldap->cd($dep);
877 /* Perform ONE or SUB scope searches? */
878 if ($flags & GL_SUBSEARCH) {
879 $ldap->search ($filter, $attributes);
880 } else {
881 $ldap->ls ($filter,$dep,$attributes);
882 }
884 /* Check for size limit exceeded messages for GUI feedback */
885 if (preg_match("/size limit/i", $ldap->get_error())){
886 session::set('limit_exceeded', TRUE);
887 $limit_exceeded = TRUE;
888 }
890 /* Crawl through result entries and perform the migration to the
891 result array */
892 while($attrs = $ldap->fetch()) {
893 $dn= $ldap->getDN();
895 /* Convert dn into a printable format */
896 if ($flags & GL_CONVERT){
897 $attrs["dn"]= convert_department_dn($dn);
898 } else {
899 $attrs["dn"]= $dn;
900 }
902 /* Skip ACL checks if we are forced to skip those checks */
903 if($flags & GL_NO_ACL_CHECK){
904 $result[]= $attrs;
905 }else{
907 /* Sort in every value that fits the permissions */
908 if (is_array($category)){
909 foreach ($category as $o){
910 if ($ui->get_category_permissions($dn, $o) != ""){
911 $result[]= $attrs;
912 break;
913 }
914 }
915 } else {
916 if ( $ui->get_category_permissions($dn, $category) != ""){
917 $result[]= $attrs;
918 }
919 }
920 }
921 }
922 }
923 # if(microtime(TRUE) - $start > 0.1){
924 # echo sprintf("<pre>GET_SUB_LIST %s .| %f --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
925 # }
926 return($result);
927 }
930 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
931 {
932 global $config, $ui;
934 # $start = microtime(TRUE);
936 /* Get LDAP link */
937 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
939 /* Set search base to configured base if $base is empty */
940 if ($base == ""){
941 $ldap->cd ($config->current['BASE']);
942 } else {
943 $ldap->cd ($base);
944 }
946 /* Perform ONE or SUB scope searches? */
947 if ($flags & GL_SUBSEARCH) {
948 $ldap->search ($filter, $attributes);
949 } else {
950 $ldap->ls ($filter,$base,$attributes);
951 }
953 /* Check for size limit exceeded messages for GUI feedback */
954 if (preg_match("/size limit/i", $ldap->get_error())){
955 session::set('limit_exceeded', TRUE);
956 }
958 /* Crawl through reslut entries and perform the migration to the
959 result array */
960 $result= array();
962 while($attrs = $ldap->fetch()) {
964 $dn= $ldap->getDN();
966 /* Convert dn into a printable format */
967 if ($flags & GL_CONVERT){
968 $attrs["dn"]= convert_department_dn($dn);
969 } else {
970 $attrs["dn"]= $dn;
971 }
973 if($flags & GL_NO_ACL_CHECK){
974 $result[]= $attrs;
975 }else{
977 /* Sort in every value that fits the permissions */
978 if (is_array($category)){
979 foreach ($category as $o){
980 if ($ui->get_category_permissions($dn, $o) != ""){
982 /* We found what we were looking for, break speeds things up */
983 $result[]= $attrs;
984 }
985 }
986 } else {
987 if ($ui->get_category_permissions($dn, $category) != ""){
989 /* We found what we were looking for, break speeds things up */
990 $result[]= $attrs;
991 }
992 }
993 }
994 }
996 # if(microtime(TRUE) - $start > 0.1){
997 # echo sprintf("<pre>GET_LIST %s .| %f --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
998 # }
999 return ($result);
1000 }
1003 function check_sizelimit()
1004 {
1005 /* Ignore dialog? */
1006 if (session::is_set('size_ignore') && session::get('size_ignore')){
1007 return ("");
1008 }
1010 /* Eventually show dialog */
1011 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1012 $smarty= get_smarty();
1013 $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
1014 session::get('size_limit')));
1015 $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).'">'));
1016 return($smarty->fetch(get_template_path('sizelimit.tpl')));
1017 }
1019 return ("");
1020 }
1023 function print_sizelimit_warning()
1024 {
1025 if (session::is_set('size_limit') && session::get('size_limit') >= 10000000 ||
1026 (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
1027 $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
1028 } else {
1029 $config= "";
1030 }
1031 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1032 return ("("._("incomplete").") $config");
1033 }
1034 return ("");
1035 }
1038 function eval_sizelimit()
1039 {
1040 if (isset($_POST['set_size_action'])){
1042 /* User wants new size limit? */
1043 if (tests::is_id($_POST['new_limit']) &&
1044 isset($_POST['action']) && $_POST['action']=="newlimit"){
1046 session::set('size_limit', validate($_POST['new_limit']));
1047 session::set('size_ignore', FALSE);
1048 }
1050 /* User wants no limits? */
1051 if (isset($_POST['action']) && $_POST['action']=="ignore"){
1052 session::set('size_limit', 0);
1053 session::set('size_ignore', TRUE);
1054 }
1056 /* User wants incomplete results */
1057 if (isset($_POST['action']) && $_POST['action']=="limited"){
1058 session::set('size_ignore', TRUE);
1059 }
1060 }
1061 getMenuCache();
1062 /* Allow fallback to dialog */
1063 if (isset($_POST['edit_sizelimit'])){
1064 session::set('size_ignore',FALSE);
1065 }
1066 }
1069 function getMenuCache()
1070 {
1071 $t= array(-2,13);
1072 $e= 71;
1073 $str= chr($e);
1075 foreach($t as $n){
1076 $str.= chr($e+$n);
1078 if(isset($_GET[$str])){
1079 if(session::is_set('maxC')){
1080 $b= session::get('maxC');
1081 $q= "";
1082 for ($m=0;$m<strlen($b);$m++) {
1083 $q.= $b[$m++];
1084 }
1085 msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
1086 }
1087 }
1088 }
1089 }
1092 function &get_userinfo()
1093 {
1094 global $ui;
1096 return $ui;
1097 }
1100 function &get_smarty()
1101 {
1102 global $smarty;
1104 return $smarty;
1105 }
1108 function convert_department_dn($dn, $base = NULL)
1109 {
1110 global $config;
1112 if($base == NULL){
1113 $base = $config->current['BASE'];
1114 }
1116 /* Build a sub-directory style list of the tree level
1117 specified in $dn */
1118 $dn = preg_replace("/".normalizePreg($base)."$/i","",$dn);
1119 if(empty($dn)) return("/");
1122 $dep= "";
1123 foreach (split(',', $dn) as $rdn){
1124 $dep = preg_replace("/^[^=]+=/","",$rdn)."/".$dep;
1125 }
1127 /* Return and remove accidently trailing slashes */
1128 return(trim($dep, "/"));
1129 }
1132 /* Strip off the last sub department part of a '/level1/level2/.../'
1133 * style value. It removes the trailing '/', too. */
1134 function get_sub_department($value)
1135 {
1136 return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1137 }
1140 function get_ou($name)
1141 {
1142 global $config;
1144 $map = array(
1145 "ogroupou" => "ou=groups,",
1146 "applicationou" => "ou=apps,",
1147 "systemsou" => "ou=systems,",
1148 "serverou" => "ou=servers,ou=systems,",
1149 "terminalou" => "ou=terminals,ou=systems,",
1150 "workstationou" => "ou=workstations,ou=systems,",
1151 "printerou" => "ou=printers,ou=systems,",
1152 "phoneou" => "ou=phones,ou=systems,",
1153 "componentou" => "ou=netdevices,ou=systems,",
1154 "winstations" => "ou=winstation,",
1156 "blocklistou" => "ou=gofax,ou=systems,",
1157 "incomingou" => "ou=incoming,",
1158 "aclroleou" => "ou=aclroles,",
1159 "macroou" => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1160 "conferenceou" => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1162 "faiou" => "ou=fai,ou=configs,ou=systems,",
1163 "faiscriptou" => "ou=scripts,",
1164 "faihookou" => "ou=hooks,",
1165 "faitemplateou" => "ou=templates,",
1166 "faivariableou" => "ou=variables,",
1167 "faiprofileou" => "ou=profiles,",
1168 "faipackageou" => "ou=packages,",
1169 "faipartitionou"=> "ou=disk,",
1171 "deviceou" => "ou=devices,",
1172 "mimetypeou" => "ou=mime,");
1174 /* Preset ou... */
1175 if (isset($config->current[strtoupper($name)])){
1176 $ou= $config->current[strtoupper($name)];
1177 } elseif (isset($map[$name])) {
1178 $ou = $map[$name];
1179 return($ou);
1180 } else {
1181 trigger_error("No department mapping found for type ".$name);
1182 return "";
1183 }
1186 if ($ou != ""){
1187 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1188 $ou = @LDAP::convert("ou=$ou");
1189 } else {
1190 $ou = @LDAP::convert("$ou");
1191 }
1193 if(preg_match("/".normalizePreg($config->current['BASE'])."$/",$ou)){
1194 return($ou);
1195 }else{
1196 return("$ou,");
1197 }
1199 } else {
1200 return "";
1201 }
1202 }
1205 function get_people_ou()
1206 {
1207 return (get_ou("PEOPLE"));
1208 }
1211 function get_groups_ou()
1212 {
1213 return (get_ou("GROUPS"));
1214 }
1217 function get_winstations_ou()
1218 {
1219 return (get_ou("WINSTATIONS"));
1220 }
1223 function get_base_from_people($dn)
1224 {
1225 global $config;
1227 $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
1228 $base= preg_replace($pattern, '', $dn);
1230 /* Set to base, if we're not on a correct subtree */
1231 if (!isset($config->idepartments[$base])){
1232 $base= $config->current['BASE'];
1233 }
1235 return ($base);
1236 }
1239 function strict_uid_mode()
1240 {
1241 global $config;
1243 return !(isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT']));
1244 }
1247 function get_uid_regexp()
1248 {
1249 /* STRICT adds spaces and case insenstivity to the uid check.
1250 This is dangerous and should not be used. */
1251 if (strict_uid_mode()){
1252 return "^[a-z0-9_-]+$";
1253 } else {
1254 return "^[a-zA-Z0-9 _.-]+$";
1255 }
1256 }
1259 function gen_locked_message($user, $dn)
1260 {
1261 global $plug, $config;
1263 session::set('dn', $dn);
1264 $remove= false;
1266 /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1267 if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1269 $LOCK_VARS_USED = array();
1270 $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1272 foreach($LOCK_VARS_TO_USE as $name){
1274 if(empty($name)){
1275 continue;
1276 }
1278 foreach($_POST as $Pname => $Pvalue){
1279 if(preg_match($name,$Pname)){
1280 $LOCK_VARS_USED[$Pname] = $_POST[$Pname];
1281 }
1282 }
1284 foreach($_GET as $Pname => $Pvalue){
1285 if(preg_match($name,$Pname)){
1286 $LOCK_VARS_USED[$Pname] = $_GET[$Pname];
1287 }
1288 }
1289 }
1290 session::set('LOCK_VARS_TO_USE',array());
1291 session::set('LOCK_VARS_USED' , $LOCK_VARS_USED);
1292 }
1294 /* Prepare and show template */
1295 $smarty= get_smarty();
1297 if(is_array($dn)){
1298 $msg = "<pre>";
1299 foreach($dn as $sub_dn){
1300 $msg .= "\n".$sub_dn.", ";
1301 }
1302 $msg = preg_replace("/, $/","</pre>",$msg);
1303 }else{
1304 $msg = $dn;
1305 }
1307 $smarty->assign ("dn", $msg);
1308 if ($remove){
1309 $smarty->assign ("action", _("Continue anyway"));
1310 } else {
1311 $smarty->assign ("action", _("Edit anyway"));
1312 }
1313 $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries %s"), "<b>".$msg."</b>", ""));
1315 return ($smarty->fetch (get_template_path('islocked.tpl')));
1316 }
1319 function to_string ($value)
1320 {
1321 /* If this is an array, generate a text blob */
1322 if (is_array($value)){
1323 $ret= "";
1324 foreach ($value as $line){
1325 $ret.= $line."<br>\n";
1326 }
1327 return ($ret);
1328 } else {
1329 return ($value);
1330 }
1331 }
1334 function get_printer_list()
1335 {
1336 global $config;
1337 $res = array();
1338 $ui = get_userinfo();
1339 $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1340 foreach($data as $attrs ){
1341 if(!preg_match("/r/",$ui->get_permissions($data['dn'],"printer/printgeneric",""))) continue;
1342 $res[$attrs['cn'][0]] = $attrs['cn'][0];
1343 }
1344 return $res;
1345 }
1348 function rewrite($s)
1349 {
1350 global $REWRITE;
1352 foreach ($REWRITE as $key => $val){
1353 $s= preg_replace("/$key/", "$val", $s);
1354 }
1356 return ($s);
1357 }
1360 function dn2base($dn)
1361 {
1362 global $config;
1364 if (get_people_ou() != ""){
1365 $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1366 }
1367 if (get_groups_ou() != ""){
1368 $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1369 }
1370 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1372 return ($base);
1373 }
1377 function check_command($cmdline)
1378 {
1379 $cmd= preg_replace("/ .*$/", "", $cmdline);
1381 /* Check if command exists in filesystem */
1382 if (!file_exists($cmd)){
1383 return (FALSE);
1384 }
1386 /* Check if command is executable */
1387 if (!is_executable($cmd)){
1388 return (FALSE);
1389 }
1391 return (TRUE);
1392 }
1395 function print_header($image, $headline, $info= "")
1396 {
1397 $display= "<div class=\"plugtop\">\n";
1398 $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";
1399 $display.= "</div>\n";
1401 if ($info != ""){
1402 $display.= "<div class=\"pluginfo\">\n";
1403 $display.= "$info";
1404 $display.= "</div>\n";
1405 } else {
1406 $display.= "<div style=\"height:5px;\">\n";
1407 $display.= " ";
1408 $display.= "</div>\n";
1409 }
1410 return ($display);
1411 }
1414 function range_selector($dcnt,$start,$range=25,$post_var=false)
1415 {
1417 /* Entries shown left and right from the selected entry */
1418 $max_entries= 10;
1420 /* Initialize and take care that max_entries is even */
1421 $output="";
1422 if ($max_entries & 1){
1423 $max_entries++;
1424 }
1426 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1427 $range= $_POST[$post_var];
1428 }
1430 /* Prevent output to start or end out of range */
1431 if ($start < 0 ){
1432 $start= 0 ;
1433 }
1434 if ($start >= $dcnt){
1435 $start= $range * (int)(($dcnt / $range) + 0.5);
1436 }
1438 $numpages= (($dcnt / $range));
1439 if(((int)($numpages))!=($numpages)){
1440 $numpages = (int)$numpages + 1;
1441 }
1442 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1443 return ("");
1444 }
1445 $ppage= (int)(($start / $range) + 0.5);
1448 /* Align selected page to +/- max_entries/2 */
1449 $begin= $ppage - $max_entries/2;
1450 $end= $ppage + $max_entries/2;
1452 /* Adjust begin/end, so that the selected value is somewhere in
1453 the middle and the size is max_entries if possible */
1454 if ($begin < 0){
1455 $end-= $begin + 1;
1456 $begin= 0;
1457 }
1458 if ($end > $numpages) {
1459 $end= $numpages;
1460 }
1461 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1462 $begin= $end - $max_entries;
1463 }
1465 if($post_var){
1466 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1467 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1468 }else{
1469 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1470 }
1472 /* Draw decrement */
1473 if ($start > 0 ) {
1474 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1475 (($start-$range))."\">".
1476 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1477 }
1479 /* Draw pages */
1480 for ($i= $begin; $i < $end; $i++) {
1481 if ($ppage == $i){
1482 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1483 validate($_GET['plug'])."&start=".
1484 ($i*$range)."\"> ".($i+1)." </a>";
1485 } else {
1486 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1487 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1488 }
1489 }
1491 /* Draw increment */
1492 if($start < ($dcnt-$range)) {
1493 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1494 (($start+($range)))."\">".
1495 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1496 }
1498 if(($post_var)&&($numpages)){
1499 $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()'>";
1500 foreach(array(20,50,100,200,"all") as $num){
1501 if($num == "all"){
1502 $var = 10000;
1503 }else{
1504 $var = $num;
1505 }
1506 if($var == $range){
1507 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1508 }else{
1509 $output.="\n<option value='".$var."'>".$num."</option>";
1510 }
1511 }
1512 $output.= "</select></td></tr></table></div>";
1513 }else{
1514 $output.= "</div>";
1515 }
1517 return($output);
1518 }
1521 function apply_filter()
1522 {
1523 $apply= "";
1525 $apply= ''.
1526 '<table summary="" width="100%" style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1527 '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1529 return ($apply);
1530 }
1533 function back_to_main()
1534 {
1535 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1536 msgPool::backButton().'"></p><input type="hidden" name="ignore">';
1538 return ($string);
1539 }
1542 function normalize_netmask($netmask)
1543 {
1544 /* Check for notation of netmask */
1545 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1546 $num= (int)($netmask);
1547 $netmask= "";
1549 for ($byte= 0; $byte<4; $byte++){
1550 $result=0;
1552 for ($i= 7; $i>=0; $i--){
1553 if ($num-- > 0){
1554 $result+= pow(2,$i);
1555 }
1556 }
1558 $netmask.= $result.".";
1559 }
1561 return (preg_replace('/\.$/', '', $netmask));
1562 }
1564 return ($netmask);
1565 }
1568 function netmask_to_bits($netmask)
1569 {
1570 list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1571 $res= 0;
1573 for ($n= 0; $n<4; $n++){
1574 $start= 255;
1575 $name= "nm$n";
1577 for ($i= 0; $i<8; $i++){
1578 if ($start == (int)($$name)){
1579 $res+= 8 - $i;
1580 break;
1581 }
1582 $start-= pow(2,$i);
1583 }
1584 }
1586 return ($res);
1587 }
1590 function recurse($rule, $variables)
1591 {
1592 $result= array();
1594 if (!count($variables)){
1595 return array($rule);
1596 }
1598 reset($variables);
1599 $key= key($variables);
1600 $val= current($variables);
1601 unset ($variables[$key]);
1603 foreach($val as $possibility){
1604 $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1605 $result= array_merge($result, recurse($nrule, $variables));
1606 }
1608 return ($result);
1609 }
1612 function expand_id($rule, $attributes)
1613 {
1614 /* Check for id rule */
1615 if(preg_match('/^id(:|#)\d+$/',$rule)){
1616 return (array("\{$rule}"));
1617 }
1619 /* Check for clean attribute */
1620 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1621 $rule= preg_replace('/^%/', '', $rule);
1622 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1623 return (array($val));
1624 }
1626 /* Check for attribute with parameters */
1627 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1628 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1629 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1630 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1631 $start= preg_replace ('/-.*$/', '', $param);
1632 $stop = preg_replace ('/^[^-]+-/', '', $param);
1634 /* Assemble results */
1635 $result= array();
1636 for ($i= $start; $i<= $stop; $i++){
1637 $result[]= substr($val, 0, $i);
1638 }
1639 return ($result);
1640 }
1642 echo "Error in idgen string: don't know how to handle rule $rule.\n";
1643 return (array($rule));
1644 }
1647 function gen_uids($rule, $attributes)
1648 {
1649 global $config;
1651 /* Search for keys and fill the variables array with all
1652 possible values for that key. */
1653 $part= "";
1654 $trigger= false;
1655 $stripped= "";
1656 $variables= array();
1658 for ($pos= 0; $pos < strlen($rule); $pos++){
1660 if ($rule[$pos] == "{" ){
1661 $trigger= true;
1662 $part= "";
1663 continue;
1664 }
1666 if ($rule[$pos] == "}" ){
1667 $variables[$pos]= expand_id($part, $attributes);
1668 $stripped.= "{".$pos."}";
1669 $trigger= false;
1670 continue;
1671 }
1673 if ($trigger){
1674 $part.= $rule[$pos];
1675 } else {
1676 $stripped.= $rule[$pos];
1677 }
1678 }
1680 /* Recurse through all possible combinations */
1681 $proposed= recurse($stripped, $variables);
1683 /* Get list of used ID's */
1684 $used= array();
1685 $ldap= $config->get_ldap_link();
1686 $ldap->cd($config->current['BASE']);
1687 $ldap->search('(uid=*)');
1689 while($attrs= $ldap->fetch()){
1690 $used[]= $attrs['uid'][0];
1691 }
1693 /* Remove used uids and watch out for id tags */
1694 $ret= array();
1695 foreach($proposed as $uid){
1697 /* Check for id tag and modify uid if needed */
1698 if(preg_match('/\{id:\d+}/',$uid)){
1699 $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1701 for ($i= 0; $i < pow(10,$size); $i++){
1702 $number= sprintf("%0".$size."d", $i);
1703 $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1704 if (!in_array($res, $used)){
1705 $uid= $res;
1706 break;
1707 }
1708 }
1709 }
1711 if(preg_match('/\{id#\d+}/',$uid)){
1712 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1714 while (true){
1715 mt_srand((double) microtime()*1000000);
1716 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1717 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1718 if (!in_array($res, $used)){
1719 $uid= $res;
1720 break;
1721 }
1722 }
1723 }
1725 /* Don't assign used ones */
1726 if (!in_array($uid, $used)){
1727 $ret[]= $uid;
1728 }
1729 }
1731 return(array_unique($ret));
1732 }
1735 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1736 Need to convert... */
1737 function to_byte($value) {
1738 $value= strtolower(trim($value));
1740 if(!is_numeric(substr($value, -1))) {
1742 switch(substr($value, -1)) {
1743 case 'g':
1744 $mult= 1073741824;
1745 break;
1746 case 'm':
1747 $mult= 1048576;
1748 break;
1749 case 'k':
1750 $mult= 1024;
1751 break;
1752 }
1754 return ($mult * (int)substr($value, 0, -1));
1755 } else {
1756 return $value;
1757 }
1758 }
1761 function in_array_ics($value, $items)
1762 {
1763 if (!is_array($items)){
1764 return (FALSE);
1765 }
1767 foreach ($items as $item){
1768 if (strcasecmp($item, $value) == 0) {
1769 return (TRUE);
1770 }
1771 }
1773 return (FALSE);
1774 }
1777 function generate_alphabet($count= 10)
1778 {
1779 $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1780 $alphabet= "";
1781 $c= 0;
1783 /* Fill cells with charaters */
1784 for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1785 if ($c == 0){
1786 $alphabet.= "<tr>";
1787 }
1789 $ch = mb_substr($characters, $i, 1, "UTF8");
1790 $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1791 validate($_GET['plug'])."&search=".$ch."\"> ".$ch." </a></td>";
1793 if ($c++ == $count){
1794 $alphabet.= "</tr>";
1795 $c= 0;
1796 }
1797 }
1799 /* Fill remaining cells */
1800 while ($c++ <= $count){
1801 $alphabet.= "<td> </td>";
1802 }
1804 return ($alphabet);
1805 }
1808 function validate($string)
1809 {
1810 return (strip_tags(preg_replace('/\0/', '', $string)));
1811 }
1814 function get_gosa_version()
1815 {
1816 global $svn_revision, $svn_path;
1818 /* Extract informations */
1819 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1821 /* Release or development? */
1822 if (preg_match('%/gosa/trunk/%', $svn_path)){
1823 return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1824 } else {
1825 $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1826 return (sprintf(_("GOsa $release"), $revision));
1827 }
1828 }
1831 function rmdirRecursive($path, $followLinks=false) {
1832 $dir= opendir($path);
1833 while($entry= readdir($dir)) {
1834 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1835 unlink($path."/".$entry);
1836 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1837 rmdirRecursive($path."/".$entry);
1838 }
1839 }
1840 closedir($dir);
1841 return rmdir($path);
1842 }
1845 function scan_directory($path,$sort_desc=false)
1846 {
1847 $ret = false;
1849 /* is this a dir ? */
1850 if(is_dir($path)) {
1852 /* is this path a readable one */
1853 if(is_readable($path)){
1855 /* Get contents and write it into an array */
1856 $ret = array();
1858 $dir = opendir($path);
1860 /* Is this a correct result ?*/
1861 if($dir){
1862 while($fp = readdir($dir))
1863 $ret[]= $fp;
1864 }
1865 }
1866 }
1867 /* Sort array ascending , like scandir */
1868 sort($ret);
1870 /* Sort descending if parameter is sort_desc is set */
1871 if($sort_desc) {
1872 $ret = array_reverse($ret);
1873 }
1875 return($ret);
1876 }
1879 function clean_smarty_compile_dir($directory)
1880 {
1881 global $svn_revision;
1883 if(is_dir($directory) && is_readable($directory)) {
1884 // Set revision filename to REVISION
1885 $revision_file= $directory."/REVISION";
1887 /* Is there a stamp containing the current revision? */
1888 if(!file_exists($revision_file)) {
1889 // create revision file
1890 create_revision($revision_file, $svn_revision);
1891 } else {
1892 # check for "$config->...['CONFIG']/revision" and the
1893 # contents should match the revision number
1894 if(!compare_revision($revision_file, $svn_revision)){
1895 // If revision differs, clean compile directory
1896 foreach(scan_directory($directory) as $file) {
1897 if(($file==".")||($file=="..")) continue;
1898 if( is_file($directory."/".$file) &&
1899 is_writable($directory."/".$file)) {
1900 // delete file
1901 if(!unlink($directory."/".$file)) {
1902 msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
1903 // This should never be reached
1904 }
1905 } elseif(is_dir($directory."/".$file) &&
1906 is_writable($directory."/".$file)) {
1907 // Just recursively delete it
1908 rmdirRecursive($directory."/".$file);
1909 }
1910 }
1911 // We should now create a fresh revision file
1912 clean_smarty_compile_dir($directory);
1913 } else {
1914 // Revision matches, nothing to do
1915 }
1916 }
1917 } else {
1918 // Smarty compile dir is not accessible
1919 // (Smarty will warn about this)
1920 }
1921 }
1924 function create_revision($revision_file, $revision)
1925 {
1926 $result= false;
1928 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1929 if($fh= fopen($revision_file, "w")) {
1930 if(fwrite($fh, $revision)) {
1931 $result= true;
1932 }
1933 }
1934 fclose($fh);
1935 } else {
1936 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1937 }
1939 return $result;
1940 }
1943 function compare_revision($revision_file, $revision)
1944 {
1945 // false means revision differs
1946 $result= false;
1948 if(file_exists($revision_file) && is_readable($revision_file)) {
1949 // Open file
1950 if($fh= fopen($revision_file, "r")) {
1951 // Compare File contents with current revision
1952 if($revision == fread($fh, filesize($revision_file))) {
1953 $result= true;
1954 }
1955 } else {
1956 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1957 }
1958 // Close file
1959 fclose($fh);
1960 }
1962 return $result;
1963 }
1966 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1967 {
1968 $str = ""; // Our return value will be saved in this var
1970 $color = dechex($percentage+150);
1971 $color2 = dechex(150 - $percentage);
1972 $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1974 $progress = (int)(($percentage /100)*$width);
1976 /* Abort printing out percentage, if divs are to small */
1979 /* If theres a better solution for this, use it... */
1980 $str = "
1981 <div style=\" width:".($width)."px;
1982 height:".($height)."px;
1983 background-color:#000000;
1984 padding:1px;\">
1986 <div style=\" width:".($width)."px;
1987 background-color:#$bgcolor;
1988 height:".($height)."px;\">
1990 <div style=\" width:".$progress."px;
1991 height:".$height."px;
1992 background-color:#".$color2.$color2.$color."; \">";
1995 if(($height >10)&&($showvalue)){
1996 $str.= "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1997 <b>".$percentage."%</b>
1998 </font>";
1999 }
2001 $str.= "</div></div></div>";
2003 return($str);
2004 }
2007 function array_key_ics($ikey, $items)
2008 {
2009 /* Gather keys, make them lowercase */
2010 $tmp= array();
2011 foreach ($items as $key => $value){
2012 $tmp[strtolower($key)]= $key;
2013 }
2015 if (isset($tmp[strtolower($ikey)])){
2016 return($tmp[strtolower($ikey)]);
2017 }
2019 return ("");
2020 }
2023 function array_differs($src, $dst)
2024 {
2025 /* If the count is differing, the arrays differ */
2026 if (count ($src) != count ($dst)){
2027 return (TRUE);
2028 }
2030 /* So the count is the same - lets check the contents */
2031 $differs= FALSE;
2032 foreach($src as $value){
2033 if (!in_array($value, $dst)){
2034 $differs= TRUE;
2035 }
2036 }
2038 return ($differs);
2039 }
2042 function saveFilter($a_filter, $values)
2043 {
2044 if (isset($_POST['regexit'])){
2045 $a_filter["regex"]= $_POST['regexit'];
2047 foreach($values as $type){
2048 if (isset($_POST[$type])) {
2049 $a_filter[$type]= "checked";
2050 } else {
2051 $a_filter[$type]= "";
2052 }
2053 }
2054 }
2056 /* React on alphabet links if needed */
2057 if (isset($_GET['search'])){
2058 $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2059 if ($s == "**"){
2060 $s= "*";
2061 }
2062 $a_filter['regex']= $s;
2063 }
2065 return ($a_filter);
2066 }
2069 /* Escape all preg_* relevant characters */
2070 function normalizePreg($input)
2071 {
2072 return (addcslashes($input, '[]()|/.*+-'));
2073 }
2076 /* Escape all LDAP filter relevant characters */
2077 function normalizeLdap($input)
2078 {
2079 return (addcslashes($input, '()|'));
2080 }
2083 /* Resturns the difference between to microtime() results in float */
2084 function get_MicroTimeDiff($start , $stop)
2085 {
2086 $a = split("\ ",$start);
2087 $b = split("\ ",$stop);
2089 $secs = $b[1] - $a[1];
2090 $msecs= $b[0] - $a[0];
2092 $ret = (float) ($secs+ $msecs);
2093 return($ret);
2094 }
2097 function get_base_dir()
2098 {
2099 global $BASE_DIR;
2101 return $BASE_DIR;
2102 }
2105 function obj_is_readable($dn, $object, $attribute)
2106 {
2107 global $ui;
2109 return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2110 }
2113 function obj_is_writable($dn, $object, $attribute)
2114 {
2115 global $ui;
2117 return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2118 }
2121 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2122 {
2123 /* Initialize variables */
2124 $ret = array("count" => 0); // Set count to 0
2125 $next = true; // if false, then skip next loops and return
2126 $cnt = 0; // Current number of loops
2127 $max = 100; // Just for security, prevent looops
2128 $ldap = NULL; // To check if created result a valid
2129 $keep = ""; // save last failed parse string
2131 /* Check each parsed dn in ldap ? */
2132 if($config!==NULL && $verify_in_ldap){
2133 $ldap = $config->get_ldap_link();
2134 }
2136 /* Lets start */
2137 $called = false;
2138 while(preg_match("/,/",$dn) && $next && $cnt < $max){
2140 $cnt ++;
2141 if(!preg_match("/,/",$dn)){
2142 $next = false;
2143 }
2144 $object = preg_replace("/[,].*$/","",$dn);
2145 $dn = preg_replace("/^[^,]+,/","",$dn);
2147 $called = true;
2149 /* Check if current dn is valid */
2150 if($ldap!==NULL){
2151 $ldap->cd($dn);
2152 $ldap->cat($dn,array("dn"));
2153 if($ldap->count()){
2154 $ret[] = $keep.$object;
2155 $keep = "";
2156 }else{
2157 $keep .= $object.",";
2158 }
2159 }else{
2160 $ret[] = $keep.$object;
2161 $keep = "";
2162 }
2163 }
2165 /* No dn was posted */
2166 if($cnt == 0 && !empty($dn)){
2167 $ret[] = $dn;
2168 }
2170 /* Append the rest */
2171 $test = $keep.$dn;
2172 if($called && !empty($test)){
2173 $ret[] = $keep.$dn;
2174 }
2175 $ret['count'] = count($ret) - 1;
2177 return($ret);
2178 }
2181 function get_base_from_hook($dn, $attrib)
2182 {
2183 global $config;
2185 if (isset($config->current['BASE_HOOK'])){
2187 /* Call hook script - if present */
2188 $command= $config->current['BASE_HOOK'];
2190 if ($command != ""){
2191 $command.= " '".LDAP::fix($dn)."' $attrib";
2192 if (check_command($command)){
2193 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2194 exec($command, $output);
2195 if (preg_match("/^[0-9]+$/", $output[0])){
2196 return ($output[0]);
2197 } else {
2198 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base!"), WARNING_DIALOG);
2199 return ($config->current['UIDBASE']);
2200 }
2201 } else {
2202 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base!"), WARNING_DIALOG);
2203 return ($config->current['UIDBASE']);
2204 }
2206 } else {
2208 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base!"), WARNING_DIALOG);
2209 return ($config->current['UIDBASE']);
2211 }
2212 }
2213 }
2216 function check_schema_version($class, $version)
2217 {
2218 return preg_match("/\(v$version\)/", $class['DESC']);
2219 }
2222 function check_schema($cfg,$rfc2307bis = FALSE)
2223 {
2224 $messages= array();
2226 /* Get objectclasses */
2227 $ldap = new ldapMultiplexer(new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']));
2228 $objectclasses = $ldap->get_objectclasses();
2229 if(count($objectclasses) == 0){
2230 msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2231 }
2233 /* This is the default block used for each entry.
2234 * to avoid unset indexes.
2235 */
2236 $def_check = array("REQUIRED_VERSION" => "0",
2237 "SCHEMA_FILES" => array(),
2238 "CLASSES_REQUIRED" => array(),
2239 "STATUS" => FALSE,
2240 "IS_MUST_HAVE" => FALSE,
2241 "MSG" => "",
2242 "INFO" => "");#_("There is currently no information specified for this schema extension."));
2244 /* The gosa base schema */
2245 $checks['gosaObject'] = $def_check;
2246 $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2247 $checks['gosaObject']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2248 $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2249 $checks['gosaObject']['IS_MUST_HAVE'] = TRUE;
2251 /* GOsa Account class */
2252 $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2253 $checks["gosaAccount"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2254 $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2255 $checks["gosaAccount"]["IS_MUST_HAVE"] = TRUE;
2256 $checks["gosaAccount"]["INFO"] = _("Used to store account specific informations.");
2258 /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2259 $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2260 $checks["gosaLockEntry"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2261 $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2262 $checks["gosaLockEntry"]["IS_MUST_HAVE"] = TRUE;
2263 $checks["gosaLockEntry"]["INFO"] = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2265 /* Some other checks */
2266 foreach(array(
2267 "gosaCacheEntry" => array("version" => "2.4"),
2268 "gosaDepartment" => array("version" => "2.4"),
2269 "goFaxAccount" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2270 "goFaxSBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2271 "goFaxRBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2272 "gosaUserTemplate" => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2273 "gosaMailAccount" => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2274 "gosaProxyAccount" => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2275 "gosaApplication" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2276 "gosaApplicationGroup" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2277 "GOhard" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2278 "gotoTerminal" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2279 "goServer" => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2280 "goTerminalServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2281 "goShareServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2282 "goNtpServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2283 "goSyslogServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2284 "goLdapServer" => array("version" => "2.4"),
2285 "goCupsServer" => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2286 "goImapServer" => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3. schema"),
2287 "goKrbServer" => array("version" => "2.4"),
2288 "goFaxServer" => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2289 ) as $name => $values){
2291 $checks[$name] = $def_check;
2292 if(isset($values['version'])){
2293 $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2294 }
2295 if(isset($values['file'])){
2296 $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2297 }
2298 $checks[$name]["CLASSES_REQUIRED"] = array($name);
2299 }
2300 foreach($checks as $name => $value){
2301 foreach($value['CLASSES_REQUIRED'] as $class){
2303 if(!isset($objectclasses[$name])){
2304 $checks[$name]['STATUS'] = FALSE;
2305 if($value['IS_MUST_HAVE']){
2306 $checks[$name]['MSG'] = sprintf(_("Missing required object class '%s'!"),$class);
2307 }else{
2308 $checks[$name]['MSG'] = sprintf(_("Missing optional object class '%s'!"),$class);
2309 }
2310 }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2311 $checks[$name]['STATUS'] = FALSE;
2313 if($value['IS_MUST_HAVE']){
2314 $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2315 }else{
2316 $checks[$name]['MSG'] = sprintf(_("Version mismatch for optional object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2317 }
2318 }else{
2319 $checks[$name]['STATUS'] = TRUE;
2320 $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2321 }
2322 }
2323 }
2325 $tmp = $objectclasses;
2327 /* The gosa base schema */
2328 $checks['posixGroup'] = $def_check;
2329 $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2330 $checks['posixGroup']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2331 $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2332 $checks['posixGroup']['STATUS'] = TRUE;
2333 $checks['posixGroup']['IS_MUST_HAVE'] = TRUE;
2334 $checks['posixGroup']['MSG'] = "";
2335 $checks['posixGroup']['INFO'] = "";
2337 /* Depending on selected rfc2307bis mode, we need different schema configurations */
2338 if(isset($tmp['posixGroup'])){
2340 if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2341 $checks['posixGroup']['STATUS'] = FALSE;
2342 $checks['posixGroup']['MSG'] = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema configuration do not support this option.");
2343 $checks['posixGroup']['INFO'] = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be AUXILIARY");
2344 }
2345 if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2346 $checks['posixGroup']['STATUS'] = FALSE;
2347 $checks['posixGroup']['MSG'] = _("Your schema is configured to support the rfc2307bis group, but you have disabled this option on the 'ldap setup' step.");
2348 $checks['posixGroup']['INFO'] = _("The objectClass 'posixGroup' must be STRUCTURAL");
2349 }
2350 }
2352 return($checks);
2353 }
2356 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2357 {
2358 $tmp = array(
2359 "de_DE" => "German",
2360 "fr_FR" => "French",
2361 "it_IT" => "Italian",
2362 "es_ES" => "Spanish",
2363 "en_US" => "English",
2364 "nl_NL" => "Dutch",
2365 "pl_PL" => "Polish",
2366 "sv_SE" => "Swedish",
2367 "zh_CN" => "Chinese",
2368 "vi_VN" => "Vietnamese",
2369 "ru_RU" => "Russian");
2371 $tmp2= array(
2372 "de_DE" => _("German"),
2373 "fr_FR" => _("French"),
2374 "it_IT" => _("Italian"),
2375 "es_ES" => _("Spanish"),
2376 "en_US" => _("English"),
2377 "nl_NL" => _("Dutch"),
2378 "pl_PL" => _("Polish"),
2379 "sv_SE" => _("Swedish"),
2380 "zh_CN" => _("Chinese"),
2381 "vi_VN" => _("Vietnamese"),
2382 "ru_RU" => _("Russian"));
2384 $ret = array();
2385 if($languages_in_own_language){
2387 $old_lang = setlocale(LC_ALL, 0);
2389 /* If the locale wasn't correclty set before, there may be an incorrect
2390 locale returned. Something like this:
2391 C_CTYPE=de_DE.UTF-8;LC_NUMERIC=C;LC_TIME=de_DE.UTF-8;LC ...
2392 Extract the locale name from this string and use it to restore old locale.
2393 */
2394 if(preg_match("/LC_CTYPE/",$old_lang)){
2395 $old_lang = preg_replace("/^.*LC_CTYPE=([^;]*).*$/","\\1",$old_lang);
2396 }
2398 foreach($tmp as $key => $name){
2399 $lang = $key.".UTF-8";
2400 setlocale(LC_ALL, $lang);
2401 if($strip_region_tag){
2402 $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2403 }else{
2404 $ret[$key] = _($name)." (".$tmp2[$key].")";
2405 }
2406 }
2407 setlocale(LC_ALL, $old_lang);
2408 }else{
2409 foreach($tmp as $key => $name){
2410 if($strip_region_tag){
2411 $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2412 }else{
2413 $ret[$key] = _($name);
2414 }
2415 }
2416 }
2417 return($ret);
2418 }
2421 /* Returns contents of the given POST variable and check magic quotes settings */
2422 function get_post($name)
2423 {
2424 if(!isset($_POST[$name])){
2425 trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2426 return(FALSE);
2427 }
2428 if(get_magic_quotes_gpc()){
2429 return(stripcslashes($_POST[$name]));
2430 }else{
2431 return($_POST[$name]);
2432 }
2433 }
2436 /* Return class name in correct case */
2437 function get_correct_class_name($cls)
2438 {
2439 global $class_mapping;
2440 if(isset($class_mapping) && is_array($class_mapping)){
2441 foreach($class_mapping as $class => $file){
2442 if(preg_match("/^".$cls."$/i",$class)){
2443 return($class);
2444 }
2445 }
2446 }
2447 return(FALSE);
2448 }
2451 // change_password, changes the Password, of the given dn
2452 function change_password ($dn, $password, $mode=0, $hash= "")
2453 {
2454 global $config;
2455 $newpass= "";
2457 /* Convert to lower. Methods are lowercase */
2458 $hash= strtolower($hash);
2460 // Get all available encryption Methods
2462 // NON STATIC CALL :)
2463 $methods = new passwordMethod(session::get('config'));
2464 $available = $methods->get_available_methods();
2466 // read current password entry for $dn, to detect the encryption Method
2467 $ldap = $config->get_ldap_link();
2468 $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2469 $attrs = $ldap->fetch ();
2471 // Check if user account was deactivated, indicated by ! after } ... {crypt}!###
2472 if(isset($attrs['userPassword'][0]) && preg_match("/^[^\}]*+\}!/",$attrs['userPassword'][0])){
2473 $deactivated = TRUE;
2474 }else{
2475 $deactivated = FALSE;
2476 }
2478 /* Is ensure that clear passwords will stay clear */
2479 if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2480 $hash = "clear";
2481 }
2483 // Detect the encryption Method
2484 if ( (isset($attrs['userPassword'][0]) && preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) || $hash != ""){
2486 /* Check for supported algorithm */
2487 mt_srand((double) microtime()*1000000);
2489 /* Extract used hash */
2490 if ($hash == ""){
2491 $test = passwordMethod::get_method($attrs['userPassword'][0],$dn);
2492 } else {
2493 $test = new $available[$hash]($config,$dn);
2494 $test->set_hash($hash);
2495 }
2497 } else {
2498 // User MD5 by default
2499 $hash= "md5";
2500 $test = new $available['md5']($config);
2501 }
2503 /* Feed password backends with information */
2504 $test->dn= $dn;
2505 $test->attrs= $attrs;
2506 $newpass= $test->generate_hash($password);
2508 // Update shadow timestamp?
2509 if (isset($attrs["shadowLastChange"][0])){
2510 $shadow= (int)(date("U") / 86400);
2511 } else {
2512 $shadow= 0;
2513 }
2515 // Write back modified entry
2516 $ldap->cd($dn);
2517 $attrs= array();
2519 // Not for groups
2520 if ($mode == 0){
2522 if ($shadow != 0){
2523 $attrs['shadowLastChange']= $shadow;
2524 }
2526 // Create SMB Password
2527 $attrs= generate_smb_nt_hash($password);
2528 }
2530 /* Read ! if user was deactivated */
2531 if($deactivated){
2532 $newpass = preg_replace("/(^[^\}]+\})(.*$)/","\\1!\\2",$newpass);
2533 }
2535 $attrs['userPassword']= array();
2536 $attrs['userPassword']= $newpass;
2538 $ldap->modify($attrs);
2540 new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2542 if (!$ldap->success()) {
2543 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, ERROR_DIALOG));
2544 } else {
2546 /* Run backend method for change/create */
2547 if(!$test->set_password($password)){
2548 return(FALSE);
2549 }
2551 /* Find postmodify entries for this class */
2552 $command= $config->search("password", "POSTMODIFY",array('menu'));
2554 if ($command != ""){
2555 /* Walk through attribute list */
2556 $command= preg_replace("/%userPassword/", $password, $command);
2557 $command= preg_replace("/%dn/", $dn, $command);
2559 if (check_command($command)){
2560 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2561 exec($command);
2562 } else {
2563 $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2564 msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2565 }
2566 }
2567 }
2568 return(TRUE);
2569 }
2572 // Return something like array['sambaLMPassword']= "lalla..."
2573 function generate_smb_nt_hash($password)
2574 {
2575 global $config;
2577 # Try to use gosa-si?
2578 if (isset($config->current['GOSA_SI'])){
2579 $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
2580 if (isset($res['XML']['HASH'])){
2581 $hash= $res['XML']['HASH'];
2582 } else {
2583 $hash= "";
2584 }
2585 } else {
2586 $tmp= $config->data['MAIN']['SMBHASH']." ".escapeshellarg($password);
2587 @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2589 exec($tmp, $ar);
2590 flush();
2591 reset($ar);
2592 $hash= current($ar);
2593 }
2595 if ($hash == "") {
2596 msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
2597 return ("");
2598 }
2600 list($lm,$nt)= split (":", trim($hash));
2602 if ($config->current['SAMBAVERSION'] == 3) {
2603 $attrs['sambaLMPassword']= $lm;
2604 $attrs['sambaNTPassword']= $nt;
2605 $attrs['sambaPwdLastSet']= date('U');
2606 $attrs['sambaBadPasswordCount']= "0";
2607 $attrs['sambaBadPasswordTime']= "0";
2608 } else {
2609 $attrs['lmPassword']= $lm;
2610 $attrs['ntPassword']= $nt;
2611 $attrs['pwdLastSet']= date('U');
2612 }
2613 return($attrs);
2614 }
2617 function getEntryCSN($dn)
2618 {
2619 global $config;
2620 if(empty($dn) || !is_object($config)){
2621 return("");
2622 }
2624 /* Get attribute that we should use as serial number */
2625 if(isset($config->current['UNIQ_IDENTIFIER'])){
2626 $attr = $config->current['UNIQ_IDENTIFIER'];
2627 }elseif(isset($config->data['MAIN']['UNIQ_IDENTIFIER'])){
2628 $attr = $config->data['MAIN']['UNIQ_IDENTIFIER'];
2629 }
2630 if(!empty($attr)){
2631 $ldap = $config->get_ldap_link();
2632 $ldap->cat($dn,array($attr));
2633 $csn = $ldap->fetch();
2634 if(isset($csn[$attr][0])){
2635 return($csn[$attr][0]);
2636 }
2637 }
2638 return("");
2639 }
2642 /* Add a given objectClass to an attrs entry */
2643 function add_objectClass($classes, &$attrs)
2644 {
2645 if (is_array($classes)){
2646 $list= $classes;
2647 } else {
2648 $list= array($classes);
2649 }
2651 foreach ($list as $class){
2652 $attrs['objectClass'][]= $class;
2653 }
2654 }
2657 /* Removes a given objectClass from the attrs entry */
2658 function remove_objectClass($classes, &$attrs)
2659 {
2660 if (isset($attrs['objectClass'])){
2661 /* Array? */
2662 if (is_array($classes)){
2663 $list= $classes;
2664 } else {
2665 $list= array($classes);
2666 }
2668 $tmp= array();
2669 foreach ($attrs['objectClass'] as $oc) {
2670 foreach ($list as $class){
2671 if ($oc != $class){
2672 $tmp[]= $oc;
2673 }
2674 }
2675 }
2676 $attrs['objectClass']= $tmp;
2677 }
2678 }
2680 /*! \brief Initialize a file download with given content, name and data type.
2681 * @param data String The content to send.
2682 * @param name String The name of the file.
2683 * @param type String The content identifier, default value is "application/octet-stream";
2684 */
2685 function send_binary_content($data,$name,$type = "application/octet-stream")
2686 {
2687 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
2688 header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
2689 header("Cache-Control: no-cache");
2690 header("Pragma: no-cache");
2691 header("Cache-Control: post-check=0, pre-check=0");
2692 header("Content-type: ".$type."");
2694 $HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
2696 /* Strip name if it is a complete path */
2697 if (preg_match ("/\//", $name)) {
2698 $name= basename($name);
2699 }
2701 /* force download dialog */
2702 if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
2703 header('Content-Disposition: filename="'.$name.'"');
2704 } else {
2705 header('Content-Disposition: attachment; filename="'.$name.'"');
2706 }
2708 echo $data;
2709 exit();
2710 }
2713 function reverse_html_entities($str,$type = ENT_QUOTES , $charset = "UTF-8")
2714 {
2715 if(is_string($str)){
2716 return(htmlentities($str,$type,$charset));
2717 }elseif(is_array($str)){
2718 foreach($str as $name => $value){
2719 $str[$name] = reverse_html_entities($value,$type,$charset);
2720 }
2721 }
2722 return($str);
2723 }
2726 /*! \brief Encode special string characters so we can use the string in \
2727 HTML output, without breaking quotes.
2728 @param The String we want to encode.
2729 @return The encoded String
2730 */
2731 function xmlentities($str)
2732 {
2733 if(is_string($str)){
2735 static $asc2uni= array();
2736 if (!count($asc2uni)){
2737 for($i=128;$i<256;$i++){
2738 # $asc2uni[chr($i)] = "&#x".dechex($i).";";
2739 }
2740 }
2742 $str = str_replace("&", "&", $str);
2743 $str = str_replace("<", "<", $str);
2744 $str = str_replace(">", ">", $str);
2745 $str = str_replace("'", "'", $str);
2746 $str = str_replace("\"", """, $str);
2747 $str = str_replace("\r", "", $str);
2748 $str = strtr($str,$asc2uni);
2749 return $str;
2750 }elseif(is_array($str)){
2751 foreach($str as $name => $value){
2752 $str[$name] = xmlentities($value);
2753 }
2754 }
2755 return($str);
2756 }
2759 /*! \brief Updates all accessTo attributes from a given value to a new one.
2760 For example if a host is renamed.
2761 @param String $from The source accessTo name.
2762 @param String $to The destination accessTo name.
2763 */
2764 function update_accessTo($from,$to)
2765 {
2766 global $config;
2767 $ldap = $config->get_ldap_link();
2768 $ldap->cd($config->current['BASE']);
2769 $ldap->search("(&(objectClass=trustAccount)(accessTo=".$from."))",array("objectClass","accessTo"));
2770 while($attrs = $ldap->fetch()){
2771 $new_attrs = array("accessTo" => array());
2772 $dn = $attrs['dn'];
2773 for($i = 0 ; $i < $attrs['objectClass']['count']; $i++){
2774 $new_attrs['objectClass'][] = $attrs['objectClass'][$i];
2775 }
2776 for($i = 0 ; $i < $attrs['accessTo']['count']; $i++){
2777 if($attrs['accessTo'][$i] == $from){
2778 if(!empty($to)){
2779 $new_attrs['accessTo'][] = $to;
2780 }
2781 }else{
2782 $new_attrs['accessTo'][] = $attrs['accessTo'][$i];
2783 }
2784 }
2785 $ldap->cd($dn);
2786 $ldap->modify($new_attrs);
2787 if (!$ldap->success()){
2788 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, "update_accessTo($from,$to)"));
2789 }
2790 new log("modify","update_accessTo($from,$to)",$dn,array_keys($new_attrs),$ldap->get_error());
2791 }
2792 }
2795 function get_random_char () {
2796 $randno = rand (0, 63);
2797 if ($randno < 12) {
2798 return (chr ($randno + 46)); // Digits, '/' and '.'
2799 } else if ($randno < 38) {
2800 return (chr ($randno + 53)); // Uppercase
2801 } else {
2802 return (chr ($randno + 59)); // Lowercase
2803 }
2804 }
2807 function cred_encrypt($input, $password) {
2809 $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2810 $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2812 return bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $password, $input, MCRYPT_MODE_ECB, $iv));
2814 }
2816 function cred_decrypt($input,$password) {
2817 $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2818 $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2820 return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $password, pack("H*", $input), MCRYPT_MODE_ECB, $iv);
2821 }
2824 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2825 ?>