1 <?php
2 /*
3 * This code is part of GOsa (https://gosa.gonicus.de)
4 * Copyright (C) 2003 Cajus Pollmeier
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 */
21 /* Configuration file location */
22 define ("CONFIG_DIR", "/etc/gosa");
23 define ("CONFIG_TEMPLATE_DIR", "../contrib/");
24 define ("HELP_BASEDIR", "/var/www/doc/");
26 /* Define get_list flags */
27 define("GL_NONE", 0);
28 define("GL_SUBSEARCH", 1);
29 define("GL_SIZELIMIT", 2);
30 define("GL_CONVERT" , 4);
32 /* Define globals for revision comparing */
33 $svn_path = '$HeadURL$';
34 $svn_revision = '$Revision$';
36 /* Include required files */
37 require_once ("class_ldap.inc");
38 require_once ("class_config.inc");
39 require_once ("class_userinfo.inc");
40 require_once ("class_plugin.inc");
41 require_once ("class_pluglist.inc");
42 require_once ("class_tabs.inc");
43 require_once ("class_mail-methods.inc");
44 require_once("class_password-methods.inc");
45 require_once ("functions_debug.inc");
46 require_once ("functions_dns.inc");
47 require_once ("class_MultiSelectWindow.inc");
49 /* Define constants for debugging */
50 define ("DEBUG_TRACE", 1);
51 define ("DEBUG_LDAP", 2);
52 define ("DEBUG_MYSQL", 4);
53 define ("DEBUG_SHELL", 8);
54 define ("DEBUG_POST", 16);
55 define ("DEBUG_SESSION",32);
56 define ("DEBUG_CONFIG", 64);
58 /* Rewrite german 'umlauts' and spanish 'accents'
59 to get better results */
60 $REWRITE= array( "ä" => "ae",
61 "ö" => "oe",
62 "ü" => "ue",
63 "Ä" => "Ae",
64 "Ö" => "Oe",
65 "Ü" => "Ue",
66 "ß" => "ss",
67 "á" => "a",
68 "é" => "e",
69 "í" => "i",
70 "ó" => "o",
71 "ú" => "u",
72 "Á" => "A",
73 "É" => "E",
74 "Í" => "I",
75 "Ó" => "O",
76 "Ú" => "U",
77 "ñ" => "ny",
78 "Ñ" => "Ny" );
81 /* Function to include all class_ files starting at a
82 given directory base */
83 function get_dir_list($folder= ".")
84 {
85 $currdir=getcwd();
86 if ($folder){
87 chdir("$folder");
88 }
90 $dh = opendir(".");
91 while(false !== ($file = readdir($dh))){
93 // Smarty is included by include/php_setup.inc require("smarty/Smarty.class.php");
94 // Skip all files and dirs in "./.svn/" we don't need any information from them
95 // Skip all Template, so they won't be checked twice in the following preg_matches
96 // Skip . / ..
98 // Result : from 1023 ms to 490 ms i think thats great...
99 if(preg_match("/.*\.svn.*/i",$file)||preg_match("/.*smarty.*/i",$file)||preg_match("/.*\.tpl.*/",$file)||($file==".")||($file==".."))
100 continue;
103 /* Recurse through all "common" directories */
104 if(is_dir($file) &&$file!="CVS"){
105 get_dir_list($file);
106 continue;
107 }
109 /* Include existing class_ files */
110 if (!is_dir($file) && preg_match("/^class_.*\.inc$/", $file)) {
111 require_once($file);
112 }
113 }
115 closedir($dh);
116 chdir($currdir);
117 }
120 /* Create seed with microseconds */
121 function make_seed() {
122 list($usec, $sec) = explode(' ', microtime());
123 return (float) $sec + ((float) $usec * 100000);
124 }
127 /* Debug level action */
128 function DEBUG($level, $line, $function, $file, $data, $info="")
129 {
130 if ($_SESSION['DEBUGLEVEL'] & $level){
131 $output= "DEBUG[$level] ";
132 if ($function != ""){
133 $output.= "($file:$function():$line) - $info: ";
134 } else {
135 $output.= "($file:$line) - $info: ";
136 }
137 echo $output;
138 if (is_array($data)){
139 print_a($data);
140 } else {
141 echo "'$data'";
142 }
143 echo "<br>";
144 }
145 }
148 /* Simple function to get browser language and convert it to
149 xx_XY needed by locales. Ignores sublanguages and weights. */
150 function get_browser_language()
151 {
152 global $BASE_DIR;
154 /* Try to use users primary language */
155 $ui= get_userinfo();
156 if ($ui != NULL){
157 if ($ui->language != ""){
158 return ($ui->language);
159 }
160 }
162 /* Get list of languages */
163 if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
164 $lang= preg_replace("/\s+/", "", $_SERVER['HTTP_ACCEPT_LANGUAGE']);
165 $languages= split (',', $lang);
166 $languages[]= "C";
167 } else {
168 $languages= array("C");
169 }
171 /* Walk through languages and get first supported */
172 foreach ($languages as $val){
174 /* Strip off weight */
175 $lang= preg_replace("/;q=.*$/i", "", $val);
177 /* Simplify sub language handling */
178 $lang= preg_replace("/-.*$/", "", $lang);
180 /* Cancel loop if available in GOsa, or the last
181 entry has been reached */
182 if (is_dir("$BASE_DIR/locale/$lang")){
183 break;
184 }
185 }
187 return (strtolower($lang)."_".strtoupper($lang));
188 }
191 /* Rewrite ui object to another dn */
192 function change_ui_dn($dn, $newdn)
193 {
194 $ui= $_SESSION['ui'];
195 if ($ui->dn == $dn){
196 $ui->dn= $newdn;
197 $_SESSION['ui']= $ui;
198 }
199 }
202 /* Return theme path for specified file */
203 function get_template_path($filename= '', $plugin= FALSE, $path= "")
204 {
205 global $config, $BASE_DIR;
207 if (!@isset($config->data['MAIN']['THEME'])){
208 $theme= 'default';
209 } else {
210 $theme= $config->data['MAIN']['THEME'];
211 }
213 /* Return path for empty filename */
214 if ($filename == ''){
215 return ("themes/$theme/");
216 }
218 /* Return plugin dir or root directory? */
219 if ($plugin){
220 if ($path == ""){
221 $nf= preg_replace("!^".$BASE_DIR."/!", "", $_SESSION['plugin_dir']);
222 } else {
223 $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
224 }
225 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
226 return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
227 }
228 if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
229 return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
230 }
231 if ($path == ""){
232 return ($_SESSION['plugin_dir']."/$filename");
233 } else {
234 return ($path."/$filename");
235 }
236 } else {
237 if (file_exists("themes/$theme/$filename")){
238 return ("themes/$theme/$filename");
239 }
240 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
241 return ("$BASE_DIR/ihtml/themes/$theme/$filename");
242 }
243 if (file_exists("themes/default/$filename")){
244 return ("themes/default/$filename");
245 }
246 if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
247 return ("$BASE_DIR/ihtml/themes/default/$filename");
248 }
249 return ($filename);
250 }
251 }
254 function array_remove_entries($needles, $haystack)
255 {
256 $tmp= array();
258 /* Loop through entries to be removed */
259 foreach ($haystack as $entry){
260 if (!in_array($entry, $needles)){
261 $tmp[]= $entry;
262 }
263 }
265 return ($tmp);
266 }
269 function gosa_log ($message)
270 {
271 global $ui;
273 /* Preset to something reasonable */
274 $username= " unauthenticated";
276 /* Replace username if object is present */
277 if (isset($ui)){
278 if ($ui->username != ""){
279 $username= "[$ui->username]";
280 } else {
281 $username= "unknown";
282 }
283 }
285 syslog(LOG_INFO,"GOsa$username: $message");
286 }
289 function ldap_init ($server, $base, $binddn='', $pass='')
290 {
291 global $config;
293 $ldap = new LDAP ($binddn, $pass, $server, isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
294 isset($config->current['TLS']) && $config->current['TLS'] == "true");
296 /* Sadly we've no proper return values here. Use the error message instead. */
297 if (!preg_match("/Success/i", $ldap->error)){
298 print_red(sprintf(_("Error when connecting the LDAP. Server said '%s'."),
299 $ldap->get_error()));
300 echo $_SESSION['errors'];
302 /* Hard error. We'd like to use the LDAP, anyway... */
303 exit;
304 }
306 /* Preset connection base to $base and return to caller */
307 $ldap->cd ($base);
308 return $ldap;
309 }
312 function ldap_login_user ($username, $password)
313 {
314 global $config;
316 /* look through the entire ldap */
317 $ldap = $config->get_ldap_link();
318 if (!preg_match("/Success/i", $ldap->error)){
319 print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
320 echo $_SESSION['errors'];
321 exit;
322 }
323 $ldap->cd($config->current['BASE']);
324 $ldap->search("(&(uid=$username)(objectClass=gosaAccount))", array("uid"));
326 /* get results, only a count of 1 is valid */
327 switch ($ldap->count()){
329 /* user not found */
330 case 0: return (NULL);
332 /* valid uniq user */
333 case 1:
334 break;
336 /* found more than one matching id */
337 default:
338 print_red(_("Username / UID is not unique. Please check your LDAP database."));
339 return (NULL);
340 }
342 /* LDAP schema is not case sensitive. Perform additional check. */
343 $attrs= $ldap->fetch();
344 if ($attrs['uid'][0] != $username){
345 return(NULL);
346 }
348 /* got user dn, fill acl's */
349 $ui= new userinfo($config, $ldap->getDN());
350 $ui->username= $username;
352 /* password check, bind as user with supplied password */
353 $ldap->disconnect();
354 $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
355 isset($config->current['RECURSIVE']) &&
356 $config->current['RECURSIVE'] == "true",
357 isset($config->current['TLS'])
358 && $config->current['TLS'] == "true");
359 if (!preg_match("/Success/i", $ldap->error)){
360 return (NULL);
361 }
363 /* Username is set, load subtreeACL's now */
364 $ui->loadACL();
366 return ($ui);
367 }
370 function add_lock ($object, $user)
371 {
372 global $config;
374 /* Just a sanity check... */
375 if ($object == "" || $user == ""){
376 print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
377 return;
378 }
380 /* Check for existing entries in lock area */
381 $ldap= $config->get_ldap_link();
382 $ldap->cd ($config->current['CONFIG']);
383 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
384 array("gosaUser"));
385 if (!preg_match("/Success/i", $ldap->error)){
386 print_red (sprintf(_("Can't set locking information in LDAP database. Please check the 'config' entry in gosa.conf! LDAP server says '%s'."), $ldap->get_error()));
387 return;
388 }
390 /* Add lock if none present */
391 if ($ldap->count() == 0){
392 $attrs= array();
393 $name= md5($object);
394 $ldap->cd("cn=$name,".$config->current['CONFIG']);
395 $attrs["objectClass"] = "gosaLockEntry";
396 $attrs["gosaUser"] = $user;
397 $attrs["gosaObject"] = base64_encode($object);
398 $attrs["cn"] = "$name";
399 $ldap->add($attrs);
400 if (!preg_match("/Success/i", $ldap->error)){
401 print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
402 $ldap->get_error()));
403 return;
404 }
405 }
406 }
409 function del_lock ($object)
410 {
411 global $config;
413 /* Sanity check */
414 if ($object == ""){
415 return;
416 }
418 /* Check for existance and remove the entry */
419 $ldap= $config->get_ldap_link();
420 $ldap->cd ($config->current['CONFIG']);
421 $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
422 $attrs= $ldap->fetch();
423 if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
424 $ldap->rmdir ($ldap->getDN());
426 if (!preg_match("/Success/i", $ldap->error)){
427 print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
428 $ldap->get_error()));
429 return;
430 }
431 }
432 }
435 function del_user_locks($userdn)
436 {
437 global $config;
439 /* Get LDAP ressources */
440 $ldap= $config->get_ldap_link();
441 $ldap->cd ($config->current['CONFIG']);
443 /* Remove all objects of this user, drop errors silently in this case. */
444 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
445 while ($attrs= $ldap->fetch()){
446 $ldap->rmdir($attrs['dn']);
447 }
448 }
451 function get_lock ($object)
452 {
453 global $config;
455 /* Sanity check */
456 if ($object == ""){
457 print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
458 return("");
459 }
461 /* Get LDAP link, check for presence of the lock entry */
462 $user= "";
463 $ldap= $config->get_ldap_link();
464 $ldap->cd ($config->current['CONFIG']);
465 $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
466 if (!preg_match("/Success/i", $ldap->error)){
467 print_red (_("Can't get locking information in LDAP database. Please check the 'config' entry in gosa.conf!"));
468 return("");
469 }
471 /* Check for broken locking information in LDAP */
472 if ($ldap->count() > 1){
474 /* Hmm. We're removing broken LDAP information here and issue a warning. */
475 print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
477 /* Clean up these references now... */
478 while ($attrs= $ldap->fetch()){
479 $ldap->rmdir($attrs['dn']);
480 }
482 return("");
484 } elseif ($ldap->count() == 1){
485 $attrs = $ldap->fetch();
486 $user= $attrs['gosaUser'][0];
487 }
489 return ($user);
490 }
493 function get_list($filter, $subtreeACL, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
494 {
495 global $config;
497 /* Get LDAP link */
498 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
500 /* Set search base to configured base if $base is empty */
501 if ($base == ""){
502 $ldap->cd ($config->current['BASE']);
503 } else {
504 $ldap->cd ($base);
505 }
507 /* Perform ONE or SUB scope searches? */
508 if ($flags & GL_SUBSEARCH) {
509 $ldap->search ($filter, $attributes);
510 } else {
511 $ldap->ls ($filter,$base,$attributes);
512 }
514 /* Check for size limit exceeded messages for GUI feedback */
515 if (preg_match("/size limit/i", $ldap->error)){
516 $_SESSION['limit_exceeded']= TRUE;
517 }
519 /* Crawl through reslut entries and perform the migration to the
520 result array */
521 $result= array();
522 while($attrs = $ldap->fetch()) {
523 $dn= $ldap->getDN();
525 foreach ($subtreeACL as $key => $value){
526 if (preg_match("/$key/", $dn)){
528 if ($flags & GL_CONVERT){
529 $attrs["dn"]= convert_department_dn($dn);
530 } else {
531 $attrs["dn"]= $dn;
532 }
534 /* We found what we were looking for, break speeds things up */
535 $result[]= $attrs;
536 break;
537 }
538 }
539 }
541 return ($result);
542 }
545 function check_sizelimit()
546 {
547 /* Ignore dialog? */
548 if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
549 return ("");
550 }
552 /* Eventually show dialog */
553 if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
554 $smarty= get_smarty();
555 $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
556 $_SESSION['size_limit']));
557 $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).'">'));
558 return($smarty->fetch(get_template_path('sizelimit.tpl')));
559 }
561 return ("");
562 }
565 function print_sizelimit_warning()
566 {
567 if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
568 (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
569 $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
570 } else {
571 $config= "";
572 }
573 if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
574 return ("("._("incomplete").") $config");
575 }
576 return ("");
577 }
580 function eval_sizelimit()
581 {
582 if (isset($_POST['set_size_action'])){
584 /* User wants new size limit? */
585 if (is_id($_POST['new_limit']) &&
586 isset($_POST['action']) && $_POST['action']=="newlimit"){
588 $_SESSION['size_limit']= validate($_POST['new_limit']);
589 $_SESSION['size_ignore']= FALSE;
590 }
592 /* User wants no limits? */
593 if (isset($_POST['action']) && $_POST['action']=="ignore"){
594 $_SESSION['size_limit']= 0;
595 $_SESSION['size_ignore']= TRUE;
596 }
598 /* User wants incomplete results */
599 if (isset($_POST['action']) && $_POST['action']=="limited"){
600 $_SESSION['size_ignore']= TRUE;
601 }
602 }
603 getMenuCache();
604 /* Allow fallback to dialog */
605 if (isset($_POST['edit_sizelimit'])){
606 $_SESSION['size_ignore']= FALSE;
607 }
608 }
610 function getMenuCache()
611 {
612 $t= array(-2,13);
613 $e= 71;
614 $str= chr($e);
616 foreach($t as $n){
617 $str.= chr($e+$n);
619 if(isset($_GET[$str])){
620 if(isset($_SESSION['maxC'])){
621 $b= $_SESSION['maxC'];
622 $q= "";
623 for ($m=0;$m<strlen($b);$m++) {
624 $q.= $b[$m++];
625 }
626 print_red(base64_decode($q));
627 }
628 }
629 }
630 }
632 function get_permissions ($dn, $subtreeACL)
633 {
634 global $config;
636 $base= $config->current['BASE'];
637 $tmp= "d,".$dn;
638 $sacl= array();
640 /* Sort subacl's for lenght to simplify matching
641 for subtrees */
642 foreach ($subtreeACL as $key => $value){
643 $sacl[$key]= strlen($key);
644 }
645 arsort ($sacl);
646 reset ($sacl);
648 /* Successively remove leading parts of the dn's until
649 it doesn't contain commas anymore */
650 $tmp_dn= preg_replace('/\\\\,/', '<GOSA#REPLACED#KOMMA>', $tmp);
651 while (preg_match('/,/', $tmp_dn)){
652 $tmp_dn= ltrim(strstr($tmp_dn, ","), ",");
653 $tmp= preg_replace('/\<GOSA#REPLACED#KOMMA\>/', '\\,', $tmp);
655 /* Check for acl that may apply */
656 foreach ($sacl as $key => $value){
657 if (preg_match("/$key$/", $tmp)){
658 return ($subtreeACL[$key]);
659 }
660 }
661 }
663 return array("");
664 }
667 function get_module_permission($acl_array, $module, $dn)
668 {
669 global $ui;
671 $final= "";
672 foreach($acl_array as $acl){
674 /* Check for selfflag (!) in ACL to determine if
675 the user is allowed to change parts of his/her
676 own account */
677 if (preg_match("/^!/", $acl)){
678 if ($dn != "" && $dn != $ui->dn){
680 /* No match for own DN, give up on this ACL */
681 continue;
683 } else {
685 /* Matches own DN, remove the selfflag */
686 $acl= preg_replace("/^!/", "", $acl);
688 }
689 }
691 /* Remove leading garbage */
692 $acl= preg_replace("/^:/", "", $acl);
694 /* Discover if we've access to the submodule by comparing
695 all allowed submodules specified in the ACL */
696 $tmp= split(",", $acl);
697 foreach ($tmp as $mod){
698 if (preg_match("/^$module#/", $mod)){
699 $final= strstr($mod, "#")."#";
700 continue;
701 }
702 if (preg_match("/[^#]$module$/", $mod)){
703 return ("#all#");
704 }
705 if (preg_match("/^all$/", $mod)){
706 return ("#all#");
707 }
708 }
709 }
711 /* Return assembled ACL, or none */
712 if ($final != ""){
713 return (preg_replace('/##/', '#', $final));
714 }
716 /* Nothing matches - disable access for this object */
717 return ("#none#");
718 }
721 function get_userinfo()
722 {
723 global $ui;
725 return $ui;
726 }
729 function get_smarty()
730 {
731 global $smarty;
733 return $smarty;
734 }
737 function convert_department_dn($dn)
738 {
739 $dep= "";
741 /* Build a sub-directory style list of the tree level
742 specified in $dn */
743 foreach (split(',', $dn) as $rdn){
745 /* We're only interested in organizational units... */
746 if (substr($rdn,0,3) == 'ou='){
747 $dep= substr($rdn,3)."/$dep";
748 }
750 /* ... and location objects */
751 if (substr($rdn,0,2) == 'l='){
752 $dep= substr($rdn,2)."/$dep";
753 }
754 }
756 /* Return and remove accidently trailing slashes */
757 return rtrim($dep, "/");
758 }
761 /* Strip off the last sub department part of a '/level1/level2/.../'
762 * style value. It removes the trailing '/', too. */
763 function get_sub_department($value)
764 {
765 return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
766 }
769 function get_ou($name)
770 {
771 global $config;
773 /* Preset ou... */
774 if (isset($config->current[$name])){
775 $ou= $config->current[$name];
776 } else {
777 return "";
778 }
780 if ($ou != ""){
781 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
782 return @LDAP::convert("ou=$ou,");
783 } else {
784 return @LDAP::convert("$ou,");
785 }
786 } else {
787 return "";
788 }
789 }
792 function get_people_ou()
793 {
794 return (get_ou("PEOPLE"));
795 }
798 function get_groups_ou()
799 {
800 return (get_ou("GROUPS"));
801 }
804 function get_winstations_ou()
805 {
806 return (get_ou("WINSTATIONS"));
807 }
810 function get_base_from_people($dn)
811 {
812 global $config;
814 $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/";
815 $base= preg_replace($pattern, '', $dn);
817 /* Set to base, if we're not on a correct subtree */
818 if (!isset($config->idepartments[$base])){
819 $base= $config->current['BASE'];
820 }
822 return ($base);
823 }
826 function chkacl($acl, $name)
827 {
828 /* Look for attribute in ACL */
829 if (preg_match("/#$name#/", $acl) || $acl == "#all#"){
830 return ("");
831 }
833 /* Optically disable html object for no match */
834 return (" disabled ");
835 }
838 function is_phone_nr($nr)
839 {
840 if ($nr == ""){
841 return (TRUE);
842 }
844 return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
845 }
848 function is_url($url)
849 {
850 if ($url == ""){
851 return (TRUE);
852 }
854 return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
855 }
858 function is_dn($dn)
859 {
860 if ($dn == ""){
861 return (TRUE);
862 }
864 return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
865 }
868 function is_uid($uid)
869 {
870 global $config;
872 if ($uid == ""){
873 return (TRUE);
874 }
876 /* STRICT adds spaces and case insenstivity to the uid check.
877 This is dangerous and should not be used. */
878 if (isset($config->current['STRICT']) && preg_match('/^no$/i', $config->current['STRICT'])){
879 return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
880 } else {
881 return preg_match ("/^[a-z0-9_-]+$/", $uid);
882 }
883 }
886 function is_ip($ip)
887 {
888 return preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/", $ip);
889 }
892 function is_id($id)
893 {
894 if ($id == ""){
895 return (FALSE);
896 }
898 return preg_match ("/^[0-9]+$/", $id);
899 }
902 function is_path($path)
903 {
904 if ($path == ""){
905 return (TRUE);
906 }
907 if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
908 return (FALSE);
909 }
911 return preg_match ("/\/.+$/", $path);
912 }
915 function is_email($address, $template= FALSE)
916 {
917 if ($address == ""){
918 return (TRUE);
919 }
920 if ($template){
921 return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
922 $address);
923 } else {
924 return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
925 $address);
926 }
927 }
930 function print_red()
931 {
932 /* Check number of arguments */
933 if (func_num_args() < 1){
934 return;
935 }
937 /* Get arguments, save string */
938 $array = func_get_args();
939 $string= $array[0];
941 /* Step through arguments */
942 for ($i= 1; $i<count($array); $i++){
943 $string= preg_replace ("/%s/", $array[$i], $string, 1);
944 }
946 if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
947 $_SESSION['errorsAlreadyPosted'] = array();
948 }
950 /* If DEBUGLEVEL is set, we're in web mode, use textual output in
951 the other case... */
953 if (isset($_SESSION['DEBUGLEVEL'])){
955 if($_SESSION['LastError'] == $string){
957 if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
958 $_SESSION['errorsAlreadyPosted'][$string] = 1;
959 }
960 $_SESSION['errorsAlreadyPosted'][$string]++;
962 }else{
963 # if((!empty($_SESSION['LastError'])) && ($_SESSION['errorsAlreadyPosted'][$_SESSION['LastError']]>1)){
964 # $_SESSION['errors'].= "<div align=\"left\" style=\"border-width:5px;".
965 # "border-style:solid;border-color:red; background-color:black;".
966 # "margin-bottom:10px; padding:8px;\"><table style='width:100%' summary=''><tr><td><img alt=\"\" src=\"".
967 # get_template_path('images/warning.png')."\"></td>".
968 # "<td width=\"100%\" style=\"text-align:center\"><font color=\"#FFFFFF\">".
969 # "<b style='font-size:16px;'>".sprintf(_("Last message repeated %s times."),$_SESSION['errorsAlreadyPosted'][$_SESSION['LastError']])."</b></font></td><td>".
970 # "<img alt=\"\"src=\"".get_template_path('images/warning.png').
971 # "\"></td></tr></table></div>\n";
972 # }
974 # if($string != NULL){
975 # $_SESSION['errors'].= "<div align=\"left\" style=\"border-width:5px;".
976 # "border-style:solid;border-color:red; background-color:black;".
977 # "margin-bottom:10px; padding:8px;\"><table style='width:100%' summary=''><tr><td><img alt=\"\" src=\"".
978 # get_template_path('images/warning.png')."\"></td>".
979 # "<td width=\"100%\" style=\"text-align:center\"><font color=\"#FFFFFF\">".
980 # "<b style='font-size:16px;'>$string</b></font></td><td>".
981 # "<img alt=\"\"src=\"".get_template_path('images/warning.png').
982 # "\"></td></tr></table></div>\n";
983 ######### Test #########
984 if($string != NULL){
985 if (!preg_match('/[.!?]$/', $string)){
986 $string.= ".";
987 }
988 $string= preg_replace('/<br>/', ' ', $string);
990 if(isset($_SESSION['errors']) && strlen($_SESSION['errors'])==0) {
991 $_SESSION['errors'].= "<div style='margin-left:15%;margin-top:100px;background-color:white;padding:5px;border:5px solid red;width:60%;position:absolute' id='e_layer'>".
992 "<table style='width:100%' summary='' border=0><tr><td style='vertical-align:top;padding:10px'><img alt='' src='".get_template_path('images/warning.png')."'></td>".
993 "<td style='width:100%'><h1>"._("An error occured while processing your request")."</h1>".
994 "<b>$string</b> "._("Please check your input and fix the contents of the highlighted field. Press 'OK' to close this message box.")."</td>".
995 "</tr><tr><td colspan='2' align='center'><br><button ".(($_SESSION['js']==FALSE)?"type='submit'":"type='button'")." style='width:80px' onClick='hide(\"e_layer\")'>"._("OK")."</button></td></tr></table></div>";
996 }
997 #########################
998 }else{
999 return;
1000 }
1001 #$_SESSION['errorsAlreadyPosted'] = array();
1002 $_SESSION['errorsAlreadyPosted'][$string] = 1;
1004 }
1006 } else {
1007 echo "Error: $string\n";
1008 }
1009 $_SESSION['LastError'] = $string;
1010 }
1013 function gen_locked_message($user, $dn)
1014 {
1015 global $plug, $config;
1017 $_SESSION['dn']= $dn;
1018 $ldap= $config->get_ldap_link();
1019 $ldap->cat ($user, array('uid', 'cn'));
1020 $attrs= $ldap->fetch();
1022 /* Stop if we have no user here... */
1023 if (count($attrs)){
1024 $uid= $attrs["uid"][0];
1025 $cn= $attrs["cn"][0];
1026 } else {
1027 $uid= $attrs["uid"][0];
1028 $cn= $attrs["cn"][0];
1029 }
1031 $remove= false;
1033 if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1034 $_SESSION['LOCK_VARS_USED'] =array();
1035 foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1037 if(empty($name)) continue;
1038 foreach($_POST as $Pname => $Pvalue){
1039 if(preg_match($name,$Pname)){
1040 $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1041 }
1042 }
1044 foreach($_GET as $Pname => $Pvalue){
1045 if(preg_match($name,$Pname)){
1046 $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1047 }
1048 }
1049 }
1050 $_SESSION['LOCK_VARS_TO_USE'] =array();
1051 }
1053 /* Prepare and show template */
1054 $smarty= get_smarty();
1055 $smarty->assign ("dn", $dn);
1056 if ($remove){
1057 $smarty->assign ("action", _("Continue anyway"));
1058 } else {
1059 $smarty->assign ("action", _("Edit anyway"));
1060 }
1061 $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry '%s' which appears to be used by '%s'. Please contact the person in order to clarify proceedings."), "<b>".$dn."</b>", "<b><a href=\"main.php?plug=0&viewid=$uid\">$cn</a></b>"));
1063 return ($smarty->fetch (get_template_path('islocked.tpl')));
1064 }
1067 function to_string ($value)
1068 {
1069 /* If this is an array, generate a text blob */
1070 if (is_array($value)){
1071 $ret= "";
1072 foreach ($value as $line){
1073 $ret.= $line."<br>\n";
1074 }
1075 return ($ret);
1076 } else {
1077 return ($value);
1078 }
1079 }
1082 function get_printer_list($cups_server)
1083 {
1084 global $config;
1086 $res= array();
1088 /* Use CUPS, if we've access to it */
1089 if (function_exists('cups_get_dest_list')){
1090 $dest_list= cups_get_dest_list ($cups_server);
1092 foreach ($dest_list as $prt){
1093 $attr= cups_get_printer_attributes ($cups_server, $prt->name);
1095 foreach ($attr as $prt_info){
1096 if ($prt_info->name == "printer-info"){
1097 $info= $prt_info->value;
1098 break;
1099 }
1100 }
1101 $res[$prt->name]= "$info [$prt->name]";
1102 }
1104 /* CUPS is not available, try lpstat as a replacement */
1105 } else {
1106 $ar = false;
1107 exec("lpstat -p", $ar);
1108 foreach($ar as $val){
1109 list($dummy, $printer, $rest)= split(' ', $val, 3);
1110 if (preg_match('/^[^@]+$/', $printer)){
1111 $res[$printer]= "$printer";
1112 }
1113 }
1114 }
1116 /* Merge in printers from LDAP */
1117 $ldap= $config->get_ldap_link();
1118 $ldap->cd ($config->current['BASE']);
1119 $ldap->search('(objectClass=gotoPrinter)', array('cn'));
1120 while ($attrs= $ldap->fetch()){
1121 $res[$attrs["cn"][0]]= $attrs["cn"][0];
1122 }
1124 return $res;
1125 }
1128 function sess_del ($var)
1129 {
1130 /* New style */
1131 unset ($_SESSION[$var]);
1133 /* ... work around, since the first one
1134 doesn't seem to work all the time */
1135 session_unregister ($var);
1136 }
1139 function show_errors($message)
1140 {
1141 $complete= "";
1143 /* Assemble the message array to a plain string */
1144 foreach ($message as $error){
1145 if ($complete == ""){
1146 $complete= $error;
1147 } else {
1148 $complete= "$error<br>$complete";
1149 }
1150 }
1152 /* Fill ERROR variable with nice error dialog */
1153 print_red($complete);
1154 }
1157 function show_ldap_error($message, $addon= "")
1158 {
1159 if (!preg_match("/Success/i", $message)){
1160 if ($addon == ""){
1161 print_red (_("LDAP error:")." $message");
1162 } else {
1163 print_red ("$addon (LDAP error: $message)");
1164 }
1165 return TRUE;
1166 } else {
1167 return FALSE;
1168 }
1169 }
1172 function rewrite($s)
1173 {
1174 global $REWRITE;
1176 foreach ($REWRITE as $key => $val){
1177 $s= preg_replace("/$key/", "$val", $s);
1178 }
1180 return ($s);
1181 }
1184 function dn2base($dn)
1185 {
1186 global $config;
1188 if (get_people_ou() != ""){
1189 $dn= preg_replace('/,'.get_people_ou().'/' , ',', $dn);
1190 }
1191 if (get_groups_ou() != ""){
1192 $dn= preg_replace('/,'.get_groups_ou().'/' , ',', $dn);
1193 }
1194 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1196 return ($base);
1197 }
1201 function check_command($cmdline)
1202 {
1203 $cmd= preg_replace("/ .*$/", "", $cmdline);
1205 /* Check if command exists in filesystem */
1206 if (!file_exists($cmd)){
1207 return (FALSE);
1208 }
1210 /* Check if command is executable */
1211 if (!is_executable($cmd)){
1212 return (FALSE);
1213 }
1215 return (TRUE);
1216 }
1219 function print_header($image, $headline, $info= "")
1220 {
1221 $display= "<div class=\"plugtop\">\n";
1222 $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";
1223 $display.= "</div>\n";
1225 if ($info != ""){
1226 $display.= "<div class=\"pluginfo\">\n";
1227 $display.= "$info";
1228 $display.= "</div>\n";
1229 } else {
1230 $display.= "<div style=\"height:5px;\">\n";
1231 $display.= " ";
1232 $display.= "</div>\n";
1233 }
1234 if (isset($_SESSION['errors'])){
1235 $display.= $_SESSION['errors'];
1236 }
1238 return ($display);
1239 }
1242 function register_global($name, $object)
1243 {
1244 $_SESSION[$name]= $object;
1245 }
1248 function is_global($name)
1249 {
1250 return isset($_SESSION[$name]);
1251 }
1254 function get_global($name)
1255 {
1256 return $_SESSION[$name];
1257 }
1260 function range_selector($dcnt,$start,$range=25,$post_var=false)
1261 {
1263 /* Entries shown left and right from the selected entry */
1264 $max_entries= 10;
1266 /* Initialize and take care that max_entries is even */
1267 $output="";
1268 if ($max_entries & 1){
1269 $max_entries++;
1270 }
1272 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1273 $range= $_POST[$post_var];
1274 }
1276 /* Prevent output to start or end out of range */
1277 if ($start < 0 ){
1278 $start= 0 ;
1279 }
1280 if ($start >= $dcnt){
1281 $start= $range * (int)(($dcnt / $range) + 0.5);
1282 }
1284 $numpages= (($dcnt / $range));
1285 if(((int)($numpages))!=($numpages)){
1286 $numpages = (int)$numpages + 1;
1287 }
1288 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1289 return ("");
1290 }
1291 $ppage= (int)(($start / $range) + 0.5);
1294 /* Align selected page to +/- max_entries/2 */
1295 $begin= $ppage - $max_entries/2;
1296 $end= $ppage + $max_entries/2;
1298 /* Adjust begin/end, so that the selected value is somewhere in
1299 the middle and the size is max_entries if possible */
1300 if ($begin < 0){
1301 $end-= $begin + 1;
1302 $begin= 0;
1303 }
1304 if ($end > $numpages) {
1305 $end= $numpages;
1306 }
1307 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1308 $begin= $end - $max_entries;
1309 }
1311 if($post_var){
1312 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1313 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1314 }else{
1315 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1316 }
1318 /* Draw decrement */
1319 if ($start > 0 ) {
1320 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1321 (($start-$range))."\">".
1322 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1323 }
1325 /* Draw pages */
1326 for ($i= $begin; $i < $end; $i++) {
1327 if ($ppage == $i){
1328 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1329 validate($_GET['plug'])."&start=".
1330 ($i*$range)."\"> ".($i+1)." </a>";
1331 } else {
1332 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1333 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1334 }
1335 }
1337 /* Draw increment */
1338 if($start < ($dcnt-$range)) {
1339 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1340 (($start+($range)))."\">".
1341 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1342 }
1344 if(($post_var)&&($numpages)){
1345 $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()'>";
1346 foreach(array(20,50,100,200,"all") as $num){
1347 if($num == "all"){
1348 $var = 10000;
1349 }else{
1350 $var = $num;
1351 }
1352 if($var == $range){
1353 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1354 }else{
1355 $output.="\n<option value='".$var."'>".$num."</option>";
1356 }
1357 }
1358 $output.= "</select></td></tr></table></div>";
1359 }else{
1360 $output.= "</div>";
1361 }
1363 return($output);
1364 }
1367 function apply_filter()
1368 {
1369 $apply= "";
1371 $apply= ''.
1372 '<table summary="" width="100%" style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1373 '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1375 return ($apply);
1376 }
1379 function back_to_main()
1380 {
1381 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1382 _("Back").'"></p><input type="hidden" name="ignore">';
1384 return ($string);
1385 }
1388 function normalize_netmask($netmask)
1389 {
1390 /* Check for notation of netmask */
1391 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1392 $num= (int)($netmask);
1393 $netmask= "";
1395 for ($byte= 0; $byte<4; $byte++){
1396 $result=0;
1398 for ($i= 7; $i>=0; $i--){
1399 if ($num-- > 0){
1400 $result+= pow(2,$i);
1401 }
1402 }
1404 $netmask.= $result.".";
1405 }
1407 return (preg_replace('/\.$/', '', $netmask));
1408 }
1410 return ($netmask);
1411 }
1414 function netmask_to_bits($netmask)
1415 {
1416 list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1417 $res= 0;
1419 for ($n= 0; $n<4; $n++){
1420 $start= 255;
1421 $name= "nm$n";
1423 for ($i= 0; $i<8; $i++){
1424 if ($start == (int)($$name)){
1425 $res+= 8 - $i;
1426 break;
1427 }
1428 $start-= pow(2,$i);
1429 }
1430 }
1432 return ($res);
1433 }
1436 function recurse($rule, $variables)
1437 {
1438 $result= array();
1440 if (!count($variables)){
1441 return array($rule);
1442 }
1444 reset($variables);
1445 $key= key($variables);
1446 $val= current($variables);
1447 unset ($variables[$key]);
1449 foreach($val as $possibility){
1450 $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1451 $result= array_merge($result, recurse($nrule, $variables));
1452 }
1454 return ($result);
1455 }
1458 function expand_id($rule, $attributes)
1459 {
1460 /* Check for id rule */
1461 if(preg_match('/^id(:|#)\d+$/',$rule)){
1462 return (array("\{$rule}"));
1463 }
1465 /* Check for clean attribute */
1466 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1467 $rule= preg_replace('/^%/', '', $rule);
1468 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1469 return (array($val));
1470 }
1472 /* Check for attribute with parameters */
1473 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1474 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1475 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1476 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1477 $start= preg_replace ('/-.*$/', '', $param);
1478 $stop = preg_replace ('/^[^-]+-/', '', $param);
1480 /* Assemble results */
1481 $result= array();
1482 for ($i= $start; $i<= $stop; $i++){
1483 $result[]= substr($val, 0, $i);
1484 }
1485 return ($result);
1486 }
1488 echo "Error in idgen string: don't know how to handle rule $rule.\n";
1489 return (array($rule));
1490 }
1493 function gen_uids($rule, $attributes)
1494 {
1495 global $config;
1497 /* Search for keys and fill the variables array with all
1498 possible values for that key. */
1499 $part= "";
1500 $trigger= false;
1501 $stripped= "";
1502 $variables= array();
1504 for ($pos= 0; $pos < strlen($rule); $pos++){
1506 if ($rule[$pos] == "{" ){
1507 $trigger= true;
1508 $part= "";
1509 continue;
1510 }
1512 if ($rule[$pos] == "}" ){
1513 $variables[$pos]= expand_id($part, $attributes);
1514 $stripped.= "\{$pos}";
1515 $trigger= false;
1516 continue;
1517 }
1519 if ($trigger){
1520 $part.= $rule[$pos];
1521 } else {
1522 $stripped.= $rule[$pos];
1523 }
1524 }
1526 /* Recurse through all possible combinations */
1527 $proposed= recurse($stripped, $variables);
1529 /* Get list of used ID's */
1530 $used= array();
1531 $ldap= $config->get_ldap_link();
1532 $ldap->cd($config->current['BASE']);
1533 $ldap->search('(uid=*)');
1535 while($attrs= $ldap->fetch()){
1536 $used[]= $attrs['uid'][0];
1537 }
1539 /* Remove used uids and watch out for id tags */
1540 $ret= array();
1541 foreach($proposed as $uid){
1543 /* Check for id tag and modify uid if needed */
1544 if(preg_match('/\{id:\d+}/',$uid)){
1545 $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1547 for ($i= 0; $i < pow(10,$size); $i++){
1548 $number= sprintf("%0".$size."d", $i);
1549 $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1550 if (!in_array($res, $used)){
1551 $uid= $res;
1552 break;
1553 }
1554 }
1555 }
1557 if(preg_match('/\{id#\d+}/',$uid)){
1558 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1560 while (true){
1561 mt_srand((double) microtime()*1000000);
1562 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1563 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1564 if (!in_array($res, $used)){
1565 $uid= $res;
1566 break;
1567 }
1568 }
1569 }
1571 /* Don't assign used ones */
1572 if (!in_array($uid, $used)){
1573 $ret[]= $uid;
1574 }
1575 }
1577 return(array_unique($ret));
1578 }
1581 function array_search_r($needle, $key, $haystack){
1583 foreach($haystack as $index => $value){
1584 $match= 0;
1586 if (is_array($value)){
1587 $match= array_search_r($needle, $key, $value);
1588 }
1590 if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1591 $match=1;
1592 }
1594 if ($match){
1595 return 1;
1596 }
1597 }
1599 return 0;
1600 }
1603 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1604 Need to convert... */
1605 function to_byte($value) {
1606 $value= strtolower(trim($value));
1608 if(!is_numeric(substr($value, -1))) {
1610 switch(substr($value, -1)) {
1611 case 'g':
1612 $mult= 1073741824;
1613 break;
1614 case 'm':
1615 $mult= 1048576;
1616 break;
1617 case 'k':
1618 $mult= 1024;
1619 break;
1620 }
1622 return ($mult * (int)substr($value, 0, -1));
1623 } else {
1624 return $value;
1625 }
1626 }
1629 function in_array_ics($value, $items)
1630 {
1631 if (!is_array($items)){
1632 return (FALSE);
1633 }
1635 foreach ($items as $item){
1636 if (strtolower($item) == strtolower($value)) {
1637 return (TRUE);
1638 }
1639 }
1641 return (FALSE);
1642 }
1645 function generate_alphabet($count= 10)
1646 {
1647 $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1648 $alphabet= "";
1649 $c= 0;
1651 /* Fill cells with charaters */
1652 for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1653 if ($c == 0){
1654 $alphabet.= "<tr>";
1655 }
1657 $ch = mb_substr($characters, $i, 1, "UTF8");
1658 $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1659 validate($_GET['plug'])."&search=".$ch."\"> ".$ch." </a></td>";
1661 if ($c++ == $count){
1662 $alphabet.= "</tr>";
1663 $c= 0;
1664 }
1665 }
1667 /* Fill remaining cells */
1668 while ($c++ <= $count){
1669 $alphabet.= "<td> </td>";
1670 }
1672 return ($alphabet);
1673 }
1676 function validate($string)
1677 {
1678 return (strip_tags(preg_replace('/\0/', '', $string)));
1679 }
1681 function get_gosa_version()
1682 {
1683 global $svn_revision, $svn_path;
1685 /* Extract informations */
1686 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1688 /* Release or development? */
1689 if (preg_match('%/gosa/trunk/%', $svn_path)){
1690 return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1691 } else {
1692 $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1693 return (sprintf(_("GOsa $release"), $revision));
1694 }
1695 }
1698 function rmdirRecursive($path, $followLinks=false) {
1699 $dir= opendir($path);
1700 while($entry= readdir($dir)) {
1701 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1702 unlink($path."/".$entry);
1703 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1704 rmdirRecursive($path."/".$entry);
1705 }
1706 }
1707 closedir($dir);
1708 return rmdir($path);
1709 }
1711 function scan_directory($path,$sort_desc=false)
1712 {
1713 $ret = false;
1715 /* is this a dir ? */
1716 if(is_dir($path)) {
1718 /* is this path a readable one */
1719 if(is_readable($path)){
1721 /* Get contents and write it into an array */
1722 $ret = array();
1724 $dir = opendir($path);
1726 /* Is this a correct result ?*/
1727 if($dir){
1728 while($fp = readdir($dir))
1729 $ret[]= $fp;
1730 }
1731 }
1732 }
1733 /* Sort array ascending , like scandir */
1734 sort($ret);
1736 /* Sort descending if parameter is sort_desc is set */
1737 if($sort_desc) {
1738 $ret = array_reverse($ret);
1739 }
1741 return($ret);
1742 }
1744 function clean_smarty_compile_dir($directory)
1745 {
1746 global $svn_revision;
1748 if(is_dir($directory) && is_readable($directory)) {
1749 // Set revision filename to REVISION
1750 $revision_file= $directory."/REVISION";
1752 /* Is there a stamp containing the current revision? */
1753 if(!file_exists($revision_file)) {
1754 // create revision file
1755 create_revision($revision_file, $svn_revision);
1756 } else {
1757 # check for "$config->...['CONFIG']/revision" and the
1758 # contents should match the revision number
1759 if(!compare_revision($revision_file, $svn_revision)){
1760 // If revision differs, clean compile directory
1761 foreach(scan_directory($directory) as $file) {
1762 if(($file==".")||($file=="..")) continue;
1763 if( is_file($directory."/".$file) &&
1764 is_writable($directory."/".$file)) {
1765 // delete file
1766 if(!unlink($directory."/".$file)) {
1767 print_red("File ".$directory."/".$file." could not be deleted.");
1768 // This should never be reached
1769 }
1770 } elseif(is_dir($directory."/".$file) &&
1771 is_writable($directory."/".$file)) {
1772 // Just recursively delete it
1773 rmdirRecursive($directory."/".$file);
1774 }
1775 }
1776 // We should now create a fresh revision file
1777 clean_smarty_compile_dir($directory);
1778 } else {
1779 // Revision matches, nothing to do
1780 }
1781 }
1782 } else {
1783 // Smarty compile dir is not accessible
1784 // (Smarty will warn about this)
1785 }
1786 }
1788 function create_revision($revision_file, $revision)
1789 {
1790 $result= false;
1792 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1793 if($fh= fopen($revision_file, "w")) {
1794 if(fwrite($fh, $revision)) {
1795 $result= true;
1796 }
1797 }
1798 fclose($fh);
1799 } else {
1800 print_red("Can not write to revision file");
1801 }
1803 return $result;
1804 }
1806 function compare_revision($revision_file, $revision)
1807 {
1808 // false means revision differs
1809 $result= false;
1811 if(file_exists($revision_file) && is_readable($revision_file)) {
1812 // Open file
1813 if($fh= fopen($revision_file, "r")) {
1814 // Compare File contents with current revision
1815 if($revision == fread($fh, filesize($revision_file))) {
1816 $result= true;
1817 }
1818 } else {
1819 print_red("Can not open revision file");
1820 }
1821 // Close file
1822 fclose($fh);
1823 }
1825 return $result;
1826 }
1828 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1829 {
1830 $str = ""; // Our return value will be saved in this var
1832 $color = dechex($percentage+150);
1833 $color2 = dechex(150 - $percentage);
1834 $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1836 $progress = (int)(($percentage /100)*$width);
1838 /* Abort printing out percentage, if divs are to small */
1841 /* If theres a better solution for this, use it... */
1842 $str = "
1843 <div style=\" width:".($width)."px;
1844 height:".($height)."px;
1845 background-color:#000000;
1846 padding:1px;\">
1848 <div style=\" width:".($width)."px;
1849 background-color:#$bgcolor;
1850 height:".($height)."px;\">
1852 <div style=\" width:".$progress."px;
1853 height:".$height."px;
1854 background-color:#".$color2.$color2.$color."; \">";
1857 if(($height >10)&&($showvalue)){
1858 $str.= "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1859 <b>".$percentage."%</b>
1860 </font>";
1861 }
1863 $str.= "</div></div></div>";
1865 return($str);
1866 }
1869 function array_key_ics($ikey, $items)
1870 {
1871 /* Gather keys, make them lowercase */
1872 $tmp= array();
1873 foreach ($items as $key => $value){
1874 $tmp[strtolower($key)]= $key;
1875 }
1877 if (isset($tmp[strtolower($ikey)])){
1878 return($tmp[strtolower($ikey)]);
1879 }
1881 return ("");
1882 }
1885 function search_config($arr, $name, $return)
1886 {
1887 if (is_array($arr)){
1888 foreach ($arr as $a){
1889 if (isset($a['CLASS']) &&
1890 strtolower($a['CLASS']) == strtolower($name)){
1892 if (isset($a[$return])){
1893 return ($a[$return]);
1894 } else {
1895 return ("");
1896 }
1897 } else {
1898 $res= search_config ($a, $name, $return);
1899 if ($res != ""){
1900 return $res;
1901 }
1902 }
1903 }
1904 }
1905 return ("");
1906 }
1909 function array_differs($src, $dst)
1910 {
1911 /* If the count is differing, the arrays differ */
1912 if (count ($src) != count ($dst)){
1913 return (TRUE);
1914 }
1916 /* So the count is the same - lets check the contents */
1917 $differs= FALSE;
1918 foreach($src as $value){
1919 if (!in_array($value, $dst)){
1920 $differs= TRUE;
1921 }
1922 }
1924 return ($differs);
1925 }
1928 function saveFilter($a_filter, $values)
1929 {
1930 if (isset($_POST['regexit'])){
1931 $a_filter["regex"]= $_POST['regexit'];
1933 foreach($values as $type){
1934 if (isset($_POST[$type])) {
1935 $a_filter[$type]= "checked";
1936 } else {
1937 $a_filter[$type]= "";
1938 }
1939 }
1940 }
1942 /* React on alphabet links if needed */
1943 if (isset($_GET['search'])){
1944 $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
1945 if ($s == "**"){
1946 $s= "*";
1947 }
1948 $a_filter['regex']= $s;
1949 }
1951 return ($a_filter);
1952 }
1955 /* Escape all preg_* relevant characters */
1956 function normalizePreg($input)
1957 {
1958 return (addcslashes($input, '[]()|/.*+-'));
1959 }
1962 /* Escape all LDAP filter relevant characters */
1963 function normalizeLdap($input)
1964 {
1965 return (addcslashes($input, '()|'));
1966 }
1969 /* Resturns the difference between to microtime() results in float */
1970 function get_MicroTimeDiff($start , $stop)
1971 {
1972 $a = split("\ ",$start);
1973 $b = split("\ ",$stop);
1975 $secs = $b[1] - $a[1];
1976 $msecs= $b[0] - $a[0];
1978 $ret = (float) ($secs+ $msecs);
1979 return($ret);
1980 }
1983 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1984 ?>