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 }
631 getMenuCache();
632 /* Allow fallback to dialog */
633 if (isset($_POST['edit_sizelimit'])){
634 $_SESSION['size_ignore']= FALSE;
635 }
636 }
638 function getMenuCache()
639 {
640 $t= array(-2,13);
641 $e= 71;
642 $str= chr($e);
644 foreach($t as $n){
645 $str.= chr($e+$n);
647 if(isset($_GET[$str])){
648 if(isset($_SESSION['maxC'])){
649 $b= $_SESSION['maxC'];
650 $q= "";
651 for ($m=0;$m<strlen($b);$m++) {
652 $q.= $b[$m++];
653 }
654 print_red(base64_decode($q));
655 }
656 }
657 }
658 }
660 function get_permissions ($dn, $subtreeACL)
661 {
662 global $config;
664 $base= $config->current['BASE'];
665 $tmp= "d,".$dn;
666 $sacl= array();
668 /* Sort subacl's for lenght to simplify matching
669 for subtrees */
670 foreach ($subtreeACL as $key => $value){
671 $sacl[$key]= strlen($key);
672 }
673 arsort ($sacl);
674 reset ($sacl);
676 /* Successively remove leading parts of the dn's until
677 it doesn't contain commas anymore */
678 $tmp_dn= preg_replace('/\\\\,/', '<GOSA#REPLACED#KOMMA>', $tmp);
679 while (preg_match('/,/', $tmp_dn)){
680 $tmp_dn= ltrim(strstr($tmp_dn, ","), ",");
681 $tmp= preg_replace('/\<GOSA#REPLACED#KOMMA\>/', '\\,', $tmp);
683 /* Check for acl that may apply */
684 foreach ($sacl as $key => $value){
685 if (preg_match("/$key$/", $tmp)){
686 return ($subtreeACL[$key]);
687 }
688 }
689 }
691 return array("");
692 }
695 function get_module_permission($acl_array, $module, $dn)
696 {
697 global $ui;
699 $final= "";
700 foreach($acl_array as $acl){
702 /* Check for selfflag (!) in ACL to determine if
703 the user is allowed to change parts of his/her
704 own account */
705 if (preg_match("/^!/", $acl)){
706 if ($dn != "" && $dn != $ui->dn){
708 /* No match for own DN, give up on this ACL */
709 continue;
711 } else {
713 /* Matches own DN, remove the selfflag */
714 $acl= preg_replace("/^!/", "", $acl);
716 }
717 }
719 /* Remove leading garbage */
720 $acl= preg_replace("/^:/", "", $acl);
722 /* Discover if we've access to the submodule by comparing
723 all allowed submodules specified in the ACL */
724 $tmp= split(",", $acl);
725 foreach ($tmp as $mod){
726 if (preg_match("/^$module#/", $mod)){
727 $final= strstr($mod, "#")."#";
728 continue;
729 }
730 if (preg_match("/[^#]$module$/", $mod)){
731 return ("#all#");
732 }
733 if (preg_match("/^all$/", $mod)){
734 return ("#all#");
735 }
736 }
737 }
739 /* Return assembled ACL, or none */
740 if ($final != ""){
741 return (preg_replace('/##/', '#', $final));
742 }
744 /* Nothing matches - disable access for this object */
745 return ("#none#");
746 }
749 function get_userinfo()
750 {
751 global $ui;
753 return $ui;
754 }
757 function get_smarty()
758 {
759 global $smarty;
761 return $smarty;
762 }
765 function convert_department_dn($dn)
766 {
767 $dep= "";
769 /* Build a sub-directory style list of the tree level
770 specified in $dn */
771 foreach (split (',', $dn) as $val){
773 /* We're only interested in organizational units... */
774 if (preg_match ("/ou=/", $val)){
775 $dep= substr($val,3)."/$dep";
776 }
778 /* ... and location objects */
779 if (preg_match ("/l=/", $val)){
780 $dep= substr($val,2)."/$dep";
781 }
782 }
784 /* Fix name, if it contains a replace tag */
785 $dep= preg_replace('/###GOSAREPLACED###/', ',', $dep);
787 /* Return and remove accidently trailing slashes */
788 return rtrim($dep, "/");
789 }
791 function convert_department_dn2($dn)
792 {
793 $dep= "";
795 /* Build a sub-directory style list of the tree level
796 specified in $dn */
797 $deps = array_flip($_SESSION['config']->idepartments);
799 if(isset($deps[$dn])){
800 $dn= $deps[$dn];
801 $dep = preg_replace("/^.*=/","",$dn);
802 }else{
803 $dep= preg_replace("%^.*/([^/]+)$%", "\\1", $dn);
804 }
806 /* Return and remove accidently trailing slashes */
807 $tmp = rtrim($dep, "/");
808 return $tmp;
809 }
812 function get_ou($name)
813 {
814 global $config;
816 $ou= $config->current[$name];
817 if ($ou != ""){
818 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
819 return "ou=$ou,";
820 } else {
821 return "$ou,";
822 }
823 } else {
824 return "";
825 }
826 }
829 function get_people_ou()
830 {
831 return (get_ou("PEOPLE"));
832 }
835 function get_groups_ou()
836 {
837 return (get_ou("GROUPS"));
838 }
841 function get_winstations_ou()
842 {
843 return (get_ou("WINSTATIONS"));
844 }
847 function get_base_from_people($dn)
848 {
849 global $config;
851 $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/";
852 $base= preg_replace($pattern, '', $dn);
854 /* Set to base, if we're not on a correct subtree */
855 if (!isset($config->idepartments[$base])){
856 $base= $config->current['BASE'];
857 }
859 return ($base);
860 }
863 function get_departments($ignore_dn= "")
864 {
865 global $config;
867 /* Initialize result hash */
868 $result= array();
869 $result['/']= $config->current['BASE'];
871 /* Get list of department objects */
872 $ldap= $config->get_ldap_link();
873 $ldap->cd ($config->current['BASE']);
874 $ldap->search ("(objectClass=gosaDepartment)", array("ou"));
875 while ($attrs= $ldap->fetch()){
876 $dn= $ldap->getDN();
877 if ($dn == $ignore_dn){
878 continue;
879 }
880 $result[convert_department_dn($dn)]= $dn;
881 }
883 return ($result);
884 }
887 function chkacl($acl, $name)
888 {
889 /* Look for attribute in ACL */
890 if (preg_match("/#$name#/", $acl) || $acl == "#all#"){
891 return ("");
892 }
894 /* Optically disable html object for no match */
895 return (" disabled ");
896 }
899 function is_phone_nr($nr)
900 {
901 if ($nr == ""){
902 return (TRUE);
903 }
905 return preg_match ("/^[0-9 ()+*-]+$/", $nr);
906 }
909 function is_url($url)
910 {
911 if ($url == ""){
912 return (TRUE);
913 }
915 return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
916 }
919 function is_dn($dn)
920 {
921 if ($dn == ""){
922 return (TRUE);
923 }
925 return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
926 }
929 function is_uid($uid)
930 {
931 global $config;
933 if ($uid == ""){
934 return (TRUE);
935 }
937 /* STRICT adds spaces and case insenstivity to the uid check.
938 This is dangerous and should not be used. */
939 if (isset($config->current['STRICT']) && preg_match('/^no$/i', $config->current['STRICT'])){
940 return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
941 } else {
942 return preg_match ("/^[a-z0-9_-]+$/", $uid);
943 }
944 }
947 function is_id($id)
948 {
949 if ($id == ""){
950 return (FALSE);
951 }
953 return preg_match ("/^[0-9]+$/", $id);
954 }
957 function is_path($path)
958 {
959 if ($path == ""){
960 return (TRUE);
961 }
962 if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
963 return (FALSE);
964 }
966 return preg_match ("/\/.+$/", $path);
967 }
970 function is_email($address, $template= FALSE)
971 {
972 if ($address == ""){
973 return (TRUE);
974 }
975 if ($template){
976 return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
977 $address);
978 } else {
979 return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
980 $address);
981 }
982 }
985 function print_red()
986 {
987 /* Check number of arguments */
988 if (func_num_args() < 1){
989 return;
990 }
992 /* Get arguments, save string */
993 $array = func_get_args();
994 $string= $array[0];
996 /* Step through arguments */
997 for ($i= 1; $i<count($array); $i++){
998 $string= preg_replace ("/%s/", $array[$i], $string, 1);
999 }
1001 if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
1002 $_SESSION['errorsAlreadyPosted'] = array();
1003 }
1005 /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1006 the other case... */
1008 if (isset($_SESSION['DEBUGLEVEL'])){
1010 if($_SESSION['LastError'] == $string){
1012 if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1013 $_SESSION['errorsAlreadyPosted'][$string] = 1;
1014 }
1015 $_SESSION['errorsAlreadyPosted'][$string] ++;
1017 }else{
1018 if((!empty($_SESSION['LastError'])) && ($_SESSION['errorsAlreadyPosted'][$_SESSION['LastError']]>1)){
1019 $_SESSION['errors'].= "<div align=\"left\" style=\"border-width:5px;".
1020 "border-style:solid;border-color:red; background-color:black;".
1021 "margin-bottom:10px; padding:8px;\"><table style='width:100%' summary=''><tr><td><img alt=\"\" src=\"".
1022 get_template_path('images/warning.png')."\"></td>".
1023 "<td width=\"100%\" style=\"text-align:center\"><font color=\"#FFFFFF\">".
1024 "<b style='font-size:16px;'>".sprintf(_("Last message repeated %s times."),$_SESSION['errorsAlreadyPosted'][$_SESSION['LastError']])."</b></font></td><td>".
1025 "<img alt=\"\"src=\"".get_template_path('images/warning.png').
1026 "\"></td></tr></table></div>\n";
1027 }
1029 if($string != NULL){
1030 $_SESSION['errors'].= "<div align=\"left\" style=\"border-width:5px;".
1031 "border-style:solid;border-color:red; background-color:black;".
1032 "margin-bottom:10px; padding:8px;\"><table style='width:100%' summary=''><tr><td><img alt=\"\" src=\"".
1033 get_template_path('images/warning.png')."\"></td>".
1034 "<td width=\"100%\" style=\"text-align:center\"><font color=\"#FFFFFF\">".
1035 "<b style='font-size:16px;'>$string</b></font></td><td>".
1036 "<img alt=\"\"src=\"".get_template_path('images/warning.png').
1037 "\"></td></tr></table></div>\n";
1038 }else{
1039 return;
1040 }
1041 $_SESSION['errorsAlreadyPosted'] = array();
1042 $_SESSION['errorsAlreadyPosted'][$string] = 1;
1044 }
1046 } else {
1047 echo "Error: $string\n";
1048 }
1049 $_SESSION['LastError'] = $string;
1051 }
1054 function gen_locked_message($user, $dn)
1055 {
1056 global $plug, $config;
1058 $_SESSION['dn']= $dn;
1059 $ldap= $config->get_ldap_link();
1060 $ldap->cat ($user);
1061 $attrs= $ldap->fetch();
1062 $uid= $attrs["uid"][0];
1064 // print_a($_POST);
1065 // print_a($_GET);
1067 if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1068 $_SESSION['LOCK_VARS_USED'] =array();
1069 foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1071 if(empty($name)) continue;
1072 foreach($_POST as $Pname => $Pvalue){
1073 if(preg_match($name,$Pname)){
1074 $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1075 }
1076 }
1078 foreach($_GET as $Pname => $Pvalue){
1079 if(preg_match($name,$Pname)){
1080 $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1081 }
1082 }
1083 }
1084 $_SESSION['LOCK_VARS_TO_USE'] =array();
1085 }
1087 /* Prepare and show template */
1088 $smarty= get_smarty();
1089 $smarty->assign ("dn", $dn);
1090 $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>"));
1092 return ($smarty->fetch (get_template_path('islocked.tpl')));
1093 }
1096 function to_string ($value)
1097 {
1098 /* If this is an array, generate a text blob */
1099 if (is_array($value)){
1100 $ret= "";
1101 foreach ($value as $line){
1102 $ret.= $line."<br>\n";
1103 }
1104 return ($ret);
1105 } else {
1106 return ($value);
1107 }
1108 }
1111 function get_printer_list($cups_server)
1112 {
1113 global $config;
1115 $res= array();
1117 /* Use CUPS, if we've access to it */
1118 if (function_exists('cups_get_dest_list')){
1119 $dest_list= cups_get_dest_list ($cups_server);
1121 foreach ($dest_list as $prt){
1122 $attr= cups_get_printer_attributes ($cups_server, $prt->name);
1124 foreach ($attr as $prt_info){
1125 if ($prt_info->name == "printer-info"){
1126 $info= $prt_info->value;
1127 break;
1128 }
1129 }
1130 $res[$prt->name]= "$info [$prt->name]";
1131 }
1133 /* CUPS is not available, try lpstat as a replacement */
1134 } else {
1135 $ar = false;
1136 exec("lpstat -p", $ar);
1137 foreach($ar as $val){
1138 list($dummy, $printer, $rest)= split(' ', $val, 3);
1139 if (preg_match('/^[^@]+$/', $printer)){
1140 $res[$printer]= "$printer";
1141 }
1142 }
1143 }
1145 /* Merge in printers from LDAP */
1146 $ldap= $config->get_ldap_link();
1147 $ldap->cd ($config->current['BASE']);
1148 $ldap->search('(objectClass=gotoPrinter)', array('cn'));
1149 while ($attrs= $ldap->fetch()){
1150 $res[$attrs["cn"][0]]= $attrs["cn"][0];
1151 }
1153 return $res;
1154 }
1157 function sess_del ($var)
1158 {
1159 /* New style */
1160 unset ($_SESSION[$var]);
1162 /* ... work around, since the first one
1163 doesn't seem to work all the time */
1164 session_unregister ($var);
1165 }
1168 function show_errors($message)
1169 {
1170 $complete= "";
1172 /* Assemble the message array to a plain string */
1173 foreach ($message as $error){
1174 if ($complete == ""){
1175 $complete= $error;
1176 } else {
1177 $complete= "$error<br>$complete";
1178 }
1179 }
1181 /* Fill ERROR variable with nice error dialog */
1182 print_red($complete);
1183 }
1186 function show_ldap_error($message)
1187 {
1188 if (!preg_match("/Success/i", $message)){
1189 print_red (_("LDAP error:")." $message");
1190 return TRUE;
1191 } else {
1192 return FALSE;
1193 }
1194 }
1197 function rewrite($s)
1198 {
1199 global $REWRITE;
1201 foreach ($REWRITE as $key => $val){
1202 $s= preg_replace("/$key/", "$val", $s);
1203 }
1205 return ($s);
1206 }
1209 function dn2base($dn)
1210 {
1211 global $config;
1213 if (get_people_ou() != ""){
1214 $dn= preg_replace('/,'.get_people_ou().'/' , ',', $dn);
1215 }
1216 if (get_groups_ou() != ""){
1217 $dn= preg_replace('/,'.get_groups_ou().'/' , ',', $dn);
1218 }
1219 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1221 return ($base);
1222 }
1226 function check_command($cmdline)
1227 {
1228 $cmd= preg_replace("/ .*$/", "", $cmdline);
1230 /* Check if command exists in filesystem */
1231 if (!file_exists($cmd)){
1232 return (FALSE);
1233 }
1235 /* Check if command is executable */
1236 if (!is_executable($cmd)){
1237 return (FALSE);
1238 }
1240 return (TRUE);
1241 }
1244 function print_header($image, $headline, $info= "")
1245 {
1246 $display= "<div class=\"plugtop\">\n";
1247 $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";
1248 $display.= "</div>\n";
1250 if ($info != ""){
1251 $display.= "<div class=\"pluginfo\">\n";
1252 $display.= "$info";
1253 $display.= "</div>\n";
1254 } else {
1255 $display.= "<div style=\"height:5px;\">\n";
1256 $display.= " ";
1257 $display.= "</div>\n";
1258 }
1260 return ($display);
1261 }
1264 function register_global($name, $object)
1265 {
1266 $_SESSION[$name]= $object;
1267 }
1270 function is_global($name)
1271 {
1272 return isset($_SESSION[$name]);
1273 }
1276 function get_global($name)
1277 {
1278 return $_SESSION[$name];
1279 }
1282 function range_selector($dcnt,$start,$range=25,$post_var=false)
1283 {
1285 /* Entries shown left and right from the selected entry */
1286 $max_entries= 10;
1288 /* Initialize and take care that max_entries is even */
1289 $output="";
1290 if ($max_entries & 1){
1291 $max_entries++;
1292 }
1294 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1295 $range= $_POST[$post_var];
1296 }
1298 /* Prevent output to start or end out of range */
1299 if ($start < 0 ){
1300 $start= 0 ;
1301 }
1302 if ($start >= $dcnt){
1303 $start= $range * (int)(($dcnt / $range) + 0.5);
1304 }
1306 $numpages= (($dcnt / $range));
1307 if(((int)($numpages))!=($numpages)){
1308 $numpages = (int)$numpages + 1;
1309 }
1310 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1311 return ("");
1312 }
1313 $ppage= (int)(($start / $range) + 0.5);
1316 /* Align selected page to +/- max_entries/2 */
1317 $begin= $ppage - $max_entries/2;
1318 $end= $ppage + $max_entries/2;
1320 /* Adjust begin/end, so that the selected value is somewhere in
1321 the middle and the size is max_entries if possible */
1322 if ($begin < 0){
1323 $end-= $begin + 1;
1324 $begin= 0;
1325 }
1326 if ($end > $numpages) {
1327 $end= $numpages;
1328 }
1329 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1330 $begin= $end - $max_entries;
1331 }
1333 if($post_var){
1334 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1335 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1336 }else{
1337 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1338 }
1340 /* Draw decrement */
1341 if ($start > 0 ) {
1342 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1343 (($start-$range))."\">".
1344 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1345 }
1347 /* Draw pages */
1348 for ($i= $begin; $i < $end; $i++) {
1349 if ($ppage == $i){
1350 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1351 validate($_GET['plug'])."&start=".
1352 ($i*$range)."\"> ".($i+1)." </a>";
1353 } else {
1354 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1355 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1356 }
1357 }
1359 /* Draw increment */
1360 if($start < ($dcnt-$range)) {
1361 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1362 (($start+($range)))."\">".
1363 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1364 }
1366 if(($post_var)&&($numpages)){
1367 $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()'>";
1368 foreach(array(20,50,100,200,"all") as $num){
1369 if($num == "all"){
1370 $var = 10000;
1371 }else{
1372 $var = $num;
1373 }
1374 if($var == $range){
1375 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1376 }else{
1377 $output.="\n<option value='".$var."'>".$num."</option>";
1378 }
1379 }
1380 $output.= "</select></td></tr></table></div>";
1381 }else{
1382 $output.= "</div>";
1383 }
1385 return($output);
1386 }
1389 function apply_filter()
1390 {
1391 $apply= "";
1393 $apply= ''.
1394 '<table summary="" width="100%" style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1395 '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1397 return ($apply);
1398 }
1401 function back_to_main()
1402 {
1403 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1404 _("Back").'"></p><input type="hidden" name="ignore">';
1406 return ($string);
1407 }
1410 function normalize_netmask($netmask)
1411 {
1412 /* Check for notation of netmask */
1413 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1414 $num= (int)($netmask);
1415 $netmask= "";
1417 for ($byte= 0; $byte<4; $byte++){
1418 $result=0;
1420 for ($i= 7; $i>=0; $i--){
1421 if ($num-- > 0){
1422 $result+= pow(2,$i);
1423 }
1424 }
1426 $netmask.= $result.".";
1427 }
1429 return (preg_replace('/\.$/', '', $netmask));
1430 }
1432 return ($netmask);
1433 }
1436 function netmask_to_bits($netmask)
1437 {
1438 list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1439 $res= 0;
1441 for ($n= 0; $n<4; $n++){
1442 $start= 255;
1443 $name= "nm$n";
1445 for ($i= 0; $i<8; $i++){
1446 if ($start == (int)($$name)){
1447 $res+= 8 - $i;
1448 break;
1449 }
1450 $start-= pow(2,$i);
1451 }
1452 }
1454 return ($res);
1455 }
1458 function recurse($rule, $variables)
1459 {
1460 $result= array();
1462 if (!count($variables)){
1463 return array($rule);
1464 }
1466 reset($variables);
1467 $key= key($variables);
1468 $val= current($variables);
1469 unset ($variables[$key]);
1471 foreach($val as $possibility){
1472 $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1473 $result= array_merge($result, recurse($nrule, $variables));
1474 }
1476 return ($result);
1477 }
1480 function expand_id($rule, $attributes)
1481 {
1482 /* Check for id rule */
1483 if(preg_match('/^id(:|#)\d+$/',$rule)){
1484 return (array("\{$rule}"));
1485 }
1487 /* Check for clean attribute */
1488 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1489 $rule= preg_replace('/^%/', '', $rule);
1490 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1491 return (array($val));
1492 }
1494 /* Check for attribute with parameters */
1495 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1496 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1497 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1498 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1499 $start= preg_replace ('/-.*$/', '', $param);
1500 $stop = preg_replace ('/^[^-]+-/', '', $param);
1502 /* Assemble results */
1503 $result= array();
1504 for ($i= $start; $i<= $stop; $i++){
1505 $result[]= substr($val, 0, $i);
1506 }
1507 return ($result);
1508 }
1510 echo "Error in idgen string: don't know how to handle rule $rule.\n";
1511 return (array($rule));
1512 }
1515 function gen_uids($rule, $attributes)
1516 {
1517 global $config;
1519 /* Search for keys and fill the variables array with all
1520 possible values for that key. */
1521 $part= "";
1522 $trigger= false;
1523 $stripped= "";
1524 $variables= array();
1526 for ($pos= 0; $pos < strlen($rule); $pos++){
1528 if ($rule[$pos] == "{" ){
1529 $trigger= true;
1530 $part= "";
1531 continue;
1532 }
1534 if ($rule[$pos] == "}" ){
1535 $variables[$pos]= expand_id($part, $attributes);
1536 $stripped.= "\{$pos}";
1537 $trigger= false;
1538 continue;
1539 }
1541 if ($trigger){
1542 $part.= $rule[$pos];
1543 } else {
1544 $stripped.= $rule[$pos];
1545 }
1546 }
1548 /* Recurse through all possible combinations */
1549 $proposed= recurse($stripped, $variables);
1551 /* Get list of used ID's */
1552 $used= array();
1553 $ldap= $config->get_ldap_link();
1554 $ldap->cd($config->current['BASE']);
1555 $ldap->search('(uid=*)');
1557 while($attrs= $ldap->fetch()){
1558 $used[]= $attrs['uid'][0];
1559 }
1561 /* Remove used uids and watch out for id tags */
1562 $ret= array();
1563 foreach($proposed as $uid){
1565 /* Check for id tag and modify uid if needed */
1566 if(preg_match('/\{id:\d+}/',$uid)){
1567 $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1569 for ($i= 0; $i < pow(10,$size); $i++){
1570 $number= sprintf("%0".$size."d", $i);
1571 $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1572 if (!in_array($res, $used)){
1573 $uid= $res;
1574 break;
1575 }
1576 }
1577 }
1579 if(preg_match('/\{id#\d+}/',$uid)){
1580 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1582 while (true){
1583 mt_srand((double) microtime()*1000000);
1584 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1585 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1586 if (!in_array($res, $used)){
1587 $uid= $res;
1588 break;
1589 }
1590 }
1591 }
1593 /* Don't assign used ones */
1594 if (!in_array($uid, $used)){
1595 $ret[]= $uid;
1596 }
1597 }
1599 return(array_unique($ret));
1600 }
1603 function array_search_r($needle, $key, $haystack){
1605 foreach($haystack as $index => $value){
1606 $match= 0;
1608 if (is_array($value)){
1609 $match= array_search_r($needle, $key, $value);
1610 }
1612 if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1613 $match=1;
1614 }
1616 if ($match){
1617 return 1;
1618 }
1619 }
1621 return 0;
1622 }
1625 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1626 Need to convert... */
1627 function to_byte($value) {
1628 $value= strtolower(trim($value));
1630 if(!is_numeric(substr($value, -1))) {
1632 switch(substr($value, -1)) {
1633 case 'g':
1634 $mult= 1073741824;
1635 break;
1636 case 'm':
1637 $mult= 1048576;
1638 break;
1639 case 'k':
1640 $mult= 1024;
1641 break;
1642 }
1644 return ($mult * (int)substr($value, 0, -1));
1645 } else {
1646 return $value;
1647 }
1648 }
1651 function in_array_ics($value, $items)
1652 {
1653 if (!is_array($items)){
1654 return (FALSE);
1655 }
1657 foreach ($items as $item){
1658 if (strtolower($item) == strtolower($value)) {
1659 return (TRUE);
1660 }
1661 }
1663 return (FALSE);
1664 }
1667 function generate_alphabet($count= 10)
1668 {
1669 $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1670 $alphabet= "";
1671 $c= 0;
1673 /* Fill cells with charaters */
1674 for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1675 if ($c == 0){
1676 $alphabet.= "<tr>";
1677 }
1679 $ch = mb_substr($characters, $i, 1, "UTF8");
1680 $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1681 validate($_GET['plug'])."&search=".$ch."\"> ".$ch." </a></td>";
1683 if ($c++ == $count){
1684 $alphabet.= "</tr>";
1685 $c= 0;
1686 }
1687 }
1689 /* Fill remaining cells */
1690 while ($c++ <= $count){
1691 $alphabet.= "<td> </td>";
1692 }
1694 return ($alphabet);
1695 }
1698 function validate($string)
1699 {
1700 return (strip_tags(preg_replace('/\0/', '', $string)));
1701 }
1703 function get_gosa_version()
1704 {
1705 global $svn_revision, $svn_path;
1707 /* Extract informations */
1708 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1710 /* Release or development? */
1711 if (preg_match('%/gosa/trunk/%', $svn_path)){
1712 return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1713 } else {
1714 $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1715 return (sprintf(_("GOsa $release"), $revision));
1716 }
1717 }
1720 function rmdirRecursive($path, $followLinks=false) {
1721 $dir= opendir($path);
1722 while($entry= readdir($dir)) {
1723 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1724 unlink($path."/".$entry);
1725 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1726 rmdirRecursive($path."/".$entry);
1727 }
1728 }
1729 closedir($dir);
1730 return rmdir($path);
1731 }
1733 function scan_directory($path,$sort_desc=false)
1734 {
1735 $ret = false;
1737 /* is this a dir ? */
1738 if(is_dir($path)) {
1740 /* is this path a readable one */
1741 if(is_readable($path)){
1743 /* Get contents and write it into an array */
1744 $ret = array();
1746 $dir = opendir($path);
1748 /* Is this a correct result ?*/
1749 if($dir){
1750 while($fp = readdir($dir))
1751 $ret[]= $fp;
1752 }
1753 }
1754 }
1755 /* Sort array ascending , like scandir */
1756 sort($ret);
1758 /* Sort descending if parameter is sort_desc is set */
1759 if($sort_desc) {
1760 $ret = array_reverse($ret);
1761 }
1763 return($ret);
1764 }
1766 function clean_smarty_compile_dir($directory)
1767 {
1768 global $svn_revision;
1770 if(is_dir($directory) && is_readable($directory)) {
1771 // Set revision filename to REVISION
1772 $revision_file= $directory."/REVISION";
1774 /* Is there a stamp containing the current revision? */
1775 if(!file_exists($revision_file)) {
1776 // create revision file
1777 create_revision($revision_file, $svn_revision);
1778 } else {
1779 # check for "$config->...['CONFIG']/revision" and the
1780 # contents should match the revision number
1781 if(!compare_revision($revision_file, $svn_revision)){
1782 // If revision differs, clean compile directory
1783 foreach(scan_directory($directory) as $file) {
1784 if(($file==".")||($file=="..")) continue;
1785 if( is_file($directory."/".$file) &&
1786 is_writable($directory."/".$file)) {
1787 // delete file
1788 if(!unlink($directory."/".$file)) {
1789 print_red("File ".$directory."/".$file." could not be deleted.");
1790 // This should never be reached
1791 }
1792 } elseif(is_dir($directory."/".$file) &&
1793 is_writable($directory."/".$file)) {
1794 // Just recursively delete it
1795 rmdirRecursive($directory."/".$file);
1796 }
1797 }
1798 // We should now create a fresh revision file
1799 clean_smarty_compile_dir($directory);
1800 } else {
1801 // Revision matches, nothing to do
1802 }
1803 }
1804 } else {
1805 // Smarty compile dir is not accessible
1806 // (Smarty will warn about this)
1807 }
1808 }
1810 function create_revision($revision_file, $revision)
1811 {
1812 $result= false;
1814 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1815 if($fh= fopen($revision_file, "w")) {
1816 if(fwrite($fh, $revision)) {
1817 $result= true;
1818 }
1819 }
1820 fclose($fh);
1821 } else {
1822 print_red("Can not write to revision file");
1823 }
1825 return $result;
1826 }
1828 function compare_revision($revision_file, $revision)
1829 {
1830 // false means revision differs
1831 $result= false;
1833 if(file_exists($revision_file) && is_readable($revision_file)) {
1834 // Open file
1835 if($fh= fopen($revision_file, "r")) {
1836 // Compare File contents with current revision
1837 if($revision == fread($fh, filesize($revision_file))) {
1838 $result= true;
1839 }
1840 } else {
1841 print_red("Can not open revision file");
1842 }
1843 // Close file
1844 fclose($fh);
1845 }
1847 return $result;
1848 }
1850 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1851 {
1852 $str = ""; // Our return value will be saved in this var
1854 $color = dechex($percentage+150);
1855 $color2 = dechex(150 - $percentage);
1856 $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1858 $progress = (int)(($percentage /100)*$width);
1860 /* Abort printing out percentage, if divs are to small */
1863 /* If theres a better solution for this, use it... */
1864 $str = "
1865 <div style=\" width:".($width)."px;
1866 height:".($height)."px;
1867 background-color:#000000;
1868 padding:1px;\">
1870 <div style=\" width:".($width)."px;
1871 background-color:#$bgcolor;
1872 height:".($height)."px;\">
1874 <div style=\" width:".$progress."px;
1875 height:".$height."px;
1876 background-color:#".$color2.$color2.$color."; \">";
1879 if(($height >10)&&($showvalue)){
1880 $str.= "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1881 <b>".$percentage."%</b>
1882 </font>";
1883 }
1885 $str.= "</div></div></div>";
1887 return($str);
1888 }
1891 function array_key_ics($ikey, $items)
1892 {
1893 /* Gather keys, make them lowercase */
1894 $tmp= array();
1895 foreach ($items as $key => $value){
1896 $tmp[strtolower($key)]= $key;
1897 }
1899 if (isset($tmp[strtolower($ikey)])){
1900 return($tmp[strtolower($ikey)]);
1901 }
1903 return ("");
1904 }
1907 function search_config($arr, $name, $return)
1908 {
1909 if (is_array($arr)){
1910 foreach ($arr as $a){
1911 if (isset($a['CLASS']) &&
1912 strtolower($a['CLASS']) == strtolower($name)){
1914 if (isset($a[$return])){
1915 return ($a[$return]);
1916 } else {
1917 return ("");
1918 }
1919 } else {
1920 $res= search_config ($a, $name, $return);
1921 if ($res != ""){
1922 return $res;
1923 }
1924 }
1925 }
1926 }
1927 return ("");
1928 }
1931 function array_differs($src, $dst)
1932 {
1933 /* If the count is differing, the arrays differ */
1934 if (count ($src) != count ($dst)){
1935 return (TRUE);
1936 }
1938 /* So the count is the same - lets check the contents */
1939 $differs= FALSE;
1940 foreach($src as $value){
1941 if (!in_array($value, $dst)){
1942 $differs= TRUE;
1943 }
1944 }
1946 return ($differs);
1947 }
1950 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1951 ?>