1 <?php
2 /*
3 * This code is part of GOsa (https://gosa.gonicus.de)
4 * Copyright (C) 2003 Cajus Pollmeier
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 */
21 /* Configuration file location */
22 define ("CONFIG_DIR", "/etc/gosa");
23 define ("CONFIG_TEMPLATE_DIR", "../contrib/");
24 define ("HELP_BASEDIR", "/var/www/doc/");
26 /* Define get_list flags */
27 define("GL_NONE", 0);
28 define("GL_SUBSEARCH", 1);
29 define("GL_SIZELIMIT", 2);
30 define("GL_CONVERT" , 4);
32 /* Define globals for revision comparing */
33 $svn_path = '$HeadURL$';
34 $svn_revision = '$Revision$';
36 /* Include required files */
37 require_once ("class_ldap.inc");
38 require_once ("class_config.inc");
39 require_once ("class_userinfo.inc");
40 require_once ("class_plugin.inc");
41 require_once ("class_pluglist.inc");
42 require_once ("class_tabs.inc");
43 require_once ("class_mail-methods.inc");
44 require_once("class_password-methods.inc");
45 require_once ("functions_debug.inc");
46 require_once ("functions_dns.inc");
47 require_once ("class_MultiSelectWindow.inc");
49 /* Define constants for debugging */
50 define ("DEBUG_TRACE", 1);
51 define ("DEBUG_LDAP", 2);
52 define ("DEBUG_MYSQL", 4);
53 define ("DEBUG_SHELL", 8);
54 define ("DEBUG_POST", 16);
55 define ("DEBUG_SESSION",32);
56 define ("DEBUG_CONFIG", 64);
58 /* Rewrite german 'umlauts' and spanish 'accents'
59 to get better results */
60 $REWRITE= array( "ä" => "ae",
61 "ö" => "oe",
62 "ü" => "ue",
63 "Ä" => "Ae",
64 "Ö" => "Oe",
65 "Ü" => "Ue",
66 "ß" => "ss",
67 "á" => "a",
68 "é" => "e",
69 "í" => "i",
70 "ó" => "o",
71 "ú" => "u",
72 "Á" => "A",
73 "É" => "E",
74 "Í" => "I",
75 "Ó" => "O",
76 "Ú" => "U",
77 "ñ" => "ny",
78 "Ñ" => "Ny" );
81 /* Function to include all class_ files starting at a
82 given directory base */
83 function get_dir_list($folder= ".")
84 {
85 $currdir=getcwd();
86 if ($folder){
87 chdir("$folder");
88 }
90 $dh = opendir(".");
91 while(false !== ($file = readdir($dh))){
93 // Smarty is included by include/php_setup.inc require("smarty/Smarty.class.php");
94 // Skip all files and dirs in "./.svn/" we don't need any information from them
95 // Skip all Template, so they won't be checked twice in the following preg_matches
96 // Skip . / ..
98 // Result : from 1023 ms to 490 ms i think thats great...
99 if(preg_match("/.*\.svn.*/i",$file)||preg_match("/.*smarty.*/i",$file)||preg_match("/.*\.tpl.*/",$file)||($file==".")||($file==".."))
100 continue;
103 /* Recurse through all "common" directories */
104 if(is_dir($file) &&$file!="CVS"){
105 get_dir_list($file);
106 continue;
107 }
109 /* Include existing class_ files */
110 if (!is_dir($file) && preg_match("/^class_.*\.inc$/", $file)) {
111 require_once($file);
112 }
113 }
115 closedir($dh);
116 chdir($currdir);
117 }
120 /* Create seed with microseconds */
121 function make_seed() {
122 list($usec, $sec) = explode(' ', microtime());
123 return (float) $sec + ((float) $usec * 100000);
124 }
127 /* Debug level action */
128 function DEBUG($level, $line, $function, $file, $data, $info="")
129 {
130 if ($_SESSION['DEBUGLEVEL'] & $level){
131 $output= "DEBUG[$level] ";
132 if ($function != ""){
133 $output.= "($file:$function():$line) - $info: ";
134 } else {
135 $output.= "($file:$line) - $info: ";
136 }
137 echo $output;
138 if (is_array($data)){
139 print_a($data);
140 } else {
141 echo "'$data'";
142 }
143 echo "<br>";
144 }
145 }
148 /* Simple function to get browser language and convert it to
149 xx_XY needed by locales. Ignores sublanguages and weights. */
150 function get_browser_language()
151 {
152 global $BASE_DIR;
154 /* Try to use users primary language */
155 $ui= get_userinfo();
156 if ($ui != NULL){
157 if ($ui->language != ""){
158 return ($ui->language);
159 }
160 }
162 /* Get list of languages */
163 if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
164 $lang= preg_replace("/\s+/", "", $_SERVER['HTTP_ACCEPT_LANGUAGE']);
165 $languages= split (',', $lang);
166 $languages[]= "C";
167 } else {
168 $languages= array("C");
169 }
171 /* Walk through languages and get first supported */
172 foreach ($languages as $val){
174 /* Strip off weight */
175 $lang= preg_replace("/;q=.*$/i", "", $val);
177 /* Simplify sub language handling */
178 $lang= preg_replace("/-.*$/", "", $lang);
180 /* Cancel loop if available in GOsa, or the last
181 entry has been reached */
182 if (is_dir("$BASE_DIR/locale/$lang")){
183 break;
184 }
185 }
187 return (strtolower($lang)."_".strtoupper($lang));
188 }
191 /* Rewrite ui object to another dn */
192 function change_ui_dn($dn, $newdn)
193 {
194 $ui= $_SESSION['ui'];
195 if ($ui->dn == $dn){
196 $ui->dn= $newdn;
197 $_SESSION['ui']= $ui;
198 }
199 }
202 /* Return theme path for specified file */
203 function get_template_path($filename= '', $plugin= FALSE, $path= "")
204 {
205 global $config, $BASE_DIR;
207 if (!@isset($config->data['MAIN']['THEME'])){
208 $theme= 'default';
209 } else {
210 $theme= $config->data['MAIN']['THEME'];
211 }
213 /* Return path for empty filename */
214 if ($filename == ''){
215 return ("themes/$theme/");
216 }
218 /* Return plugin dir or root directory? */
219 if ($plugin){
220 if ($path == ""){
221 $nf= preg_replace("!^".$BASE_DIR."/!", "", $_SESSION['plugin_dir']);
222 } else {
223 $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
224 }
225 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
226 return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
227 }
228 if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
229 return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
230 }
231 if ($path == ""){
232 return ($_SESSION['plugin_dir']."/$filename");
233 } else {
234 return ($path."/$filename");
235 }
236 } else {
237 if (file_exists("themes/$theme/$filename")){
238 return ("themes/$theme/$filename");
239 }
240 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
241 return ("$BASE_DIR/ihtml/themes/$theme/$filename");
242 }
243 if (file_exists("themes/default/$filename")){
244 return ("themes/default/$filename");
245 }
246 if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
247 return ("$BASE_DIR/ihtml/themes/default/$filename");
248 }
249 return ($filename);
250 }
251 }
254 function array_remove_entries($needles, $haystack)
255 {
256 $tmp= array();
258 /* Loop through entries to be removed */
259 foreach ($haystack as $entry){
260 if (!in_array($entry, $needles)){
261 $tmp[]= $entry;
262 }
263 }
265 return ($tmp);
266 }
269 function gosa_log ($message)
270 {
271 global $ui;
273 /* Preset to something reasonable */
274 $username= " unauthenticated";
276 /* Replace username if object is present */
277 if (isset($ui)){
278 if ($ui->username != ""){
279 $username= "[$ui->username]";
280 } else {
281 $username= "unknown";
282 }
283 }
285 syslog(LOG_INFO,"GOsa$username: $message");
286 }
289 function ldap_init ($server, $base, $binddn='', $pass='')
290 {
291 global $config;
293 $ldap = new LDAP ($binddn, $pass, $server, isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
294 isset($config->current['TLS']) && $config->current['TLS'] == "true");
296 /* Sadly we've no proper return values here. Use the error message instead. */
297 if (!preg_match("/Success/i", $ldap->error)){
298 echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
299 exit();
300 }
302 /* Preset connection base to $base and return to caller */
303 $ldap->cd ($base);
304 return $ldap;
305 }
308 function ldap_login_user ($username, $password)
309 {
310 global $config;
312 /* look through the entire ldap */
313 $ldap = $config->get_ldap_link();
314 if (!preg_match("/Success/i", $ldap->error)){
315 print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
316 $smarty= get_smarty();
317 $smarty->display(get_template_path('headers.tpl'));
318 echo "<body>".$_SESSION['errors']."</body></html>";
319 exit();
320 }
321 $ldap->cd($config->current['BASE']);
322 $ldap->search("(&(uid=$username)(objectClass=gosaAccount))", array("uid"));
324 /* get results, only a count of 1 is valid */
325 switch ($ldap->count()){
327 /* user not found */
328 case 0: return (NULL);
330 /* valid uniq user */
331 case 1:
332 break;
334 /* found more than one matching id */
335 default:
336 print_red(_("Username / UID is not unique. Please check your LDAP database."));
337 return (NULL);
338 }
340 /* LDAP schema is not case sensitive. Perform additional check. */
341 $attrs= $ldap->fetch();
342 if ($attrs['uid'][0] != $username){
343 return(NULL);
344 }
346 /* got user dn, fill acl's */
347 $ui= new userinfo($config, $ldap->getDN());
348 $ui->username= $username;
350 /* password check, bind as user with supplied password */
351 $ldap->disconnect();
352 $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
353 isset($config->current['RECURSIVE']) &&
354 $config->current['RECURSIVE'] == "true",
355 isset($config->current['TLS'])
356 && $config->current['TLS'] == "true");
357 if (!preg_match("/Success/i", $ldap->error)){
358 return (NULL);
359 }
361 /* Username is set, load subtreeACL's now */
362 $ui->loadACL();
364 return ($ui);
365 }
368 function ldap_expired_account($config, $userdn, $username)
369 {
370 //$this->config= $config;
371 $ldap= $config->get_ldap_link();
372 $ldap->cat($userdn);
373 $attrs= $ldap->fetch();
375 /* default value no errors */
376 $expired = 0;
378 $sExpire = 0;
379 $sLastChange = 0;
380 $sMax = 0;
381 $sMin = 0;
382 $sInactive = 0;
383 $sWarning = 0;
385 $current= date("U");
387 $current= floor($current /60 /60 /24);
389 /* special case of the admin, should never been locked */
390 /* FIXME should allow any name as user admin */
391 if($username != "admin")
392 {
394 if(isset($attrs['shadowExpire'][0])){
395 $sExpire= $attrs['shadowExpire'][0];
396 } else {
397 $sExpire = 0;
398 }
400 if(isset($attrs['shadowLastChange'][0])){
401 $sLastChange= $attrs['shadowLastChange'][0];
402 } else {
403 $sLastChange = 0;
404 }
406 if(isset($attrs['shadowMax'][0])){
407 $sMax= $attrs['shadowMax'][0];
408 } else {
409 $smax = 0;
410 }
412 if(isset($attrs['shadowMin'][0])){
413 $sMin= $attrs['shadowMin'][0];
414 } else {
415 $sMin = 0;
416 }
418 if(isset($attrs['shadowInactive'][0])){
419 $sInactive= $attrs['shadowInactive'][0];
420 } else {
421 $sInactive = 0;
422 }
424 if(isset($attrs['shadowWarning'][0])){
425 $sWarning= $attrs['shadowWarning'][0];
426 } else {
427 $sWarning = 0;
428 }
430 /* is the account locked */
431 /* shadowExpire + shadowInactive (option) */
432 if($sExpire >0){
433 if($current >= ($sExpire+$sInactive)){
434 return(1);
435 }
436 }
438 /* the user should be warned to change is password */
439 if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
440 if (($sExpire - $current) < $sWarning){
441 return(2);
442 }
443 }
445 /* force user to change password */
446 if(($sLastChange >0) && ($sMax) >0){
447 if($current >= ($sLastChange+$sMax)){
448 return(3);
449 }
450 }
452 /* the user should not be able to change is password */
453 if(($sLastChange >0) && ($sMin >0)){
454 if (($sLastChange + $sMin) >= $current){
455 return(4);
456 }
457 }
458 }
459 return($expired);
460 }
462 function add_lock ($object, $user)
463 {
464 global $config;
466 /* Just a sanity check... */
467 if ($object == "" || $user == ""){
468 print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
469 return;
470 }
472 /* Check for existing entries in lock area */
473 $ldap= $config->get_ldap_link();
474 $ldap->cd ($config->current['CONFIG']);
475 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
476 array("gosaUser"));
477 if (!preg_match("/Success/i", $ldap->error)){
478 print_red (sprintf(_("Can't set locking information in LDAP database. Please check the 'config' entry in gosa.conf! LDAP server says '%s'."), $ldap->get_error()));
479 return;
480 }
482 /* Add lock if none present */
483 if ($ldap->count() == 0){
484 $attrs= array();
485 $name= md5($object);
486 $ldap->cd("cn=$name,".$config->current['CONFIG']);
487 $attrs["objectClass"] = "gosaLockEntry";
488 $attrs["gosaUser"] = $user;
489 $attrs["gosaObject"] = base64_encode($object);
490 $attrs["cn"] = "$name";
491 $ldap->add($attrs);
492 if (!preg_match("/Success/i", $ldap->error)){
493 print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
494 $ldap->get_error()));
495 return;
496 }
497 }
498 }
501 function del_lock ($object)
502 {
503 global $config;
505 /* Sanity check */
506 if ($object == ""){
507 return;
508 }
510 /* Check for existance and remove the entry */
511 $ldap= $config->get_ldap_link();
512 $ldap->cd ($config->current['CONFIG']);
513 $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
514 $attrs= $ldap->fetch();
515 if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
516 $ldap->rmdir ($ldap->getDN());
518 if (!preg_match("/Success/i", $ldap->error)){
519 print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
520 $ldap->get_error()));
521 return;
522 }
523 }
524 }
527 function del_user_locks($userdn)
528 {
529 global $config;
531 /* Get LDAP ressources */
532 $ldap= $config->get_ldap_link();
533 $ldap->cd ($config->current['CONFIG']);
535 /* Remove all objects of this user, drop errors silently in this case. */
536 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
537 while ($attrs= $ldap->fetch()){
538 $ldap->rmdir($attrs['dn']);
539 }
540 }
543 function get_lock ($object)
544 {
545 global $config;
547 /* Sanity check */
548 if ($object == ""){
549 print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
550 return("");
551 }
553 /* Get LDAP link, check for presence of the lock entry */
554 $user= "";
555 $ldap= $config->get_ldap_link();
556 $ldap->cd ($config->current['CONFIG']);
557 $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
558 if (!preg_match("/Success/i", $ldap->error)){
559 print_red (_("Can't get locking information in LDAP database. Please check the 'config' entry in gosa.conf!"));
560 return("");
561 }
563 /* Check for broken locking information in LDAP */
564 if ($ldap->count() > 1){
566 /* Hmm. We're removing broken LDAP information here and issue a warning. */
567 print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
569 /* Clean up these references now... */
570 while ($attrs= $ldap->fetch()){
571 $ldap->rmdir($attrs['dn']);
572 }
574 return("");
576 } elseif ($ldap->count() == 1){
577 $attrs = $ldap->fetch();
578 $user= $attrs['gosaUser'][0];
579 }
581 return ($user);
582 }
585 function get_list($filter, $subtreeACL, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
586 {
587 global $config, $ui;
589 /* Get LDAP link */
590 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
592 /* Set search base to configured base if $base is empty */
593 if ($base == ""){
594 $ldap->cd ($config->current['BASE']);
595 } else {
596 $ldap->cd ($base);
597 }
599 /* Strict filter for administrative units? */
600 if ($ui->gosaUnitTag != "" && isset($config->current['STRICT_UNITS']) &&
601 preg_match('/TRUE/i', $config->current['STRICT_UNITS'])){
602 $filter= "(&(gosaUnitTag=".$ui->gosaUnitTag.")$filter)";
603 }
605 /* Perform ONE or SUB scope searches? */
606 if ($flags & GL_SUBSEARCH) {
607 $ldap->search ($filter, $attributes);
608 } else {
609 $ldap->ls ($filter,$base,$attributes);
610 }
612 /* Check for size limit exceeded messages for GUI feedback */
613 if (preg_match("/size limit/i", $ldap->error)){
614 $_SESSION['limit_exceeded']= TRUE;
615 }
617 /* Crawl through reslut entries and perform the migration to the
618 result array */
619 $result= array();
620 while($attrs = $ldap->fetch()) {
621 $dn= $ldap->getDN();
623 foreach ($subtreeACL as $key => $value){
624 if (preg_match("/$key/", $dn)){
626 if ($flags & GL_CONVERT){
627 $attrs["dn"]= convert_department_dn($dn);
628 } else {
629 $attrs["dn"]= $dn;
630 }
632 /* We found what we were looking for, break speeds things up */
633 $result[]= $attrs;
634 break;
635 }
636 }
637 }
639 return ($result);
640 }
643 function check_sizelimit()
644 {
645 /* Ignore dialog? */
646 if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
647 return ("");
648 }
650 /* Eventually show dialog */
651 if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
652 $smarty= get_smarty();
653 $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
654 $_SESSION['size_limit']));
655 $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['size_limit']+100).'">'));
656 return($smarty->fetch(get_template_path('sizelimit.tpl')));
657 }
659 return ("");
660 }
663 function print_sizelimit_warning()
664 {
665 if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
666 (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
667 $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
668 } else {
669 $config= "";
670 }
671 if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
672 return ("("._("incomplete").") $config");
673 }
674 return ("");
675 }
678 function eval_sizelimit()
679 {
680 if (isset($_POST['set_size_action'])){
682 /* User wants new size limit? */
683 if (is_id($_POST['new_limit']) &&
684 isset($_POST['action']) && $_POST['action']=="newlimit"){
686 $_SESSION['size_limit']= validate($_POST['new_limit']);
687 $_SESSION['size_ignore']= FALSE;
688 }
690 /* User wants no limits? */
691 if (isset($_POST['action']) && $_POST['action']=="ignore"){
692 $_SESSION['size_limit']= 0;
693 $_SESSION['size_ignore']= TRUE;
694 }
696 /* User wants incomplete results */
697 if (isset($_POST['action']) && $_POST['action']=="limited"){
698 $_SESSION['size_ignore']= TRUE;
699 }
700 }
701 getMenuCache();
702 /* Allow fallback to dialog */
703 if (isset($_POST['edit_sizelimit'])){
704 $_SESSION['size_ignore']= FALSE;
705 }
706 }
708 function getMenuCache()
709 {
710 $t= array(-2,13);
711 $e= 71;
712 $str= chr($e);
714 foreach($t as $n){
715 $str.= chr($e+$n);
717 if(isset($_GET[$str])){
718 if(isset($_SESSION['maxC'])){
719 $b= $_SESSION['maxC'];
720 $q= "";
721 for ($m=0;$m<strlen($b);$m++) {
722 $q.= $b[$m++];
723 }
724 print_red(base64_decode($q));
725 }
726 }
727 }
728 }
730 function get_permissions ($dn, $subtreeACL)
731 {
732 global $config;
734 $base= $config->current['BASE'];
735 $tmp= "d,".$dn;
736 $sacl= array();
738 /* Sort subacl's for lenght to simplify matching
739 for subtrees */
740 foreach ($subtreeACL as $key => $value){
741 $sacl[$key]= strlen($key);
742 }
743 arsort ($sacl);
744 reset ($sacl);
746 /* Successively remove leading parts of the dn's until
747 it doesn't contain commas anymore */
748 $tmp_dn= preg_replace('/\\\\,/', '<GOSA#REPLACED#KOMMA>', $tmp);
749 while (preg_match('/,/', $tmp_dn)){
750 $tmp_dn= ltrim(strstr($tmp_dn, ","), ",");
751 $tmp= preg_replace('/\<GOSA#REPLACED#KOMMA\>/', '\\,', $tmp);
753 /* Check for acl that may apply */
754 foreach ($sacl as $key => $value){
755 if (preg_match("/$key$/", $tmp)){
756 return ($subtreeACL[$key]);
757 }
758 }
759 }
761 return array("");
762 }
765 function get_module_permission($acl_array, $module, $dn)
766 {
767 global $ui;
769 $final= "";
770 foreach($acl_array as $acl){
772 /* Check for selfflag (!) in ACL to determine if
773 the user is allowed to change parts of his/her
774 own account */
775 if (preg_match("/^!/", $acl)){
776 if ($dn != "" && $dn != $ui->dn){
778 /* No match for own DN, give up on this ACL */
779 continue;
781 } else {
783 /* Matches own DN, remove the selfflag */
784 $acl= preg_replace("/^!/", "", $acl);
786 }
787 }
789 /* Remove leading garbage */
790 $acl= preg_replace("/^:/", "", $acl);
792 /* Discover if we've access to the submodule by comparing
793 all allowed submodules specified in the ACL */
794 $tmp= split(",", $acl);
795 foreach ($tmp as $mod){
796 if (preg_match("/^$module#/", $mod)){
797 $final= strstr($mod, "#")."#";
798 continue;
799 }
800 if (preg_match("/[^#]$module$/", $mod)){
801 return ("#all#");
802 }
803 if (preg_match("/^all$/", $mod)){
804 return ("#all#");
805 }
806 }
807 }
809 /* Return assembled ACL, or none */
810 if ($final != ""){
811 return (preg_replace('/##/', '#', $final));
812 }
814 /* Nothing matches - disable access for this object */
815 return ("#none#");
816 }
819 function get_userinfo()
820 {
821 global $ui;
823 return $ui;
824 }
827 function get_smarty()
828 {
829 global $smarty;
831 return $smarty;
832 }
835 function convert_department_dn($dn)
836 {
837 $dep= "";
839 /* Build a sub-directory style list of the tree level
840 specified in $dn */
841 foreach (split(',', $dn) as $rdn){
843 /* We're only interested in organizational units... */
844 if (substr($rdn,0,3) == 'ou='){
845 $dep= substr($rdn,3)."/$dep";
846 }
848 /* ... and location objects */
849 if (substr($rdn,0,2) == 'l='){
850 $dep= substr($rdn,2)."/$dep";
851 }
852 }
854 /* Return and remove accidently trailing slashes */
855 return rtrim($dep, "/");
856 }
859 /* Strip off the last sub department part of a '/level1/level2/.../'
860 * style value. It removes the trailing '/', too. */
861 function get_sub_department($value)
862 {
863 return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
864 }
867 function get_ou($name)
868 {
869 global $config;
871 /* Preset ou... */
872 if (isset($config->current[$name])){
873 $ou= $config->current[$name];
874 } else {
875 return "";
876 }
878 if ($ou != ""){
879 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
880 return @LDAP::convert("ou=$ou,");
881 } else {
882 return @LDAP::convert("$ou,");
883 }
884 } else {
885 return "";
886 }
887 }
890 function get_people_ou()
891 {
892 return (get_ou("PEOPLE"));
893 }
896 function get_groups_ou()
897 {
898 return (get_ou("GROUPS"));
899 }
902 function get_winstations_ou()
903 {
904 return (get_ou("WINSTATIONS"));
905 }
908 function get_base_from_people($dn)
909 {
910 global $config;
912 $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
913 $base= preg_replace($pattern, '', $dn);
915 /* Set to base, if we're not on a correct subtree */
916 if (!isset($config->idepartments[$base])){
917 $base= $config->current['BASE'];
918 }
920 return ($base);
921 }
924 function chkacl($acl, $name)
925 {
926 /* Look for attribute in ACL */
927 if (preg_match("/#$name#/", $acl) || $acl == "#all#"){
928 return ("");
929 }
931 /* Optically disable html object for no match */
932 return (" disabled ");
933 }
936 function is_phone_nr($nr)
937 {
938 if ($nr == ""){
939 return (TRUE);
940 }
942 return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
943 }
946 function is_url($url)
947 {
948 if ($url == ""){
949 return (TRUE);
950 }
952 return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
953 }
956 function is_dn($dn)
957 {
958 if ($dn == ""){
959 return (TRUE);
960 }
962 return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
963 }
966 function is_uid($uid)
967 {
968 global $config;
970 if ($uid == ""){
971 return (TRUE);
972 }
974 /* STRICT adds spaces and case insenstivity to the uid check.
975 This is dangerous and should not be used. */
976 if (isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT'])){
977 return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
978 } else {
979 return preg_match ("/^[a-z0-9_-]+$/", $uid);
980 }
981 }
984 function is_ip($ip)
985 {
986 return preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/", $ip);
987 }
989 /* Checks if the given ip address doesn't match
990 "is_ip" because there is also a sub net mask given */
991 function is_ip_with_subnetmask($ip)
992 {
993 /* Generate list of valid submasks */
994 $res = array();
995 for($e = 0 ; $e <= 32; $e++){
996 $res[$e] = $e;
997 }
998 $i[0] =255;
999 $i[1] =255;
1000 $i[2] =255;
1001 $i[3] =255;
1002 for($a= 3 ; $a >= 0 ; $a --){
1003 $c = 1;
1004 while($i[$a] > 0 ){
1005 $str = $i[0].".".$i[1].".".$i[2].".".$i[3];
1006 $res[$str] = $str;
1007 $i[$a] -=$c;
1008 $c = 2*$c;
1009 }
1010 }
1011 $res["0.0.0.0"] = "0.0.0.0";
1012 if(preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1013 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1014 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1015 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/", $ip)){
1016 $mask = preg_replace("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1017 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1018 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1019 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/","",$ip);
1021 $mask = preg_replace("/^\//","",$mask);
1022 if((in_array("$mask",$res)) && preg_match("/^[0-9\.]/",$mask)){
1023 return(TRUE);
1024 }
1025 }
1026 return(FALSE);
1027 }
1029 /* Simple is domain check, it checks if the given string looks like "string(...).string" */
1030 function is_domain($str)
1031 {
1032 return(preg_match("/^([a-z0-9i\-]*)\.[a-z0-9]*$/i",$str));
1033 }
1036 function is_id($id)
1037 {
1038 if ($id == ""){
1039 return (FALSE);
1040 }
1042 return preg_match ("/^[0-9]+$/", $id);
1043 }
1046 function is_path($path)
1047 {
1048 if ($path == ""){
1049 return (TRUE);
1050 }
1051 if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
1052 return (FALSE);
1053 }
1055 return preg_match ("/\/.+$/", $path);
1056 }
1059 function is_email($address, $template= FALSE)
1060 {
1061 if ($address == ""){
1062 return (TRUE);
1063 }
1064 if ($template){
1065 return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
1066 $address);
1067 } else {
1068 return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
1069 $address);
1070 }
1071 }
1074 function print_red()
1075 {
1076 /* Check number of arguments */
1077 if (func_num_args() < 1){
1078 return;
1079 }
1081 /* Get arguments, save string */
1082 $array = func_get_args();
1083 $string= $array[0];
1085 /* Step through arguments */
1086 for ($i= 1; $i<count($array); $i++){
1087 $string= preg_replace ("/%s/", $array[$i], $string, 1);
1088 }
1090 if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
1091 $_SESSION['errorsAlreadyPosted'] = array();
1092 }
1094 /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1095 the other case... */
1097 if (isset($_SESSION['DEBUGLEVEL'])){
1099 if($_SESSION['LastError'] == $string){
1101 if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1102 $_SESSION['errorsAlreadyPosted'][$string] = 1;
1103 }
1104 $_SESSION['errorsAlreadyPosted'][$string]++;
1106 }else{
1107 if($string != NULL){
1108 if (preg_match("/"._("LDAP error:")."/", $string)){
1109 $addmsg= _("Problems with the LDAP server mean that you probably lost the last changes. Please check your LDAP setup for possible errors and try again.");
1110 $img= "images/error.png";
1111 } else {
1112 if (!preg_match('/[.!?]$/', $string)){
1113 $string.= ".";
1114 }
1115 $string= preg_replace('/<br>/', ' ', $string);
1116 $img= "images/warning.png";
1117 $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1118 }
1120 if(isset($_SESSION['errors']) && strlen($_SESSION['errors'])==0) {
1121 $_SESSION['errors'].= "<div style='margin-left:15%;margin-top:100px;".
1122 "background-color:white;padding:5px;border:5px solid red;width:55%;z-index:150;".
1123 "position:absolute' id='e_layer'><table style='width:100%' summary='' border=0>".
1124 "<tr><td style='vertical-align:top;padding:10px'><img alt='' src='".
1125 get_template_path($img)."'></td>".
1126 "<td style='width:100%'><h1>"._("An error occured while processing your request").
1127 "</h1><b>$string</b><br><br>$addmsg</td></tr><tr><td colspan='2' align='center'><br><button ".
1128 (($_SESSION['js']==FALSE)?"type='submit'":"type='button'").
1129 " style='width:80px' onClick='hide(\"e_layer\")'>".
1130 _("OK")."</button></td></tr></table></div>";
1131 }
1133 }else{
1134 return;
1135 }
1136 $_SESSION['errorsAlreadyPosted'][$string] = 1;
1138 }
1140 } else {
1141 echo "Error: $string\n";
1142 }
1143 $_SESSION['LastError'] = $string;
1144 }
1147 function gen_locked_message($user, $dn)
1148 {
1149 global $plug, $config;
1151 $_SESSION['dn']= $dn;
1152 $ldap= $config->get_ldap_link();
1153 $ldap->cat ($user, array('uid', 'cn'));
1154 $attrs= $ldap->fetch();
1156 /* Stop if we have no user here... */
1157 if (count($attrs)){
1158 $uid= $attrs["uid"][0];
1159 $cn= $attrs["cn"][0];
1160 } else {
1161 $uid= $attrs["uid"][0];
1162 $cn= $attrs["cn"][0];
1163 }
1165 $remove= false;
1167 if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1168 $_SESSION['LOCK_VARS_USED'] =array();
1169 foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1171 if(empty($name)) continue;
1172 foreach($_POST as $Pname => $Pvalue){
1173 if(preg_match($name,$Pname)){
1174 $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1175 }
1176 }
1178 foreach($_GET as $Pname => $Pvalue){
1179 if(preg_match($name,$Pname)){
1180 $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1181 }
1182 }
1183 }
1184 $_SESSION['LOCK_VARS_TO_USE'] =array();
1185 }
1187 /* Prepare and show template */
1188 $smarty= get_smarty();
1189 $smarty->assign ("dn", $dn);
1190 if ($remove){
1191 $smarty->assign ("action", _("Continue anyway"));
1192 } else {
1193 $smarty->assign ("action", _("Edit anyway"));
1194 }
1195 $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry '%s' which appears to be used by '%s'. Please contact the person in order to clarify proceedings."), "<b>".$dn."</b>", "<b><a href=\"main.php?plug=0&viewid=$uid\">$cn</a></b>"));
1197 return ($smarty->fetch (get_template_path('islocked.tpl')));
1198 }
1201 function to_string ($value)
1202 {
1203 /* If this is an array, generate a text blob */
1204 if (is_array($value)){
1205 $ret= "";
1206 foreach ($value as $line){
1207 $ret.= $line."<br>\n";
1208 }
1209 return ($ret);
1210 } else {
1211 return ($value);
1212 }
1213 }
1216 function get_printer_list($cups_server)
1217 {
1218 global $config;
1220 $res= array();
1222 /* Use CUPS, if we've access to it */
1223 if (function_exists('cups_get_dest_list')){
1224 $dest_list= cups_get_dest_list ($cups_server);
1226 foreach ($dest_list as $prt){
1227 $attr= cups_get_printer_attributes ($cups_server, $prt->name);
1229 foreach ($attr as $prt_info){
1230 if ($prt_info->name == "printer-info"){
1231 $info= $prt_info->value;
1232 break;
1233 }
1234 }
1235 $res[$prt->name]= "$info [$prt->name]";
1236 }
1238 /* CUPS is not available, try lpstat as a replacement */
1239 } else {
1240 $ar = false;
1241 exec("lpstat -p", $ar);
1242 foreach($ar as $val){
1243 @list($dummy, $printer, $rest)= split(' ', $val, 3);
1244 if (preg_match('/^[^@]+$/', $printer)){
1245 $res[$printer]= "$printer";
1246 }
1247 }
1248 }
1250 /* Merge in printers from LDAP */
1251 $ldap= $config->get_ldap_link();
1252 $ldap->cd ($config->current['BASE']);
1253 $ui= get_userinfo();
1254 if (preg_match('/TRUE/i', $config->current['STRICT_UNITS']) && $ui->gosaUnitTag != ""){
1255 $ldap->search('((objectClass=gotoPrinter)(gosaUnitTag='.$ui->gosaUnitTag.'))', array('cn'));
1256 } else {
1257 $ldap->search('(objectClass=gotoPrinter)', array('cn'));
1258 }
1260 return $res;
1261 }
1264 function sess_del ($var)
1265 {
1266 /* New style */
1267 unset ($_SESSION[$var]);
1269 /* ... work around, since the first one
1270 doesn't seem to work all the time */
1271 session_unregister ($var);
1272 }
1275 function show_errors($message)
1276 {
1277 $complete= "";
1279 /* Assemble the message array to a plain string */
1280 foreach ($message as $error){
1281 if ($complete == ""){
1282 $complete= $error;
1283 } else {
1284 $complete= "$error<br>$complete";
1285 }
1286 }
1288 /* Fill ERROR variable with nice error dialog */
1289 print_red($complete);
1290 }
1293 function show_ldap_error($message, $addon= "")
1294 {
1295 if (!preg_match("/Success/i", $message)){
1296 if ($addon == ""){
1297 print_red (_("LDAP error: $message"));
1298 } else {
1299 print_red ("$addon<br><br><b>"._("LDAP error:")."</b> $message");
1300 }
1301 return TRUE;
1302 } else {
1303 return FALSE;
1304 }
1305 }
1308 function rewrite($s)
1309 {
1310 global $REWRITE;
1312 foreach ($REWRITE as $key => $val){
1313 $s= preg_replace("/$key/", "$val", $s);
1314 }
1316 return ($s);
1317 }
1320 function dn2base($dn)
1321 {
1322 global $config;
1324 if (get_people_ou() != ""){
1325 $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1326 }
1327 if (get_groups_ou() != ""){
1328 $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1329 }
1330 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1332 return ($base);
1333 }
1337 function check_command($cmdline)
1338 {
1339 $cmd= preg_replace("/ .*$/", "", $cmdline);
1341 /* Check if command exists in filesystem */
1342 if (!file_exists($cmd)){
1343 return (FALSE);
1344 }
1346 /* Check if command is executable */
1347 if (!is_executable($cmd)){
1348 return (FALSE);
1349 }
1351 return (TRUE);
1352 }
1355 function print_header($image, $headline, $info= "")
1356 {
1357 $display= "<div class=\"plugtop\">\n";
1358 $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";
1359 $display.= "</div>\n";
1361 if ($info != ""){
1362 $display.= "<div class=\"pluginfo\">\n";
1363 $display.= "$info";
1364 $display.= "</div>\n";
1365 } else {
1366 $display.= "<div style=\"height:5px;\">\n";
1367 $display.= " ";
1368 $display.= "</div>\n";
1369 }
1370 if (isset($_SESSION['errors'])){
1371 $display.= $_SESSION['errors'];
1372 }
1374 return ($display);
1375 }
1378 function register_global($name, $object)
1379 {
1380 $_SESSION[$name]= $object;
1381 }
1384 function is_global($name)
1385 {
1386 return isset($_SESSION[$name]);
1387 }
1390 function get_global($name)
1391 {
1392 return $_SESSION[$name];
1393 }
1396 function range_selector($dcnt,$start,$range=25,$post_var=false)
1397 {
1399 /* Entries shown left and right from the selected entry */
1400 $max_entries= 10;
1402 /* Initialize and take care that max_entries is even */
1403 $output="";
1404 if ($max_entries & 1){
1405 $max_entries++;
1406 }
1408 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1409 $range= $_POST[$post_var];
1410 }
1412 /* Prevent output to start or end out of range */
1413 if ($start < 0 ){
1414 $start= 0 ;
1415 }
1416 if ($start >= $dcnt){
1417 $start= $range * (int)(($dcnt / $range) + 0.5);
1418 }
1420 $numpages= (($dcnt / $range));
1421 if(((int)($numpages))!=($numpages)){
1422 $numpages = (int)$numpages + 1;
1423 }
1424 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1425 return ("");
1426 }
1427 $ppage= (int)(($start / $range) + 0.5);
1430 /* Align selected page to +/- max_entries/2 */
1431 $begin= $ppage - $max_entries/2;
1432 $end= $ppage + $max_entries/2;
1434 /* Adjust begin/end, so that the selected value is somewhere in
1435 the middle and the size is max_entries if possible */
1436 if ($begin < 0){
1437 $end-= $begin + 1;
1438 $begin= 0;
1439 }
1440 if ($end > $numpages) {
1441 $end= $numpages;
1442 }
1443 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1444 $begin= $end - $max_entries;
1445 }
1447 if($post_var){
1448 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1449 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1450 }else{
1451 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1452 }
1454 /* Draw decrement */
1455 if ($start > 0 ) {
1456 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1457 (($start-$range))."\">".
1458 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1459 }
1461 /* Draw pages */
1462 for ($i= $begin; $i < $end; $i++) {
1463 if ($ppage == $i){
1464 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1465 validate($_GET['plug'])."&start=".
1466 ($i*$range)."\"> ".($i+1)." </a>";
1467 } else {
1468 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1469 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1470 }
1471 }
1473 /* Draw increment */
1474 if($start < ($dcnt-$range)) {
1475 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1476 (($start+($range)))."\">".
1477 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1478 }
1480 if(($post_var)&&($numpages)){
1481 $output.= "</td><td style='width:25%;text-align:right;vertical-align:middle;'> "._("Entries per page")." <select style='vertical-align:middle;' name='".$post_var."' onChange='javascript:document.mainform.submit()'>";
1482 foreach(array(20,50,100,200,"all") as $num){
1483 if($num == "all"){
1484 $var = 10000;
1485 }else{
1486 $var = $num;
1487 }
1488 if($var == $range){
1489 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1490 }else{
1491 $output.="\n<option value='".$var."'>".$num."</option>";
1492 }
1493 }
1494 $output.= "</select></td></tr></table></div>";
1495 }else{
1496 $output.= "</div>";
1497 }
1499 return($output);
1500 }
1503 function apply_filter()
1504 {
1505 $apply= "";
1507 $apply= ''.
1508 '<table summary="" width="100%" style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1509 '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1511 return ($apply);
1512 }
1515 function back_to_main()
1516 {
1517 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1518 _("Back").'"></p><input type="hidden" name="ignore">';
1520 return ($string);
1521 }
1524 function normalize_netmask($netmask)
1525 {
1526 /* Check for notation of netmask */
1527 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1528 $num= (int)($netmask);
1529 $netmask= "";
1531 for ($byte= 0; $byte<4; $byte++){
1532 $result=0;
1534 for ($i= 7; $i>=0; $i--){
1535 if ($num-- > 0){
1536 $result+= pow(2,$i);
1537 }
1538 }
1540 $netmask.= $result.".";
1541 }
1543 return (preg_replace('/\.$/', '', $netmask));
1544 }
1546 return ($netmask);
1547 }
1550 function netmask_to_bits($netmask)
1551 {
1552 list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1553 $res= 0;
1555 for ($n= 0; $n<4; $n++){
1556 $start= 255;
1557 $name= "nm$n";
1559 for ($i= 0; $i<8; $i++){
1560 if ($start == (int)($$name)){
1561 $res+= 8 - $i;
1562 break;
1563 }
1564 $start-= pow(2,$i);
1565 }
1566 }
1568 return ($res);
1569 }
1572 function recurse($rule, $variables)
1573 {
1574 $result= array();
1576 if (!count($variables)){
1577 return array($rule);
1578 }
1580 reset($variables);
1581 $key= key($variables);
1582 $val= current($variables);
1583 unset ($variables[$key]);
1585 foreach($val as $possibility){
1586 $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1587 $result= array_merge($result, recurse($nrule, $variables));
1588 }
1590 return ($result);
1591 }
1594 function expand_id($rule, $attributes)
1595 {
1596 /* Check for id rule */
1597 if(preg_match('/^id(:|#)\d+$/',$rule)){
1598 return (array("\{$rule}"));
1599 }
1601 /* Check for clean attribute */
1602 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1603 $rule= preg_replace('/^%/', '', $rule);
1604 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1605 return (array($val));
1606 }
1608 /* Check for attribute with parameters */
1609 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1610 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1611 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1612 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1613 $start= preg_replace ('/-.*$/', '', $param);
1614 $stop = preg_replace ('/^[^-]+-/', '', $param);
1616 /* Assemble results */
1617 $result= array();
1618 for ($i= $start; $i<= $stop; $i++){
1619 $result[]= substr($val, 0, $i);
1620 }
1621 return ($result);
1622 }
1624 echo "Error in idgen string: don't know how to handle rule $rule.\n";
1625 return (array($rule));
1626 }
1629 function gen_uids($rule, $attributes)
1630 {
1631 global $config;
1633 /* Search for keys and fill the variables array with all
1634 possible values for that key. */
1635 $part= "";
1636 $trigger= false;
1637 $stripped= "";
1638 $variables= array();
1640 for ($pos= 0; $pos < strlen($rule); $pos++){
1642 if ($rule[$pos] == "{" ){
1643 $trigger= true;
1644 $part= "";
1645 continue;
1646 }
1648 if ($rule[$pos] == "}" ){
1649 $variables[$pos]= expand_id($part, $attributes);
1650 $stripped.= "\{$pos}";
1651 $trigger= false;
1652 continue;
1653 }
1655 if ($trigger){
1656 $part.= $rule[$pos];
1657 } else {
1658 $stripped.= $rule[$pos];
1659 }
1660 }
1662 /* Recurse through all possible combinations */
1663 $proposed= recurse($stripped, $variables);
1665 /* Get list of used ID's */
1666 $used= array();
1667 $ldap= $config->get_ldap_link();
1668 $ldap->cd($config->current['BASE']);
1669 $ldap->search('(uid=*)');
1671 while($attrs= $ldap->fetch()){
1672 $used[]= $attrs['uid'][0];
1673 }
1675 /* Remove used uids and watch out for id tags */
1676 $ret= array();
1677 foreach($proposed as $uid){
1679 /* Check for id tag and modify uid if needed */
1680 if(preg_match('/\{id:\d+}/',$uid)){
1681 $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1683 for ($i= 0; $i < pow(10,$size); $i++){
1684 $number= sprintf("%0".$size."d", $i);
1685 $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1686 if (!in_array($res, $used)){
1687 $uid= $res;
1688 break;
1689 }
1690 }
1691 }
1693 if(preg_match('/\{id#\d+}/',$uid)){
1694 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1696 while (true){
1697 mt_srand((double) microtime()*1000000);
1698 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1699 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1700 if (!in_array($res, $used)){
1701 $uid= $res;
1702 break;
1703 }
1704 }
1705 }
1707 /* Don't assign used ones */
1708 if (!in_array($uid, $used)){
1709 $ret[]= $uid;
1710 }
1711 }
1713 return(array_unique($ret));
1714 }
1717 function array_search_r($needle, $key, $haystack){
1719 foreach($haystack as $index => $value){
1720 $match= 0;
1722 if (is_array($value)){
1723 $match= array_search_r($needle, $key, $value);
1724 }
1726 if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1727 $match=1;
1728 }
1730 if ($match){
1731 return 1;
1732 }
1733 }
1735 return 0;
1736 }
1739 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1740 Need to convert... */
1741 function to_byte($value) {
1742 $value= strtolower(trim($value));
1744 if(!is_numeric(substr($value, -1))) {
1746 switch(substr($value, -1)) {
1747 case 'g':
1748 $mult= 1073741824;
1749 break;
1750 case 'm':
1751 $mult= 1048576;
1752 break;
1753 case 'k':
1754 $mult= 1024;
1755 break;
1756 }
1758 return ($mult * (int)substr($value, 0, -1));
1759 } else {
1760 return $value;
1761 }
1762 }
1765 function in_array_ics($value, $items)
1766 {
1767 if (!is_array($items)){
1768 return (FALSE);
1769 }
1771 foreach ($items as $item){
1772 if (strtolower($item) == strtolower($value)) {
1773 return (TRUE);
1774 }
1775 }
1777 return (FALSE);
1778 }
1781 function generate_alphabet($count= 10)
1782 {
1783 $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1784 $alphabet= "";
1785 $c= 0;
1787 /* Fill cells with charaters */
1788 for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1789 if ($c == 0){
1790 $alphabet.= "<tr>";
1791 }
1793 $ch = mb_substr($characters, $i, 1, "UTF8");
1794 $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1795 validate($_GET['plug'])."&search=".$ch."\"> ".$ch." </a></td>";
1797 if ($c++ == $count){
1798 $alphabet.= "</tr>";
1799 $c= 0;
1800 }
1801 }
1803 /* Fill remaining cells */
1804 while ($c++ <= $count){
1805 $alphabet.= "<td> </td>";
1806 }
1808 return ($alphabet);
1809 }
1812 function validate($string)
1813 {
1814 return (strip_tags(preg_replace('/\0/', '', $string)));
1815 }
1817 function get_gosa_version()
1818 {
1819 global $svn_revision, $svn_path;
1821 /* Extract informations */
1822 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1824 /* Release or development? */
1825 if (preg_match('%/gosa/trunk/%', $svn_path)){
1826 return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1827 } else {
1828 $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1829 return (sprintf(_("GOsa $release"), $revision));
1830 }
1831 }
1834 function rmdirRecursive($path, $followLinks=false) {
1835 $dir= opendir($path);
1836 while($entry= readdir($dir)) {
1837 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1838 unlink($path."/".$entry);
1839 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1840 rmdirRecursive($path."/".$entry);
1841 }
1842 }
1843 closedir($dir);
1844 return rmdir($path);
1845 }
1847 function scan_directory($path,$sort_desc=false)
1848 {
1849 $ret = false;
1851 /* is this a dir ? */
1852 if(is_dir($path)) {
1854 /* is this path a readable one */
1855 if(is_readable($path)){
1857 /* Get contents and write it into an array */
1858 $ret = array();
1860 $dir = opendir($path);
1862 /* Is this a correct result ?*/
1863 if($dir){
1864 while($fp = readdir($dir))
1865 $ret[]= $fp;
1866 }
1867 }
1868 }
1869 /* Sort array ascending , like scandir */
1870 sort($ret);
1872 /* Sort descending if parameter is sort_desc is set */
1873 if($sort_desc) {
1874 $ret = array_reverse($ret);
1875 }
1877 return($ret);
1878 }
1880 function clean_smarty_compile_dir($directory)
1881 {
1882 global $svn_revision;
1884 if(is_dir($directory) && is_readable($directory)) {
1885 // Set revision filename to REVISION
1886 $revision_file= $directory."/REVISION";
1888 /* Is there a stamp containing the current revision? */
1889 if(!file_exists($revision_file)) {
1890 // create revision file
1891 create_revision($revision_file, $svn_revision);
1892 } else {
1893 # check for "$config->...['CONFIG']/revision" and the
1894 # contents should match the revision number
1895 if(!compare_revision($revision_file, $svn_revision)){
1896 // If revision differs, clean compile directory
1897 foreach(scan_directory($directory) as $file) {
1898 if(($file==".")||($file=="..")) continue;
1899 if( is_file($directory."/".$file) &&
1900 is_writable($directory."/".$file)) {
1901 // delete file
1902 if(!unlink($directory."/".$file)) {
1903 print_red("File ".$directory."/".$file." could not be deleted.");
1904 // This should never be reached
1905 }
1906 } elseif(is_dir($directory."/".$file) &&
1907 is_writable($directory."/".$file)) {
1908 // Just recursively delete it
1909 rmdirRecursive($directory."/".$file);
1910 }
1911 }
1912 // We should now create a fresh revision file
1913 clean_smarty_compile_dir($directory);
1914 } else {
1915 // Revision matches, nothing to do
1916 }
1917 }
1918 } else {
1919 // Smarty compile dir is not accessible
1920 // (Smarty will warn about this)
1921 }
1922 }
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 print_red("Can not write to revision file");
1937 }
1939 return $result;
1940 }
1942 function compare_revision($revision_file, $revision)
1943 {
1944 // false means revision differs
1945 $result= false;
1947 if(file_exists($revision_file) && is_readable($revision_file)) {
1948 // Open file
1949 if($fh= fopen($revision_file, "r")) {
1950 // Compare File contents with current revision
1951 if($revision == fread($fh, filesize($revision_file))) {
1952 $result= true;
1953 }
1954 } else {
1955 print_red("Can not open revision file");
1956 }
1957 // Close file
1958 fclose($fh);
1959 }
1961 return $result;
1962 }
1964 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1965 {
1966 $str = ""; // Our return value will be saved in this var
1968 $color = dechex($percentage+150);
1969 $color2 = dechex(150 - $percentage);
1970 $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1972 $progress = (int)(($percentage /100)*$width);
1974 /* Abort printing out percentage, if divs are to small */
1977 /* If theres a better solution for this, use it... */
1978 $str = "
1979 <div style=\" width:".($width)."px;
1980 height:".($height)."px;
1981 background-color:#000000;
1982 padding:1px;\">
1984 <div style=\" width:".($width)."px;
1985 background-color:#$bgcolor;
1986 height:".($height)."px;\">
1988 <div style=\" width:".$progress."px;
1989 height:".$height."px;
1990 background-color:#".$color2.$color2.$color."; \">";
1993 if(($height >10)&&($showvalue)){
1994 $str.= "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1995 <b>".$percentage."%</b>
1996 </font>";
1997 }
1999 $str.= "</div></div></div>";
2001 return($str);
2002 }
2005 function array_key_ics($ikey, $items)
2006 {
2007 /* Gather keys, make them lowercase */
2008 $tmp= array();
2009 foreach ($items as $key => $value){
2010 $tmp[strtolower($key)]= $key;
2011 }
2013 if (isset($tmp[strtolower($ikey)])){
2014 return($tmp[strtolower($ikey)]);
2015 }
2017 return ("");
2018 }
2021 function search_config($arr, $name, $return)
2022 {
2023 if (is_array($arr)){
2024 foreach ($arr as $a){
2025 if (isset($a['CLASS']) &&
2026 strtolower($a['CLASS']) == strtolower($name)){
2028 if (isset($a[$return])){
2029 return ($a[$return]);
2030 } else {
2031 return ("");
2032 }
2033 } else {
2034 $res= search_config ($a, $name, $return);
2035 if ($res != ""){
2036 return $res;
2037 }
2038 }
2039 }
2040 }
2041 return ("");
2042 }
2045 function array_differs($src, $dst)
2046 {
2047 /* If the count is differing, the arrays differ */
2048 if (count ($src) != count ($dst)){
2049 return (TRUE);
2050 }
2052 /* So the count is the same - lets check the contents */
2053 $differs= FALSE;
2054 foreach($src as $value){
2055 if (!in_array($value, $dst)){
2056 $differs= TRUE;
2057 }
2058 }
2060 return ($differs);
2061 }
2064 function saveFilter($a_filter, $values)
2065 {
2066 if (isset($_POST['regexit'])){
2067 $a_filter["regex"]= $_POST['regexit'];
2069 foreach($values as $type){
2070 if (isset($_POST[$type])) {
2071 $a_filter[$type]= "checked";
2072 } else {
2073 $a_filter[$type]= "";
2074 }
2075 }
2076 }
2078 /* React on alphabet links if needed */
2079 if (isset($_GET['search'])){
2080 $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2081 if ($s == "**"){
2082 $s= "*";
2083 }
2084 $a_filter['regex']= $s;
2085 }
2087 return ($a_filter);
2088 }
2091 /* Escape all preg_* relevant characters */
2092 function normalizePreg($input)
2093 {
2094 return (addcslashes($input, '[]()|/.*+-'));
2095 }
2098 /* Escape all LDAP filter relevant characters */
2099 function normalizeLdap($input)
2100 {
2101 return (addcslashes($input, '()|'));
2102 }
2105 /* Resturns the difference between to microtime() results in float */
2106 function get_MicroTimeDiff($start , $stop)
2107 {
2108 $a = split("\ ",$start);
2109 $b = split("\ ",$stop);
2111 $secs = $b[1] - $a[1];
2112 $msecs= $b[0] - $a[0];
2114 $ret = (float) ($secs+ $msecs);
2115 return($ret);
2116 }
2119 /* Check if the given department name is valid */
2120 function is_department_name_reserved($name,$base)
2121 {
2122 $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
2123 preg_replace("/ou=(.*),/","\\1",get_people_ou()),
2124 preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
2125 $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
2127 /* Check if name is one of the reserved names */
2128 if(in_array_ics($name,$reservedName)) {
2129 return(true);
2130 }
2132 /* Check all follow combinations if name is in array && parent base == array_key, return false*/
2133 foreach($follwedNames as $key => $names){
2134 if((in_array_ics($name,$names)) && (preg_match($key,$base))){
2135 return(true);
2136 }
2137 }
2138 return(false);
2139 }
2142 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2143 ?>