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", "/home/cajus/");
26 /* Define globals for revision comparing */
27 $svn_path = '$HeadURL$';
28 $svn_revision = '$Revision$';
30 /* Include required files */
31 require_once ("class_ldap.inc");
32 require_once ("class_config.inc");
33 require_once ("class_userinfo.inc");
34 require_once ("class_plugin.inc");
35 require_once ("class_pluglist.inc");
36 require_once ("class_tabs.inc");
37 require_once ("class_mail-methods.inc");
38 require_once("class_password-methods.inc");
39 require_once ("functions_debug.inc");
41 /* Define constants for debugging */
42 define ("DEBUG_TRACE", 1);
43 define ("DEBUG_LDAP", 2);
44 define ("DEBUG_MYSQL", 4);
45 define ("DEBUG_SHELL", 8);
46 define ("DEBUG_POST", 16);
47 define ("DEBUG_SESSION",32);
48 define ("DEBUG_CONFIG", 64);
50 /* Rewrite german 'umlauts' and spanish 'accents'
51 to get better results */
52 $REWRITE= array( "ä" => "ae",
53 "ö" => "oe",
54 "ü" => "ue",
55 "Ä" => "Ae",
56 "Ö" => "Oe",
57 "Ü" => "Ue",
58 "ß" => "ss",
59 "á" => "a",
60 "é" => "e",
61 "í" => "i",
62 "ó" => "o",
63 "ú" => "u",
64 "Á" => "A",
65 "É" => "E",
66 "Í" => "I",
67 "Ó" => "O",
68 "Ú" => "U",
69 "ñ" => "ny",
70 "Ñ" => "Ny" );
73 /* Function to include all class_ files starting at a
74 given directory base */
75 function get_dir_list($folder= ".")
76 {
77 $currdir=getcwd();
78 if ($folder){
79 chdir("$folder");
80 }
82 $dh = opendir(".");
83 while(false !== ($file = readdir($dh))){
85 /* Recurse through all "common" directories */
86 if(is_dir($file) && $file!="." && $file!=".." && $file!="CVS"){
87 get_dir_list($file);
88 continue;
89 }
91 /* Include existing class_ files */
92 if (!is_dir($file) && preg_match("/^class_.*\.inc$/", $file)) {
93 require_once($file);
94 }
95 }
97 closedir($dh);
98 chdir($currdir);
99 }
102 /* Create seed with microseconds */
103 function make_seed() {
104 list($usec, $sec) = explode(' ', microtime());
105 return (float) $sec + ((float) $usec * 100000);
106 }
109 /* Debug level action */
110 function DEBUG($level, $line, $function, $file, $data, $info="")
111 {
112 if ($_SESSION['DEBUGLEVEL'] & $level){
113 $output= "DEBUG[$level] ";
114 if ($function != ""){
115 $output.= "($file:$function():$line) - $info: ";
116 } else {
117 $output.= "($file:$line) - $info: ";
118 }
119 echo $output;
120 if (is_array($data)){
121 print_a($data);
122 } else {
123 echo "'$data'";
124 }
125 echo "<br>";
126 }
127 }
130 /* Simple function to get browser language and convert it to
131 xx_XY needed by locales. Ignores sublanguages and weights. */
132 function get_browser_language()
133 {
134 global $BASE_DIR;
136 /* Get list of languages */
137 if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
138 $lang= preg_replace("/\s+/", "", $_SERVER['HTTP_ACCEPT_LANGUAGE']);
139 $languages= split (',', $lang);
140 $languages[]= "C";
141 } else {
142 $languages= array("C");
143 }
145 /* Walk through languages and get first supported */
146 foreach ($languages as $val){
148 /* Strip off weight */
149 $lang= preg_replace("/;q=.*$/i", "", $val);
151 /* Simplify sub language handling */
152 $lang= preg_replace("/-.*$/", "", $lang);
154 /* Cancel loop if available in GOsa, or the last
155 entry has been reached */
156 if (is_dir("$BASE_DIR/locale/$lang")){
157 break;
158 }
159 }
161 return (strtolower($lang)."_".strtoupper($lang));
162 }
165 /* Rewrite ui object to another dn */
166 function change_ui_dn($dn, $newdn)
167 {
168 $ui= $_SESSION['ui'];
169 if ($ui->dn == $dn){
170 $ui->dn= $newdn;
171 $_SESSION['ui']= $ui;
172 }
173 }
176 /* Return theme path for specified file */
177 function get_template_path($filename= '', $plugin= FALSE, $path= "")
178 {
179 global $config, $BASE_DIR;
181 if (!@isset($config->data['MAIN']['THEME'])){
182 $theme= 'default';
183 } else {
184 $theme= $config->data['MAIN']['THEME'];
185 }
187 /* Return path for empty filename */
188 if ($filename == ''){
189 return ("themes/$theme/");
190 }
192 /* Return plugin dir or root directory? */
193 if ($plugin){
194 if ($path == ""){
195 $nf= preg_replace("!^".$BASE_DIR."/!", "", $_SESSION['plugin_dir']);
196 } else {
197 $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
198 }
199 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
200 return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
201 }
202 if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
203 return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
204 }
205 if ($path == ""){
206 return ($_SESSION['plugin_dir']."/$filename");
207 } else {
208 return ($path."/$filename");
209 }
210 } else {
211 if (file_exists("themes/$theme/$filename")){
212 return ("themes/$theme/$filename");
213 }
214 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
215 return ("$BASE_DIR/ihtml/themes/$theme/$filename");
216 }
217 if (file_exists("themes/default/$filename")){
218 return ("themes/default/$filename");
219 }
220 if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
221 return ("$BASE_DIR/ihtml/themes/default/$filename");
222 }
223 return ($filename);
224 }
225 }
228 function array_remove_entries($needles, $haystack)
229 {
230 $tmp= array();
232 /* Loop through entries to be removed */
233 foreach ($haystack as $entry){
234 if (!in_array($entry, $needles)){
235 $tmp[]= $entry;
236 }
237 }
239 return ($tmp);
240 }
243 function gosa_log ($message)
244 {
245 global $ui;
247 /* Preset to something reasonable */
248 $username= " unauthenticated";
250 /* Replace username if object is present */
251 if (isset($ui)){
252 if ($ui->username != ""){
253 $username= "[$ui->username]";
254 } else {
255 $username= "unknown";
256 }
257 }
259 syslog(LOG_INFO,"GOsa$username: $message");
260 }
263 function ldap_init ($server, $base, $binddn='', $pass='')
264 {
265 global $config;
267 $ldap = new LDAP ($binddn, $pass, $server, isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
268 isset($config->current['TLS']) && $config->current['TLS'] == "true");
270 /* Sadly we've no proper return values here. Use the error message instead. */
271 if (!preg_match("/Success/i", $ldap->error)){
272 print_red(sprintf(_("Error when connecting the LDAP. Server said '%s'."),
273 $ldap->get_error()));
274 echo $_SESSION['errors'];
276 /* Hard error. We'd like to use the LDAP, anyway... */
277 exit;
278 }
280 /* Preset connection base to $base and return to caller */
281 $ldap->cd ($base);
282 return $ldap;
283 }
286 function ldap_login_user ($username, $password)
287 {
288 global $config;
290 /* look through the entire ldap */
291 $ldap = $config->get_ldap_link();
292 if (!preg_match("/Success/i", $ldap->error)){
293 print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
294 echo $_SESSION['errors'];
295 exit;
296 }
297 $ldap->cd($config->current['BASE']);
298 $ldap->search("(&(uid=$username)(objectClass=gosaAccount))", array("uid"));
300 /* get results, only a count of 1 is valid */
301 switch ($ldap->count()){
303 /* user not found */
304 case 0: return (NULL);
306 /* valid uniq user */
307 case 1:
308 break;
310 /* found more than one matching id */
311 default:
312 print_red(_("Username / UID is not unique. Please check your LDAP database."));
313 return (NULL);
314 }
316 /* LDAP schema is not case sensitive. Perform additional check. */
317 $attrs= $ldap->fetch();
318 if ($attrs['uid'][0] != $username){
319 return(NULL);
320 }
322 /* got user dn, fill acl's */
323 $ui= new userinfo($config, $ldap->getDN());
324 $ui->username= $username;
326 /* password check, bind as user with supplied password */
327 $ldap->disconnect();
328 $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
329 isset($config->current['RECURSIVE']) &&
330 $config->current['RECURSIVE'] == "true",
331 isset($config->current['TLS'])
332 && $config->current['TLS'] == "true");
333 if (!preg_match("/Success/i", $ldap->error)){
334 return (NULL);
335 }
337 /* Username is set, load subtreeACL's now */
338 $ui->loadACL();
340 return ($ui);
341 }
344 function add_lock ($object, $user)
345 {
346 global $config;
348 /* Just a sanity check... */
349 if ($object == "" || $user == ""){
350 print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
351 return;
352 }
354 /* Check for existing entries in lock area */
355 $ldap= $config->get_ldap_link();
356 $ldap->cd ($config->current['CONFIG']);
357 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=$object))",
358 array("gosaUser"));
359 if (!preg_match("/Success/i", $ldap->error)){
360 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()));
361 return;
362 }
364 /* Add lock if none present */
365 if ($ldap->count() == 0){
366 $attrs= array();
367 $name= md5($object);
368 $ldap->cd("cn=$name,".$config->current['CONFIG']);
369 $attrs["objectClass"] = "gosaLockEntry";
370 $attrs["gosaUser"] = $user;
371 $attrs["gosaObject"] = $object;
372 $attrs["cn"] = "$name";
373 $ldap->add($attrs);
374 if (!preg_match("/Success/i", $ldap->error)){
375 print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
376 $ldap->get_error()));
377 return;
378 }
379 }
380 }
383 function del_lock ($object)
384 {
385 global $config;
387 /* Sanity check */
388 if ($object == ""){
389 return;
390 }
392 /* Check for existance and remove the entry */
393 $ldap= $config->get_ldap_link();
394 $ldap->cd ($config->current['CONFIG']);
395 $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=$object))", array("gosaObject"));
396 $attrs= $ldap->fetch();
397 if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
398 $ldap->rmdir ($ldap->getDN());
400 if (!preg_match("/Success/i", $ldap->error)){
401 print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
402 $ldap->get_error()));
403 return;
404 }
405 }
406 }
409 function del_user_locks($userdn)
410 {
411 global $config;
413 /* Get LDAP ressources */
414 $ldap= $config->get_ldap_link();
415 $ldap->cd ($config->current['CONFIG']);
417 /* Remove all objects of this user, drop errors silently in this case. */
418 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
419 while ($attrs= $ldap->fetch()){
420 $ldap->rmdir($attrs['dn']);
421 }
422 }
425 function get_lock ($object)
426 {
427 global $config;
429 /* Sanity check */
430 if ($object == ""){
431 print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
432 return("");
433 }
435 /* Get LDAP link, check for presence of the lock entry */
436 $user= "";
437 $ldap= $config->get_ldap_link();
438 $ldap->cd ($config->current['CONFIG']);
439 $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=$object))", array("gosaUser"));
440 if (!preg_match("/Success/i", $ldap->error)){
441 print_red (_("Can't get locking information in LDAP database. Please check the 'config' entry in gosa.conf!"));
442 return("");
443 }
445 /* Check for broken locking information in LDAP */
446 if ($ldap->count() > 1){
448 /* Hmm. We're removing broken LDAP information here and issue a warning. */
449 print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
451 /* Clean up these references now... */
452 while ($attrs= $ldap->fetch()){
453 $ldap->rmdir($attrs['dn']);
454 }
456 return("");
458 } elseif ($ldap->count() == 1){
459 $attrs = $ldap->fetch();
460 $user= $attrs['gosaUser'][0];
461 }
463 return ($user);
464 }
467 function get_list($subtreeACL, $filter, $subsearch= TRUE, $base="", $attrs= array(), $flag= FALSE)
468 {
469 global $config;
471 /* Base the search on default base if not set */
472 $ldap= $config->get_ldap_link($flag);
473 if ($base == ""){
474 $ldap->cd ($config->current['BASE']);
475 } else {
476 $ldap->cd ($base);
477 }
479 /* Perform ONE or SUB scope searches? */
480 if ($subsearch) {
481 $ldap->search ($filter, $attrs);
482 } else {
483 $ldap->ls ($filter);
484 }
486 /* Check for size limit exceeded messages for GUI feedback */
487 if (preg_match("/size limit/i", $ldap->error)){
488 $_SESSION['limit_exceeded']= TRUE;
489 } else {
490 $_SESSION['limit_exceeded']= FALSE;
491 }
493 /* Crawl through reslut entries and perform the migration to the
494 result array */
495 $result= array();
496 while($attrs = $ldap->fetch()) {
497 $dn= preg_replace("/[ ]*,[ ]*/", ",", $ldap->getDN());
498 foreach ($subtreeACL as $key => $value){
499 if (preg_match("/$key/", $dn)){
500 $attrs["dn"]= $dn;
501 $result[]= $attrs;
502 break;
503 }
504 }
505 }
507 return ($result);
508 }
511 function check_sizelimit()
512 {
513 /* Ignore dialog? */
514 if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
515 return ("");
516 }
518 /* Eventually show dialog */
519 if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
520 $smarty= get_smarty();
521 $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
522 $_SESSION['size_limit']));
523 $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).'">'));
524 return($smarty->fetch(get_template_path('sizelimit.tpl')));
525 }
527 return ("");
528 }
531 function print_sizelimit_warning()
532 {
533 if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
534 (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
535 $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
536 } else {
537 $config= "";
538 }
539 if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
540 return ("("._("incomplete").") $config");
541 }
542 return ("");
543 }
546 function eval_sizelimit()
547 {
548 if (isset($_POST['set_size_action'])){
550 /* User wants new size limit? */
551 if (is_id($_POST['new_limit']) &&
552 isset($_POST['action']) && $_POST['action']=="newlimit"){
554 $_SESSION['size_limit']= validate($_POST['new_limit']);
555 $_SESSION['size_ignore']= FALSE;
556 }
558 /* User wants no limits? */
559 if (isset($_POST['action']) && $_POST['action']=="ignore"){
560 $_SESSION['size_limit']= 0;
561 $_SESSION['size_ignore']= TRUE;
562 }
564 /* User wants incomplete results */
565 if (isset($_POST['action']) && $_POST['action']=="limited"){
566 $_SESSION['size_ignore']= TRUE;
567 }
568 }
570 /* Allow fallback to dialog */
571 if (isset($_POST['edit_sizelimit'])){
572 $_SESSION['size_ignore']= FALSE;
573 }
574 }
577 function get_permissions ($dn, $subtreeACL)
578 {
579 global $config;
581 $base= $config->current['BASE'];
582 $tmp= "d,".$dn;
583 $sacl= array();
585 /* Sort subacl's for lenght to simplify matching
586 for subtrees */
587 foreach ($subtreeACL as $key => $value){
588 $sacl[$key]= strlen($key);
589 }
590 arsort ($sacl);
591 reset ($sacl);
593 /* Successively remove leading parts of the dn's until
594 it doesn't contain commas anymore */
595 while (preg_match('/,/', $tmp)){
596 $tmp= ltrim(strstr($tmp, ","), ",");
598 /* Check for acl that may apply */
599 foreach ($sacl as $key => $value){
600 if (preg_match("/$key$/", $tmp)){
601 return ($subtreeACL[$key]);
602 }
603 }
604 }
606 return array("");
607 }
610 function get_module_permission($acl_array, $module, $dn)
611 {
612 global $ui;
614 $final= "";
615 foreach($acl_array as $acl){
617 /* Check for selfflag (!) in ACL to determine if
618 the user is allowed to change parts of his/her
619 own account */
620 if (preg_match("/^!/", $acl)){
621 if ($dn != "" && $dn != $ui->dn){
623 /* No match for own DN, give up on this ACL */
624 continue;
626 } else {
628 /* Matches own DN, remove the selfflag */
629 $acl= preg_replace("/^!/", "", $acl);
631 }
632 }
634 /* Remove leading garbage */
635 $acl= preg_replace("/^:/", "", $acl);
637 /* Discover if we've access to the submodule by comparing
638 all allowed submodules specified in the ACL */
639 $tmp= split(",", $acl);
640 foreach ($tmp as $mod){
641 if (preg_match("/$module#/", $mod)){
642 $final= strstr($mod, "#")."#";
643 continue;
644 }
645 if (preg_match("/[^#]$module$/", $mod)){
646 return ("#all#");
647 }
648 if (preg_match("/^all$/", $mod)){
649 return ("#all#");
650 }
651 }
652 }
654 /* Return assembled ACL, or none */
655 if ($final != ""){
656 return (preg_replace('/##/', '#', $final));
657 }
659 /* Nothing matches - disable access for this object */
660 return ("#none#");
661 }
664 function get_userinfo()
665 {
666 global $ui;
668 return $ui;
669 }
672 function get_smarty()
673 {
674 global $smarty;
676 return $smarty;
677 }
680 function convert_department_dn($dn)
681 {
682 $dep= "";
684 /* Build a sub-directory style list of the tree level
685 specified in $dn */
686 foreach (split (",", $dn) as $val){
688 /* We're only interested in organizational units... */
689 if (preg_match ("/ou=/", $val)){
690 $dep= preg_replace("/ou=([^,]+)/", "\\1", $val)."/$dep";
691 }
693 /* ... and location objects */
694 if (preg_match ("/l=/", $val)){
695 $dep= preg_replace("/l=([^,]+)/", "\\1", $val)."/$dep";
696 }
697 }
699 /* Return and remove accidently trailing slashes */
700 return rtrim($dep, "/");
701 }
704 function get_ou($name)
705 {
706 global $config;
708 $ou= $config->current[$name];
709 if ($ou != ""){
710 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
711 return "ou=$ou,";
712 } else {
713 return "$ou,";
714 }
715 } else {
716 return "";
717 }
718 }
721 function get_people_ou()
722 {
723 return (get_ou("PEOPLE"));
724 }
727 function get_groups_ou()
728 {
729 return (get_ou("GROUPS"));
730 }
733 function get_winstations_ou()
734 {
735 return (get_ou("WINSTATIONS"));
736 }
739 function get_base_from_people($dn)
740 {
741 global $config;
743 $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/";
744 $base= preg_replace($pattern, '', $dn);
746 /* Set to base, if we're not on a correct subtree */
747 if (!isset($config->idepartments[$base])){
748 $base= $config->current['BASE'];
749 }
751 return ($base);
752 }
755 function get_departments($ignore_dn= "")
756 {
757 global $config;
759 /* Initialize result hash */
760 $result= array();
761 $result['/']= $config->current['BASE'];
763 /* Get list of department objects */
764 $ldap= $config->get_ldap_link();
765 $ldap->cd ($config->current['BASE']);
766 $ldap->search ("(objectClass=gosaDepartment)", array("ou"));
767 while ($attrs= $ldap->fetch()){
768 $dn= $ldap->getDN();
769 if ($dn == $ignore_dn){
770 continue;
771 }
772 $result[convert_department_dn($dn)]= $dn;
773 }
775 return ($result);
776 }
779 function chkacl($acl, $name)
780 {
781 /* Look for attribute in ACL */
782 if (preg_match("/#$name#/", $acl) || $acl == "#all#"){
783 return ("");
784 }
786 /* Optically disable html object for no match */
787 return (" disabled ");
788 }
791 function is_phone_nr($nr)
792 {
793 if ($nr == ""){
794 return (TRUE);
795 }
797 return preg_match ("/^[0-9 ()+*-]+$/", $nr);
798 }
801 function is_url($url)
802 {
803 if ($url == ""){
804 return (TRUE);
805 }
807 return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
808 }
811 function is_dn($dn)
812 {
813 if ($dn == ""){
814 return (TRUE);
815 }
817 return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
818 }
821 function is_uid($uid)
822 {
823 global $config;
825 if ($uid == ""){
826 return (TRUE);
827 }
829 /* STRICT adds spaces and case insenstivity to the uid check.
830 This is dangerous and should not be used. */
831 if (isset($config->current['STRICT']) && preg_match('/^no$/i', $config->current['STRICT'])){
832 return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
833 } else {
834 return preg_match ("/^[a-z0-9_-]+$/", $uid);
835 }
836 }
839 function is_id($id)
840 {
841 if ($id == ""){
842 return (FALSE);
843 }
845 return preg_match ("/^[0-9]+$/", $id);
846 }
849 function is_path($path)
850 {
851 if ($path == ""){
852 return (TRUE);
853 }
854 if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
855 return (FALSE);
856 }
858 return preg_match ("/\/.+$/", $path);
859 }
862 function is_email($address, $template= FALSE)
863 {
864 if ($address == ""){
865 return (TRUE);
866 }
867 if ($template){
868 return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
869 $address);
870 } else {
871 return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
872 $address);
873 }
874 }
877 function print_red()
878 {
879 /* Check number of arguments */
880 if (func_num_args() < 1){
881 return;
882 }
884 /* Get arguments, save string */
885 $array = func_get_args();
886 $string= $array[0];
888 /* Step through arguments */
889 for ($i= 1; $i<count($array); $i++){
890 $string= preg_replace ("/%s/", $array[$i], $string, 1);
891 }
893 /* If DEBUGLEVEL is set, we're in web mode, use textual output in
894 the other case... */
895 if (isset($_SESSION['DEBUGLEVEL'])){
896 $_SESSION['errors'].= "<div align=\"left\" style=\"border-width:5px;".
897 "border-style:solid;border-color:red; background-color:black;".
898 "margin-bottom:10px; padding:8px;\"><table summary=''><tr><td><img alt=\"\" src=\"".
899 get_template_path('images/warning.png')."\"></td>".
900 "<td width=\"100%\" align=\"center\"><font color=\"#FFFFFF\">".
901 "<b style='font-size:16px;'>$string</b></font></td><td>".
902 "<img alt=\"\"src=\"".get_template_path('images/warning.png').
903 "\"></td></tr></table></div>\n";
904 } else {
905 echo "Error: $string\n";
906 }
907 }
910 function gen_locked_message($user, $dn)
911 {
912 global $plug, $config;
914 $_SESSION['dn']= $dn;
915 $ldap= $config->get_ldap_link();
916 $ldap->cat ($user);
917 $attrs= $ldap->fetch();
918 $uid= $attrs["uid"][0];
920 /* Prepare and show template */
921 $smarty= get_smarty();
922 $smarty->assign ("dn", $dn);
923 $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry '%s' which appears to be used by '%s'. Please contact the person in order to clarify proceedings."), $dn, "<a href=\"main.php?plug=0&viewid=$uid\">$uid</a>"));
925 return ($smarty->fetch (get_template_path('islocked.tpl')));
926 }
929 function to_string ($value)
930 {
931 /* If this is an array, generate a text blob */
932 if (is_array($value)){
933 $ret= "";
934 foreach ($value as $line){
935 $ret.= $line."<br>\n";
936 }
937 return ($ret);
938 } else {
939 return ($value);
940 }
941 }
944 function get_printer_list($cups_server)
945 {
946 global $config;
948 $res= array();
950 /* Use CUPS, if we've access to it */
951 if (function_exists('cups_get_dest_list')){
952 $dest_list= cups_get_dest_list ($cups_server);
954 foreach ($dest_list as $prt){
955 $attr= cups_get_printer_attributes ($cups_server, $prt->name);
957 foreach ($attr as $prt_info){
958 if ($prt_info->name == "printer-info"){
959 $info= $prt_info->value;
960 break;
961 }
962 }
963 $res[$prt->name]= "$info [$prt->name]";
964 }
966 /* CUPS is not available, try lpstat as a replacement */
967 } else {
968 $ar = false;
969 exec("lpstat -p", $ar);
970 foreach($ar as $val){
971 list($dummy, $printer, $rest)= split(' ', $val, 3);
972 if (preg_match('/^[^@]+$/', $printer)){
973 $res[$printer]= "$printer";
974 }
975 }
976 }
978 /* Merge in printers from LDAP */
979 $ldap= $config->get_ldap_link();
980 $ldap->cd ($config->current['BASE']);
981 $ldap->search('(objectClass=gotoPrinter)', array('cn'));
982 while ($attrs= $ldap->fetch()){
983 $res[$attrs["cn"][0]]= $attrs["cn"][0];
984 }
986 return $res;
987 }
990 function sess_del ($var)
991 {
992 /* New style */
993 unset ($_SESSION[$var]);
995 /* ... work around, since the first one
996 doesn't seem to work all the time */
997 session_unregister ($var);
998 }
1001 function show_errors($message)
1002 {
1003 $complete= "";
1005 /* Assemble the message array to a plain string */
1006 foreach ($message as $error){
1007 if ($complete == ""){
1008 $complete= $error;
1009 } else {
1010 $complete= "$error<br>$complete";
1011 }
1012 }
1014 /* Fill ERROR variable with nice error dialog */
1015 print_red($complete);
1016 }
1019 function show_ldap_error($message)
1020 {
1021 if (!preg_match("/Success/i", $message)){
1022 print_red (_("LDAP error:")." $message");
1023 return TRUE;
1024 } else {
1025 return FALSE;
1026 }
1027 }
1030 function rewrite($s)
1031 {
1032 global $REWRITE;
1034 foreach ($REWRITE as $key => $val){
1035 $s= preg_replace("/$key/", "$val", $s);
1036 }
1038 return ($s);
1039 }
1042 function dn2base($dn)
1043 {
1044 global $config;
1046 if (get_people_ou() != ""){
1047 $dn= preg_replace('/,'.get_people_ou().'/' , ',', $dn);
1048 }
1049 if (get_groups_ou() != ""){
1050 $dn= preg_replace('/,'.get_groups_ou().'/' , ',', $dn);
1051 }
1052 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1054 return ($base);
1055 }
1059 function check_command($cmdline)
1060 {
1061 $cmd= preg_replace("/ .*$/", "", $cmdline);
1063 /* Check if command exists in filesystem */
1064 if (!file_exists($cmd)){
1065 return (FALSE);
1066 }
1068 /* Check if command is executable */
1069 if (!is_executable($cmd)){
1070 return (FALSE);
1071 }
1073 return (TRUE);
1074 }
1077 function print_header($image, $headline, $info= "")
1078 {
1079 $display= "<div class=\"plugtop\">\n";
1080 $display.= " <img src=\"$image\" align=\"middle\" alt=\"*\"> $headline\n";
1081 $display.= "</div>\n";
1083 if ($info != ""){
1084 $display.= "<div class=\"pluginfo\">\n";
1085 $display.= "$info";
1086 $display.= "</div>\n";
1087 } else {
1088 $display.= "<div style=\"height:5px;\">\n";
1089 $display.= " ";
1090 $display.= "</div>\n";
1091 }
1093 return ($display);
1094 }
1097 function register_global($name, $object)
1098 {
1099 $_SESSION[$name]= $object;
1100 }
1103 function is_global($name)
1104 {
1105 return isset($_SESSION[$name]);
1106 }
1109 function get_global($name)
1110 {
1111 return $_SESSION[$name];
1112 }
1115 function range_selector($dcnt,$start,$range=25)
1116 {
1118 /* Entries shown left and right from the selected entry */
1119 $max_entries= 10;
1121 /* Initialize and take care that max_entries is even */
1122 $output="";
1123 if ($max_entries & 1){
1124 $max_entries++;
1125 }
1127 /* Prevent output to start or end out of range */
1128 if ($start < 0 ){
1129 $start= 0 ;
1130 }
1131 if ($start >= $dcnt){
1132 $start= $range * (int)(($dcnt / $range) + 0.5);
1133 }
1135 $numpages= (($dcnt / $range));
1136 if(((int)($numpages))!=($numpages))
1137 $numpages = (int)$numpages + 1;
1138 $ppage= (int)(($start / $range) + 0.5);
1141 /* Align selected page to +/- max_entries/2 */
1142 $begin= $ppage - $max_entries/2;
1143 $end= $ppage + $max_entries/2;
1145 /* Adjust begin/end, so that the selected value is somewhere in
1146 the middle and the size is max_entries if possible */
1147 if ($begin < 0){
1148 $end-= $begin + 1;
1149 $begin= 0;
1150 }
1151 if ($end > $numpages) {
1152 $end= $numpages;
1153 }
1154 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1155 $begin= $end - $max_entries;
1156 }
1158 /* Draw decrement */
1159 if ($start > 0 ) {
1160 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1161 (($start-$range))."\">".
1162 "<img alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1163 }
1165 /* Draw pages */
1166 for ($i= $begin; $i < $end; $i++) {
1167 if ($ppage == $i){
1168 $output.= "<a style=\"background-color:#D0D0D0;\" href=\"main.php?plug=".
1169 validate($_GET['plug'])."&start=".
1170 ($i*$range)."\"> ".($i+1)." </a>";
1171 } else {
1172 $output.= "<a href=\"main.php?plug=".validate($_GET['plug']).
1173 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1174 }
1175 }
1177 /* Draw increment */
1178 if($start < ($dcnt-$range)) {
1179 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1180 (($start+($range)))."\">".
1181 "<img alt=\"\" src=\"images/forward.png\" border=0 align=\"middle\"></a>";
1182 }
1184 return($output);
1185 }
1188 function apply_filter()
1189 {
1190 $apply= "";
1192 $apply= ''.
1193 '<table summary="" width="100%" style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1194 '<input type="submit" name="apply" value="'._("Apply").'"></td></tr></table>';
1196 return ($apply);
1197 }
1200 function back_to_main()
1201 {
1202 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1203 _("Back").'"></p><input type="hidden" name="ignore">';
1205 return ($string);
1206 }
1209 function normalize_netmask($netmask)
1210 {
1211 /* Check for notation of netmask */
1212 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1213 $num= (int)($netmask);
1214 $netmask= "";
1216 for ($byte= 0; $byte<4; $byte++){
1217 $result=0;
1219 for ($i= 7; $i>=0; $i--){
1220 if ($num-- > 0){
1221 $result+= pow(2,$i);
1222 }
1223 }
1225 $netmask.= $result.".";
1226 }
1228 return (preg_replace('/\.$/', '', $netmask));
1229 }
1231 return ($netmask);
1232 }
1235 function netmask_to_bits($netmask)
1236 {
1237 list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1238 $res= 0;
1240 for ($n= 0; $n<4; $n++){
1241 $start= 255;
1242 $name= "nm$n";
1244 for ($i= 0; $i<8; $i++){
1245 if ($start == (int)($$name)){
1246 $res+= 8 - $i;
1247 break;
1248 }
1249 $start-= pow(2,$i);
1250 }
1251 }
1253 return ($res);
1254 }
1257 function recurse($rule, $variables)
1258 {
1259 $result= array();
1261 if (!count($variables)){
1262 return array($rule);
1263 }
1265 reset($variables);
1266 $key= key($variables);
1267 $val= current($variables);
1268 unset ($variables[$key]);
1270 foreach($val as $possibility){
1271 $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1272 $result= array_merge($result, recurse($nrule, $variables));
1273 }
1275 return ($result);
1276 }
1279 function expand_id($rule, $attributes)
1280 {
1281 /* Check for id rule */
1282 if(preg_match('/^id(:|#)\d+$/',$rule)){
1283 return (array("\{$rule}"));
1284 }
1286 /* Check for clean attribute */
1287 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1288 $rule= preg_replace('/^%/', '', $rule);
1289 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1290 return (array($val));
1291 }
1293 /* Check for attribute with parameters */
1294 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1295 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1296 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1297 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1298 $start= preg_replace ('/-.*$/', '', $param);
1299 $stop = preg_replace ('/^[^-]+-/', '', $param);
1301 /* Assemble results */
1302 $result= array();
1303 for ($i= $start; $i<= $stop; $i++){
1304 $result[]= substr($val, 0, $i);
1305 }
1306 return ($result);
1307 }
1309 echo "Error in idgen string: don't know how to handle rule $rule.\n";
1310 return (array($rule));
1311 }
1314 function gen_uids($rule, $attributes)
1315 {
1316 global $config;
1318 /* Search for keys and fill the variables array with all
1319 possible values for that key. */
1320 $part= "";
1321 $trigger= false;
1322 $stripped= "";
1323 $variables= array();
1325 for ($pos= 0; $pos < strlen($rule); $pos++){
1327 if ($rule[$pos] == "{" ){
1328 $trigger= true;
1329 $part= "";
1330 continue;
1331 }
1333 if ($rule[$pos] == "}" ){
1334 $variables[$pos]= expand_id($part, $attributes);
1335 $stripped.= "\{$pos}";
1336 $trigger= false;
1337 continue;
1338 }
1340 if ($trigger){
1341 $part.= $rule[$pos];
1342 } else {
1343 $stripped.= $rule[$pos];
1344 }
1345 }
1347 /* Recurse through all possible combinations */
1348 $proposed= recurse($stripped, $variables);
1350 /* Get list of used ID's */
1351 $used= array();
1352 $ldap= $config->get_ldap_link();
1353 $ldap->cd($config->current['BASE']);
1354 $ldap->search('(uid=*)');
1356 while($attrs= $ldap->fetch()){
1357 $used[]= $attrs['uid'][0];
1358 }
1360 /* Remove used uids and watch out for id tags */
1361 $ret= array();
1362 foreach($proposed as $uid){
1364 /* Check for id tag and modify uid if needed */
1365 if(preg_match('/\{id:\d+}/',$uid)){
1366 $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1368 for ($i= 0; $i < pow(10,$size); $i++){
1369 $number= sprintf("%0".$size."d", $i);
1370 $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1371 if (!in_array($res, $used)){
1372 $uid= $res;
1373 break;
1374 }
1375 }
1376 }
1378 if(preg_match('/\{id#\d+}/',$uid)){
1379 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1381 while (true){
1382 mt_srand((double) microtime()*1000000);
1383 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1384 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1385 if (!in_array($res, $used)){
1386 $uid= $res;
1387 break;
1388 }
1389 }
1390 }
1392 /* Don't assign used ones */
1393 if (!in_array($uid, $used)){
1394 $ret[]= $uid;
1395 }
1396 }
1398 return(array_unique($ret));
1399 }
1402 function array_search_r($needle, $key, $haystack){
1404 foreach($haystack as $index => $value){
1405 $match= 0;
1407 if (is_array($value)){
1408 $match= array_search_r($needle, $key, $value);
1409 }
1411 if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1412 $match=1;
1413 }
1415 if ($match){
1416 return 1;
1417 }
1418 }
1420 return 0;
1421 }
1424 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1425 Need to convert... */
1426 function to_byte($value) {
1427 $value= strtolower(trim($value));
1429 if(!is_numeric(substr($value, -1))) {
1431 switch(substr($value, -1)) {
1432 case 'g':
1433 $mult= 1073741824;
1434 break;
1435 case 'm':
1436 $mult= 1048576;
1437 break;
1438 case 'k':
1439 $mult= 1024;
1440 break;
1441 }
1443 return ($mult * (int)substr($value, 0, -1));
1444 } else {
1445 return $value;
1446 }
1447 }
1450 function in_array_ics($value, $items)
1451 {
1452 if (!is_array($items)){
1453 return (FALSE);
1454 }
1456 foreach ($items as $item){
1457 if (strtolower($item) == strtolower($value)) {
1458 return (TRUE);
1459 }
1460 }
1462 return (FALSE);
1463 }
1466 function generate_alphabet($count= 10)
1467 {
1468 $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1469 $alphabet= "";
1470 $c= 0;
1472 /* Fill cells with charaters */
1473 for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1474 if ($c == 0){
1475 $alphabet.= "<tr>";
1476 }
1478 $ch = mb_substr($characters, $i, 1, "UTF8");
1479 $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1480 validate($_GET['plug'])."&search=".$ch."\"> ".$ch." </a></td>";
1482 if ($c++ == $count){
1483 $alphabet.= "</tr>";
1484 $c= 0;
1485 }
1486 }
1488 /* Fill remaining cells */
1489 while ($c++ <= $count){
1490 $alphabet.= "<td> </td>";
1491 }
1493 return ($alphabet);
1494 }
1497 function validate($string)
1498 {
1499 return (strip_tags(preg_replace('/\0/', '', $string)));
1500 }
1502 function get_gosa_version()
1503 {
1504 global $svn_revision, $svn_path;
1506 /* Extract informations */
1507 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1509 /* Release or development? */
1510 if (preg_match('%/gosa/trunk/%', $svn_path)){
1511 return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1512 } else {
1513 $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1514 return (sprintf(_("GOsa $release"), $revision));
1515 }
1516 }
1519 function rmdirRecursive($path, $followLinks=false) {
1520 $dir= opendir($path);
1521 while($entry= readdir($dir)) {
1522 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1523 unlink($path."/".$entry);
1524 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1525 rmdirRecursive($path."/".$entry);
1526 }
1527 }
1528 closedir($dir);
1529 return rmdir($path);
1530 }
1532 function scan_directory($path,$sort_desc=false)
1533 {
1534 $ret = false;
1536 /* is this a dir ? */
1537 if(is_dir($path)) {
1539 /* is this path a readable one */
1540 if(is_readable($path)){
1542 /* Get contents and write it into an array */
1543 $ret = array();
1545 $dir = opendir($path);
1547 /* Is this a correct result ?*/
1548 if($dir){
1549 while($fp = readdir($dir))
1550 $ret[]= $fp;
1551 }
1552 }
1553 }
1554 /* Sort array ascending , like scandir */
1555 sort($ret);
1557 /* Sort descending if parameter is sort_desc is set */
1558 if($sort_desc) {
1559 $ret = array_reverse($ret);
1560 }
1562 return($ret);
1563 }
1565 function clean_smarty_compile_dir($directory)
1566 {
1567 global $svn_revision;
1569 if(is_dir($directory) && is_readable($directory)) {
1570 // Set revision filename to REVISION
1571 $revision_file= $directory."/REVISION";
1573 /* Is there a stamp containing the current revision? */
1574 if(!file_exists($revision_file)) {
1575 // create revision file
1576 create_revision($revision_file, $svn_revision);
1577 } else {
1578 # check for "$config->...['CONFIG']/revision" and the
1579 # contents should match the revision number
1580 if(!compare_revision($revision_file, $svn_revision)){
1581 // If revision differs, clean compile directory
1582 foreach(scan_directory($directory) as $file) {
1583 if( is_file($directory."/".$file) &&
1584 is_writable($directory."/".$file)) {
1585 // delete file
1586 if(!unlink($directory."/".$file)) {
1587 print_red("File ".$directory."/".$file." could not be deleted.");
1588 // This should never be reached
1589 }
1590 } elseif(is_dir($directory."/".$file) &&
1591 is_writable($directory."/".$file)) {
1592 // Just recursively delete it
1593 rmdirRecursive($directory."/".$file);
1594 }
1595 }
1596 // We should now create a fresh revision file
1597 clean_smarty_compile_dir($directory);
1598 } else {
1599 // Revision matches, nothing to do
1600 }
1601 }
1602 } else {
1603 // Smarty compile dir is not accessible
1604 // (Smarty will warn about this)
1605 }
1606 }
1608 function create_revision($revision_file, $revision)
1609 {
1610 $result= false;
1612 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1613 if($fh= fopen($revision_file, "w")) {
1614 if(fwrite($fh, $revision)) {
1615 $result= true;
1616 }
1617 }
1618 fclose($fh);
1619 } else {
1620 print_red("Can not write to revision file");
1621 }
1623 return $result;
1624 }
1626 function compare_revision($revision_file, $revision)
1627 {
1628 // false means revision differs
1629 $result= false;
1631 if(file_exists($revision_file) && is_readable($revision_file)) {
1632 // Open file
1633 if($fh= fopen($revision_file, "r")) {
1634 // Compare File contents with current revision
1635 if($revision == fread($fh, filesize($revision_file))) {
1636 $result= true;
1637 }
1638 } else {
1639 print_red("Can not open revision file");
1640 }
1641 // Close file
1642 fclose($fh);
1643 }
1645 return $result;
1646 }
1648 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1649 {
1650 $str = ""; // Our return value will be saved in this var
1652 $color = dechex($percentage+150);
1653 $color2 = dechex(150 - $percentage);
1654 $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1656 $progress = (int)(($percentage /100)*$width);
1658 /* Abort printing out percentage, if divs are to small */
1661 /* If theres a better solution for this, use it... */
1662 $str = "
1663 <div style=\" width:".($width)."px;
1664 height:".($height)."px;
1665 background-color:#000000;
1666 padding:1px;\">
1668 <div style=\" width:".($width)."px;
1669 background-color:#$bgcolor;
1670 height:".($height)."px;\">
1672 <div style=\" width:".$progress."px;
1673 height:".$height."px;
1674 background-color:#".$color2.$color2.$color."; \">";
1677 if(($height >10)&&($showvalue)){
1678 $str.= "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1679 <b>".$percentage."%</b>
1680 </font>";
1681 }
1683 $str.= "</div></div></div>";
1685 return($str);
1686 }
1689 function search_config($arr, $name, $return)
1690 {
1691 if (is_array($arr)){
1692 foreach ($arr as $a){
1693 if (isset($a['CLASS']) &&
1694 strtolower($a['CLASS']) == strtolower($name)){
1696 if (isset($a[$return])){
1697 return ($a[$return]);
1698 } else {
1699 return ("");
1700 }
1701 } else {
1702 $res= search_config ($a, $name, $return);
1703 if ($res != ""){
1704 return $res;
1705 }
1706 }
1707 }
1708 }
1709 return ("");
1710 }
1713 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1714 ?>