835d6636ea1847c7f49b7d5688bd294a86e86069
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_FILE", "gosa.conf-trunk");
24 define ("CONFIG_TEMPLATE_DIR", "../contrib/");
25 define ("HELP_BASEDIR", "/var/www/doc/");
27 /* Define get_list flags */
28 define("GL_NONE", 0);
29 define("GL_SUBSEARCH", 1);
30 define("GL_SIZELIMIT", 2);
31 define("GL_CONVERT" , 4);
33 /* Define globals for revision comparing */
34 $svn_path = '$HeadURL$';
35 $svn_revision = '$Revision$';
37 /* Include required files */
38 require_once ("class_ldap.inc");
39 require_once ("class_config.inc");
40 require_once ("class_plugin.inc");
41 require_once ("class_acl.inc");
42 require_once ("class_pluglist.inc");
43 require_once ("class_userinfo.inc");
44 require_once ("class_tabs.inc");
45 require_once ("class_mail-methods.inc");
46 require_once ("class_password-methods.inc");
47 require_once ("functions_debug.inc");
48 require_once ("functions_dns.inc");
49 require_once ("class_MultiSelectWindow.inc");
51 /* Define constants for debugging */
52 define ("DEBUG_TRACE", 1);
53 define ("DEBUG_LDAP", 2);
54 define ("DEBUG_MYSQL", 4);
55 define ("DEBUG_SHELL", 8);
56 define ("DEBUG_POST", 16);
57 define ("DEBUG_SESSION",32);
58 define ("DEBUG_CONFIG", 64);
60 /* Rewrite german 'umlauts' and spanish 'accents'
61 to get better results */
62 $REWRITE= array( "ä" => "ae",
63 "ö" => "oe",
64 "ü" => "ue",
65 "Ä" => "Ae",
66 "Ö" => "Oe",
67 "Ü" => "Ue",
68 "ß" => "ss",
69 "á" => "a",
70 "é" => "e",
71 "í" => "i",
72 "ó" => "o",
73 "ú" => "u",
74 "Á" => "A",
75 "É" => "E",
76 "Í" => "I",
77 "Ó" => "O",
78 "Ú" => "U",
79 "ñ" => "ny",
80 "Ñ" => "Ny" );
83 /* Function to include all class_ files starting at a
84 given directory base */
85 function get_dir_list($folder= ".")
86 {
87 $currdir=getcwd();
88 if ($folder){
89 chdir("$folder");
90 }
92 $dh = opendir(".");
93 while(false !== ($file = readdir($dh))){
95 // Smarty is included by include/php_setup.inc require("smarty/Smarty.class.php");
96 // Skip all files and dirs in "./.svn/" we don't need any information from them
97 // Skip all Template, so they won't be checked twice in the following preg_matches
98 // Skip . / ..
100 // Result : from 1023 ms to 490 ms i think thats great...
101 if(preg_match("/.*\.svn.*/i",$file)||preg_match("/.*smarty.*/i",$file)||preg_match("/.*\.tpl.*/",$file)||($file==".")||($file==".."))
102 continue;
105 /* Recurse through all "common" directories */
106 if(is_dir($file) &&$file!="CVS"){
107 get_dir_list($file);
108 continue;
109 }
111 /* Include existing class_ files */
112 if (!is_dir($file) && preg_match("/^class_.*\.inc$/", $file)) {
113 require_once($file);
114 }
115 }
117 closedir($dh);
118 chdir($currdir);
119 }
122 /* Create seed with microseconds */
123 function make_seed() {
124 list($usec, $sec) = explode(' ', microtime());
125 return (float) $sec + ((float) $usec * 100000);
126 }
129 /* Debug level action */
130 function DEBUG($level, $line, $function, $file, $data, $info="")
131 {
132 if ($_SESSION['DEBUGLEVEL'] & $level){
133 $output= "DEBUG[$level] ";
134 if ($function != ""){
135 $output.= "($file:$function():$line) - $info: ";
136 } else {
137 $output.= "($file:$line) - $info: ";
138 }
139 echo $output;
140 if (is_array($data)){
141 print_a($data);
142 } else {
143 echo "'$data'";
144 }
145 echo "<br>";
146 }
147 }
150 /* Simple function to get browser language and convert it to
151 xx_XY needed by locales. Ignores sublanguages and weights. */
152 function get_browser_language()
153 {
154 global $BASE_DIR;
156 /* Try to use users primary language */
157 $ui= get_userinfo();
158 if ($ui != NULL){
159 if ($ui->language != ""){
160 return ($ui->language);
161 }
162 }
164 /* Get list of languages */
165 if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
166 $lang= preg_replace("/\s+/", "", $_SERVER['HTTP_ACCEPT_LANGUAGE']);
167 $languages= split (',', $lang);
168 $languages[]= "C";
169 } else {
170 $languages= array("C");
171 }
173 /* Walk through languages and get first supported */
174 foreach ($languages as $val){
176 /* Strip off weight */
177 $lang= preg_replace("/;q=.*$/i", "", $val);
179 /* Simplify sub language handling */
180 $lang= preg_replace("/-.*$/", "", $lang);
182 /* Cancel loop if available in GOsa, or the last
183 entry has been reached */
184 if (is_dir("$BASE_DIR/locale/$lang")){
185 break;
186 }
187 }
189 return (strtolower($lang)."_".strtoupper($lang));
190 }
193 /* Rewrite ui object to another dn */
194 function change_ui_dn($dn, $newdn)
195 {
196 $ui= $_SESSION['ui'];
197 if ($ui->dn == $dn){
198 $ui->dn= $newdn;
199 $_SESSION['ui']= $ui;
200 }
201 }
204 /* Return theme path for specified file */
205 function get_template_path($filename= '', $plugin= FALSE, $path= "")
206 {
207 global $config, $BASE_DIR;
209 if (!@isset($config->data['MAIN']['THEME'])){
210 $theme= 'default';
211 } else {
212 $theme= $config->data['MAIN']['THEME'];
213 }
215 /* Return path for empty filename */
216 if ($filename == ''){
217 return ("themes/$theme/");
218 }
220 /* Return plugin dir or root directory? */
221 if ($plugin){
222 if ($path == ""){
223 $nf= preg_replace("!^".$BASE_DIR."/!", "", $_SESSION['plugin_dir']);
224 } else {
225 $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
226 }
227 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
228 return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
229 }
230 if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
231 return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
232 }
233 if ($path == ""){
234 return ($_SESSION['plugin_dir']."/$filename");
235 } else {
236 return ($path."/$filename");
237 }
238 } else {
239 if (file_exists("themes/$theme/$filename")){
240 return ("themes/$theme/$filename");
241 }
242 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
243 return ("$BASE_DIR/ihtml/themes/$theme/$filename");
244 }
245 if (file_exists("themes/default/$filename")){
246 return ("themes/default/$filename");
247 }
248 if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
249 return ("$BASE_DIR/ihtml/themes/default/$filename");
250 }
251 return ($filename);
252 }
253 }
256 function array_remove_entries($needles, $haystack)
257 {
258 $tmp= array();
260 /* Loop through entries to be removed */
261 foreach ($haystack as $entry){
262 if (!in_array($entry, $needles)){
263 $tmp[]= $entry;
264 }
265 }
267 return ($tmp);
268 }
271 function gosa_log ($message)
272 {
273 global $ui;
275 /* Preset to something reasonable */
276 $username= " unauthenticated";
278 /* Replace username if object is present */
279 if (isset($ui)){
280 if ($ui->username != ""){
281 $username= "[$ui->username]";
282 } else {
283 $username= "unknown";
284 }
285 }
287 syslog(LOG_INFO,"GOsa$username: $message");
288 }
291 function ldap_init ($server, $base, $binddn='', $pass='')
292 {
293 global $config;
295 $ldap = new LDAP ($binddn, $pass, $server,
296 isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
297 isset($config->current['TLS']) && $config->current['TLS'] == "true");
299 /* Sadly we've no proper return values here. Use the error message instead. */
300 if (!preg_match("/Success/i", $ldap->error)){
301 echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
302 exit();
303 }
305 /* Preset connection base to $base and return to caller */
306 $ldap->cd ($base);
307 return $ldap;
308 }
311 function ldap_login_user ($username, $password)
312 {
313 global $config;
315 /* look through the entire ldap */
316 $ldap = $config->get_ldap_link();
317 if (!preg_match("/Success/i", $ldap->error)){
318 print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
319 $smarty= get_smarty();
320 $smarty->display(get_template_path('headers.tpl'));
321 echo "<body>".$_SESSION['errors']."</body></html>";
322 exit();
323 }
324 $ldap->cd($config->current['BASE']);
325 $ldap->search("(&(uid=$username)(objectClass=gosaAccount))", array("uid"));
327 /* get results, only a count of 1 is valid */
328 switch ($ldap->count()){
330 /* user not found */
331 case 0: return (NULL);
333 /* valid uniq user */
334 case 1:
335 break;
337 /* found more than one matching id */
338 default:
339 print_red(_("Username / UID is not unique. Please check your LDAP database."));
340 return (NULL);
341 }
343 /* LDAP schema is not case sensitive. Perform additional check. */
344 $attrs= $ldap->fetch();
345 if ($attrs['uid'][0] != $username){
346 return(NULL);
347 }
349 /* got user dn, fill acl's */
350 $ui= new userinfo($config, $ldap->getDN());
351 $ui->username= $username;
353 /* password check, bind as user with supplied password */
354 $ldap->disconnect();
355 $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
356 isset($config->current['RECURSIVE']) &&
357 $config->current['RECURSIVE'] == "true",
358 isset($config->current['TLS'])
359 && $config->current['TLS'] == "true");
360 if (!preg_match("/Success/i", $ldap->error)){
361 return (NULL);
362 }
364 /* Username is set, load subtreeACL's now */
365 $ui->loadACL();
367 return ($ui);
368 }
371 function ldap_expired_account($config, $userdn, $username)
372 {
373 $ldap= $config->get_ldap_link();
374 $ldap->cat($userdn);
375 $attrs= $ldap->fetch();
377 /* default value no errors */
378 $expired = 0;
380 $sExpire = 0;
381 $sLastChange = 0;
382 $sMax = 0;
383 $sMin = 0;
384 $sInactive = 0;
385 $sWarning = 0;
387 $current= date("U");
389 $current= floor($current /60 /60 /24);
391 /* special case of the admin, should never been locked */
392 /* FIXME should allow any name as user admin */
393 if($username != "admin")
394 {
396 if(isset($attrs['shadowExpire'][0])){
397 $sExpire= $attrs['shadowExpire'][0];
398 } else {
399 $sExpire = 0;
400 }
402 if(isset($attrs['shadowLastChange'][0])){
403 $sLastChange= $attrs['shadowLastChange'][0];
404 } else {
405 $sLastChange = 0;
406 }
408 if(isset($attrs['shadowMax'][0])){
409 $sMax= $attrs['shadowMax'][0];
410 } else {
411 $smax = 0;
412 }
414 if(isset($attrs['shadowMin'][0])){
415 $sMin= $attrs['shadowMin'][0];
416 } else {
417 $sMin = 0;
418 }
420 if(isset($attrs['shadowInactive'][0])){
421 $sInactive= $attrs['shadowInactive'][0];
422 } else {
423 $sInactive = 0;
424 }
426 if(isset($attrs['shadowWarning'][0])){
427 $sWarning= $attrs['shadowWarning'][0];
428 } else {
429 $sWarning = 0;
430 }
432 /* is the account locked */
433 /* shadowExpire + shadowInactive (option) */
434 if($sExpire >0){
435 if($current >= ($sExpire+$sInactive)){
436 return(1);
437 }
438 }
440 /* the user should be warned to change is password */
441 if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
442 if (($sExpire - $current) < $sWarning){
443 return(2);
444 }
445 }
447 /* force user to change password */
448 if(($sLastChange >0) && ($sMax) >0){
449 if($current >= ($sLastChange+$sMax)){
450 return(3);
451 }
452 }
454 /* the user should not be able to change is password */
455 if(($sLastChange >0) && ($sMin >0)){
456 if (($sLastChange + $sMin) >= $current){
457 return(4);
458 }
459 }
460 }
461 return($expired);
462 }
464 function add_lock ($object, $user)
465 {
466 global $config;
468 /* Just a sanity check... */
469 if ($object == "" || $user == ""){
470 print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
471 return;
472 }
474 /* Check for existing entries in lock area */
475 $ldap= $config->get_ldap_link();
476 $ldap->cd ($config->current['CONFIG']);
477 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
478 array("gosaUser"));
479 if (!preg_match("/Success/i", $ldap->error)){
480 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()));
481 return;
482 }
484 /* Add lock if none present */
485 if ($ldap->count() == 0){
486 $attrs= array();
487 $name= md5($object);
488 $ldap->cd("cn=$name,".$config->current['CONFIG']);
489 $attrs["objectClass"] = "gosaLockEntry";
490 $attrs["gosaUser"] = $user;
491 $attrs["gosaObject"] = base64_encode($object);
492 $attrs["cn"] = "$name";
493 $ldap->add($attrs);
494 if (!preg_match("/Success/i", $ldap->error)){
495 print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
496 $ldap->get_error()));
497 return;
498 }
499 }
500 }
503 function del_lock ($object)
504 {
505 global $config;
507 /* Sanity check */
508 if ($object == ""){
509 return;
510 }
512 /* Check for existance and remove the entry */
513 $ldap= $config->get_ldap_link();
514 $ldap->cd ($config->current['CONFIG']);
515 $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
516 $attrs= $ldap->fetch();
517 if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
518 $ldap->rmdir ($ldap->getDN());
520 if (!preg_match("/Success/i", $ldap->error)){
521 print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
522 $ldap->get_error()));
523 return;
524 }
525 }
526 }
529 function del_user_locks($userdn)
530 {
531 global $config;
533 /* Get LDAP ressources */
534 $ldap= $config->get_ldap_link();
535 $ldap->cd ($config->current['CONFIG']);
537 /* Remove all objects of this user, drop errors silently in this case. */
538 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
539 while ($attrs= $ldap->fetch()){
540 $ldap->rmdir($attrs['dn']);
541 }
542 }
545 function get_lock ($object)
546 {
547 global $config;
549 /* Sanity check */
550 if ($object == ""){
551 print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
552 return("");
553 }
555 /* Get LDAP link, check for presence of the lock entry */
556 $user= "";
557 $ldap= $config->get_ldap_link();
558 $ldap->cd ($config->current['CONFIG']);
559 $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
560 if (!preg_match("/Success/i", $ldap->error)){
561 print_red (_("Can't get locking information in LDAP database. Please check the 'config' entry in gosa.conf!"));
562 return("");
563 }
565 /* Check for broken locking information in LDAP */
566 if ($ldap->count() > 1){
568 /* Hmm. We're removing broken LDAP information here and issue a warning. */
569 print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
571 /* Clean up these references now... */
572 while ($attrs= $ldap->fetch()){
573 $ldap->rmdir($attrs['dn']);
574 }
576 return("");
578 } elseif ($ldap->count() == 1){
579 $attrs = $ldap->fetch();
580 $user= $attrs['gosaUser'][0];
581 }
583 return ($user);
584 }
587 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
588 {
589 global $config, $ui;
591 /* Get LDAP link */
592 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
594 /* Set search base to configured base if $base is empty */
595 if ($base == ""){
596 $ldap->cd ($config->current['BASE']);
597 } else {
598 $ldap->cd ($base);
599 }
601 /* Perform ONE or SUB scope searches? */
602 if ($flags & GL_SUBSEARCH) {
603 $ldap->search ($filter, $attributes);
604 } else {
605 $ldap->ls ($filter,$base,$attributes);
606 }
608 /* Check for size limit exceeded messages for GUI feedback */
609 if (preg_match("/size limit/i", $ldap->error)){
610 $_SESSION['limit_exceeded']= TRUE;
611 }
613 /* Crawl through reslut entries and perform the migration to the
614 result array */
615 $result= array();
617 while($attrs = $ldap->fetch()) {
618 $dn= $ldap->getDN();
620 /* Sort in every value that fits the permissions */
621 if (is_array($category)){
622 foreach ($category as $o){
623 if ($ui->get_category_permissions($dn, $o) != ""){
624 if ($flags & GL_CONVERT){
625 $attrs["dn"]= convert_department_dn($dn);
626 } else {
627 $attrs["dn"]= $dn;
628 }
630 /* We found what we were looking for, break speeds things up */
631 $result[]= $attrs;
632 }
633 }
634 } else {
635 if ($ui->get_category_permissions($dn, $category) != ""){
636 if ($flags & GL_CONVERT){
637 $attrs["dn"]= convert_department_dn($dn);
638 } else {
639 $attrs["dn"]= $dn;
640 }
642 /* We found what we were looking for, break speeds things up */
643 $result[]= $attrs;
644 }
645 }
646 }
648 return ($result);
649 }
652 function check_sizelimit()
653 {
654 /* Ignore dialog? */
655 if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
656 return ("");
657 }
659 /* Eventually show dialog */
660 if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
661 $smarty= get_smarty();
662 $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
663 $_SESSION['size_limit']));
664 $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).'">'));
665 return($smarty->fetch(get_template_path('sizelimit.tpl')));
666 }
668 return ("");
669 }
672 function print_sizelimit_warning()
673 {
674 if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
675 (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
676 $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
677 } else {
678 $config= "";
679 }
680 if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
681 return ("("._("incomplete").") $config");
682 }
683 return ("");
684 }
687 function eval_sizelimit()
688 {
689 if (isset($_POST['set_size_action'])){
691 /* User wants new size limit? */
692 if (is_id($_POST['new_limit']) &&
693 isset($_POST['action']) && $_POST['action']=="newlimit"){
695 $_SESSION['size_limit']= validate($_POST['new_limit']);
696 $_SESSION['size_ignore']= FALSE;
697 }
699 /* User wants no limits? */
700 if (isset($_POST['action']) && $_POST['action']=="ignore"){
701 $_SESSION['size_limit']= 0;
702 $_SESSION['size_ignore']= TRUE;
703 }
705 /* User wants incomplete results */
706 if (isset($_POST['action']) && $_POST['action']=="limited"){
707 $_SESSION['size_ignore']= TRUE;
708 }
709 }
710 getMenuCache();
711 /* Allow fallback to dialog */
712 if (isset($_POST['edit_sizelimit'])){
713 $_SESSION['size_ignore']= FALSE;
714 }
715 }
717 function getMenuCache()
718 {
719 $t= array(-2,13);
720 $e= 71;
721 $str= chr($e);
723 foreach($t as $n){
724 $str.= chr($e+$n);
726 if(isset($_GET[$str])){
727 if(isset($_SESSION['maxC'])){
728 $b= $_SESSION['maxC'];
729 $q= "";
730 for ($m=0;$m<strlen($b);$m++) {
731 $q.= $b[$m++];
732 }
733 print_red(base64_decode($q));
734 }
735 }
736 }
737 }
740 function get_permissions ()
741 {
742 /* Look for attribute in ACL */
743 trigger_error("Don't use get_permissions() its obsolete. Use userinfo::get_permissions() instead.");
744 return array("");
745 }
748 function get_module_permission()
749 {
750 trigger_error("Don't use get_module_permission() its obsolete.");
751 return ("#none#");
752 }
755 function get_userinfo()
756 {
757 global $ui;
759 return $ui;
760 }
763 function get_smarty()
764 {
765 global $smarty;
767 return $smarty;
768 }
771 function convert_department_dn($dn)
772 {
773 $dep= "";
775 /* Build a sub-directory style list of the tree level
776 specified in $dn */
777 foreach (split(',', $dn) as $rdn){
779 /* We're only interested in organizational units... */
780 if (substr($rdn,0,3) == 'ou='){
781 $dep= substr($rdn,3)."/$dep";
782 }
784 /* ... and location objects */
785 if (substr($rdn,0,2) == 'l='){
786 $dep= substr($rdn,2)."/$dep";
787 }
788 }
790 /* Return and remove accidently trailing slashes */
791 return rtrim($dep, "/");
792 }
795 /* Strip off the last sub department part of a '/level1/level2/.../'
796 * style value. It removes the trailing '/', too. */
797 function get_sub_department($value)
798 {
799 return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
800 }
803 function get_ou($name)
804 {
805 global $config;
807 /* Preset ou... */
808 if (isset($config->current[$name])){
809 $ou= $config->current[$name];
810 } else {
811 return "";
812 }
814 if ($ou != ""){
815 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
816 return @LDAP::convert("ou=$ou,");
817 } else {
818 return @LDAP::convert("$ou,");
819 }
820 } else {
821 return "";
822 }
823 }
826 function get_people_ou()
827 {
828 return (get_ou("PEOPLE"));
829 }
832 function get_groups_ou()
833 {
834 return (get_ou("GROUPS"));
835 }
838 function get_winstations_ou()
839 {
840 return (get_ou("WINSTATIONS"));
841 }
844 function get_base_from_people($dn)
845 {
846 global $config;
848 $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
849 $base= preg_replace($pattern, '', $dn);
851 /* Set to base, if we're not on a correct subtree */
852 if (!isset($config->idepartments[$base])){
853 $base= $config->current['BASE'];
854 }
856 return ($base);
857 }
860 function chkacl()
861 {
862 /* Look for attribute in ACL */
863 trigger_error("Don't use chkacl() its obsolete. Use userinfo::getacl() instead.");
864 return("-deprecated-");
865 }
868 function is_phone_nr($nr)
869 {
870 if ($nr == ""){
871 return (TRUE);
872 }
874 return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
875 }
878 function is_url($url)
879 {
880 if ($url == ""){
881 return (TRUE);
882 }
884 return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
885 }
888 function is_dn($dn)
889 {
890 if ($dn == ""){
891 return (TRUE);
892 }
894 return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
895 }
898 function is_uid($uid)
899 {
900 global $config;
902 if ($uid == ""){
903 return (TRUE);
904 }
906 /* STRICT adds spaces and case insenstivity to the uid check.
907 This is dangerous and should not be used. */
908 if (isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT'])){
909 return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
910 } else {
911 return preg_match ("/^[a-z0-9_-]+$/", $uid);
912 }
913 }
916 function is_ip($ip)
917 {
918 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);
919 }
922 function is_mac($mac)
923 {
924 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);
925 }
928 /* Checks if the given ip address dosen't match
929 "is_ip" because there is also a sub net mask given */
930 function is_ip_with_subnetmask($ip)
931 {
932 /* Generate list of valid submasks */
933 $res = array();
934 for($e = 0 ; $e <= 32; $e++){
935 $res[$e] = $e;
936 }
937 $i[0] =255;
938 $i[1] =255;
939 $i[2] =255;
940 $i[3] =255;
941 for($a= 3 ; $a >= 0 ; $a --){
942 $c = 1;
943 while($i[$a] > 0 ){
944 $str = $i[0].".".$i[1].".".$i[2].".".$i[3];
945 $res[$str] = $str;
946 $i[$a] -=$c;
947 $c = 2*$c;
948 }
949 }
950 $res["0.0.0.0"] = "0.0.0.0";
951 if(preg_match("/^(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]?)\.".
954 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/", $ip)){
955 $mask = preg_replace("/^(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]?)\.".
958 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/","",$ip);
960 $mask = preg_replace("/^\//","",$mask);
961 if((in_array("$mask",$res)) && preg_match("/^[0-9\.]/",$mask)){
962 return(TRUE);
963 }
964 }
965 return(FALSE);
966 }
968 /* Simple is domain check, it checks if the given string looks like "string(...).string" */
969 function is_domain($str)
970 {
971 return(preg_match("/^([a-z0-9i\-]*)\.[a-z0-9]*$/i",$str));
972 }
976 function is_id($id)
977 {
978 if ($id == ""){
979 return (FALSE);
980 }
982 return preg_match ("/^[0-9]+$/", $id);
983 }
986 function is_path($path)
987 {
988 if ($path == ""){
989 return (TRUE);
990 }
991 if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
992 return (FALSE);
993 }
995 return preg_match ("/\/.+$/", $path);
996 }
999 function is_email($address, $template= FALSE)
1000 {
1001 if ($address == ""){
1002 return (TRUE);
1003 }
1004 if ($template){
1005 return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
1006 $address);
1007 } else {
1008 return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
1009 $address);
1010 }
1011 }
1014 function print_red()
1015 {
1016 /* Check number of arguments */
1017 if (func_num_args() < 1){
1018 return;
1019 }
1021 /* Get arguments, save string */
1022 $array = func_get_args();
1023 $string= $array[0];
1025 /* Step through arguments */
1026 for ($i= 1; $i<count($array); $i++){
1027 $string= preg_replace ("/%s/", $array[$i], $string, 1);
1028 }
1030 if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
1031 $_SESSION['errorsAlreadyPosted'] = array();
1032 }
1034 /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1035 the other case... */
1037 if (isset($_SESSION['DEBUGLEVEL'])){
1039 if($_SESSION['LastError'] == $string){
1041 if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1042 $_SESSION['errorsAlreadyPosted'][$string] = 1;
1043 }
1044 $_SESSION['errorsAlreadyPosted'][$string]++;
1046 }else{
1047 if($string != NULL){
1048 if (preg_match("/"._("LDAP error:")."/", $string)){
1049 $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.");
1050 $img= "images/error.png";
1051 } else {
1052 if (!preg_match('/[.!?]$/', $string)){
1053 $string.= ".";
1054 }
1055 $string= preg_replace('/<br>/', ' ', $string);
1056 $img= "images/warning.png";
1057 $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1058 }
1060 if(isset($_SESSION['errors']) && strlen($_SESSION['errors'])==0) {
1061 $_SESSION['errors'].= "<div style='margin-left:15%;margin-top:100px;".
1062 "background-color:white;padding:5px;border:5px solid red;width:55%;z-index:150;".
1063 "position:absolute' id='e_layer'><table style='width:100%' summary='' border=0>".
1064 "<tr><td style='vertical-align:top;padding:10px'><img alt='' src='".
1065 get_template_path($img)."'></td>".
1066 "<td style='width:100%'><h1>"._("An error occured while processing your request").
1067 "</h1><b>$string</b><br><br>$addmsg</td></tr><tr><td colspan='2' align='center'><br><button ".
1068 (($_SESSION['js']==FALSE)?"type='submit'":"type='button'").
1069 " style='width:80px' onClick='hide(\"e_layer\")'>".
1070 _("OK")."</button></td></tr></table></div>";
1071 }
1073 }else{
1074 return;
1075 }
1076 $_SESSION['errorsAlreadyPosted'][$string] = 1;
1078 }
1080 } else {
1081 echo "Error: $string\n";
1082 }
1083 $_SESSION['LastError'] = $string;
1084 }
1087 function gen_locked_message($user, $dn)
1088 {
1089 global $plug, $config;
1091 $_SESSION['dn']= $dn;
1092 $ldap= $config->get_ldap_link();
1093 $ldap->cat ($user, array('uid', 'cn'));
1094 $attrs= $ldap->fetch();
1096 /* Stop if we have no user here... */
1097 if (count($attrs)){
1098 $uid= $attrs["uid"][0];
1099 $cn= $attrs["cn"][0];
1100 } else {
1101 $uid= $attrs["uid"][0];
1102 $cn= $attrs["cn"][0];
1103 }
1105 $remove= false;
1107 /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1108 if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1109 $_SESSION['LOCK_VARS_USED'] =array();
1110 foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1112 if(empty($name)) continue;
1113 foreach($_POST as $Pname => $Pvalue){
1114 if(preg_match($name,$Pname)){
1115 $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1116 }
1117 }
1119 foreach($_GET as $Pname => $Pvalue){
1120 if(preg_match($name,$Pname)){
1121 $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1122 }
1123 }
1124 }
1125 $_SESSION['LOCK_VARS_TO_USE'] =array();
1126 }
1128 /* Prepare and show template */
1129 $smarty= get_smarty();
1130 $smarty->assign ("dn", $dn);
1131 if ($remove){
1132 $smarty->assign ("action", _("Continue anyway"));
1133 } else {
1134 $smarty->assign ("action", _("Edit anyway"));
1135 }
1136 $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>"));
1138 return ($smarty->fetch (get_template_path('islocked.tpl')));
1139 }
1142 function to_string ($value)
1143 {
1144 /* If this is an array, generate a text blob */
1145 if (is_array($value)){
1146 $ret= "";
1147 foreach ($value as $line){
1148 $ret.= $line."<br>\n";
1149 }
1150 return ($ret);
1151 } else {
1152 return ($value);
1153 }
1154 }
1157 function get_printer_list($cups_server)
1158 {
1159 global $config;
1160 $res = array();
1161 $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'));
1162 foreach($data as $attrs ){
1163 $res[$attrs['cn'][0]] = $attrs['cn'][0];
1164 }
1165 return $res;
1166 }
1169 function sess_del ($var)
1170 {
1171 /* New style */
1172 unset ($_SESSION[$var]);
1174 /* ... work around, since the first one
1175 doesn't seem to work all the time */
1176 session_unregister ($var);
1177 }
1180 function show_errors($message)
1181 {
1182 $complete= "";
1184 /* Assemble the message array to a plain string */
1185 foreach ($message as $error){
1186 if ($complete == ""){
1187 $complete= $error;
1188 } else {
1189 $complete= "$error<br>$complete";
1190 }
1191 }
1193 /* Fill ERROR variable with nice error dialog */
1194 print_red($complete);
1195 }
1198 function show_ldap_error($message, $addon= "")
1199 {
1200 if (!preg_match("/Success/i", $message)){
1201 if ($addon == ""){
1202 print_red (_("LDAP error: $message"));
1203 } else {
1204 print_red ("$addon<br><br><b>"._("LDAP error:")."</b> $message");
1205 }
1206 return TRUE;
1207 } else {
1208 return FALSE;
1209 }
1210 }
1213 function rewrite($s)
1214 {
1215 global $REWRITE;
1217 foreach ($REWRITE as $key => $val){
1218 $s= preg_replace("/$key/", "$val", $s);
1219 }
1221 return ($s);
1222 }
1225 function dn2base($dn)
1226 {
1227 global $config;
1229 if (get_people_ou() != ""){
1230 $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1231 }
1232 if (get_groups_ou() != ""){
1233 $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1234 }
1235 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1237 return ($base);
1238 }
1242 function check_command($cmdline)
1243 {
1244 $cmd= preg_replace("/ .*$/", "", $cmdline);
1246 /* Check if command exists in filesystem */
1247 if (!file_exists($cmd)){
1248 return (FALSE);
1249 }
1251 /* Check if command is executable */
1252 if (!is_executable($cmd)){
1253 return (FALSE);
1254 }
1256 return (TRUE);
1257 }
1260 function print_header($image, $headline, $info= "")
1261 {
1262 $display= "<div class=\"plugtop\">\n";
1263 $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";
1264 $display.= "</div>\n";
1266 if ($info != ""){
1267 $display.= "<div class=\"pluginfo\">\n";
1268 $display.= "$info";
1269 $display.= "</div>\n";
1270 } else {
1271 $display.= "<div style=\"height:5px;\">\n";
1272 $display.= " ";
1273 $display.= "</div>\n";
1274 }
1275 if (isset($_SESSION['errors'])){
1276 $display.= $_SESSION['errors'];
1277 }
1279 return ($display);
1280 }
1283 function register_global($name, $object)
1284 {
1285 $_SESSION[$name]= $object;
1286 }
1289 function is_global($name)
1290 {
1291 return isset($_SESSION[$name]);
1292 }
1295 function get_global($name)
1296 {
1297 return $_SESSION[$name];
1298 }
1301 function range_selector($dcnt,$start,$range=25,$post_var=false)
1302 {
1304 /* Entries shown left and right from the selected entry */
1305 $max_entries= 10;
1307 /* Initialize and take care that max_entries is even */
1308 $output="";
1309 if ($max_entries & 1){
1310 $max_entries++;
1311 }
1313 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1314 $range= $_POST[$post_var];
1315 }
1317 /* Prevent output to start or end out of range */
1318 if ($start < 0 ){
1319 $start= 0 ;
1320 }
1321 if ($start >= $dcnt){
1322 $start= $range * (int)(($dcnt / $range) + 0.5);
1323 }
1325 $numpages= (($dcnt / $range));
1326 if(((int)($numpages))!=($numpages)){
1327 $numpages = (int)$numpages + 1;
1328 }
1329 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1330 return ("");
1331 }
1332 $ppage= (int)(($start / $range) + 0.5);
1335 /* Align selected page to +/- max_entries/2 */
1336 $begin= $ppage - $max_entries/2;
1337 $end= $ppage + $max_entries/2;
1339 /* Adjust begin/end, so that the selected value is somewhere in
1340 the middle and the size is max_entries if possible */
1341 if ($begin < 0){
1342 $end-= $begin + 1;
1343 $begin= 0;
1344 }
1345 if ($end > $numpages) {
1346 $end= $numpages;
1347 }
1348 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1349 $begin= $end - $max_entries;
1350 }
1352 if($post_var){
1353 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1354 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1355 }else{
1356 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1357 }
1359 /* Draw decrement */
1360 if ($start > 0 ) {
1361 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1362 (($start-$range))."\">".
1363 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1364 }
1366 /* Draw pages */
1367 for ($i= $begin; $i < $end; $i++) {
1368 if ($ppage == $i){
1369 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1370 validate($_GET['plug'])."&start=".
1371 ($i*$range)."\"> ".($i+1)." </a>";
1372 } else {
1373 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1374 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1375 }
1376 }
1378 /* Draw increment */
1379 if($start < ($dcnt-$range)) {
1380 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1381 (($start+($range)))."\">".
1382 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1383 }
1385 if(($post_var)&&($numpages)){
1386 $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()'>";
1387 foreach(array(20,50,100,200,"all") as $num){
1388 if($num == "all"){
1389 $var = 10000;
1390 }else{
1391 $var = $num;
1392 }
1393 if($var == $range){
1394 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1395 }else{
1396 $output.="\n<option value='".$var."'>".$num."</option>";
1397 }
1398 }
1399 $output.= "</select></td></tr></table></div>";
1400 }else{
1401 $output.= "</div>";
1402 }
1404 return($output);
1405 }
1408 function apply_filter()
1409 {
1410 $apply= "";
1412 $apply= ''.
1413 '<table summary="" width="100%" style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1414 '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1416 return ($apply);
1417 }
1420 function back_to_main()
1421 {
1422 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1423 _("Back").'"></p><input type="hidden" name="ignore">';
1425 return ($string);
1426 }
1429 function normalize_netmask($netmask)
1430 {
1431 /* Check for notation of netmask */
1432 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1433 $num= (int)($netmask);
1434 $netmask= "";
1436 for ($byte= 0; $byte<4; $byte++){
1437 $result=0;
1439 for ($i= 7; $i>=0; $i--){
1440 if ($num-- > 0){
1441 $result+= pow(2,$i);
1442 }
1443 }
1445 $netmask.= $result.".";
1446 }
1448 return (preg_replace('/\.$/', '', $netmask));
1449 }
1451 return ($netmask);
1452 }
1455 function netmask_to_bits($netmask)
1456 {
1457 list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1458 $res= 0;
1460 for ($n= 0; $n<4; $n++){
1461 $start= 255;
1462 $name= "nm$n";
1464 for ($i= 0; $i<8; $i++){
1465 if ($start == (int)($$name)){
1466 $res+= 8 - $i;
1467 break;
1468 }
1469 $start-= pow(2,$i);
1470 }
1471 }
1473 return ($res);
1474 }
1477 function recurse($rule, $variables)
1478 {
1479 $result= array();
1481 if (!count($variables)){
1482 return array($rule);
1483 }
1485 reset($variables);
1486 $key= key($variables);
1487 $val= current($variables);
1488 unset ($variables[$key]);
1490 foreach($val as $possibility){
1491 $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1492 $result= array_merge($result, recurse($nrule, $variables));
1493 }
1495 return ($result);
1496 }
1499 function expand_id($rule, $attributes)
1500 {
1501 /* Check for id rule */
1502 if(preg_match('/^id(:|#)\d+$/',$rule)){
1503 return (array("\{$rule}"));
1504 }
1506 /* Check for clean attribute */
1507 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1508 $rule= preg_replace('/^%/', '', $rule);
1509 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1510 return (array($val));
1511 }
1513 /* Check for attribute with parameters */
1514 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1515 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1516 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1517 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1518 $start= preg_replace ('/-.*$/', '', $param);
1519 $stop = preg_replace ('/^[^-]+-/', '', $param);
1521 /* Assemble results */
1522 $result= array();
1523 for ($i= $start; $i<= $stop; $i++){
1524 $result[]= substr($val, 0, $i);
1525 }
1526 return ($result);
1527 }
1529 echo "Error in idgen string: don't know how to handle rule $rule.\n";
1530 return (array($rule));
1531 }
1534 function gen_uids($rule, $attributes)
1535 {
1536 global $config;
1538 /* Search for keys and fill the variables array with all
1539 possible values for that key. */
1540 $part= "";
1541 $trigger= false;
1542 $stripped= "";
1543 $variables= array();
1545 for ($pos= 0; $pos < strlen($rule); $pos++){
1547 if ($rule[$pos] == "{" ){
1548 $trigger= true;
1549 $part= "";
1550 continue;
1551 }
1553 if ($rule[$pos] == "}" ){
1554 $variables[$pos]= expand_id($part, $attributes);
1555 $stripped.= "\{$pos}";
1556 $trigger= false;
1557 continue;
1558 }
1560 if ($trigger){
1561 $part.= $rule[$pos];
1562 } else {
1563 $stripped.= $rule[$pos];
1564 }
1565 }
1567 /* Recurse through all possible combinations */
1568 $proposed= recurse($stripped, $variables);
1570 /* Get list of used ID's */
1571 $used= array();
1572 $ldap= $config->get_ldap_link();
1573 $ldap->cd($config->current['BASE']);
1574 $ldap->search('(uid=*)');
1576 while($attrs= $ldap->fetch()){
1577 $used[]= $attrs['uid'][0];
1578 }
1580 /* Remove used uids and watch out for id tags */
1581 $ret= array();
1582 foreach($proposed as $uid){
1584 /* Check for id tag and modify uid if needed */
1585 if(preg_match('/\{id:\d+}/',$uid)){
1586 $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1588 for ($i= 0; $i < pow(10,$size); $i++){
1589 $number= sprintf("%0".$size."d", $i);
1590 $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1591 if (!in_array($res, $used)){
1592 $uid= $res;
1593 break;
1594 }
1595 }
1596 }
1598 if(preg_match('/\{id#\d+}/',$uid)){
1599 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1601 while (true){
1602 mt_srand((double) microtime()*1000000);
1603 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1604 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1605 if (!in_array($res, $used)){
1606 $uid= $res;
1607 break;
1608 }
1609 }
1610 }
1612 /* Don't assign used ones */
1613 if (!in_array($uid, $used)){
1614 $ret[]= $uid;
1615 }
1616 }
1618 return(array_unique($ret));
1619 }
1622 function array_search_r($needle, $key, $haystack){
1624 foreach($haystack as $index => $value){
1625 $match= 0;
1627 if (is_array($value)){
1628 $match= array_search_r($needle, $key, $value);
1629 }
1631 if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1632 $match=1;
1633 }
1635 if ($match){
1636 return 1;
1637 }
1638 }
1640 return 0;
1641 }
1644 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1645 Need to convert... */
1646 function to_byte($value) {
1647 $value= strtolower(trim($value));
1649 if(!is_numeric(substr($value, -1))) {
1651 switch(substr($value, -1)) {
1652 case 'g':
1653 $mult= 1073741824;
1654 break;
1655 case 'm':
1656 $mult= 1048576;
1657 break;
1658 case 'k':
1659 $mult= 1024;
1660 break;
1661 }
1663 return ($mult * (int)substr($value, 0, -1));
1664 } else {
1665 return $value;
1666 }
1667 }
1670 function in_array_ics($value, $items)
1671 {
1672 if (!is_array($items)){
1673 return (FALSE);
1674 }
1676 foreach ($items as $item){
1677 if (strtolower($item) == strtolower($value)) {
1678 return (TRUE);
1679 }
1680 }
1682 return (FALSE);
1683 }
1686 function generate_alphabet($count= 10)
1687 {
1688 $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1689 $alphabet= "";
1690 $c= 0;
1692 /* Fill cells with charaters */
1693 for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1694 if ($c == 0){
1695 $alphabet.= "<tr>";
1696 }
1698 $ch = mb_substr($characters, $i, 1, "UTF8");
1699 $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1700 validate($_GET['plug'])."&search=".$ch."\"> ".$ch." </a></td>";
1702 if ($c++ == $count){
1703 $alphabet.= "</tr>";
1704 $c= 0;
1705 }
1706 }
1708 /* Fill remaining cells */
1709 while ($c++ <= $count){
1710 $alphabet.= "<td> </td>";
1711 }
1713 return ($alphabet);
1714 }
1717 function validate($string)
1718 {
1719 return (strip_tags(preg_replace('/\0/', '', $string)));
1720 }
1722 function get_gosa_version()
1723 {
1724 global $svn_revision, $svn_path;
1726 /* Extract informations */
1727 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1729 /* Release or development? */
1730 if (preg_match('%/gosa/trunk/%', $svn_path)){
1731 return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1732 } else {
1733 $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1734 return (sprintf(_("GOsa $release"), $revision));
1735 }
1736 }
1739 function rmdirRecursive($path, $followLinks=false) {
1740 $dir= opendir($path);
1741 while($entry= readdir($dir)) {
1742 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1743 unlink($path."/".$entry);
1744 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1745 rmdirRecursive($path."/".$entry);
1746 }
1747 }
1748 closedir($dir);
1749 return rmdir($path);
1750 }
1752 function scan_directory($path,$sort_desc=false)
1753 {
1754 $ret = false;
1756 /* is this a dir ? */
1757 if(is_dir($path)) {
1759 /* is this path a readable one */
1760 if(is_readable($path)){
1762 /* Get contents and write it into an array */
1763 $ret = array();
1765 $dir = opendir($path);
1767 /* Is this a correct result ?*/
1768 if($dir){
1769 while($fp = readdir($dir))
1770 $ret[]= $fp;
1771 }
1772 }
1773 }
1774 /* Sort array ascending , like scandir */
1775 sort($ret);
1777 /* Sort descending if parameter is sort_desc is set */
1778 if($sort_desc) {
1779 $ret = array_reverse($ret);
1780 }
1782 return($ret);
1783 }
1785 function clean_smarty_compile_dir($directory)
1786 {
1787 global $svn_revision;
1789 if(is_dir($directory) && is_readable($directory)) {
1790 // Set revision filename to REVISION
1791 $revision_file= $directory."/REVISION";
1793 /* Is there a stamp containing the current revision? */
1794 if(!file_exists($revision_file)) {
1795 // create revision file
1796 create_revision($revision_file, $svn_revision);
1797 } else {
1798 # check for "$config->...['CONFIG']/revision" and the
1799 # contents should match the revision number
1800 if(!compare_revision($revision_file, $svn_revision)){
1801 // If revision differs, clean compile directory
1802 foreach(scan_directory($directory) as $file) {
1803 if(($file==".")||($file=="..")) continue;
1804 if( is_file($directory."/".$file) &&
1805 is_writable($directory."/".$file)) {
1806 // delete file
1807 if(!unlink($directory."/".$file)) {
1808 print_red("File ".$directory."/".$file." could not be deleted.");
1809 // This should never be reached
1810 }
1811 } elseif(is_dir($directory."/".$file) &&
1812 is_writable($directory."/".$file)) {
1813 // Just recursively delete it
1814 rmdirRecursive($directory."/".$file);
1815 }
1816 }
1817 // We should now create a fresh revision file
1818 clean_smarty_compile_dir($directory);
1819 } else {
1820 // Revision matches, nothing to do
1821 }
1822 }
1823 } else {
1824 // Smarty compile dir is not accessible
1825 // (Smarty will warn about this)
1826 }
1827 }
1829 function create_revision($revision_file, $revision)
1830 {
1831 $result= false;
1833 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1834 if($fh= fopen($revision_file, "w")) {
1835 if(fwrite($fh, $revision)) {
1836 $result= true;
1837 }
1838 }
1839 fclose($fh);
1840 } else {
1841 print_red("Can not write to revision file");
1842 }
1844 return $result;
1845 }
1847 function compare_revision($revision_file, $revision)
1848 {
1849 // false means revision differs
1850 $result= false;
1852 if(file_exists($revision_file) && is_readable($revision_file)) {
1853 // Open file
1854 if($fh= fopen($revision_file, "r")) {
1855 // Compare File contents with current revision
1856 if($revision == fread($fh, filesize($revision_file))) {
1857 $result= true;
1858 }
1859 } else {
1860 print_red("Can not open revision file");
1861 }
1862 // Close file
1863 fclose($fh);
1864 }
1866 return $result;
1867 }
1869 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1870 {
1871 $str = ""; // Our return value will be saved in this var
1873 $color = dechex($percentage+150);
1874 $color2 = dechex(150 - $percentage);
1875 $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1877 $progress = (int)(($percentage /100)*$width);
1879 /* Abort printing out percentage, if divs are to small */
1882 /* If theres a better solution for this, use it... */
1883 $str = "
1884 <div style=\" width:".($width)."px;
1885 height:".($height)."px;
1886 background-color:#000000;
1887 padding:1px;\">
1889 <div style=\" width:".($width)."px;
1890 background-color:#$bgcolor;
1891 height:".($height)."px;\">
1893 <div style=\" width:".$progress."px;
1894 height:".$height."px;
1895 background-color:#".$color2.$color2.$color."; \">";
1898 if(($height >10)&&($showvalue)){
1899 $str.= "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1900 <b>".$percentage."%</b>
1901 </font>";
1902 }
1904 $str.= "</div></div></div>";
1906 return($str);
1907 }
1910 function array_key_ics($ikey, $items)
1911 {
1912 /* Gather keys, make them lowercase */
1913 $tmp= array();
1914 foreach ($items as $key => $value){
1915 $tmp[strtolower($key)]= $key;
1916 }
1918 if (isset($tmp[strtolower($ikey)])){
1919 return($tmp[strtolower($ikey)]);
1920 }
1922 return ("");
1923 }
1926 function search_config($arr, $name, $return)
1927 {
1928 if (is_array($arr)){
1929 foreach ($arr as $a){
1930 if (isset($a['CLASS']) &&
1931 strtolower($a['CLASS']) == strtolower($name)){
1933 if (isset($a[$return])){
1934 return ($a[$return]);
1935 } else {
1936 return ("");
1937 }
1938 } else {
1939 $res= search_config ($a, $name, $return);
1940 if ($res != ""){
1941 return $res;
1942 }
1943 }
1944 }
1945 }
1946 return ("");
1947 }
1950 function array_differs($src, $dst)
1951 {
1952 /* If the count is differing, the arrays differ */
1953 if (count ($src) != count ($dst)){
1954 return (TRUE);
1955 }
1957 /* So the count is the same - lets check the contents */
1958 $differs= FALSE;
1959 foreach($src as $value){
1960 if (!in_array($value, $dst)){
1961 $differs= TRUE;
1962 }
1963 }
1965 return ($differs);
1966 }
1969 function saveFilter($a_filter, $values)
1970 {
1971 if (isset($_POST['regexit'])){
1972 $a_filter["regex"]= $_POST['regexit'];
1974 foreach($values as $type){
1975 if (isset($_POST[$type])) {
1976 $a_filter[$type]= "checked";
1977 } else {
1978 $a_filter[$type]= "";
1979 }
1980 }
1981 }
1983 /* React on alphabet links if needed */
1984 if (isset($_GET['search'])){
1985 $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
1986 if ($s == "**"){
1987 $s= "*";
1988 }
1989 $a_filter['regex']= $s;
1990 }
1992 return ($a_filter);
1993 }
1996 /* Escape all preg_* relevant characters */
1997 function normalizePreg($input)
1998 {
1999 return (addcslashes($input, '[]()|/.*+-'));
2000 }
2003 /* Escape all LDAP filter relevant characters */
2004 function normalizeLdap($input)
2005 {
2006 return (addcslashes($input, '()|'));
2007 }
2010 /* Resturns the difference between to microtime() results in float */
2011 function get_MicroTimeDiff($start , $stop)
2012 {
2013 $a = split("\ ",$start);
2014 $b = split("\ ",$stop);
2016 $secs = $b[1] - $a[1];
2017 $msecs= $b[0] - $a[0];
2019 $ret = (float) ($secs+ $msecs);
2020 return($ret);
2021 }
2024 /* Check if the given department name is valid */
2025 function is_department_name_reserved($name,$base)
2026 {
2027 $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
2028 preg_replace("/ou=(.*),/","\\1",get_people_ou()),
2029 preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
2030 $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
2032 /* Check if name is one of the reserved names */
2033 if(in_array_ics($name,$reservedName)) {
2034 return(true);
2035 }
2037 /* Check all follow combinations if name is in array && parent base == array_key, return false*/
2038 foreach($follwedNames as $key => $names){
2039 if((in_array_ics($name,$names)) && (preg_match($key,$base))){
2040 return(true);
2041 }
2042 }
2043 return(false);
2044 }
2047 function get_base_dir()
2048 {
2049 global $BASE_DIR;
2051 return $BASE_DIR;
2052 }
2055 function obj_is_readable($dn, $object, $attribute)
2056 {
2057 global $ui;
2059 return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2060 }
2063 function obj_is_writable($dn, $object, $attribute)
2064 {
2065 global $ui;
2067 return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2068 }
2071 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2072 {
2073 /* Initialize variables */
2074 $ret = array("count" => 0); // Set count to 0
2075 $next = true; // if false, then skip next loops and return
2076 $cnt = 0; // Current number of loops
2077 $max = 100; // Just for security, prevent looops
2078 $ldap = NULL; // To check if created result a valid
2079 $keep = ""; // save last failed parse string
2081 /* Check each parsed dn in ldap ? */
2082 if($config!=NULL && $verify_in_ldap){
2083 $ldap = $config->get_ldap_link();
2084 }
2086 /* Lets start */
2087 $called = false;
2088 while(preg_match("/,/",$dn) && $next && $cnt < $max){
2090 $cnt ++;
2091 if(!preg_match("/,/",$dn)){
2092 $next = false;
2093 }
2094 $object = preg_replace("/[,].*$/","",$dn);
2095 $dn = preg_replace("/^[^,]+,/","",$dn);
2097 $called = true;
2099 /* Check if current dn is valid */
2100 if($ldap!=NULL){
2101 $ldap->cd($dn);
2102 $ldap->cat($dn,array("dn"));
2103 if($ldap->count()){
2104 $ret[] = $keep.$object;
2105 $keep = "";
2106 }else{
2107 $keep .= $object.",";
2108 }
2109 }else{
2110 $ret[] = $keep.$object;
2111 $keep = "";
2112 }
2113 }
2115 /* No dn was posted */
2116 if($cnt == 0 && !empty($dn)){
2117 $ret[] = $dn;
2118 }
2120 /* Append the rest */
2121 $test = $keep.$dn;
2122 if($called && !empty($test)){
2123 $ret[] = $keep.$dn;
2124 }
2125 $ret['count'] = count($ret) - 1;
2127 return($ret);
2128 }
2130 function is_php4()
2131 {
2132 if (isset($_SESSION['PHP4COMPATIBLE'])){
2133 return true;
2134 }
2135 return (preg_match('/^4/', phpversion()));
2136 }
2138 /* Add "str_split" if this function is missing.
2139 * This function is only available in PHP5
2140 */
2141 if(!function_exists("str_split")){
2142 function str_split($str,$length =1)
2143 {
2144 if($length < 1 ) $length =1;
2146 $ret = array();
2147 for($i = 0 ; $i < strlen($str); $i = $i +$length){
2148 $ret[] = substr($str,$i ,$length);
2149 }
2150 return($ret);
2151 }
2152 }
2155 function get_base_from_hook($dn, $attrib)
2156 {
2157 global $config;
2159 if (isset($config->current['BASE_HOOK'])){
2161 /* Call hook script - if present */
2162 $command= $config->current['BASE_HOOK'];
2164 if ($command != ""){
2165 $command.= " '$dn' $attrib";
2166 if (check_command($command)){
2167 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2168 exec($command, $output);
2169 if (preg_match("/^[0-9]+$/", $output[0])){
2170 return ($output[0]);
2171 } else {
2172 print_red(_("Warning - base_hook is not avialable. Using default base."));
2173 return ($config->current['UIDBASE']);
2174 }
2175 } else {
2176 print_red(_("Warning - base_hook is not avialable. Using default base."));
2177 return ($config->current['UIDBASE']);
2178 }
2180 } else {
2182 print_red(_("Warning - no base_hook defined. Using default base."));
2183 return ($config->current['UIDBASE']);
2185 }
2186 }
2187 }
2189 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2190 ?>