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 globals for revision comparing */
27 $svn_path = '$HeadURL$';
28 $svn_revision = '$Revision$';
30 /* Include required files */
31 require_once ("class_ldap.inc");
32 require_once ("class_config.inc");
33 require_once ("class_userinfo.inc");
34 require_once ("class_plugin.inc");
35 require_once ("class_pluglist.inc");
36 require_once ("class_tabs.inc");
37 require_once ("class_mail-methods.inc");
38 require_once("class_password-methods.inc");
39 require_once ("functions_debug.inc");
40 require_once ("functions_dns.inc");
41 require_once ("class_MultiSelectWindow.inc");
43 /* Define constants for debugging */
44 define ("DEBUG_TRACE", 1);
45 define ("DEBUG_LDAP", 2);
46 define ("DEBUG_MYSQL", 4);
47 define ("DEBUG_SHELL", 8);
48 define ("DEBUG_POST", 16);
49 define ("DEBUG_SESSION",32);
50 define ("DEBUG_CONFIG", 64);
52 /* Rewrite german 'umlauts' and spanish 'accents'
53 to get better results */
54 $REWRITE= array( "ä" => "ae",
55 "ö" => "oe",
56 "ü" => "ue",
57 "Ä" => "Ae",
58 "Ö" => "Oe",
59 "Ü" => "Ue",
60 "ß" => "ss",
61 "á" => "a",
62 "é" => "e",
63 "í" => "i",
64 "ó" => "o",
65 "ú" => "u",
66 "Á" => "A",
67 "É" => "E",
68 "Í" => "I",
69 "Ó" => "O",
70 "Ú" => "U",
71 "ñ" => "ny",
72 "Ñ" => "Ny" );
75 /* Function to include all class_ files starting at a
76 given directory base */
77 function get_dir_list($folder= ".")
78 {
79 $currdir=getcwd();
80 if ($folder){
81 chdir("$folder");
82 }
84 $dh = opendir(".");
85 while(false !== ($file = readdir($dh))){
87 // Smarty is included by include/php_setup.inc require("smarty/Smarty.class.php");
88 // Skip all files and dirs in "./.svn/" we don't need any information from them
89 // Skip all Template, so they won't be checked twice in the following preg_matches
90 // Skip . / ..
92 // Result : from 1023 ms to 490 ms i think thats great...
93 if(preg_match("/.*\.svn.*/i",$file)||preg_match("/.*smarty.*/i",$file)||preg_match("/.*\.tpl.*/",$file)||($file==".")||($file==".."))
94 continue;
97 /* Recurse through all "common" directories */
98 if(is_dir($file) &&$file!="CVS"){
99 get_dir_list($file);
100 continue;
101 }
103 /* Include existing class_ files */
104 if (!is_dir($file) && preg_match("/^class_.*\.inc$/", $file)) {
105 require_once($file);
106 }
107 }
109 closedir($dh);
110 chdir($currdir);
111 }
114 /* Create seed with microseconds */
115 function make_seed() {
116 list($usec, $sec) = explode(' ', microtime());
117 return (float) $sec + ((float) $usec * 100000);
118 }
121 /* Debug level action */
122 function DEBUG($level, $line, $function, $file, $data, $info="")
123 {
124 if ($_SESSION['DEBUGLEVEL'] & $level){
125 $output= "DEBUG[$level] ";
126 if ($function != ""){
127 $output.= "($file:$function():$line) - $info: ";
128 } else {
129 $output.= "($file:$line) - $info: ";
130 }
131 echo $output;
132 if (is_array($data)){
133 print_a($data);
134 } else {
135 echo "'$data'";
136 }
137 echo "<br>";
138 }
139 }
142 /* Simple function to get browser language and convert it to
143 xx_XY needed by locales. Ignores sublanguages and weights. */
144 function get_browser_language()
145 {
146 global $BASE_DIR;
148 /* Try to use users primary language */
149 $ui= get_userinfo();
150 if ($ui != NULL){
151 if ($ui->language != ""){
152 return ($ui->language);
153 }
154 }
156 /* Get list of languages */
157 if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
158 $lang= preg_replace("/\s+/", "", $_SERVER['HTTP_ACCEPT_LANGUAGE']);
159 $languages= split (',', $lang);
160 $languages[]= "C";
161 } else {
162 $languages= array("C");
163 }
165 /* Walk through languages and get first supported */
166 foreach ($languages as $val){
168 /* Strip off weight */
169 $lang= preg_replace("/;q=.*$/i", "", $val);
171 /* Simplify sub language handling */
172 $lang= preg_replace("/-.*$/", "", $lang);
174 /* Cancel loop if available in GOsa, or the last
175 entry has been reached */
176 if (is_dir("$BASE_DIR/locale/$lang")){
177 break;
178 }
179 }
181 return (strtolower($lang)."_".strtoupper($lang));
182 }
185 /* Rewrite ui object to another dn */
186 function change_ui_dn($dn, $newdn)
187 {
188 $ui= $_SESSION['ui'];
189 if ($ui->dn == $dn){
190 $ui->dn= $newdn;
191 $_SESSION['ui']= $ui;
192 }
193 }
196 /* Return theme path for specified file */
197 function get_template_path($filename= '', $plugin= FALSE, $path= "")
198 {
199 global $config, $BASE_DIR;
201 if (!@isset($config->data['MAIN']['THEME'])){
202 $theme= 'default';
203 } else {
204 $theme= $config->data['MAIN']['THEME'];
205 }
207 /* Return path for empty filename */
208 if ($filename == ''){
209 return ("themes/$theme/");
210 }
212 /* Return plugin dir or root directory? */
213 if ($plugin){
214 if ($path == ""){
215 $nf= preg_replace("!^".$BASE_DIR."/!", "", $_SESSION['plugin_dir']);
216 } else {
217 $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
218 }
219 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
220 return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
221 }
222 if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
223 return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
224 }
225 if ($path == ""){
226 return ($_SESSION['plugin_dir']."/$filename");
227 } else {
228 return ($path."/$filename");
229 }
230 } else {
231 if (file_exists("themes/$theme/$filename")){
232 return ("themes/$theme/$filename");
233 }
234 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
235 return ("$BASE_DIR/ihtml/themes/$theme/$filename");
236 }
237 if (file_exists("themes/default/$filename")){
238 return ("themes/default/$filename");
239 }
240 if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
241 return ("$BASE_DIR/ihtml/themes/default/$filename");
242 }
243 return ($filename);
244 }
245 }
248 function array_remove_entries($needles, $haystack)
249 {
250 $tmp= array();
252 /* Loop through entries to be removed */
253 foreach ($haystack as $entry){
254 if (!in_array($entry, $needles)){
255 $tmp[]= $entry;
256 }
257 }
259 return ($tmp);
260 }
263 function gosa_log ($message)
264 {
265 global $ui;
267 /* Preset to something reasonable */
268 $username= " unauthenticated";
270 /* Replace username if object is present */
271 if (isset($ui)){
272 if ($ui->username != ""){
273 $username= "[$ui->username]";
274 } else {
275 $username= "unknown";
276 }
277 }
279 syslog(LOG_INFO,"GOsa$username: $message");
280 }
283 function ldap_init ($server, $base, $binddn='', $pass='')
284 {
285 global $config;
287 $ldap = new LDAP ($binddn, $pass, $server, isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
288 isset($config->current['TLS']) && $config->current['TLS'] == "true");
290 /* Sadly we've no proper return values here. Use the error message instead. */
291 if (!preg_match("/Success/i", $ldap->error)){
292 print_red(sprintf(_("Error when connecting the LDAP. Server said '%s'."),
293 $ldap->get_error()));
294 echo $_SESSION['errors'];
296 /* Hard error. We'd like to use the LDAP, anyway... */
297 exit;
298 }
300 /* Preset connection base to $base and return to caller */
301 $ldap->cd ($base);
302 return $ldap;
303 }
306 function ldap_login_user ($username, $password)
307 {
308 global $config;
310 /* look through the entire ldap */
311 $ldap = $config->get_ldap_link();
312 if (!preg_match("/Success/i", $ldap->error)){
313 print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
314 echo $_SESSION['errors'];
315 exit;
316 }
317 $ldap->cd($config->current['BASE']);
318 $ldap->search("(&(uid=$username)(objectClass=gosaAccount))", array("uid"));
320 /* get results, only a count of 1 is valid */
321 switch ($ldap->count()){
323 /* user not found */
324 case 0: return (NULL);
326 /* valid uniq user */
327 case 1:
328 break;
330 /* found more than one matching id */
331 default:
332 print_red(_("Username / UID is not unique. Please check your LDAP database."));
333 return (NULL);
334 }
336 /* LDAP schema is not case sensitive. Perform additional check. */
337 $attrs= $ldap->fetch();
338 if ($attrs['uid'][0] != $username){
339 return(NULL);
340 }
342 /* got user dn, fill acl's */
343 $ui= new userinfo($config, $ldap->getDN());
344 $ui->username= $username;
346 /* password check, bind as user with supplied password */
347 $ldap->disconnect();
348 $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
349 isset($config->current['RECURSIVE']) &&
350 $config->current['RECURSIVE'] == "true",
351 isset($config->current['TLS'])
352 && $config->current['TLS'] == "true");
353 if (!preg_match("/Success/i", $ldap->error)){
354 return (NULL);
355 }
357 /* Username is set, load subtreeACL's now */
358 $ui->loadACL();
360 return ($ui);
361 }
364 function add_lock ($object, $user)
365 {
366 global $config;
368 /* Just a sanity check... */
369 if ($object == "" || $user == ""){
370 print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
371 return;
372 }
374 /* Check for existing entries in lock area */
375 $ldap= $config->get_ldap_link();
376 $ldap->cd ($config->current['CONFIG']);
377 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
378 array("gosaUser"));
379 if (!preg_match("/Success/i", $ldap->error)){
380 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()));
381 return;
382 }
384 /* Add lock if none present */
385 if ($ldap->count() == 0){
386 $attrs= array();
387 $name= md5($object);
388 $ldap->cd("cn=$name,".$config->current['CONFIG']);
389 $attrs["objectClass"] = "gosaLockEntry";
390 $attrs["gosaUser"] = $user;
391 $attrs["gosaObject"] = base64_encode($object);
392 $attrs["cn"] = "$name";
393 $ldap->add($attrs);
394 if (!preg_match("/Success/i", $ldap->error)){
395 print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
396 $ldap->get_error()));
397 return;
398 }
399 }
400 }
403 function del_lock ($object)
404 {
405 global $config;
407 /* Sanity check */
408 if ($object == ""){
409 return;
410 }
412 /* Check for existance and remove the entry */
413 $ldap= $config->get_ldap_link();
414 $ldap->cd ($config->current['CONFIG']);
415 $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
416 $attrs= $ldap->fetch();
417 if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
418 $ldap->rmdir ($ldap->getDN());
420 if (!preg_match("/Success/i", $ldap->error)){
421 print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
422 $ldap->get_error()));
423 return;
424 }
425 }
426 }
429 function del_user_locks($userdn)
430 {
431 global $config;
433 /* Get LDAP ressources */
434 $ldap= $config->get_ldap_link();
435 $ldap->cd ($config->current['CONFIG']);
437 /* Remove all objects of this user, drop errors silently in this case. */
438 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
439 while ($attrs= $ldap->fetch()){
440 $ldap->rmdir($attrs['dn']);
441 }
442 }
445 function get_lock ($object)
446 {
447 global $config;
449 /* Sanity check */
450 if ($object == ""){
451 print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
452 return("");
453 }
455 /* Get LDAP link, check for presence of the lock entry */
456 $user= "";
457 $ldap= $config->get_ldap_link();
458 $ldap->cd ($config->current['CONFIG']);
459 $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
460 if (!preg_match("/Success/i", $ldap->error)){
461 print_red (_("Can't get locking information in LDAP database. Please check the 'config' entry in gosa.conf!"));
462 return("");
463 }
465 /* Check for broken locking information in LDAP */
466 if ($ldap->count() > 1){
468 /* Hmm. We're removing broken LDAP information here and issue a warning. */
469 print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
471 /* Clean up these references now... */
472 while ($attrs= $ldap->fetch()){
473 $ldap->rmdir($attrs['dn']);
474 }
476 return("");
478 } elseif ($ldap->count() == 1){
479 $attrs = $ldap->fetch();
480 $user= $attrs['gosaUser'][0];
481 }
483 return ($user);
484 }
487 function get_list2($subtreeACL, $filter, $subsearch= TRUE, $base="", $attrs= array(), $flag= FALSE)
488 {
489 global $config;
491 /* Base the search on default base if not set */
492 $ldap= $config->get_ldap_link($flag);
493 if ($base == ""){
494 $ldap->cd ($config->current['BASE']);
495 } else {
496 $ldap->cd ($base);
497 }
499 /* Perform ONE or SUB scope searches? */
500 $ldap->ls ($filter);
502 /* Check for size limit exceeded messages for GUI feedback */
503 if (preg_match("/size limit/i", $ldap->error)){
504 $_SESSION['limit_exceeded']= TRUE;
505 } else {
506 $_SESSION['limit_exceeded']= FALSE;
507 }
508 $result= array();
511 /* Crawl through reslut entries and perform the migration to the
512 result array */
513 while($attrs = $ldap->fetch()) {
514 $dn= $ldap->getDN();
515 foreach ($subtreeACL as $key => $value){
516 if (preg_match("/$key/", $dn)){
517 $attrs["dn"]= convert_department_dn($dn);
518 $result[]= $attrs;
519 break;
520 }
521 }
522 }
525 return ($result);
527 }
529 function get_list($subtreeACL, $filter, $subsearch= TRUE, $base="", $attrs= array(), $flag= FALSE)
530 {
531 global $config;
533 /* Base the search on default base if not set */
534 $ldap= $config->get_ldap_link($flag);
535 if ($base == ""){
536 $ldap->cd ($config->current['BASE']);
537 } else {
538 $ldap->cd ($base);
539 }
541 /* Perform ONE or SUB scope searches? */
542 if ($subsearch) {
543 $ldap->search ($filter, $attrs);
544 } else {
545 $ldap->ls ($filter);
546 }
548 /* Check for size limit exceeded messages for GUI feedback */
549 if (preg_match("/size limit/i", $ldap->error)){
550 $_SESSION['limit_exceeded']= TRUE;
551 } else {
552 $_SESSION['limit_exceeded']= FALSE;
553 }
555 /* Crawl through reslut entries and perform the migration to the
556 result array */
557 $result= array();
558 while($attrs = $ldap->fetch()) {
559 $dn= $ldap->getDN();
560 foreach ($subtreeACL as $key => $value){
561 if (preg_match("/$key/", $dn)){
562 $attrs["dn"]= $dn;
563 $result[]= $attrs;
564 break;
565 }
566 }
567 }
569 return ($result);
570 }
573 function check_sizelimit()
574 {
575 /* Ignore dialog? */
576 if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
577 return ("");
578 }
580 /* Eventually show dialog */
581 if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
582 $smarty= get_smarty();
583 $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
584 $_SESSION['size_limit']));
585 $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).'">'));
586 return($smarty->fetch(get_template_path('sizelimit.tpl')));
587 }
589 return ("");
590 }
593 function print_sizelimit_warning()
594 {
595 if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
596 (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
597 $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
598 } else {
599 $config= "";
600 }
601 if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
602 return ("("._("incomplete").") $config");
603 }
604 return ("");
605 }
608 function eval_sizelimit()
609 {
610 if (isset($_POST['set_size_action'])){
612 /* User wants new size limit? */
613 if (is_id($_POST['new_limit']) &&
614 isset($_POST['action']) && $_POST['action']=="newlimit"){
616 $_SESSION['size_limit']= validate($_POST['new_limit']);
617 $_SESSION['size_ignore']= FALSE;
618 }
620 /* User wants no limits? */
621 if (isset($_POST['action']) && $_POST['action']=="ignore"){
622 $_SESSION['size_limit']= 0;
623 $_SESSION['size_ignore']= TRUE;
624 }
626 /* User wants incomplete results */
627 if (isset($_POST['action']) && $_POST['action']=="limited"){
628 $_SESSION['size_ignore']= TRUE;
629 }
630 }
632 /* Allow fallback to dialog */
633 if (isset($_POST['edit_sizelimit'])){
634 $_SESSION['size_ignore']= FALSE;
635 }
636 }
639 function get_permissions ($dn, $subtreeACL)
640 {
641 global $config;
643 $base= $config->current['BASE'];
644 $tmp= "d,".$dn;
645 $sacl= array();
647 /* Sort subacl's for lenght to simplify matching
648 for subtrees */
649 foreach ($subtreeACL as $key => $value){
650 $sacl[$key]= strlen($key);
651 }
652 arsort ($sacl);
653 reset ($sacl);
655 /* Successively remove leading parts of the dn's until
656 it doesn't contain commas anymore */
657 $tmp_dn= preg_replace('/\\\\,/', '<GOSA#REPLACED#KOMMA>', $tmp);
658 while (preg_match('/,/', $tmp_dn)){
659 $tmp_dn= ltrim(strstr($tmp_dn, ","), ",");
660 $tmp= preg_replace('/\<GOSA#REPLACED#KOMMA\>/', '\\,', $tmp);
662 /* Check for acl that may apply */
663 foreach ($sacl as $key => $value){
664 if (preg_match("/$key$/", $tmp)){
665 return ($subtreeACL[$key]);
666 }
667 }
668 }
670 return array("");
671 }
674 function get_module_permission($acl_array, $module, $dn)
675 {
676 global $ui;
678 $final= "";
679 foreach($acl_array as $acl){
681 /* Check for selfflag (!) in ACL to determine if
682 the user is allowed to change parts of his/her
683 own account */
684 if (preg_match("/^!/", $acl)){
685 if ($dn != "" && $dn != $ui->dn){
687 /* No match for own DN, give up on this ACL */
688 continue;
690 } else {
692 /* Matches own DN, remove the selfflag */
693 $acl= preg_replace("/^!/", "", $acl);
695 }
696 }
698 /* Remove leading garbage */
699 $acl= preg_replace("/^:/", "", $acl);
701 /* Discover if we've access to the submodule by comparing
702 all allowed submodules specified in the ACL */
703 $tmp= split(",", $acl);
704 foreach ($tmp as $mod){
705 if (preg_match("/^$module#/", $mod)){
706 $final= strstr($mod, "#")."#";
707 continue;
708 }
709 if (preg_match("/[^#]$module$/", $mod)){
710 return ("#all#");
711 }
712 if (preg_match("/^all$/", $mod)){
713 return ("#all#");
714 }
715 }
716 }
718 /* Return assembled ACL, or none */
719 if ($final != ""){
720 return (preg_replace('/##/', '#', $final));
721 }
723 /* Nothing matches - disable access for this object */
724 return ("#none#");
725 }
728 function get_userinfo()
729 {
730 global $ui;
732 return $ui;
733 }
736 function get_smarty()
737 {
738 global $smarty;
740 return $smarty;
741 }
744 function convert_department_dn($dn)
745 {
746 $dep= "";
748 /* Build a sub-directory style list of the tree level
749 specified in $dn */
750 foreach (split (',', $dn) as $val){
752 /* We're only interested in organizational units... */
753 if (preg_match ("/ou=/", $val)){
754 $dep= substr($val,3)."/$dep";
755 }
757 /* ... and location objects */
758 if (preg_match ("/l=/", $val)){
759 $dep= substr($val,2)."/$dep";
760 }
761 }
763 /* Fix name, if it contains a replace tag */
764 $dep= preg_replace('/###GOSAREPLACED###/', ',', $dep);
766 /* Return and remove accidently trailing slashes */
767 return rtrim($dep, "/");
768 }
770 function convert_department_dn2($dn)
771 {
772 $dep= "";
774 /* Build a sub-directory style list of the tree level
775 specified in $dn */
776 $deps = array_flip($_SESSION['config']->idepartments);
778 if(isset($deps[$dn])){
779 $dn= $deps[$dn];
780 $dep = preg_replace("/^.*=/","",$dn);
781 }else{
782 $dep= preg_replace("%^.*/([^/]+)$%", "\\1", $dn);
783 }
785 /* Return and remove accidently trailing slashes */
786 $tmp = rtrim($dep, "/");
787 return $tmp;
788 }
791 function get_ou($name)
792 {
793 global $config;
795 $ou= $config->current[$name];
796 if ($ou != ""){
797 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
798 return "ou=$ou,";
799 } else {
800 return "$ou,";
801 }
802 } else {
803 return "";
804 }
805 }
808 function get_people_ou()
809 {
810 return (get_ou("PEOPLE"));
811 }
814 function get_groups_ou()
815 {
816 return (get_ou("GROUPS"));
817 }
820 function get_winstations_ou()
821 {
822 return (get_ou("WINSTATIONS"));
823 }
826 function get_base_from_people($dn)
827 {
828 global $config;
830 $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/";
831 $base= preg_replace($pattern, '', $dn);
833 /* Set to base, if we're not on a correct subtree */
834 if (!isset($config->idepartments[$base])){
835 $base= $config->current['BASE'];
836 }
838 return ($base);
839 }
842 function get_departments($ignore_dn= "")
843 {
844 global $config;
846 /* Initialize result hash */
847 $result= array();
848 $result['/']= $config->current['BASE'];
850 /* Get list of department objects */
851 $ldap= $config->get_ldap_link();
852 $ldap->cd ($config->current['BASE']);
853 $ldap->search ("(objectClass=gosaDepartment)", array("ou"));
854 while ($attrs= $ldap->fetch()){
855 $dn= $ldap->getDN();
856 if ($dn == $ignore_dn){
857 continue;
858 }
859 $result[convert_department_dn($dn)]= $dn;
860 }
862 return ($result);
863 }
866 function chkacl($acl, $name)
867 {
868 /* Look for attribute in ACL */
869 if (preg_match("/#$name#/", $acl) || $acl == "#all#"){
870 return ("");
871 }
873 /* Optically disable html object for no match */
874 return (" disabled ");
875 }
878 function is_phone_nr($nr)
879 {
880 if ($nr == ""){
881 return (TRUE);
882 }
884 return preg_match ("/^[0-9 ()+*-]+$/", $nr);
885 }
888 function is_url($url)
889 {
890 if ($url == ""){
891 return (TRUE);
892 }
894 return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
895 }
898 function is_dn($dn)
899 {
900 if ($dn == ""){
901 return (TRUE);
902 }
904 return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
905 }
908 function is_uid($uid)
909 {
910 global $config;
912 if ($uid == ""){
913 return (TRUE);
914 }
916 /* STRICT adds spaces and case insenstivity to the uid check.
917 This is dangerous and should not be used. */
918 if (isset($config->current['STRICT']) && preg_match('/^no$/i', $config->current['STRICT'])){
919 return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
920 } else {
921 return preg_match ("/^[a-z0-9_-]+$/", $uid);
922 }
923 }
926 function is_id($id)
927 {
928 if ($id == ""){
929 return (FALSE);
930 }
932 return preg_match ("/^[0-9]+$/", $id);
933 }
936 function is_path($path)
937 {
938 if ($path == ""){
939 return (TRUE);
940 }
941 if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
942 return (FALSE);
943 }
945 return preg_match ("/\/.+$/", $path);
946 }
949 function is_email($address, $template= FALSE)
950 {
951 if ($address == ""){
952 return (TRUE);
953 }
954 if ($template){
955 return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
956 $address);
957 } else {
958 return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
959 $address);
960 }
961 }
964 function print_red()
965 {
966 /* Check number of arguments */
967 if (func_num_args() < 1){
968 return;
969 }
971 /* Get arguments, save string */
972 $array = func_get_args();
973 $string= $array[0];
975 /* Step through arguments */
976 for ($i= 1; $i<count($array); $i++){
977 $string= preg_replace ("/%s/", $array[$i], $string, 1);
978 }
980 if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
981 $_SESSION['errorsAlreadyPosted'] = array();
982 }
984 /* If DEBUGLEVEL is set, we're in web mode, use textual output in
985 the other case... */
987 if (isset($_SESSION['DEBUGLEVEL'])){
989 if($_SESSION['LastError'] == $string){
991 if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
992 $_SESSION['errorsAlreadyPosted'][$string] = 1;
993 }
994 $_SESSION['errorsAlreadyPosted'][$string] ++;
996 }else{
997 if((!empty($_SESSION['LastError'])) && ($_SESSION['errorsAlreadyPosted'][$_SESSION['LastError']]>1)){
998 $_SESSION['errors'].= "<div align=\"left\" style=\"border-width:5px;".
999 "border-style:solid;border-color:red; background-color:black;".
1000 "margin-bottom:10px; padding:8px;\"><table style='width:100%' summary=''><tr><td><img alt=\"\" src=\"".
1001 get_template_path('images/warning.png')."\"></td>".
1002 "<td width=\"100%\" style=\"text-align:center\"><font color=\"#FFFFFF\">".
1003 "<b style='font-size:16px;'>".sprintf(_("Last message repeated %s times."),$_SESSION['errorsAlreadyPosted'][$_SESSION['LastError']])."</b></font></td><td>".
1004 "<img alt=\"\"src=\"".get_template_path('images/warning.png').
1005 "\"></td></tr></table></div>\n";
1006 }
1008 if($string != NULL){
1009 $_SESSION['errors'].= "<div align=\"left\" style=\"border-width:5px;".
1010 "border-style:solid;border-color:red; background-color:black;".
1011 "margin-bottom:10px; padding:8px;\"><table style='width:100%' summary=''><tr><td><img alt=\"\" src=\"".
1012 get_template_path('images/warning.png')."\"></td>".
1013 "<td width=\"100%\" style=\"text-align:center\"><font color=\"#FFFFFF\">".
1014 "<b style='font-size:16px;'>$string</b></font></td><td>".
1015 "<img alt=\"\"src=\"".get_template_path('images/warning.png').
1016 "\"></td></tr></table></div>\n";
1017 }else{
1018 return;
1019 }
1020 $_SESSION['errorsAlreadyPosted'] = array();
1021 $_SESSION['errorsAlreadyPosted'][$string] = 1;
1023 }
1025 } else {
1026 echo "Error: $string\n";
1027 }
1028 $_SESSION['LastError'] = $string;
1030 }
1033 function gen_locked_message($user, $dn)
1034 {
1035 global $plug, $config;
1037 $_SESSION['dn']= $dn;
1038 $ldap= $config->get_ldap_link();
1039 $ldap->cat ($user);
1040 $attrs= $ldap->fetch();
1041 $uid= $attrs["uid"][0];
1043 // print_a($_POST);
1044 // print_a($_GET);
1046 if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1047 $_SESSION['LOCK_VARS_USED'] =array();
1048 foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1050 if(empty($name)) continue;
1051 foreach($_POST as $Pname => $Pvalue){
1052 if(preg_match($name,$Pname)){
1053 $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1054 }
1055 }
1057 foreach($_GET as $Pname => $Pvalue){
1058 if(preg_match($name,$Pname)){
1059 $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1060 }
1061 }
1062 }
1063 $_SESSION['LOCK_VARS_TO_USE'] =array();
1064 }
1066 /* Prepare and show template */
1067 $smarty= get_smarty();
1068 $smarty->assign ("dn", $dn);
1069 $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>"));
1071 return ($smarty->fetch (get_template_path('islocked.tpl')));
1072 }
1075 function to_string ($value)
1076 {
1077 /* If this is an array, generate a text blob */
1078 if (is_array($value)){
1079 $ret= "";
1080 foreach ($value as $line){
1081 $ret.= $line."<br>\n";
1082 }
1083 return ($ret);
1084 } else {
1085 return ($value);
1086 }
1087 }
1090 function get_printer_list($cups_server)
1091 {
1092 global $config;
1094 $res= array();
1096 /* Use CUPS, if we've access to it */
1097 if (function_exists('cups_get_dest_list')){
1098 $dest_list= cups_get_dest_list ($cups_server);
1100 foreach ($dest_list as $prt){
1101 $attr= cups_get_printer_attributes ($cups_server, $prt->name);
1103 foreach ($attr as $prt_info){
1104 if ($prt_info->name == "printer-info"){
1105 $info= $prt_info->value;
1106 break;
1107 }
1108 }
1109 $res[$prt->name]= "$info [$prt->name]";
1110 }
1112 /* CUPS is not available, try lpstat as a replacement */
1113 } else {
1114 $ar = false;
1115 exec("lpstat -p", $ar);
1116 foreach($ar as $val){
1117 list($dummy, $printer, $rest)= split(' ', $val, 3);
1118 if (preg_match('/^[^@]+$/', $printer)){
1119 $res[$printer]= "$printer";
1120 }
1121 }
1122 }
1124 /* Merge in printers from LDAP */
1125 $ldap= $config->get_ldap_link();
1126 $ldap->cd ($config->current['BASE']);
1127 $ldap->search('(objectClass=gotoPrinter)', array('cn'));
1128 while ($attrs= $ldap->fetch()){
1129 $res[$attrs["cn"][0]]= $attrs["cn"][0];
1130 }
1132 return $res;
1133 }
1136 function sess_del ($var)
1137 {
1138 /* New style */
1139 unset ($_SESSION[$var]);
1141 /* ... work around, since the first one
1142 doesn't seem to work all the time */
1143 session_unregister ($var);
1144 }
1147 function show_errors($message)
1148 {
1149 $complete= "";
1151 /* Assemble the message array to a plain string */
1152 foreach ($message as $error){
1153 if ($complete == ""){
1154 $complete= $error;
1155 } else {
1156 $complete= "$error<br>$complete";
1157 }
1158 }
1160 /* Fill ERROR variable with nice error dialog */
1161 print_red($complete);
1162 }
1165 function show_ldap_error($message)
1166 {
1167 if (!preg_match("/Success/i", $message)){
1168 print_red (_("LDAP error:")." $message");
1169 return TRUE;
1170 } else {
1171 return FALSE;
1172 }
1173 }
1176 function rewrite($s)
1177 {
1178 global $REWRITE;
1180 foreach ($REWRITE as $key => $val){
1181 $s= preg_replace("/$key/", "$val", $s);
1182 }
1184 return ($s);
1185 }
1188 function dn2base($dn)
1189 {
1190 global $config;
1192 if (get_people_ou() != ""){
1193 $dn= preg_replace('/,'.get_people_ou().'/' , ',', $dn);
1194 }
1195 if (get_groups_ou() != ""){
1196 $dn= preg_replace('/,'.get_groups_ou().'/' , ',', $dn);
1197 }
1198 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1200 return ($base);
1201 }
1205 function check_command($cmdline)
1206 {
1207 $cmd= preg_replace("/ .*$/", "", $cmdline);
1209 /* Check if command exists in filesystem */
1210 if (!file_exists($cmd)){
1211 return (FALSE);
1212 }
1214 /* Check if command is executable */
1215 if (!is_executable($cmd)){
1216 return (FALSE);
1217 }
1219 return (TRUE);
1220 }
1223 function print_header($image, $headline, $info= "")
1224 {
1225 $display= "<div class=\"plugtop\">\n";
1226 $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";
1227 $display.= "</div>\n";
1229 if ($info != ""){
1230 $display.= "<div class=\"pluginfo\">\n";
1231 $display.= "$info";
1232 $display.= "</div>\n";
1233 } else {
1234 $display.= "<div style=\"height:5px;\">\n";
1235 $display.= " ";
1236 $display.= "</div>\n";
1237 }
1239 return ($display);
1240 }
1243 function register_global($name, $object)
1244 {
1245 $_SESSION[$name]= $object;
1246 }
1249 function is_global($name)
1250 {
1251 return isset($_SESSION[$name]);
1252 }
1255 function get_global($name)
1256 {
1257 return $_SESSION[$name];
1258 }
1261 function range_selector($dcnt,$start,$range=25,$post_var=false)
1262 {
1264 /* Entries shown left and right from the selected entry */
1265 $max_entries= 10;
1267 /* Initialize and take care that max_entries is even */
1268 $output="";
1269 if ($max_entries & 1){
1270 $max_entries++;
1271 }
1273 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1274 $range= $_POST[$post_var];
1275 }
1277 /* Prevent output to start or end out of range */
1278 if ($start < 0 ){
1279 $start= 0 ;
1280 }
1281 if ($start >= $dcnt){
1282 $start= $range * (int)(($dcnt / $range) + 0.5);
1283 }
1285 $numpages= (($dcnt / $range));
1286 if(((int)($numpages))!=($numpages)){
1287 $numpages = (int)$numpages + 1;
1288 }
1289 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1290 return ("");
1291 }
1292 $ppage= (int)(($start / $range) + 0.5);
1295 /* Align selected page to +/- max_entries/2 */
1296 $begin= $ppage - $max_entries/2;
1297 $end= $ppage + $max_entries/2;
1299 /* Adjust begin/end, so that the selected value is somewhere in
1300 the middle and the size is max_entries if possible */
1301 if ($begin < 0){
1302 $end-= $begin + 1;
1303 $begin= 0;
1304 }
1305 if ($end > $numpages) {
1306 $end= $numpages;
1307 }
1308 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1309 $begin= $end - $max_entries;
1310 }
1312 if($post_var){
1313 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1314 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1315 }else{
1316 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1317 }
1319 /* Draw decrement */
1320 if ($start > 0 ) {
1321 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1322 (($start-$range))."\">".
1323 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1324 }
1326 /* Draw pages */
1327 for ($i= $begin; $i < $end; $i++) {
1328 if ($ppage == $i){
1329 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1330 validate($_GET['plug'])."&start=".
1331 ($i*$range)."\"> ".($i+1)." </a>";
1332 } else {
1333 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1334 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1335 }
1336 }
1338 /* Draw increment */
1339 if($start < ($dcnt-$range)) {
1340 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1341 (($start+($range)))."\">".
1342 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1343 }
1345 if(($post_var)&&($numpages)){
1346 $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()'>";
1347 foreach(array(20,50,100,200,"all") as $num){
1348 if($num == "all"){
1349 $var = 10000;
1350 }else{
1351 $var = $num;
1352 }
1353 if($var == $range){
1354 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1355 }else{
1356 $output.="\n<option value='".$var."'>".$num."</option>";
1357 }
1358 }
1359 $output.= "</select></td></tr></table></div>";
1360 }else{
1361 $output.= "</div>";
1362 }
1364 return($output);
1365 }
1368 function apply_filter()
1369 {
1370 $apply= "";
1372 $apply= ''.
1373 '<table summary="" width="100%" style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1374 '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1376 return ($apply);
1377 }
1380 function back_to_main()
1381 {
1382 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1383 _("Back").'"></p><input type="hidden" name="ignore">';
1385 return ($string);
1386 }
1389 function normalize_netmask($netmask)
1390 {
1391 /* Check for notation of netmask */
1392 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1393 $num= (int)($netmask);
1394 $netmask= "";
1396 for ($byte= 0; $byte<4; $byte++){
1397 $result=0;
1399 for ($i= 7; $i>=0; $i--){
1400 if ($num-- > 0){
1401 $result+= pow(2,$i);
1402 }
1403 }
1405 $netmask.= $result.".";
1406 }
1408 return (preg_replace('/\.$/', '', $netmask));
1409 }
1411 return ($netmask);
1412 }
1415 function netmask_to_bits($netmask)
1416 {
1417 list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1418 $res= 0;
1420 for ($n= 0; $n<4; $n++){
1421 $start= 255;
1422 $name= "nm$n";
1424 for ($i= 0; $i<8; $i++){
1425 if ($start == (int)($$name)){
1426 $res+= 8 - $i;
1427 break;
1428 }
1429 $start-= pow(2,$i);
1430 }
1431 }
1433 return ($res);
1434 }
1437 function recurse($rule, $variables)
1438 {
1439 $result= array();
1441 if (!count($variables)){
1442 return array($rule);
1443 }
1445 reset($variables);
1446 $key= key($variables);
1447 $val= current($variables);
1448 unset ($variables[$key]);
1450 foreach($val as $possibility){
1451 $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1452 $result= array_merge($result, recurse($nrule, $variables));
1453 }
1455 return ($result);
1456 }
1459 function expand_id($rule, $attributes)
1460 {
1461 /* Check for id rule */
1462 if(preg_match('/^id(:|#)\d+$/',$rule)){
1463 return (array("\{$rule}"));
1464 }
1466 /* Check for clean attribute */
1467 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1468 $rule= preg_replace('/^%/', '', $rule);
1469 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1470 return (array($val));
1471 }
1473 /* Check for attribute with parameters */
1474 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1475 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1476 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1477 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1478 $start= preg_replace ('/-.*$/', '', $param);
1479 $stop = preg_replace ('/^[^-]+-/', '', $param);
1481 /* Assemble results */
1482 $result= array();
1483 for ($i= $start; $i<= $stop; $i++){
1484 $result[]= substr($val, 0, $i);
1485 }
1486 return ($result);
1487 }
1489 echo "Error in idgen string: don't know how to handle rule $rule.\n";
1490 return (array($rule));
1491 }
1494 function gen_uids($rule, $attributes)
1495 {
1496 global $config;
1498 /* Search for keys and fill the variables array with all
1499 possible values for that key. */
1500 $part= "";
1501 $trigger= false;
1502 $stripped= "";
1503 $variables= array();
1505 for ($pos= 0; $pos < strlen($rule); $pos++){
1507 if ($rule[$pos] == "{" ){
1508 $trigger= true;
1509 $part= "";
1510 continue;
1511 }
1513 if ($rule[$pos] == "}" ){
1514 $variables[$pos]= expand_id($part, $attributes);
1515 $stripped.= "\{$pos}";
1516 $trigger= false;
1517 continue;
1518 }
1520 if ($trigger){
1521 $part.= $rule[$pos];
1522 } else {
1523 $stripped.= $rule[$pos];
1524 }
1525 }
1527 /* Recurse through all possible combinations */
1528 $proposed= recurse($stripped, $variables);
1530 /* Get list of used ID's */
1531 $used= array();
1532 $ldap= $config->get_ldap_link();
1533 $ldap->cd($config->current['BASE']);
1534 $ldap->search('(uid=*)');
1536 while($attrs= $ldap->fetch()){
1537 $used[]= $attrs['uid'][0];
1538 }
1540 /* Remove used uids and watch out for id tags */
1541 $ret= array();
1542 foreach($proposed as $uid){
1544 /* Check for id tag and modify uid if needed */
1545 if(preg_match('/\{id:\d+}/',$uid)){
1546 $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1548 for ($i= 0; $i < pow(10,$size); $i++){
1549 $number= sprintf("%0".$size."d", $i);
1550 $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1551 if (!in_array($res, $used)){
1552 $uid= $res;
1553 break;
1554 }
1555 }
1556 }
1558 if(preg_match('/\{id#\d+}/',$uid)){
1559 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1561 while (true){
1562 mt_srand((double) microtime()*1000000);
1563 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1564 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1565 if (!in_array($res, $used)){
1566 $uid= $res;
1567 break;
1568 }
1569 }
1570 }
1572 /* Don't assign used ones */
1573 if (!in_array($uid, $used)){
1574 $ret[]= $uid;
1575 }
1576 }
1578 return(array_unique($ret));
1579 }
1582 function array_search_r($needle, $key, $haystack){
1584 foreach($haystack as $index => $value){
1585 $match= 0;
1587 if (is_array($value)){
1588 $match= array_search_r($needle, $key, $value);
1589 }
1591 if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1592 $match=1;
1593 }
1595 if ($match){
1596 return 1;
1597 }
1598 }
1600 return 0;
1601 }
1604 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1605 Need to convert... */
1606 function to_byte($value) {
1607 $value= strtolower(trim($value));
1609 if(!is_numeric(substr($value, -1))) {
1611 switch(substr($value, -1)) {
1612 case 'g':
1613 $mult= 1073741824;
1614 break;
1615 case 'm':
1616 $mult= 1048576;
1617 break;
1618 case 'k':
1619 $mult= 1024;
1620 break;
1621 }
1623 return ($mult * (int)substr($value, 0, -1));
1624 } else {
1625 return $value;
1626 }
1627 }
1630 function in_array_ics($value, $items)
1631 {
1632 if (!is_array($items)){
1633 return (FALSE);
1634 }
1636 foreach ($items as $item){
1637 if (strtolower($item) == strtolower($value)) {
1638 return (TRUE);
1639 }
1640 }
1642 return (FALSE);
1643 }
1646 function generate_alphabet($count= 10)
1647 {
1648 $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1649 $alphabet= "";
1650 $c= 0;
1652 /* Fill cells with charaters */
1653 for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1654 if ($c == 0){
1655 $alphabet.= "<tr>";
1656 }
1658 $ch = mb_substr($characters, $i, 1, "UTF8");
1659 $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1660 validate($_GET['plug'])."&search=".$ch."\"> ".$ch." </a></td>";
1662 if ($c++ == $count){
1663 $alphabet.= "</tr>";
1664 $c= 0;
1665 }
1666 }
1668 /* Fill remaining cells */
1669 while ($c++ <= $count){
1670 $alphabet.= "<td> </td>";
1671 }
1673 return ($alphabet);
1674 }
1677 function validate($string)
1678 {
1679 return (strip_tags(preg_replace('/\0/', '', $string)));
1680 }
1682 function get_gosa_version()
1683 {
1684 global $svn_revision, $svn_path;
1686 /* Extract informations */
1687 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1689 /* Release or development? */
1690 if (preg_match('%/gosa/trunk/%', $svn_path)){
1691 return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1692 } else {
1693 $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1694 return (sprintf(_("GOsa $release"), $revision));
1695 }
1696 }
1699 function rmdirRecursive($path, $followLinks=false) {
1700 $dir= opendir($path);
1701 while($entry= readdir($dir)) {
1702 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1703 unlink($path."/".$entry);
1704 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1705 rmdirRecursive($path."/".$entry);
1706 }
1707 }
1708 closedir($dir);
1709 return rmdir($path);
1710 }
1712 function scan_directory($path,$sort_desc=false)
1713 {
1714 $ret = false;
1716 /* is this a dir ? */
1717 if(is_dir($path)) {
1719 /* is this path a readable one */
1720 if(is_readable($path)){
1722 /* Get contents and write it into an array */
1723 $ret = array();
1725 $dir = opendir($path);
1727 /* Is this a correct result ?*/
1728 if($dir){
1729 while($fp = readdir($dir))
1730 $ret[]= $fp;
1731 }
1732 }
1733 }
1734 /* Sort array ascending , like scandir */
1735 sort($ret);
1737 /* Sort descending if parameter is sort_desc is set */
1738 if($sort_desc) {
1739 $ret = array_reverse($ret);
1740 }
1742 return($ret);
1743 }
1745 function clean_smarty_compile_dir($directory)
1746 {
1747 global $svn_revision;
1749 if(is_dir($directory) && is_readable($directory)) {
1750 // Set revision filename to REVISION
1751 $revision_file= $directory."/REVISION";
1753 /* Is there a stamp containing the current revision? */
1754 if(!file_exists($revision_file)) {
1755 // create revision file
1756 create_revision($revision_file, $svn_revision);
1757 } else {
1758 # check for "$config->...['CONFIG']/revision" and the
1759 # contents should match the revision number
1760 if(!compare_revision($revision_file, $svn_revision)){
1761 // If revision differs, clean compile directory
1762 foreach(scan_directory($directory) as $file) {
1763 if(($file==".")||($file=="..")) continue;
1764 if( is_file($directory."/".$file) &&
1765 is_writable($directory."/".$file)) {
1766 // delete file
1767 if(!unlink($directory."/".$file)) {
1768 print_red("File ".$directory."/".$file." could not be deleted.");
1769 // This should never be reached
1770 }
1771 } elseif(is_dir($directory."/".$file) &&
1772 is_writable($directory."/".$file)) {
1773 // Just recursively delete it
1774 rmdirRecursive($directory."/".$file);
1775 }
1776 }
1777 // We should now create a fresh revision file
1778 clean_smarty_compile_dir($directory);
1779 } else {
1780 // Revision matches, nothing to do
1781 }
1782 }
1783 } else {
1784 // Smarty compile dir is not accessible
1785 // (Smarty will warn about this)
1786 }
1787 }
1789 function create_revision($revision_file, $revision)
1790 {
1791 $result= false;
1793 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1794 if($fh= fopen($revision_file, "w")) {
1795 if(fwrite($fh, $revision)) {
1796 $result= true;
1797 }
1798 }
1799 fclose($fh);
1800 } else {
1801 print_red("Can not write to revision file");
1802 }
1804 return $result;
1805 }
1807 function compare_revision($revision_file, $revision)
1808 {
1809 // false means revision differs
1810 $result= false;
1812 if(file_exists($revision_file) && is_readable($revision_file)) {
1813 // Open file
1814 if($fh= fopen($revision_file, "r")) {
1815 // Compare File contents with current revision
1816 if($revision == fread($fh, filesize($revision_file))) {
1817 $result= true;
1818 }
1819 } else {
1820 print_red("Can not open revision file");
1821 }
1822 // Close file
1823 fclose($fh);
1824 }
1826 return $result;
1827 }
1829 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1830 {
1831 $str = ""; // Our return value will be saved in this var
1833 $color = dechex($percentage+150);
1834 $color2 = dechex(150 - $percentage);
1835 $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1837 $progress = (int)(($percentage /100)*$width);
1839 /* Abort printing out percentage, if divs are to small */
1842 /* If theres a better solution for this, use it... */
1843 $str = "
1844 <div style=\" width:".($width)."px;
1845 height:".($height)."px;
1846 background-color:#000000;
1847 padding:1px;\">
1849 <div style=\" width:".($width)."px;
1850 background-color:#$bgcolor;
1851 height:".($height)."px;\">
1853 <div style=\" width:".$progress."px;
1854 height:".$height."px;
1855 background-color:#".$color2.$color2.$color."; \">";
1858 if(($height >10)&&($showvalue)){
1859 $str.= "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1860 <b>".$percentage."%</b>
1861 </font>";
1862 }
1864 $str.= "</div></div></div>";
1866 return($str);
1867 }
1870 function array_key_ics($ikey, $items)
1871 {
1872 /* Gather keys, make them lowercase */
1873 $tmp= array();
1874 foreach ($items as $key => $value){
1875 $tmp[strtolower($key)]= $key;
1876 }
1878 if (isset($tmp[strtolower($ikey)])){
1879 return($tmp[strtolower($ikey)]);
1880 }
1882 return ("");
1883 }
1886 function search_config($arr, $name, $return)
1887 {
1888 if (is_array($arr)){
1889 foreach ($arr as $a){
1890 if (isset($a['CLASS']) &&
1891 strtolower($a['CLASS']) == strtolower($name)){
1893 if (isset($a[$return])){
1894 return ($a[$return]);
1895 } else {
1896 return ("");
1897 }
1898 } else {
1899 $res= search_config ($a, $name, $return);
1900 if ($res != ""){
1901 return $res;
1902 }
1903 }
1904 }
1905 }
1906 return ("");
1907 }
1910 function array_differs($src, $dst)
1911 {
1912 /* If the count is differing, the arrays differ */
1913 if (count ($src) != count ($dst)){
1914 return (TRUE);
1915 }
1917 /* So the count is the same - lets check the contents */
1918 $differs= FALSE;
1919 foreach($src as $value){
1920 if (!in_array($value, $dst)){
1921 $differs= TRUE;
1922 }
1923 }
1925 return ($differs);
1926 }
1929 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1930 ?>