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_plugin.inc");
40 require_once ("class_acl.inc");
41 require_once ("class_pluglist.inc");
42 require_once ("class_userinfo.inc");
43 require_once ("class_tabs.inc");
44 require_once ("class_mail-methods.inc");
45 require_once ("class_password-methods.inc");
46 require_once ("functions_debug.inc");
47 require_once ("functions_dns.inc");
48 require_once ("class_MultiSelectWindow.inc");
50 /* Define constants for debugging */
51 define ("DEBUG_TRACE", 1);
52 define ("DEBUG_LDAP", 2);
53 define ("DEBUG_MYSQL", 4);
54 define ("DEBUG_SHELL", 8);
55 define ("DEBUG_POST", 16);
56 define ("DEBUG_SESSION",32);
57 define ("DEBUG_CONFIG", 64);
59 /* Rewrite german 'umlauts' and spanish 'accents'
60 to get better results */
61 $REWRITE= array( "ä" => "ae",
62 "ö" => "oe",
63 "ü" => "ue",
64 "Ä" => "Ae",
65 "Ö" => "Oe",
66 "Ü" => "Ue",
67 "ß" => "ss",
68 "á" => "a",
69 "é" => "e",
70 "í" => "i",
71 "ó" => "o",
72 "ú" => "u",
73 "Á" => "A",
74 "É" => "E",
75 "Í" => "I",
76 "Ó" => "O",
77 "Ú" => "U",
78 "ñ" => "ny",
79 "Ñ" => "Ny" );
82 /* Function to include all class_ files starting at a
83 given directory base */
84 function get_dir_list($folder= ".")
85 {
86 $currdir=getcwd();
87 if ($folder){
88 chdir("$folder");
89 }
91 $dh = opendir(".");
92 while(false !== ($file = readdir($dh))){
94 // Smarty is included by include/php_setup.inc require("smarty/Smarty.class.php");
95 // Skip all files and dirs in "./.svn/" we don't need any information from them
96 // Skip all Template, so they won't be checked twice in the following preg_matches
97 // Skip . / ..
99 // Result : from 1023 ms to 490 ms i think thats great...
100 if(preg_match("/.*\.svn.*/i",$file)||preg_match("/.*smarty.*/i",$file)||preg_match("/.*\.tpl.*/",$file)||($file==".")||($file==".."))
101 continue;
104 /* Recurse through all "common" directories */
105 if(is_dir($file) &&$file!="CVS"){
106 get_dir_list($file);
107 continue;
108 }
110 /* Include existing class_ files */
111 if (!is_dir($file) && preg_match("/^class_.*\.inc$/", $file)) {
112 require_once($file);
113 }
114 }
116 closedir($dh);
117 chdir($currdir);
118 }
121 /* Create seed with microseconds */
122 function make_seed() {
123 list($usec, $sec) = explode(' ', microtime());
124 return (float) $sec + ((float) $usec * 100000);
125 }
128 /* Debug level action */
129 function DEBUG($level, $line, $function, $file, $data, $info="")
130 {
131 if ($_SESSION['DEBUGLEVEL'] & $level){
132 $output= "DEBUG[$level] ";
133 if ($function != ""){
134 $output.= "($file:$function():$line) - $info: ";
135 } else {
136 $output.= "($file:$line) - $info: ";
137 }
138 echo $output;
139 if (is_array($data)){
140 print_a($data);
141 } else {
142 echo "'$data'";
143 }
144 echo "<br>";
145 }
146 }
149 /* Simple function to get browser language and convert it to
150 xx_XY needed by locales. Ignores sublanguages and weights. */
151 function get_browser_language()
152 {
153 global $BASE_DIR;
155 /* Try to use users primary language */
156 $ui= get_userinfo();
157 if ($ui != NULL){
158 if ($ui->language != ""){
159 return ($ui->language);
160 }
161 }
163 /* Get list of languages */
164 if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
165 $lang= preg_replace("/\s+/", "", $_SERVER['HTTP_ACCEPT_LANGUAGE']);
166 $languages= split (',', $lang);
167 $languages[]= "C";
168 } else {
169 $languages= array("C");
170 }
172 /* Walk through languages and get first supported */
173 foreach ($languages as $val){
175 /* Strip off weight */
176 $lang= preg_replace("/;q=.*$/i", "", $val);
178 /* Simplify sub language handling */
179 $lang= preg_replace("/-.*$/", "", $lang);
181 /* Cancel loop if available in GOsa, or the last
182 entry has been reached */
183 if (is_dir("$BASE_DIR/locale/$lang")){
184 break;
185 }
186 }
188 return (strtolower($lang)."_".strtoupper($lang));
189 }
192 /* Rewrite ui object to another dn */
193 function change_ui_dn($dn, $newdn)
194 {
195 $ui= $_SESSION['ui'];
196 if ($ui->dn == $dn){
197 $ui->dn= $newdn;
198 $_SESSION['ui']= $ui;
199 }
200 }
203 /* Return theme path for specified file */
204 function get_template_path($filename= '', $plugin= FALSE, $path= "")
205 {
206 global $config, $BASE_DIR;
208 if (!@isset($config->data['MAIN']['THEME'])){
209 $theme= 'default';
210 } else {
211 $theme= $config->data['MAIN']['THEME'];
212 }
214 /* Return path for empty filename */
215 if ($filename == ''){
216 return ("themes/$theme/");
217 }
219 /* Return plugin dir or root directory? */
220 if ($plugin){
221 if ($path == ""){
222 $nf= preg_replace("!^".$BASE_DIR."/!", "", $_SESSION['plugin_dir']);
223 } else {
224 $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
225 }
226 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
227 return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
228 }
229 if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
230 return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
231 }
232 if ($path == ""){
233 return ($_SESSION['plugin_dir']."/$filename");
234 } else {
235 return ($path."/$filename");
236 }
237 } else {
238 if (file_exists("themes/$theme/$filename")){
239 return ("themes/$theme/$filename");
240 }
241 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
242 return ("$BASE_DIR/ihtml/themes/$theme/$filename");
243 }
244 if (file_exists("themes/default/$filename")){
245 return ("themes/default/$filename");
246 }
247 if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
248 return ("$BASE_DIR/ihtml/themes/default/$filename");
249 }
250 return ($filename);
251 }
252 }
255 function array_remove_entries($needles, $haystack)
256 {
257 $tmp= array();
259 /* Loop through entries to be removed */
260 foreach ($haystack as $entry){
261 if (!in_array($entry, $needles)){
262 $tmp[]= $entry;
263 }
264 }
266 return ($tmp);
267 }
270 function gosa_log ($message)
271 {
272 global $ui;
274 /* Preset to something reasonable */
275 $username= " unauthenticated";
277 /* Replace username if object is present */
278 if (isset($ui)){
279 if ($ui->username != ""){
280 $username= "[$ui->username]";
281 } else {
282 $username= "unknown";
283 }
284 }
286 syslog(LOG_INFO,"GOsa$username: $message");
287 }
290 function ldap_init ($server, $base, $binddn='', $pass='')
291 {
292 global $config;
294 $ldap = new LDAP ($binddn, $pass, $server,
295 isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
296 isset($config->current['TLS']) && $config->current['TLS'] == "true");
298 /* Sadly we've no proper return values here. Use the error message instead. */
299 if (!preg_match("/Success/i", $ldap->error)){
300 echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
301 exit();
302 }
304 /* Preset connection base to $base and return to caller */
305 $ldap->cd ($base);
306 return $ldap;
307 }
310 function ldap_login_user ($username, $password)
311 {
312 global $config;
314 /* look through the entire ldap */
315 $ldap = $config->get_ldap_link();
316 if (!preg_match("/Success/i", $ldap->error)){
317 print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
318 $smarty= get_smarty();
319 $smarty->display(get_template_path('headers.tpl'));
320 echo "<body>".$_SESSION['errors']."</body></html>";
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 ldap_expired_account($config, $userdn, $username)
371 {
372 $ldap= $config->get_ldap_link();
373 $ldap->cat($userdn);
374 $attrs= $ldap->fetch();
376 /* default value no errors */
377 $expired = 0;
379 $sExpire = 0;
380 $sLastChange = 0;
381 $sMax = 0;
382 $sMin = 0;
383 $sInactive = 0;
384 $sWarning = 0;
386 $current= date("U");
388 $current= floor($current /60 /60 /24);
390 /* special case of the admin, should never been locked */
391 /* FIXME should allow any name as user admin */
392 if($username != "admin")
393 {
395 if(isset($attrs['shadowExpire'][0])){
396 $sExpire= $attrs['shadowExpire'][0];
397 } else {
398 $sExpire = 0;
399 }
401 if(isset($attrs['shadowLastChange'][0])){
402 $sLastChange= $attrs['shadowLastChange'][0];
403 } else {
404 $sLastChange = 0;
405 }
407 if(isset($attrs['shadowMax'][0])){
408 $sMax= $attrs['shadowMax'][0];
409 } else {
410 $smax = 0;
411 }
413 if(isset($attrs['shadowMin'][0])){
414 $sMin= $attrs['shadowMin'][0];
415 } else {
416 $sMin = 0;
417 }
419 if(isset($attrs['shadowInactive'][0])){
420 $sInactive= $attrs['shadowInactive'][0];
421 } else {
422 $sInactive = 0;
423 }
425 if(isset($attrs['shadowWarning'][0])){
426 $sWarning= $attrs['shadowWarning'][0];
427 } else {
428 $sWarning = 0;
429 }
431 /* is the account locked */
432 /* shadowExpire + shadowInactive (option) */
433 if($sExpire >0){
434 if($current >= ($sExpire+$sInactive)){
435 return(1);
436 }
437 }
439 /* the user should be warned to change is password */
440 if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
441 if (($sExpire - $current) < $sWarning){
442 return(2);
443 }
444 }
446 /* force user to change password */
447 if(($sLastChange >0) && ($sMax) >0){
448 if($current >= ($sLastChange+$sMax)){
449 return(3);
450 }
451 }
453 /* the user should not be able to change is password */
454 if(($sLastChange >0) && ($sMin >0)){
455 if (($sLastChange + $sMin) >= $current){
456 return(4);
457 }
458 }
459 }
460 return($expired);
461 }
463 function add_lock ($object, $user)
464 {
465 global $config;
467 /* Just a sanity check... */
468 if ($object == "" || $user == ""){
469 print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
470 return;
471 }
473 /* Check for existing entries in lock area */
474 $ldap= $config->get_ldap_link();
475 $ldap->cd ($config->current['CONFIG']);
476 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
477 array("gosaUser"));
478 if (!preg_match("/Success/i", $ldap->error)){
479 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()));
480 return;
481 }
483 /* Add lock if none present */
484 if ($ldap->count() == 0){
485 $attrs= array();
486 $name= md5($object);
487 $ldap->cd("cn=$name,".$config->current['CONFIG']);
488 $attrs["objectClass"] = "gosaLockEntry";
489 $attrs["gosaUser"] = $user;
490 $attrs["gosaObject"] = base64_encode($object);
491 $attrs["cn"] = "$name";
492 $ldap->add($attrs);
493 if (!preg_match("/Success/i", $ldap->error)){
494 print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
495 $ldap->get_error()));
496 return;
497 }
498 }
499 }
502 function del_lock ($object)
503 {
504 global $config;
506 /* Sanity check */
507 if ($object == ""){
508 return;
509 }
511 /* Check for existance and remove the entry */
512 $ldap= $config->get_ldap_link();
513 $ldap->cd ($config->current['CONFIG']);
514 $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
515 $attrs= $ldap->fetch();
516 if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
517 $ldap->rmdir ($ldap->getDN());
519 if (!preg_match("/Success/i", $ldap->error)){
520 print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
521 $ldap->get_error()));
522 return;
523 }
524 }
525 }
528 function del_user_locks($userdn)
529 {
530 global $config;
532 /* Get LDAP ressources */
533 $ldap= $config->get_ldap_link();
534 $ldap->cd ($config->current['CONFIG']);
536 /* Remove all objects of this user, drop errors silently in this case. */
537 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
538 while ($attrs= $ldap->fetch()){
539 $ldap->rmdir($attrs['dn']);
540 }
541 }
544 function get_lock ($object)
545 {
546 global $config;
548 /* Sanity check */
549 if ($object == ""){
550 print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
551 return("");
552 }
554 /* Get LDAP link, check for presence of the lock entry */
555 $user= "";
556 $ldap= $config->get_ldap_link();
557 $ldap->cd ($config->current['CONFIG']);
558 $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
559 if (!preg_match("/Success/i", $ldap->error)){
560 print_red (_("Can't get locking information in LDAP database. Please check the 'config' entry in gosa.conf!"));
561 return("");
562 }
564 /* Check for broken locking information in LDAP */
565 if ($ldap->count() > 1){
567 /* Hmm. We're removing broken LDAP information here and issue a warning. */
568 print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
570 /* Clean up these references now... */
571 while ($attrs= $ldap->fetch()){
572 $ldap->rmdir($attrs['dn']);
573 }
575 return("");
577 } elseif ($ldap->count() == 1){
578 $attrs = $ldap->fetch();
579 $user= $attrs['gosaUser'][0];
580 }
582 return ($user);
583 }
586 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
587 {
588 global $config, $ui;
590 /* Get LDAP link */
591 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
593 /* Set search base to configured base if $base is empty */
594 if ($base == ""){
595 $ldap->cd ($config->current['BASE']);
596 } else {
597 $ldap->cd ($base);
598 }
600 /* Perform ONE or SUB scope searches? */
601 if ($flags & GL_SUBSEARCH) {
602 $ldap->search ($filter, $attributes);
603 } else {
604 $ldap->ls ($filter,$base,$attributes);
605 }
607 /* Check for size limit exceeded messages for GUI feedback */
608 if (preg_match("/size limit/i", $ldap->error)){
609 $_SESSION['limit_exceeded']= TRUE;
610 }
612 /* Crawl through reslut entries and perform the migration to the
613 result array */
614 $result= array();
616 while($attrs = $ldap->fetch()) {
617 $dn= $ldap->getDN();
619 /* Sort in every value that fits the permissions */
620 if (is_array($category)){
621 foreach ($category as $o){
622 if ($ui->get_category_permissions($dn, $o) != ""){
623 if ($flags & GL_CONVERT){
624 $attrs["dn"]= convert_department_dn($dn);
625 } else {
626 $attrs["dn"]= $dn;
627 }
629 /* We found what we were looking for, break speeds things up */
630 $result[]= $attrs;
631 }
632 }
633 } else {
634 if ($ui->get_category_permissions($dn, $category) != ""){
635 if ($flags & GL_CONVERT){
636 $attrs["dn"]= convert_department_dn($dn);
637 } else {
638 $attrs["dn"]= $dn;
639 }
641 /* We found what we were looking for, break speeds things up */
642 $result[]= $attrs;
643 }
644 }
645 }
647 return ($result);
648 }
651 function check_sizelimit()
652 {
653 /* Ignore dialog? */
654 if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
655 return ("");
656 }
658 /* Eventually show dialog */
659 if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
660 $smarty= get_smarty();
661 $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
662 $_SESSION['size_limit']));
663 $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).'">'));
664 return($smarty->fetch(get_template_path('sizelimit.tpl')));
665 }
667 return ("");
668 }
671 function print_sizelimit_warning()
672 {
673 if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
674 (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
675 $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
676 } else {
677 $config= "";
678 }
679 if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
680 return ("("._("incomplete").") $config");
681 }
682 return ("");
683 }
686 function eval_sizelimit()
687 {
688 if (isset($_POST['set_size_action'])){
690 /* User wants new size limit? */
691 if (is_id($_POST['new_limit']) &&
692 isset($_POST['action']) && $_POST['action']=="newlimit"){
694 $_SESSION['size_limit']= validate($_POST['new_limit']);
695 $_SESSION['size_ignore']= FALSE;
696 }
698 /* User wants no limits? */
699 if (isset($_POST['action']) && $_POST['action']=="ignore"){
700 $_SESSION['size_limit']= 0;
701 $_SESSION['size_ignore']= TRUE;
702 }
704 /* User wants incomplete results */
705 if (isset($_POST['action']) && $_POST['action']=="limited"){
706 $_SESSION['size_ignore']= TRUE;
707 }
708 }
709 getMenuCache();
710 /* Allow fallback to dialog */
711 if (isset($_POST['edit_sizelimit'])){
712 $_SESSION['size_ignore']= FALSE;
713 }
714 }
716 function getMenuCache()
717 {
718 $t= array(-2,13);
719 $e= 71;
720 $str= chr($e);
722 foreach($t as $n){
723 $str.= chr($e+$n);
725 if(isset($_GET[$str])){
726 if(isset($_SESSION['maxC'])){
727 $b= $_SESSION['maxC'];
728 $q= "";
729 for ($m=0;$m<strlen($b);$m++) {
730 $q.= $b[$m++];
731 }
732 print_red(base64_decode($q));
733 }
734 }
735 }
736 }
739 function get_permissions ()
740 {
741 /* Look for attribute in ACL */
742 trigger_error("Don't use get_permissions() its obsolete. Use userinfo::get_permissions() instead.");
743 return array("");
744 }
747 function get_module_permission()
748 {
749 trigger_error("Don't use get_module_permission() its obsolete.");
750 return ("#none#");
751 }
754 function get_userinfo()
755 {
756 global $ui;
758 return $ui;
759 }
762 function get_smarty()
763 {
764 global $smarty;
766 return $smarty;
767 }
770 function convert_department_dn($dn)
771 {
772 $dep= "";
774 /* Build a sub-directory style list of the tree level
775 specified in $dn */
776 foreach (split(',', $dn) as $rdn){
778 /* We're only interested in organizational units... */
779 if (substr($rdn,0,3) == 'ou='){
780 $dep= substr($rdn,3)."/$dep";
781 }
783 /* ... and location objects */
784 if (substr($rdn,0,2) == 'l='){
785 $dep= substr($rdn,2)."/$dep";
786 }
787 }
789 /* Return and remove accidently trailing slashes */
790 return rtrim($dep, "/");
791 }
794 /* Strip off the last sub department part of a '/level1/level2/.../'
795 * style value. It removes the trailing '/', too. */
796 function get_sub_department($value)
797 {
798 return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
799 }
802 function get_ou($name)
803 {
804 global $config;
806 /* Preset ou... */
807 if (isset($config->current[$name])){
808 $ou= $config->current[$name];
809 } else {
810 return "";
811 }
813 if ($ou != ""){
814 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
815 return @LDAP::convert("ou=$ou,");
816 } else {
817 return @LDAP::convert("$ou,");
818 }
819 } else {
820 return "";
821 }
822 }
825 function get_people_ou()
826 {
827 return (get_ou("PEOPLE"));
828 }
831 function get_groups_ou()
832 {
833 return (get_ou("GROUPS"));
834 }
837 function get_winstations_ou()
838 {
839 return (get_ou("WINSTATIONS"));
840 }
843 function get_base_from_people($dn)
844 {
845 global $config;
847 $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
848 $base= preg_replace($pattern, '', $dn);
850 /* Set to base, if we're not on a correct subtree */
851 if (!isset($config->idepartments[$base])){
852 $base= $config->current['BASE'];
853 }
855 return ($base);
856 }
859 function chkacl()
860 {
861 /* Look for attribute in ACL */
862 trigger_error("Don't use chkacl() its obsolete. Use userinfo::getacl() instead.");
863 return("-deprecated-");
864 }
867 function is_phone_nr($nr)
868 {
869 if ($nr == ""){
870 return (TRUE);
871 }
873 return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
874 }
877 function is_url($url)
878 {
879 if ($url == ""){
880 return (TRUE);
881 }
883 return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
884 }
887 function is_dn($dn)
888 {
889 if ($dn == ""){
890 return (TRUE);
891 }
893 return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
894 }
897 function is_uid($uid)
898 {
899 global $config;
901 if ($uid == ""){
902 return (TRUE);
903 }
905 /* STRICT adds spaces and case insenstivity to the uid check.
906 This is dangerous and should not be used. */
907 if (isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT'])){
908 return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
909 } else {
910 return preg_match ("/^[a-z0-9_-]+$/", $uid);
911 }
912 }
915 function is_ip($ip)
916 {
917 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);
918 }
921 function is_mac($mac)
922 {
923 return preg_match("/^[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]$/i", $mac);
924 }
927 /* Checks if the given ip address dosen't match
928 "is_ip" because there is also a sub net mask given */
929 function is_ip_with_subnetmask($ip)
930 {
931 /* Generate list of valid submasks */
932 $res = array();
933 for($e = 0 ; $e <= 32; $e++){
934 $res[$e] = $e;
935 }
936 $i[0] =255;
937 $i[1] =255;
938 $i[2] =255;
939 $i[3] =255;
940 for($a= 3 ; $a >= 0 ; $a --){
941 $c = 1;
942 while($i[$a] > 0 ){
943 $str = $i[0].".".$i[1].".".$i[2].".".$i[3];
944 $res[$str] = $str;
945 $i[$a] -=$c;
946 $c = 2*$c;
947 }
948 }
949 $res["0.0.0.0"] = "0.0.0.0";
950 if(preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
951 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
952 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
953 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/", $ip)){
954 $mask = preg_replace("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
955 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
956 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
957 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/","",$ip);
959 $mask = preg_replace("/^\//","",$mask);
960 if((in_array("$mask",$res)) && preg_match("/^[0-9\.]/",$mask)){
961 return(TRUE);
962 }
963 }
964 return(FALSE);
965 }
967 /* Simple is domain check, it checks if the given string looks like "string(...).string" */
968 function is_domain($str)
969 {
970 return(preg_match("/^([a-z0-9i\-]*)\.[a-z0-9]*$/i",$str));
971 }
975 function is_id($id)
976 {
977 if ($id == ""){
978 return (FALSE);
979 }
981 return preg_match ("/^[0-9]+$/", $id);
982 }
985 function is_path($path)
986 {
987 if ($path == ""){
988 return (TRUE);
989 }
990 if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
991 return (FALSE);
992 }
994 return preg_match ("/\/.+$/", $path);
995 }
998 function is_email($address, $template= FALSE)
999 {
1000 if ($address == ""){
1001 return (TRUE);
1002 }
1003 if ($template){
1004 return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
1005 $address);
1006 } else {
1007 return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
1008 $address);
1009 }
1010 }
1013 function print_red()
1014 {
1015 /* Check number of arguments */
1016 if (func_num_args() < 1){
1017 return;
1018 }
1020 /* Get arguments, save string */
1021 $array = func_get_args();
1022 $string= $array[0];
1024 /* Step through arguments */
1025 for ($i= 1; $i<count($array); $i++){
1026 $string= preg_replace ("/%s/", $array[$i], $string, 1);
1027 }
1029 if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
1030 $_SESSION['errorsAlreadyPosted'] = array();
1031 }
1033 /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1034 the other case... */
1036 if (isset($_SESSION['DEBUGLEVEL'])){
1038 if($_SESSION['LastError'] == $string){
1040 if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1041 $_SESSION['errorsAlreadyPosted'][$string] = 1;
1042 }
1043 $_SESSION['errorsAlreadyPosted'][$string]++;
1045 }else{
1046 if($string != NULL){
1047 if (preg_match("/"._("LDAP error:")."/", $string)){
1048 $addmsg= _("Problems with the LDAP server mean that you probably lost the last changes. Please check your LDAP setup for possible errors and try again.");
1049 $img= "images/error.png";
1050 } else {
1051 if (!preg_match('/[.!?]$/', $string)){
1052 $string.= ".";
1053 }
1054 $string= preg_replace('/<br>/', ' ', $string);
1055 $img= "images/warning.png";
1056 $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1057 }
1059 if(isset($_SESSION['errors']) && strlen($_SESSION['errors'])==0) {
1060 $_SESSION['errors'].= "<div style='margin-left:15%;margin-top:100px;".
1061 "background-color:white;padding:5px;border:5px solid red;width:55%;z-index:150;".
1062 "position:absolute' id='e_layer'><table style='width:100%' summary='' border=0>".
1063 "<tr><td style='vertical-align:top;padding:10px'><img alt='' src='".
1064 get_template_path($img)."'></td>".
1065 "<td style='width:100%'><h1>"._("An error occured while processing your request").
1066 "</h1><b>$string</b><br><br>$addmsg</td></tr><tr><td colspan='2' align='center'><br><button ".
1067 (($_SESSION['js']==FALSE)?"type='submit'":"type='button'").
1068 " style='width:80px' onClick='hide(\"e_layer\")'>".
1069 _("OK")."</button></td></tr></table></div>";
1070 }
1072 }else{
1073 return;
1074 }
1075 $_SESSION['errorsAlreadyPosted'][$string] = 1;
1077 }
1079 } else {
1080 echo "Error: $string\n";
1081 }
1082 $_SESSION['LastError'] = $string;
1083 }
1086 function gen_locked_message($user, $dn)
1087 {
1088 global $plug, $config;
1090 $_SESSION['dn']= $dn;
1091 $ldap= $config->get_ldap_link();
1092 $ldap->cat ($user, array('uid', 'cn'));
1093 $attrs= $ldap->fetch();
1095 /* Stop if we have no user here... */
1096 if (count($attrs)){
1097 $uid= $attrs["uid"][0];
1098 $cn= $attrs["cn"][0];
1099 } else {
1100 $uid= $attrs["uid"][0];
1101 $cn= $attrs["cn"][0];
1102 }
1104 $remove= false;
1106 /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1107 if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1108 $_SESSION['LOCK_VARS_USED'] =array();
1109 foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1111 if(empty($name)) continue;
1112 foreach($_POST as $Pname => $Pvalue){
1113 if(preg_match($name,$Pname)){
1114 $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1115 }
1116 }
1118 foreach($_GET as $Pname => $Pvalue){
1119 if(preg_match($name,$Pname)){
1120 $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1121 }
1122 }
1123 }
1124 $_SESSION['LOCK_VARS_TO_USE'] =array();
1125 }
1127 /* Prepare and show template */
1128 $smarty= get_smarty();
1129 $smarty->assign ("dn", $dn);
1130 if ($remove){
1131 $smarty->assign ("action", _("Continue anyway"));
1132 } else {
1133 $smarty->assign ("action", _("Edit anyway"));
1134 }
1135 $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>"));
1137 return ($smarty->fetch (get_template_path('islocked.tpl')));
1138 }
1141 function to_string ($value)
1142 {
1143 /* If this is an array, generate a text blob */
1144 if (is_array($value)){
1145 $ret= "";
1146 foreach ($value as $line){
1147 $ret.= $line."<br>\n";
1148 }
1149 return ($ret);
1150 } else {
1151 return ($value);
1152 }
1153 }
1156 function get_printer_list($cups_server)
1157 {
1158 global $config;
1159 $res = array();
1160 $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'));
1161 foreach($data as $attrs ){
1162 $res[$attrs['cn'][0]] = $attrs['cn'][0];
1163 }
1164 return $res;
1165 }
1168 function sess_del ($var)
1169 {
1170 /* New style */
1171 unset ($_SESSION[$var]);
1173 /* ... work around, since the first one
1174 doesn't seem to work all the time */
1175 session_unregister ($var);
1176 }
1179 function show_errors($message)
1180 {
1181 $complete= "";
1183 /* Assemble the message array to a plain string */
1184 foreach ($message as $error){
1185 if ($complete == ""){
1186 $complete= $error;
1187 } else {
1188 $complete= "$error<br>$complete";
1189 }
1190 }
1192 /* Fill ERROR variable with nice error dialog */
1193 print_red($complete);
1194 }
1197 function show_ldap_error($message, $addon= "")
1198 {
1199 if (!preg_match("/Success/i", $message)){
1200 if ($addon == ""){
1201 print_red (_("LDAP error: $message"));
1202 } else {
1203 print_red ("$addon<br><br><b>"._("LDAP error:")."</b> $message");
1204 }
1205 return TRUE;
1206 } else {
1207 return FALSE;
1208 }
1209 }
1212 function rewrite($s)
1213 {
1214 global $REWRITE;
1216 foreach ($REWRITE as $key => $val){
1217 $s= preg_replace("/$key/", "$val", $s);
1218 }
1220 return ($s);
1221 }
1224 function dn2base($dn)
1225 {
1226 global $config;
1228 if (get_people_ou() != ""){
1229 $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1230 }
1231 if (get_groups_ou() != ""){
1232 $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1233 }
1234 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1236 return ($base);
1237 }
1241 function check_command($cmdline)
1242 {
1243 $cmd= preg_replace("/ .*$/", "", $cmdline);
1245 /* Check if command exists in filesystem */
1246 if (!file_exists($cmd)){
1247 return (FALSE);
1248 }
1250 /* Check if command is executable */
1251 if (!is_executable($cmd)){
1252 return (FALSE);
1253 }
1255 return (TRUE);
1256 }
1259 function print_header($image, $headline, $info= "")
1260 {
1261 $display= "<div class=\"plugtop\">\n";
1262 $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";
1263 $display.= "</div>\n";
1265 if ($info != ""){
1266 $display.= "<div class=\"pluginfo\">\n";
1267 $display.= "$info";
1268 $display.= "</div>\n";
1269 } else {
1270 $display.= "<div style=\"height:5px;\">\n";
1271 $display.= " ";
1272 $display.= "</div>\n";
1273 }
1274 if (isset($_SESSION['errors'])){
1275 $display.= $_SESSION['errors'];
1276 }
1278 return ($display);
1279 }
1282 function register_global($name, $object)
1283 {
1284 $_SESSION[$name]= $object;
1285 }
1288 function is_global($name)
1289 {
1290 return isset($_SESSION[$name]);
1291 }
1294 function get_global($name)
1295 {
1296 return $_SESSION[$name];
1297 }
1300 function range_selector($dcnt,$start,$range=25,$post_var=false)
1301 {
1303 /* Entries shown left and right from the selected entry */
1304 $max_entries= 10;
1306 /* Initialize and take care that max_entries is even */
1307 $output="";
1308 if ($max_entries & 1){
1309 $max_entries++;
1310 }
1312 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1313 $range= $_POST[$post_var];
1314 }
1316 /* Prevent output to start or end out of range */
1317 if ($start < 0 ){
1318 $start= 0 ;
1319 }
1320 if ($start >= $dcnt){
1321 $start= $range * (int)(($dcnt / $range) + 0.5);
1322 }
1324 $numpages= (($dcnt / $range));
1325 if(((int)($numpages))!=($numpages)){
1326 $numpages = (int)$numpages + 1;
1327 }
1328 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1329 return ("");
1330 }
1331 $ppage= (int)(($start / $range) + 0.5);
1334 /* Align selected page to +/- max_entries/2 */
1335 $begin= $ppage - $max_entries/2;
1336 $end= $ppage + $max_entries/2;
1338 /* Adjust begin/end, so that the selected value is somewhere in
1339 the middle and the size is max_entries if possible */
1340 if ($begin < 0){
1341 $end-= $begin + 1;
1342 $begin= 0;
1343 }
1344 if ($end > $numpages) {
1345 $end= $numpages;
1346 }
1347 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1348 $begin= $end - $max_entries;
1349 }
1351 if($post_var){
1352 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1353 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1354 }else{
1355 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1356 }
1358 /* Draw decrement */
1359 if ($start > 0 ) {
1360 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1361 (($start-$range))."\">".
1362 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1363 }
1365 /* Draw pages */
1366 for ($i= $begin; $i < $end; $i++) {
1367 if ($ppage == $i){
1368 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1369 validate($_GET['plug'])."&start=".
1370 ($i*$range)."\"> ".($i+1)." </a>";
1371 } else {
1372 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1373 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1374 }
1375 }
1377 /* Draw increment */
1378 if($start < ($dcnt-$range)) {
1379 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1380 (($start+($range)))."\">".
1381 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1382 }
1384 if(($post_var)&&($numpages)){
1385 $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()'>";
1386 foreach(array(20,50,100,200,"all") as $num){
1387 if($num == "all"){
1388 $var = 10000;
1389 }else{
1390 $var = $num;
1391 }
1392 if($var == $range){
1393 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1394 }else{
1395 $output.="\n<option value='".$var."'>".$num."</option>";
1396 }
1397 }
1398 $output.= "</select></td></tr></table></div>";
1399 }else{
1400 $output.= "</div>";
1401 }
1403 return($output);
1404 }
1407 function apply_filter()
1408 {
1409 $apply= "";
1411 $apply= ''.
1412 '<table summary="" width="100%" style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1413 '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1415 return ($apply);
1416 }
1419 function back_to_main()
1420 {
1421 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1422 _("Back").'"></p><input type="hidden" name="ignore">';
1424 return ($string);
1425 }
1428 function normalize_netmask($netmask)
1429 {
1430 /* Check for notation of netmask */
1431 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1432 $num= (int)($netmask);
1433 $netmask= "";
1435 for ($byte= 0; $byte<4; $byte++){
1436 $result=0;
1438 for ($i= 7; $i>=0; $i--){
1439 if ($num-- > 0){
1440 $result+= pow(2,$i);
1441 }
1442 }
1444 $netmask.= $result.".";
1445 }
1447 return (preg_replace('/\.$/', '', $netmask));
1448 }
1450 return ($netmask);
1451 }
1454 function netmask_to_bits($netmask)
1455 {
1456 list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1457 $res= 0;
1459 for ($n= 0; $n<4; $n++){
1460 $start= 255;
1461 $name= "nm$n";
1463 for ($i= 0; $i<8; $i++){
1464 if ($start == (int)($$name)){
1465 $res+= 8 - $i;
1466 break;
1467 }
1468 $start-= pow(2,$i);
1469 }
1470 }
1472 return ($res);
1473 }
1476 function recurse($rule, $variables)
1477 {
1478 $result= array();
1480 if (!count($variables)){
1481 return array($rule);
1482 }
1484 reset($variables);
1485 $key= key($variables);
1486 $val= current($variables);
1487 unset ($variables[$key]);
1489 foreach($val as $possibility){
1490 $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1491 $result= array_merge($result, recurse($nrule, $variables));
1492 }
1494 return ($result);
1495 }
1498 function expand_id($rule, $attributes)
1499 {
1500 /* Check for id rule */
1501 if(preg_match('/^id(:|#)\d+$/',$rule)){
1502 return (array("\{$rule}"));
1503 }
1505 /* Check for clean attribute */
1506 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1507 $rule= preg_replace('/^%/', '', $rule);
1508 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1509 return (array($val));
1510 }
1512 /* Check for attribute with parameters */
1513 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1514 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1515 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1516 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1517 $start= preg_replace ('/-.*$/', '', $param);
1518 $stop = preg_replace ('/^[^-]+-/', '', $param);
1520 /* Assemble results */
1521 $result= array();
1522 for ($i= $start; $i<= $stop; $i++){
1523 $result[]= substr($val, 0, $i);
1524 }
1525 return ($result);
1526 }
1528 echo "Error in idgen string: don't know how to handle rule $rule.\n";
1529 return (array($rule));
1530 }
1533 function gen_uids($rule, $attributes)
1534 {
1535 global $config;
1537 /* Search for keys and fill the variables array with all
1538 possible values for that key. */
1539 $part= "";
1540 $trigger= false;
1541 $stripped= "";
1542 $variables= array();
1544 for ($pos= 0; $pos < strlen($rule); $pos++){
1546 if ($rule[$pos] == "{" ){
1547 $trigger= true;
1548 $part= "";
1549 continue;
1550 }
1552 if ($rule[$pos] == "}" ){
1553 $variables[$pos]= expand_id($part, $attributes);
1554 $stripped.= "\{$pos}";
1555 $trigger= false;
1556 continue;
1557 }
1559 if ($trigger){
1560 $part.= $rule[$pos];
1561 } else {
1562 $stripped.= $rule[$pos];
1563 }
1564 }
1566 /* Recurse through all possible combinations */
1567 $proposed= recurse($stripped, $variables);
1569 /* Get list of used ID's */
1570 $used= array();
1571 $ldap= $config->get_ldap_link();
1572 $ldap->cd($config->current['BASE']);
1573 $ldap->search('(uid=*)');
1575 while($attrs= $ldap->fetch()){
1576 $used[]= $attrs['uid'][0];
1577 }
1579 /* Remove used uids and watch out for id tags */
1580 $ret= array();
1581 foreach($proposed as $uid){
1583 /* Check for id tag and modify uid if needed */
1584 if(preg_match('/\{id:\d+}/',$uid)){
1585 $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1587 for ($i= 0; $i < pow(10,$size); $i++){
1588 $number= sprintf("%0".$size."d", $i);
1589 $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1590 if (!in_array($res, $used)){
1591 $uid= $res;
1592 break;
1593 }
1594 }
1595 }
1597 if(preg_match('/\{id#\d+}/',$uid)){
1598 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1600 while (true){
1601 mt_srand((double) microtime()*1000000);
1602 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1603 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1604 if (!in_array($res, $used)){
1605 $uid= $res;
1606 break;
1607 }
1608 }
1609 }
1611 /* Don't assign used ones */
1612 if (!in_array($uid, $used)){
1613 $ret[]= $uid;
1614 }
1615 }
1617 return(array_unique($ret));
1618 }
1621 function array_search_r($needle, $key, $haystack){
1623 foreach($haystack as $index => $value){
1624 $match= 0;
1626 if (is_array($value)){
1627 $match= array_search_r($needle, $key, $value);
1628 }
1630 if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1631 $match=1;
1632 }
1634 if ($match){
1635 return 1;
1636 }
1637 }
1639 return 0;
1640 }
1643 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1644 Need to convert... */
1645 function to_byte($value) {
1646 $value= strtolower(trim($value));
1648 if(!is_numeric(substr($value, -1))) {
1650 switch(substr($value, -1)) {
1651 case 'g':
1652 $mult= 1073741824;
1653 break;
1654 case 'm':
1655 $mult= 1048576;
1656 break;
1657 case 'k':
1658 $mult= 1024;
1659 break;
1660 }
1662 return ($mult * (int)substr($value, 0, -1));
1663 } else {
1664 return $value;
1665 }
1666 }
1669 function in_array_ics($value, $items)
1670 {
1671 if (!is_array($items)){
1672 return (FALSE);
1673 }
1675 foreach ($items as $item){
1676 if (strtolower($item) == strtolower($value)) {
1677 return (TRUE);
1678 }
1679 }
1681 return (FALSE);
1682 }
1685 function generate_alphabet($count= 10)
1686 {
1687 $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1688 $alphabet= "";
1689 $c= 0;
1691 /* Fill cells with charaters */
1692 for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1693 if ($c == 0){
1694 $alphabet.= "<tr>";
1695 }
1697 $ch = mb_substr($characters, $i, 1, "UTF8");
1698 $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1699 validate($_GET['plug'])."&search=".$ch."\"> ".$ch." </a></td>";
1701 if ($c++ == $count){
1702 $alphabet.= "</tr>";
1703 $c= 0;
1704 }
1705 }
1707 /* Fill remaining cells */
1708 while ($c++ <= $count){
1709 $alphabet.= "<td> </td>";
1710 }
1712 return ($alphabet);
1713 }
1716 function validate($string)
1717 {
1718 return (strip_tags(preg_replace('/\0/', '', $string)));
1719 }
1721 function get_gosa_version()
1722 {
1723 global $svn_revision, $svn_path;
1725 /* Extract informations */
1726 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1728 /* Release or development? */
1729 if (preg_match('%/gosa/trunk/%', $svn_path)){
1730 return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1731 } else {
1732 $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1733 return (sprintf(_("GOsa $release"), $revision));
1734 }
1735 }
1738 function rmdirRecursive($path, $followLinks=false) {
1739 $dir= opendir($path);
1740 while($entry= readdir($dir)) {
1741 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1742 unlink($path."/".$entry);
1743 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1744 rmdirRecursive($path."/".$entry);
1745 }
1746 }
1747 closedir($dir);
1748 return rmdir($path);
1749 }
1751 function scan_directory($path,$sort_desc=false)
1752 {
1753 $ret = false;
1755 /* is this a dir ? */
1756 if(is_dir($path)) {
1758 /* is this path a readable one */
1759 if(is_readable($path)){
1761 /* Get contents and write it into an array */
1762 $ret = array();
1764 $dir = opendir($path);
1766 /* Is this a correct result ?*/
1767 if($dir){
1768 while($fp = readdir($dir))
1769 $ret[]= $fp;
1770 }
1771 }
1772 }
1773 /* Sort array ascending , like scandir */
1774 sort($ret);
1776 /* Sort descending if parameter is sort_desc is set */
1777 if($sort_desc) {
1778 $ret = array_reverse($ret);
1779 }
1781 return($ret);
1782 }
1784 function clean_smarty_compile_dir($directory)
1785 {
1786 global $svn_revision;
1788 if(is_dir($directory) && is_readable($directory)) {
1789 // Set revision filename to REVISION
1790 $revision_file= $directory."/REVISION";
1792 /* Is there a stamp containing the current revision? */
1793 if(!file_exists($revision_file)) {
1794 // create revision file
1795 create_revision($revision_file, $svn_revision);
1796 } else {
1797 # check for "$config->...['CONFIG']/revision" and the
1798 # contents should match the revision number
1799 if(!compare_revision($revision_file, $svn_revision)){
1800 // If revision differs, clean compile directory
1801 foreach(scan_directory($directory) as $file) {
1802 if(($file==".")||($file=="..")) continue;
1803 if( is_file($directory."/".$file) &&
1804 is_writable($directory."/".$file)) {
1805 // delete file
1806 if(!unlink($directory."/".$file)) {
1807 print_red("File ".$directory."/".$file." could not be deleted.");
1808 // This should never be reached
1809 }
1810 } elseif(is_dir($directory."/".$file) &&
1811 is_writable($directory."/".$file)) {
1812 // Just recursively delete it
1813 rmdirRecursive($directory."/".$file);
1814 }
1815 }
1816 // We should now create a fresh revision file
1817 clean_smarty_compile_dir($directory);
1818 } else {
1819 // Revision matches, nothing to do
1820 }
1821 }
1822 } else {
1823 // Smarty compile dir is not accessible
1824 // (Smarty will warn about this)
1825 }
1826 }
1828 function create_revision($revision_file, $revision)
1829 {
1830 $result= false;
1832 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1833 if($fh= fopen($revision_file, "w")) {
1834 if(fwrite($fh, $revision)) {
1835 $result= true;
1836 }
1837 }
1838 fclose($fh);
1839 } else {
1840 print_red("Can not write to revision file");
1841 }
1843 return $result;
1844 }
1846 function compare_revision($revision_file, $revision)
1847 {
1848 // false means revision differs
1849 $result= false;
1851 if(file_exists($revision_file) && is_readable($revision_file)) {
1852 // Open file
1853 if($fh= fopen($revision_file, "r")) {
1854 // Compare File contents with current revision
1855 if($revision == fread($fh, filesize($revision_file))) {
1856 $result= true;
1857 }
1858 } else {
1859 print_red("Can not open revision file");
1860 }
1861 // Close file
1862 fclose($fh);
1863 }
1865 return $result;
1866 }
1868 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1869 {
1870 $str = ""; // Our return value will be saved in this var
1872 $color = dechex($percentage+150);
1873 $color2 = dechex(150 - $percentage);
1874 $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1876 $progress = (int)(($percentage /100)*$width);
1878 /* Abort printing out percentage, if divs are to small */
1881 /* If theres a better solution for this, use it... */
1882 $str = "
1883 <div style=\" width:".($width)."px;
1884 height:".($height)."px;
1885 background-color:#000000;
1886 padding:1px;\">
1888 <div style=\" width:".($width)."px;
1889 background-color:#$bgcolor;
1890 height:".($height)."px;\">
1892 <div style=\" width:".$progress."px;
1893 height:".$height."px;
1894 background-color:#".$color2.$color2.$color."; \">";
1897 if(($height >10)&&($showvalue)){
1898 $str.= "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1899 <b>".$percentage."%</b>
1900 </font>";
1901 }
1903 $str.= "</div></div></div>";
1905 return($str);
1906 }
1909 function array_key_ics($ikey, $items)
1910 {
1911 /* Gather keys, make them lowercase */
1912 $tmp= array();
1913 foreach ($items as $key => $value){
1914 $tmp[strtolower($key)]= $key;
1915 }
1917 if (isset($tmp[strtolower($ikey)])){
1918 return($tmp[strtolower($ikey)]);
1919 }
1921 return ("");
1922 }
1925 function search_config($arr, $name, $return)
1926 {
1927 if (is_array($arr)){
1928 foreach ($arr as $a){
1929 if (isset($a['CLASS']) &&
1930 strtolower($a['CLASS']) == strtolower($name)){
1932 if (isset($a[$return])){
1933 return ($a[$return]);
1934 } else {
1935 return ("");
1936 }
1937 } else {
1938 $res= search_config ($a, $name, $return);
1939 if ($res != ""){
1940 return $res;
1941 }
1942 }
1943 }
1944 }
1945 return ("");
1946 }
1949 function array_differs($src, $dst)
1950 {
1951 /* If the count is differing, the arrays differ */
1952 if (count ($src) != count ($dst)){
1953 return (TRUE);
1954 }
1956 /* So the count is the same - lets check the contents */
1957 $differs= FALSE;
1958 foreach($src as $value){
1959 if (!in_array($value, $dst)){
1960 $differs= TRUE;
1961 }
1962 }
1964 return ($differs);
1965 }
1968 function saveFilter($a_filter, $values)
1969 {
1970 if (isset($_POST['regexit'])){
1971 $a_filter["regex"]= $_POST['regexit'];
1973 foreach($values as $type){
1974 if (isset($_POST[$type])) {
1975 $a_filter[$type]= "checked";
1976 } else {
1977 $a_filter[$type]= "";
1978 }
1979 }
1980 }
1982 /* React on alphabet links if needed */
1983 if (isset($_GET['search'])){
1984 $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
1985 if ($s == "**"){
1986 $s= "*";
1987 }
1988 $a_filter['regex']= $s;
1989 }
1991 return ($a_filter);
1992 }
1995 /* Escape all preg_* relevant characters */
1996 function normalizePreg($input)
1997 {
1998 return (addcslashes($input, '[]()|/.*+-'));
1999 }
2002 /* Escape all LDAP filter relevant characters */
2003 function normalizeLdap($input)
2004 {
2005 return (addcslashes($input, '()|'));
2006 }
2009 /* Resturns the difference between to microtime() results in float */
2010 function get_MicroTimeDiff($start , $stop)
2011 {
2012 $a = split("\ ",$start);
2013 $b = split("\ ",$stop);
2015 $secs = $b[1] - $a[1];
2016 $msecs= $b[0] - $a[0];
2018 $ret = (float) ($secs+ $msecs);
2019 return($ret);
2020 }
2023 /* Check if the given department name is valid */
2024 function is_department_name_reserved($name,$base)
2025 {
2026 $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
2027 preg_replace("/ou=(.*),/","\\1",get_people_ou()),
2028 preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
2029 $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
2031 /* Check if name is one of the reserved names */
2032 if(in_array_ics($name,$reservedName)) {
2033 return(true);
2034 }
2036 /* Check all follow combinations if name is in array && parent base == array_key, return false*/
2037 foreach($follwedNames as $key => $names){
2038 if((in_array_ics($name,$names)) && (preg_match($key,$base))){
2039 return(true);
2040 }
2041 }
2042 return(false);
2043 }
2046 function get_base_dir()
2047 {
2048 global $BASE_DIR;
2050 return $BASE_DIR;
2051 }
2054 function obj_is_readable($dn, $object, $attribute)
2055 {
2056 global $ui;
2058 return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2059 }
2062 function obj_is_writable($dn, $object, $attribute)
2063 {
2064 global $ui;
2066 return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2067 }
2070 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2071 {
2072 /* Initialize variables */
2073 $ret = array("count" => 0); // Set count to 0
2074 $next = true; // if false, then skip next loops and return
2075 $cnt = 0; // Current number of loops
2076 $max = 100; // Just for security, prevent looops
2077 $ldap = NULL; // To check if created result a valid
2078 $keep = ""; // save last failed parse string
2080 /* Check each parsed dn in ldap ? */
2081 if($config!=NULL && $verify_in_ldap){
2082 $ldap = $config->get_ldap_link();
2083 }
2085 /* Lets start */
2086 $called = false;
2087 while(preg_match("/,/",$dn) && $next && $cnt < $max){
2089 $cnt ++;
2090 if(!preg_match("/,/",$dn)){
2091 $next = false;
2092 }
2093 $object = preg_replace("/[,].*$/","",$dn);
2094 $dn = preg_replace("/^[^,]+,/","",$dn);
2096 $called = true;
2098 /* Check if current dn is valid */
2099 if($ldap!=NULL){
2100 $ldap->cd($dn);
2101 $ldap->cat($dn,array("dn"));
2102 if($ldap->count()){
2103 $ret[] = $keep.$object;
2104 $keep = "";
2105 }else{
2106 $keep .= $object.",";
2107 }
2108 }else{
2109 $ret[] = $keep.$object;
2110 $keep = "";
2111 }
2112 }
2114 /* No dn was posted */
2115 if($cnt == 0 && !empty($dn)){
2116 $ret[] = $dn;
2117 }
2119 /* Append the rest */
2120 $test = $keep.$dn;
2121 if($called && !empty($test)){
2122 $ret[] = $keep.$dn;
2123 }
2124 $ret['count'] = count($ret) - 1;
2126 return($ret);
2127 }
2129 function is_php4()
2130 {
2131 return (preg_match('/^4/', phpversion()));
2132 }
2134 /* Add "str_split" if this function is missing.
2135 * This function is only available in PHP5
2136 */
2137 if(!function_exists("str_split")){
2138 function str_split($str,$length =1)
2139 {
2140 if($length < 1 ) $length =1;
2142 $ret = array();
2143 for($i = 0 ; $i < strlen($str); $i = $i +$length){
2144 $ret[] = substr($str,$i ,$length);
2145 }
2146 return($ret);
2147 }
2148 }
2151 function get_base_from_hook($dn, $attrib)
2152 {
2153 global $config;
2155 if (isset($config->current['BASE_HOOK'])){
2157 /* Call hook script - if present */
2158 $command= $config->current['BASE_HOOK'];
2160 if ($command != ""){
2161 $command.= " '$dn' $attrib";
2162 if (check_command($command)){
2163 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2164 exec($command, $output);
2165 if (preg_match("/^[0-9]+$/", $output[0])){
2166 return ($output[0]);
2167 } else {
2168 print_red(_("Warning - base_hook is not avialable. Using default base."));
2169 return ($config->current['UIDBASE']);
2170 }
2171 } else {
2172 print_red(_("Warning - base_hook is not avialable. Using default base."));
2173 return ($config->current['UIDBASE']);
2174 }
2176 } else {
2178 print_red(_("Warning - no base_hook defined. Using default base."));
2179 return ($config->current['UIDBASE']);
2181 }
2182 }
2183 }
2185 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2186 ?>