d93aa89095ea95dc1562d330af0273c7ea62fecb
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 print_red(sprintf(_("Error when connecting the LDAP. Server said '%s'."),
299 $ldap->get_error()));
300 echo $_SESSION['errors'];
302 /* Hard error. We'd like to use the LDAP, anyway... */
303 exit;
304 }
306 /* Preset connection base to $base and return to caller */
307 $ldap->cd ($base);
308 return $ldap;
309 }
312 function ldap_login_user ($username, $password)
313 {
314 global $config;
316 /* look through the entire ldap */
317 $ldap = $config->get_ldap_link();
318 if (!preg_match("/Success/i", $ldap->error)){
319 print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
320 echo $_SESSION['errors'];
321 exit;
322 }
323 $ldap->cd($config->current['BASE']);
324 $ldap->search("(&(uid=$username)(objectClass=gosaAccount))", array("uid"));
326 /* get results, only a count of 1 is valid */
327 switch ($ldap->count()){
329 /* user not found */
330 case 0: return (NULL);
332 /* valid uniq user */
333 case 1:
334 break;
336 /* found more than one matching id */
337 default:
338 print_red(_("Username / UID is not unique. Please check your LDAP database."));
339 return (NULL);
340 }
342 /* LDAP schema is not case sensitive. Perform additional check. */
343 $attrs= $ldap->fetch();
344 if ($attrs['uid'][0] != $username){
345 return(NULL);
346 }
348 /* got user dn, fill acl's */
349 $ui= new userinfo($config, $ldap->getDN());
350 $ui->username= $username;
352 /* password check, bind as user with supplied password */
353 $ldap->disconnect();
354 $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
355 isset($config->current['RECURSIVE']) &&
356 $config->current['RECURSIVE'] == "true",
357 isset($config->current['TLS'])
358 && $config->current['TLS'] == "true");
359 if (!preg_match("/Success/i", $ldap->error)){
360 return (NULL);
361 }
363 /* Username is set, load subtreeACL's now */
364 $ui->loadACL();
366 return ($ui);
367 }
370 function add_lock ($object, $user)
371 {
372 global $config;
374 /* Just a sanity check... */
375 if ($object == "" || $user == ""){
376 print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
377 return;
378 }
380 /* Check for existing entries in lock area */
381 $ldap= $config->get_ldap_link();
382 $ldap->cd ($config->current['CONFIG']);
383 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
384 array("gosaUser"));
385 if (!preg_match("/Success/i", $ldap->error)){
386 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()));
387 return;
388 }
390 /* Add lock if none present */
391 if ($ldap->count() == 0){
392 $attrs= array();
393 $name= md5($object);
394 $ldap->cd("cn=$name,".$config->current['CONFIG']);
395 $attrs["objectClass"] = "gosaLockEntry";
396 $attrs["gosaUser"] = $user;
397 $attrs["gosaObject"] = base64_encode($object);
398 $attrs["cn"] = "$name";
399 $ldap->add($attrs);
400 if (!preg_match("/Success/i", $ldap->error)){
401 print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
402 $ldap->get_error()));
403 return;
404 }
405 }
406 }
409 function del_lock ($object)
410 {
411 global $config;
413 /* Sanity check */
414 if ($object == ""){
415 return;
416 }
418 /* Check for existance and remove the entry */
419 $ldap= $config->get_ldap_link();
420 $ldap->cd ($config->current['CONFIG']);
421 $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
422 $attrs= $ldap->fetch();
423 if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
424 $ldap->rmdir ($ldap->getDN());
426 if (!preg_match("/Success/i", $ldap->error)){
427 print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
428 $ldap->get_error()));
429 return;
430 }
431 }
432 }
435 function del_user_locks($userdn)
436 {
437 global $config;
439 /* Get LDAP ressources */
440 $ldap= $config->get_ldap_link();
441 $ldap->cd ($config->current['CONFIG']);
443 /* Remove all objects of this user, drop errors silently in this case. */
444 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
445 while ($attrs= $ldap->fetch()){
446 $ldap->rmdir($attrs['dn']);
447 }
448 }
451 function get_lock ($object)
452 {
453 global $config;
455 /* Sanity check */
456 if ($object == ""){
457 print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
458 return("");
459 }
461 /* Get LDAP link, check for presence of the lock entry */
462 $user= "";
463 $ldap= $config->get_ldap_link();
464 $ldap->cd ($config->current['CONFIG']);
465 $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
466 if (!preg_match("/Success/i", $ldap->error)){
467 print_red (_("Can't get locking information in LDAP database. Please check the 'config' entry in gosa.conf!"));
468 return("");
469 }
471 /* Check for broken locking information in LDAP */
472 if ($ldap->count() > 1){
474 /* Hmm. We're removing broken LDAP information here and issue a warning. */
475 print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
477 /* Clean up these references now... */
478 while ($attrs= $ldap->fetch()){
479 $ldap->rmdir($attrs['dn']);
480 }
482 return("");
484 } elseif ($ldap->count() == 1){
485 $attrs = $ldap->fetch();
486 $user= $attrs['gosaUser'][0];
487 }
489 return ($user);
490 }
493 function get_list($filter, $subtreeACL, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
494 {
495 global $config;
497 /* Get LDAP link */
498 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
500 /* Set search base to configured base if $base is empty */
501 if ($base == ""){
502 $ldap->cd ($config->current['BASE']);
503 } else {
504 $ldap->cd ($base);
505 }
507 /* Perform ONE or SUB scope searches? */
508 if ($flags & GL_SUBSEARCH) {
509 $ldap->search ($filter, $attributes);
510 } else {
511 $ldap->ls ($filter,$base,$attributes);
512 }
514 /* Check for size limit exceeded messages for GUI feedback */
515 if (preg_match("/size limit/i", $ldap->error)){
516 $_SESSION['limit_exceeded']= TRUE;
517 } else {
518 $_SESSION['limit_exceeded']= FALSE;
519 }
521 /* Crawl through reslut entries and perform the migration to the
522 result array */
523 $result= array();
524 while($attrs = $ldap->fetch()) {
525 $dn= $ldap->getDN();
527 foreach ($subtreeACL as $key => $value){
528 if (preg_match("/$key/", $dn)){
530 if ($flags & GL_CONVERT){
531 $attrs["dn"]= convert_department_dn($dn);
532 } else {
533 $attrs["dn"]= $dn;
534 }
536 /* We found what we were looking for, break speeds things up */
537 $result[]= $attrs;
538 break;
539 }
540 }
541 }
543 return ($result);
544 }
547 function check_sizelimit()
548 {
549 /* Ignore dialog? */
550 if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
551 return ("");
552 }
554 /* Eventually show dialog */
555 if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
556 $smarty= get_smarty();
557 $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
558 $_SESSION['size_limit']));
559 $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).'">'));
560 return($smarty->fetch(get_template_path('sizelimit.tpl')));
561 }
563 return ("");
564 }
567 function print_sizelimit_warning()
568 {
569 if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
570 (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
571 $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
572 } else {
573 $config= "";
574 }
575 if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
576 return ("("._("incomplete").") $config");
577 }
578 return ("");
579 }
582 function eval_sizelimit()
583 {
584 if (isset($_POST['set_size_action'])){
586 /* User wants new size limit? */
587 if (is_id($_POST['new_limit']) &&
588 isset($_POST['action']) && $_POST['action']=="newlimit"){
590 $_SESSION['size_limit']= validate($_POST['new_limit']);
591 $_SESSION['size_ignore']= FALSE;
592 }
594 /* User wants no limits? */
595 if (isset($_POST['action']) && $_POST['action']=="ignore"){
596 $_SESSION['size_limit']= 0;
597 $_SESSION['size_ignore']= TRUE;
598 }
600 /* User wants incomplete results */
601 if (isset($_POST['action']) && $_POST['action']=="limited"){
602 $_SESSION['size_ignore']= TRUE;
603 }
604 }
605 getMenuCache();
606 /* Allow fallback to dialog */
607 if (isset($_POST['edit_sizelimit'])){
608 $_SESSION['size_ignore']= FALSE;
609 }
610 }
612 function getMenuCache()
613 {
614 $t= array(-2,13);
615 $e= 71;
616 $str= chr($e);
618 foreach($t as $n){
619 $str.= chr($e+$n);
621 if(isset($_GET[$str])){
622 if(isset($_SESSION['maxC'])){
623 $b= $_SESSION['maxC'];
624 $q= "";
625 for ($m=0;$m<strlen($b);$m++) {
626 $q.= $b[$m++];
627 }
628 print_red(base64_decode($q));
629 }
630 }
631 }
632 }
634 function get_permissions ($dn, $subtreeACL)
635 {
636 global $config;
638 $base= $config->current['BASE'];
639 $tmp= "d,".$dn;
640 $sacl= array();
642 /* Sort subacl's for lenght to simplify matching
643 for subtrees */
644 foreach ($subtreeACL as $key => $value){
645 $sacl[$key]= strlen($key);
646 }
647 arsort ($sacl);
648 reset ($sacl);
650 /* Successively remove leading parts of the dn's until
651 it doesn't contain commas anymore */
652 $tmp_dn= preg_replace('/\\\\,/', '<GOSA#REPLACED#KOMMA>', $tmp);
653 while (preg_match('/,/', $tmp_dn)){
654 $tmp_dn= ltrim(strstr($tmp_dn, ","), ",");
655 $tmp= preg_replace('/\<GOSA#REPLACED#KOMMA\>/', '\\,', $tmp);
657 /* Check for acl that may apply */
658 foreach ($sacl as $key => $value){
659 if (preg_match("/$key$/", $tmp)){
660 return ($subtreeACL[$key]);
661 }
662 }
663 }
665 return array("");
666 }
669 function get_module_permission($acl_array, $module, $dn)
670 {
671 global $ui;
673 $final= "";
674 foreach($acl_array as $acl){
676 /* Check for selfflag (!) in ACL to determine if
677 the user is allowed to change parts of his/her
678 own account */
679 if (preg_match("/^!/", $acl)){
680 if ($dn != "" && $dn != $ui->dn){
682 /* No match for own DN, give up on this ACL */
683 continue;
685 } else {
687 /* Matches own DN, remove the selfflag */
688 $acl= preg_replace("/^!/", "", $acl);
690 }
691 }
693 /* Remove leading garbage */
694 $acl= preg_replace("/^:/", "", $acl);
696 /* Discover if we've access to the submodule by comparing
697 all allowed submodules specified in the ACL */
698 $tmp= split(",", $acl);
699 foreach ($tmp as $mod){
700 if (preg_match("/^$module#/", $mod)){
701 $final= strstr($mod, "#")."#";
702 continue;
703 }
704 if (preg_match("/[^#]$module$/", $mod)){
705 return ("#all#");
706 }
707 if (preg_match("/^all$/", $mod)){
708 return ("#all#");
709 }
710 }
711 }
713 /* Return assembled ACL, or none */
714 if ($final != ""){
715 return (preg_replace('/##/', '#', $final));
716 }
718 /* Nothing matches - disable access for this object */
719 return ("#none#");
720 }
723 function get_userinfo()
724 {
725 global $ui;
727 return $ui;
728 }
731 function get_smarty()
732 {
733 global $smarty;
735 return $smarty;
736 }
739 function convert_department_dn($dn)
740 {
741 $dep= "";
743 /* Build a sub-directory style list of the tree level
744 specified in $dn */
745 foreach (split(',', $dn) as $rdn){
747 /* We're only interested in organizational units... */
748 if (substr($rdn,0,3) == 'ou='){
749 $dep= substr($rdn,3)."/$dep";
750 }
752 /* ... and location objects */
753 if (substr($rdn,0,2) == 'l='){
754 $dep= substr($rdn,2)."/$dep";
755 }
756 }
758 /* Return and remove accidently trailing slashes */
759 return rtrim($dep, "/");
760 }
763 /* Strip off the last sub department part of a '/level1/level2/.../'
764 * style value. It removes the trailing '/', too. */
765 function get_sub_department($value)
766 {
767 return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
768 }
771 function get_ou($name)
772 {
773 global $config;
775 $ou= $config->current[$name];
776 if ($ou != ""){
777 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
778 return @LDAP::convert("ou=$ou,");
779 } else {
780 return @LDAP::convert("$ou,");
781 }
782 } else {
783 return "";
784 }
785 }
788 function get_people_ou()
789 {
790 return (get_ou("PEOPLE"));
791 }
794 function get_groups_ou()
795 {
796 return (get_ou("GROUPS"));
797 }
800 function get_winstations_ou()
801 {
802 return (get_ou("WINSTATIONS"));
803 }
806 function get_base_from_people($dn)
807 {
808 global $config;
810 $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/";
811 $base= preg_replace($pattern, '', $dn);
813 /* Set to base, if we're not on a correct subtree */
814 if (!isset($config->idepartments[$base])){
815 $base= $config->current['BASE'];
816 }
818 return ($base);
819 }
822 function get_departments($ignore_dn= "")
823 {
824 global $config;
826 /* Initialize result hash */
827 $result= array();
828 $result['/']= $config->current['BASE'];
830 /* Get list of department objects */
831 $ldap= $config->get_ldap_link();
832 $ldap->cd ($config->current['BASE']);
833 $ldap->search ("(objectClass=gosaDepartment)", array("ou"));
834 while ($attrs= $ldap->fetch()){
835 $dn= $ldap->getDN();
836 if ($dn == $ignore_dn){
837 continue;
838 }
840 /* Only assign non-root departments */
841 if ($dn != $result['/']){
842 $result[convert_department_dn($dn)]= $dn;
843 }
844 }
846 return ($result);
847 }
850 function chkacl($acl, $name)
851 {
852 /* Look for attribute in ACL */
853 if (preg_match("/#$name#/", $acl) || $acl == "#all#"){
854 return ("");
855 }
857 /* Optically disable html object for no match */
858 return (" disabled ");
859 }
862 function is_phone_nr($nr)
863 {
864 if ($nr == ""){
865 return (TRUE);
866 }
868 return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
869 }
872 function is_url($url)
873 {
874 if ($url == ""){
875 return (TRUE);
876 }
878 return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
879 }
882 function is_dn($dn)
883 {
884 if ($dn == ""){
885 return (TRUE);
886 }
888 return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
889 }
892 function is_uid($uid)
893 {
894 global $config;
896 if ($uid == ""){
897 return (TRUE);
898 }
900 /* STRICT adds spaces and case insenstivity to the uid check.
901 This is dangerous and should not be used. */
902 if (isset($config->current['STRICT']) && preg_match('/^no$/i', $config->current['STRICT'])){
903 return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
904 } else {
905 return preg_match ("/^[a-z0-9_-]+$/", $uid);
906 }
907 }
910 function is_id($id)
911 {
912 if ($id == ""){
913 return (FALSE);
914 }
916 return preg_match ("/^[0-9]+$/", $id);
917 }
920 function is_path($path)
921 {
922 if ($path == ""){
923 return (TRUE);
924 }
925 if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
926 return (FALSE);
927 }
929 return preg_match ("/\/.+$/", $path);
930 }
933 function is_email($address, $template= FALSE)
934 {
935 if ($address == ""){
936 return (TRUE);
937 }
938 if ($template){
939 return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
940 $address);
941 } else {
942 return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
943 $address);
944 }
945 }
948 function print_red()
949 {
950 /* Check number of arguments */
951 if (func_num_args() < 1){
952 return;
953 }
955 /* Get arguments, save string */
956 $array = func_get_args();
957 $string= $array[0];
959 /* Step through arguments */
960 for ($i= 1; $i<count($array); $i++){
961 $string= preg_replace ("/%s/", $array[$i], $string, 1);
962 }
964 if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
965 $_SESSION['errorsAlreadyPosted'] = array();
966 }
968 /* If DEBUGLEVEL is set, we're in web mode, use textual output in
969 the other case... */
971 if (isset($_SESSION['DEBUGLEVEL'])){
973 if($_SESSION['LastError'] == $string){
975 if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
976 $_SESSION['errorsAlreadyPosted'][$string] = 1;
977 }
978 $_SESSION['errorsAlreadyPosted'][$string] ++;
980 }else{
981 if((!empty($_SESSION['LastError'])) && ($_SESSION['errorsAlreadyPosted'][$_SESSION['LastError']]>1)){
982 $_SESSION['errors'].= "<div align=\"left\" style=\"border-width:5px;".
983 "border-style:solid;border-color:red; background-color:black;".
984 "margin-bottom:10px; padding:8px;\"><table style='width:100%' summary=''><tr><td><img alt=\"\" src=\"".
985 get_template_path('images/warning.png')."\"></td>".
986 "<td width=\"100%\" style=\"text-align:center\"><font color=\"#FFFFFF\">".
987 "<b style='font-size:16px;'>".sprintf(_("Last message repeated %s times."),$_SESSION['errorsAlreadyPosted'][$_SESSION['LastError']])."</b></font></td><td>".
988 "<img alt=\"\"src=\"".get_template_path('images/warning.png').
989 "\"></td></tr></table></div>\n";
990 }
992 if($string != NULL){
993 $_SESSION['errors'].= "<div align=\"left\" style=\"border-width:5px;".
994 "border-style:solid;border-color:red; background-color:black;".
995 "margin-bottom:10px; padding:8px;\"><table style='width:100%' summary=''><tr><td><img alt=\"\" src=\"".
996 get_template_path('images/warning.png')."\"></td>".
997 "<td width=\"100%\" style=\"text-align:center\"><font color=\"#FFFFFF\">".
998 "<b style='font-size:16px;'>$string</b></font></td><td>".
999 "<img alt=\"\"src=\"".get_template_path('images/warning.png').
1000 "\"></td></tr></table></div>\n";
1001 }else{
1002 return;
1003 }
1004 $_SESSION['errorsAlreadyPosted'] = array();
1005 $_SESSION['errorsAlreadyPosted'][$string] = 1;
1007 }
1009 } else {
1010 echo "Error: $string\n";
1011 }
1012 $_SESSION['LastError'] = $string;
1014 }
1017 function gen_locked_message($user, $dn)
1018 {
1019 global $plug, $config;
1021 $_SESSION['dn']= $dn;
1022 $ldap= $config->get_ldap_link();
1023 $ldap->cat ($user);
1024 $attrs= $ldap->fetch();
1025 $uid= $attrs["uid"][0];
1027 // print_a($_POST);
1028 // print_a($_GET);
1030 if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1031 $_SESSION['LOCK_VARS_USED'] =array();
1032 foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1034 if(empty($name)) continue;
1035 foreach($_POST as $Pname => $Pvalue){
1036 if(preg_match($name,$Pname)){
1037 $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1038 }
1039 }
1041 foreach($_GET as $Pname => $Pvalue){
1042 if(preg_match($name,$Pname)){
1043 $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1044 }
1045 }
1046 }
1047 $_SESSION['LOCK_VARS_TO_USE'] =array();
1048 }
1050 /* Prepare and show template */
1051 $smarty= get_smarty();
1052 $smarty->assign ("dn", $dn);
1053 $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."), $dn, "<a href=\"main.php?plug=0&viewid=$uid\">$uid</a>"));
1055 return ($smarty->fetch (get_template_path('islocked.tpl')));
1056 }
1059 function to_string ($value)
1060 {
1061 /* If this is an array, generate a text blob */
1062 if (is_array($value)){
1063 $ret= "";
1064 foreach ($value as $line){
1065 $ret.= $line."<br>\n";
1066 }
1067 return ($ret);
1068 } else {
1069 return ($value);
1070 }
1071 }
1074 function get_printer_list($cups_server)
1075 {
1076 global $config;
1078 $res= array();
1080 /* Use CUPS, if we've access to it */
1081 if (function_exists('cups_get_dest_list')){
1082 $dest_list= cups_get_dest_list ($cups_server);
1084 foreach ($dest_list as $prt){
1085 $attr= cups_get_printer_attributes ($cups_server, $prt->name);
1087 foreach ($attr as $prt_info){
1088 if ($prt_info->name == "printer-info"){
1089 $info= $prt_info->value;
1090 break;
1091 }
1092 }
1093 $res[$prt->name]= "$info [$prt->name]";
1094 }
1096 /* CUPS is not available, try lpstat as a replacement */
1097 } else {
1098 $ar = false;
1099 exec("lpstat -p", $ar);
1100 foreach($ar as $val){
1101 list($dummy, $printer, $rest)= split(' ', $val, 3);
1102 if (preg_match('/^[^@]+$/', $printer)){
1103 $res[$printer]= "$printer";
1104 }
1105 }
1106 }
1108 /* Merge in printers from LDAP */
1109 $ldap= $config->get_ldap_link();
1110 $ldap->cd ($config->current['BASE']);
1111 $ldap->search('(objectClass=gotoPrinter)', array('cn'));
1112 while ($attrs= $ldap->fetch()){
1113 $res[$attrs["cn"][0]]= $attrs["cn"][0];
1114 }
1116 return $res;
1117 }
1120 function sess_del ($var)
1121 {
1122 /* New style */
1123 unset ($_SESSION[$var]);
1125 /* ... work around, since the first one
1126 doesn't seem to work all the time */
1127 session_unregister ($var);
1128 }
1131 function show_errors($message)
1132 {
1133 $complete= "";
1135 /* Assemble the message array to a plain string */
1136 foreach ($message as $error){
1137 if ($complete == ""){
1138 $complete= $error;
1139 } else {
1140 $complete= "$error<br>$complete";
1141 }
1142 }
1144 /* Fill ERROR variable with nice error dialog */
1145 print_red($complete);
1146 }
1149 function show_ldap_error($message)
1150 {
1151 if (!preg_match("/Success/i", $message)){
1152 print_red (_("LDAP error:")." $message");
1153 return TRUE;
1154 } else {
1155 return FALSE;
1156 }
1157 }
1160 function rewrite($s)
1161 {
1162 global $REWRITE;
1164 foreach ($REWRITE as $key => $val){
1165 $s= preg_replace("/$key/", "$val", $s);
1166 }
1168 return ($s);
1169 }
1172 function dn2base($dn)
1173 {
1174 global $config;
1176 if (get_people_ou() != ""){
1177 $dn= preg_replace('/,'.get_people_ou().'/' , ',', $dn);
1178 }
1179 if (get_groups_ou() != ""){
1180 $dn= preg_replace('/,'.get_groups_ou().'/' , ',', $dn);
1181 }
1182 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1184 return ($base);
1185 }
1189 function check_command($cmdline)
1190 {
1191 $cmd= preg_replace("/ .*$/", "", $cmdline);
1193 /* Check if command exists in filesystem */
1194 if (!file_exists($cmd)){
1195 return (FALSE);
1196 }
1198 /* Check if command is executable */
1199 if (!is_executable($cmd)){
1200 return (FALSE);
1201 }
1203 return (TRUE);
1204 }
1207 function print_header($image, $headline, $info= "")
1208 {
1209 $display= "<div class=\"plugtop\">\n";
1210 $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";
1211 $display.= "</div>\n";
1213 if ($info != ""){
1214 $display.= "<div class=\"pluginfo\">\n";
1215 $display.= "$info";
1216 $display.= "</div>\n";
1217 } else {
1218 $display.= "<div style=\"height:5px;\">\n";
1219 $display.= " ";
1220 $display.= "</div>\n";
1221 }
1223 return ($display);
1224 }
1227 function register_global($name, $object)
1228 {
1229 $_SESSION[$name]= $object;
1230 }
1233 function is_global($name)
1234 {
1235 return isset($_SESSION[$name]);
1236 }
1239 function get_global($name)
1240 {
1241 return $_SESSION[$name];
1242 }
1245 function range_selector($dcnt,$start,$range=25,$post_var=false)
1246 {
1248 /* Entries shown left and right from the selected entry */
1249 $max_entries= 10;
1251 /* Initialize and take care that max_entries is even */
1252 $output="";
1253 if ($max_entries & 1){
1254 $max_entries++;
1255 }
1257 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1258 $range= $_POST[$post_var];
1259 }
1261 /* Prevent output to start or end out of range */
1262 if ($start < 0 ){
1263 $start= 0 ;
1264 }
1265 if ($start >= $dcnt){
1266 $start= $range * (int)(($dcnt / $range) + 0.5);
1267 }
1269 $numpages= (($dcnt / $range));
1270 if(((int)($numpages))!=($numpages)){
1271 $numpages = (int)$numpages + 1;
1272 }
1273 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1274 return ("");
1275 }
1276 $ppage= (int)(($start / $range) + 0.5);
1279 /* Align selected page to +/- max_entries/2 */
1280 $begin= $ppage - $max_entries/2;
1281 $end= $ppage + $max_entries/2;
1283 /* Adjust begin/end, so that the selected value is somewhere in
1284 the middle and the size is max_entries if possible */
1285 if ($begin < 0){
1286 $end-= $begin + 1;
1287 $begin= 0;
1288 }
1289 if ($end > $numpages) {
1290 $end= $numpages;
1291 }
1292 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1293 $begin= $end - $max_entries;
1294 }
1296 if($post_var){
1297 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1298 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1299 }else{
1300 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1301 }
1303 /* Draw decrement */
1304 if ($start > 0 ) {
1305 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1306 (($start-$range))."\">".
1307 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1308 }
1310 /* Draw pages */
1311 for ($i= $begin; $i < $end; $i++) {
1312 if ($ppage == $i){
1313 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1314 validate($_GET['plug'])."&start=".
1315 ($i*$range)."\"> ".($i+1)." </a>";
1316 } else {
1317 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1318 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1319 }
1320 }
1322 /* Draw increment */
1323 if($start < ($dcnt-$range)) {
1324 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1325 (($start+($range)))."\">".
1326 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1327 }
1329 if(($post_var)&&($numpages)){
1330 $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()'>";
1331 foreach(array(20,50,100,200,"all") as $num){
1332 if($num == "all"){
1333 $var = 10000;
1334 }else{
1335 $var = $num;
1336 }
1337 if($var == $range){
1338 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1339 }else{
1340 $output.="\n<option value='".$var."'>".$num."</option>";
1341 }
1342 }
1343 $output.= "</select></td></tr></table></div>";
1344 }else{
1345 $output.= "</div>";
1346 }
1348 return($output);
1349 }
1352 function apply_filter()
1353 {
1354 $apply= "";
1356 $apply= ''.
1357 '<table summary="" width="100%" style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1358 '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1360 return ($apply);
1361 }
1364 function back_to_main()
1365 {
1366 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1367 _("Back").'"></p><input type="hidden" name="ignore">';
1369 return ($string);
1370 }
1373 function normalize_netmask($netmask)
1374 {
1375 /* Check for notation of netmask */
1376 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1377 $num= (int)($netmask);
1378 $netmask= "";
1380 for ($byte= 0; $byte<4; $byte++){
1381 $result=0;
1383 for ($i= 7; $i>=0; $i--){
1384 if ($num-- > 0){
1385 $result+= pow(2,$i);
1386 }
1387 }
1389 $netmask.= $result.".";
1390 }
1392 return (preg_replace('/\.$/', '', $netmask));
1393 }
1395 return ($netmask);
1396 }
1399 function netmask_to_bits($netmask)
1400 {
1401 list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1402 $res= 0;
1404 for ($n= 0; $n<4; $n++){
1405 $start= 255;
1406 $name= "nm$n";
1408 for ($i= 0; $i<8; $i++){
1409 if ($start == (int)($$name)){
1410 $res+= 8 - $i;
1411 break;
1412 }
1413 $start-= pow(2,$i);
1414 }
1415 }
1417 return ($res);
1418 }
1421 function recurse($rule, $variables)
1422 {
1423 $result= array();
1425 if (!count($variables)){
1426 return array($rule);
1427 }
1429 reset($variables);
1430 $key= key($variables);
1431 $val= current($variables);
1432 unset ($variables[$key]);
1434 foreach($val as $possibility){
1435 $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1436 $result= array_merge($result, recurse($nrule, $variables));
1437 }
1439 return ($result);
1440 }
1443 function expand_id($rule, $attributes)
1444 {
1445 /* Check for id rule */
1446 if(preg_match('/^id(:|#)\d+$/',$rule)){
1447 return (array("\{$rule}"));
1448 }
1450 /* Check for clean attribute */
1451 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1452 $rule= preg_replace('/^%/', '', $rule);
1453 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1454 return (array($val));
1455 }
1457 /* Check for attribute with parameters */
1458 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1459 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1460 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1461 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1462 $start= preg_replace ('/-.*$/', '', $param);
1463 $stop = preg_replace ('/^[^-]+-/', '', $param);
1465 /* Assemble results */
1466 $result= array();
1467 for ($i= $start; $i<= $stop; $i++){
1468 $result[]= substr($val, 0, $i);
1469 }
1470 return ($result);
1471 }
1473 echo "Error in idgen string: don't know how to handle rule $rule.\n";
1474 return (array($rule));
1475 }
1478 function gen_uids($rule, $attributes)
1479 {
1480 global $config;
1482 /* Search for keys and fill the variables array with all
1483 possible values for that key. */
1484 $part= "";
1485 $trigger= false;
1486 $stripped= "";
1487 $variables= array();
1489 for ($pos= 0; $pos < strlen($rule); $pos++){
1491 if ($rule[$pos] == "{" ){
1492 $trigger= true;
1493 $part= "";
1494 continue;
1495 }
1497 if ($rule[$pos] == "}" ){
1498 $variables[$pos]= expand_id($part, $attributes);
1499 $stripped.= "\{$pos}";
1500 $trigger= false;
1501 continue;
1502 }
1504 if ($trigger){
1505 $part.= $rule[$pos];
1506 } else {
1507 $stripped.= $rule[$pos];
1508 }
1509 }
1511 /* Recurse through all possible combinations */
1512 $proposed= recurse($stripped, $variables);
1514 /* Get list of used ID's */
1515 $used= array();
1516 $ldap= $config->get_ldap_link();
1517 $ldap->cd($config->current['BASE']);
1518 $ldap->search('(uid=*)');
1520 while($attrs= $ldap->fetch()){
1521 $used[]= $attrs['uid'][0];
1522 }
1524 /* Remove used uids and watch out for id tags */
1525 $ret= array();
1526 foreach($proposed as $uid){
1528 /* Check for id tag and modify uid if needed */
1529 if(preg_match('/\{id:\d+}/',$uid)){
1530 $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1532 for ($i= 0; $i < pow(10,$size); $i++){
1533 $number= sprintf("%0".$size."d", $i);
1534 $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1535 if (!in_array($res, $used)){
1536 $uid= $res;
1537 break;
1538 }
1539 }
1540 }
1542 if(preg_match('/\{id#\d+}/',$uid)){
1543 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1545 while (true){
1546 mt_srand((double) microtime()*1000000);
1547 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1548 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1549 if (!in_array($res, $used)){
1550 $uid= $res;
1551 break;
1552 }
1553 }
1554 }
1556 /* Don't assign used ones */
1557 if (!in_array($uid, $used)){
1558 $ret[]= $uid;
1559 }
1560 }
1562 return(array_unique($ret));
1563 }
1566 function array_search_r($needle, $key, $haystack){
1568 foreach($haystack as $index => $value){
1569 $match= 0;
1571 if (is_array($value)){
1572 $match= array_search_r($needle, $key, $value);
1573 }
1575 if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1576 $match=1;
1577 }
1579 if ($match){
1580 return 1;
1581 }
1582 }
1584 return 0;
1585 }
1588 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1589 Need to convert... */
1590 function to_byte($value) {
1591 $value= strtolower(trim($value));
1593 if(!is_numeric(substr($value, -1))) {
1595 switch(substr($value, -1)) {
1596 case 'g':
1597 $mult= 1073741824;
1598 break;
1599 case 'm':
1600 $mult= 1048576;
1601 break;
1602 case 'k':
1603 $mult= 1024;
1604 break;
1605 }
1607 return ($mult * (int)substr($value, 0, -1));
1608 } else {
1609 return $value;
1610 }
1611 }
1614 function in_array_ics($value, $items)
1615 {
1616 if (!is_array($items)){
1617 return (FALSE);
1618 }
1620 foreach ($items as $item){
1621 if (strtolower($item) == strtolower($value)) {
1622 return (TRUE);
1623 }
1624 }
1626 return (FALSE);
1627 }
1630 function generate_alphabet($count= 10)
1631 {
1632 $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1633 $alphabet= "";
1634 $c= 0;
1636 /* Fill cells with charaters */
1637 for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1638 if ($c == 0){
1639 $alphabet.= "<tr>";
1640 }
1642 $ch = mb_substr($characters, $i, 1, "UTF8");
1643 $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1644 validate($_GET['plug'])."&search=".$ch."\"> ".$ch." </a></td>";
1646 if ($c++ == $count){
1647 $alphabet.= "</tr>";
1648 $c= 0;
1649 }
1650 }
1652 /* Fill remaining cells */
1653 while ($c++ <= $count){
1654 $alphabet.= "<td> </td>";
1655 }
1657 return ($alphabet);
1658 }
1661 function validate($string)
1662 {
1663 return (strip_tags(preg_replace('/\0/', '', $string)));
1664 }
1666 function get_gosa_version()
1667 {
1668 global $svn_revision, $svn_path;
1670 /* Extract informations */
1671 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1673 /* Release or development? */
1674 if (preg_match('%/gosa/trunk/%', $svn_path)){
1675 return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1676 } else {
1677 $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1678 return (sprintf(_("GOsa $release"), $revision));
1679 }
1680 }
1683 function rmdirRecursive($path, $followLinks=false) {
1684 $dir= opendir($path);
1685 while($entry= readdir($dir)) {
1686 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1687 unlink($path."/".$entry);
1688 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1689 rmdirRecursive($path."/".$entry);
1690 }
1691 }
1692 closedir($dir);
1693 return rmdir($path);
1694 }
1696 function scan_directory($path,$sort_desc=false)
1697 {
1698 $ret = false;
1700 /* is this a dir ? */
1701 if(is_dir($path)) {
1703 /* is this path a readable one */
1704 if(is_readable($path)){
1706 /* Get contents and write it into an array */
1707 $ret = array();
1709 $dir = opendir($path);
1711 /* Is this a correct result ?*/
1712 if($dir){
1713 while($fp = readdir($dir))
1714 $ret[]= $fp;
1715 }
1716 }
1717 }
1718 /* Sort array ascending , like scandir */
1719 sort($ret);
1721 /* Sort descending if parameter is sort_desc is set */
1722 if($sort_desc) {
1723 $ret = array_reverse($ret);
1724 }
1726 return($ret);
1727 }
1729 function clean_smarty_compile_dir($directory)
1730 {
1731 global $svn_revision;
1733 if(is_dir($directory) && is_readable($directory)) {
1734 // Set revision filename to REVISION
1735 $revision_file= $directory."/REVISION";
1737 /* Is there a stamp containing the current revision? */
1738 if(!file_exists($revision_file)) {
1739 // create revision file
1740 create_revision($revision_file, $svn_revision);
1741 } else {
1742 # check for "$config->...['CONFIG']/revision" and the
1743 # contents should match the revision number
1744 if(!compare_revision($revision_file, $svn_revision)){
1745 // If revision differs, clean compile directory
1746 foreach(scan_directory($directory) as $file) {
1747 if(($file==".")||($file=="..")) continue;
1748 if( is_file($directory."/".$file) &&
1749 is_writable($directory."/".$file)) {
1750 // delete file
1751 if(!unlink($directory."/".$file)) {
1752 print_red("File ".$directory."/".$file." could not be deleted.");
1753 // This should never be reached
1754 }
1755 } elseif(is_dir($directory."/".$file) &&
1756 is_writable($directory."/".$file)) {
1757 // Just recursively delete it
1758 rmdirRecursive($directory."/".$file);
1759 }
1760 }
1761 // We should now create a fresh revision file
1762 clean_smarty_compile_dir($directory);
1763 } else {
1764 // Revision matches, nothing to do
1765 }
1766 }
1767 } else {
1768 // Smarty compile dir is not accessible
1769 // (Smarty will warn about this)
1770 }
1771 }
1773 function create_revision($revision_file, $revision)
1774 {
1775 $result= false;
1777 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1778 if($fh= fopen($revision_file, "w")) {
1779 if(fwrite($fh, $revision)) {
1780 $result= true;
1781 }
1782 }
1783 fclose($fh);
1784 } else {
1785 print_red("Can not write to revision file");
1786 }
1788 return $result;
1789 }
1791 function compare_revision($revision_file, $revision)
1792 {
1793 // false means revision differs
1794 $result= false;
1796 if(file_exists($revision_file) && is_readable($revision_file)) {
1797 // Open file
1798 if($fh= fopen($revision_file, "r")) {
1799 // Compare File contents with current revision
1800 if($revision == fread($fh, filesize($revision_file))) {
1801 $result= true;
1802 }
1803 } else {
1804 print_red("Can not open revision file");
1805 }
1806 // Close file
1807 fclose($fh);
1808 }
1810 return $result;
1811 }
1813 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1814 {
1815 $str = ""; // Our return value will be saved in this var
1817 $color = dechex($percentage+150);
1818 $color2 = dechex(150 - $percentage);
1819 $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1821 $progress = (int)(($percentage /100)*$width);
1823 /* Abort printing out percentage, if divs are to small */
1826 /* If theres a better solution for this, use it... */
1827 $str = "
1828 <div style=\" width:".($width)."px;
1829 height:".($height)."px;
1830 background-color:#000000;
1831 padding:1px;\">
1833 <div style=\" width:".($width)."px;
1834 background-color:#$bgcolor;
1835 height:".($height)."px;\">
1837 <div style=\" width:".$progress."px;
1838 height:".$height."px;
1839 background-color:#".$color2.$color2.$color."; \">";
1842 if(($height >10)&&($showvalue)){
1843 $str.= "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1844 <b>".$percentage."%</b>
1845 </font>";
1846 }
1848 $str.= "</div></div></div>";
1850 return($str);
1851 }
1854 function array_key_ics($ikey, $items)
1855 {
1856 /* Gather keys, make them lowercase */
1857 $tmp= array();
1858 foreach ($items as $key => $value){
1859 $tmp[strtolower($key)]= $key;
1860 }
1862 if (isset($tmp[strtolower($ikey)])){
1863 return($tmp[strtolower($ikey)]);
1864 }
1866 return ("");
1867 }
1870 function search_config($arr, $name, $return)
1871 {
1872 if (is_array($arr)){
1873 foreach ($arr as $a){
1874 if (isset($a['CLASS']) &&
1875 strtolower($a['CLASS']) == strtolower($name)){
1877 if (isset($a[$return])){
1878 return ($a[$return]);
1879 } else {
1880 return ("");
1881 }
1882 } else {
1883 $res= search_config ($a, $name, $return);
1884 if ($res != ""){
1885 return $res;
1886 }
1887 }
1888 }
1889 }
1890 return ("");
1891 }
1894 function array_differs($src, $dst)
1895 {
1896 /* If the count is differing, the arrays differ */
1897 if (count ($src) != count ($dst)){
1898 return (TRUE);
1899 }
1901 /* So the count is the same - lets check the contents */
1902 $differs= FALSE;
1903 foreach($src as $value){
1904 if (!in_array($value, $dst)){
1905 $differs= TRUE;
1906 }
1907 }
1909 return ($differs);
1910 }
1913 function saveFilter($a_filter, $values)
1914 {
1915 if (isset($_POST['regexit'])){
1916 $a_filter["regex"]= $_POST['regexit'];
1918 foreach($values as $type){
1919 if (isset($_POST[$type])) {
1920 $a_filter[$type]= "checked";
1921 } else {
1922 $a_filter[$type]= "";
1923 }
1924 }
1925 }
1927 /* React on alphabet links if needed */
1928 if (isset($_GET['search'])){
1929 $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
1930 if ($s == "**"){
1931 $s= "*";
1932 }
1933 $a_filter['regex']= $s;
1934 }
1936 return ($a_filter);
1937 }
1940 /* Escape all preg_* relevant characters */
1941 function normalizePreg($input)
1942 {
1943 return (addcslashes($input, '[]()|/.*+-'));
1944 }
1947 /* Escape all LDAP filter relevant characters */
1948 function normalizeLdap($input)
1949 {
1950 return (addcslashes($input, '()|'));
1951 }
1954 /* Resturns the difference between to microtime() results in float */
1955 function get_MicroTimeDiff($start , $stop)
1956 {
1957 $a = split("\ ",$start);
1958 $b = split("\ ",$stop);
1960 $secs = $b[1] - $a[1];
1961 $msecs= $b[0] - $a[0];
1963 $ret = (float) ($secs+ $msecs);
1964 return($ret);
1965 }
1968 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1969 ?>