ILIAS  release_5-1 Revision 5.0.0-5477-g43f3e3fab5f
class.ilUtil.php
Go to the documentation of this file.
1<?php
2/* Copyright (c) 1998-2010 ILIAS open source, Extended GPL, see docs/LICENSE */
3
17class ilUtil
18{
29 public static function getImageTagByType($a_type, $a_path, $a_big = false)
30 {
31 global $lng;
32
33 $size = ($a_big)
34 ? "big"
35 : "small";
36
37 include_once("./Services/Object/classes/class.ilObject.php");
38 $filename = ilObject::_getIcon("", $size, $a_type);
39
40 return "<img src=\"".$filename."\" alt=\"".$lng->txt("obj_".$a_type)."\" title=\"".$lng->txt("obj_".$a_type)."\" border=\"0\" vspace=\"0\"/>";
41 }
42
55 public static function getTypeIconPath($a_type,$a_obj_id,$a_size = 'small')
56 {
57 include_once("./Services/Object/classes/class.ilObject.php");
58 return ilObject::_getIcon($a_obj_id, $a_size, $a_type);
59 }
60
71 public static function getImagePath($img, $module_path = "", $mode = "output", $offline = false)
72 {
73 global $ilias, $styleDefinition, $ilCtrl, $ilUser;
74
75 if (is_int(strpos($_SERVER["PHP_SELF"], "setup.php")))
76 {
77 $module_path = "..";
78 }
79 if ($module_path != "")
80 {
81 $module_path = "/".$module_path;
82 }
83
84 // default image
85 $default_img = ".".$module_path."/templates/default/images/".$img;
86
87 // use ilStyleDefinition instead of account to get the current skin and style
88 require_once("./Services/Style/classes/class.ilStyleDefinition.php");
89 $current_skin = ilStyleDefinition::getCurrentSkin();
90 $current_style = ilStyleDefinition::getCurrentStyle();
91
92 if (is_object($styleDefinition))
93 {
94 $image_dir = $styleDefinition->getImageDirectory(
96 $current_style);
97 }
98 if ($current_skin == "default")
99 {
100 $user_img = ".".$module_path."/templates/default/".$image_dir."/".$img;
101 $skin_img = ".".$module_path."/templates/default/images/".$img;
102 }
103 else if (is_object($styleDefinition) && $current_skin != "default")
104 {
105 $user_img = "./Customizing/global/skin/".
106 $current_skin.$module_path."/".$image_dir."/".$img;
107 $skin_img = "./Customizing/global/skin/".
108 $current_skin.$module_path."/images/".$img;
109 }
110
111 // temp svg patch
112 /*
113 $pi = pathinfo($img);
114 if ($pi["dirname"] != "") {
115 $pi["dirname"] = $pi["dirname"]."/";
116 }
117 $svg_img = ".".$module_path."/templates/default/images/".$pi["dirname"].$pi["filename"].".svg";
118 if (file_exists($svg_img))
119 {
120 return $svg_img;
121 }*/
122
123
124 if ($offline)
125 {
126 return "./images/".$img;
127 }
128 else if (@file_exists($user_img) && $image_dir != "")
129 {
130 return $user_img; // found image for skin and style
131 }
132 else if (file_exists($skin_img))
133 {
134 return $skin_img; // found image in skin/images
135 }
136
137 return $default_img; // take image in default
138 }
139
150 public static function getHtmlPath($relative_path)
151 {
152 if (substr($relative_path, 0, 2) == './')
153 {
154 $relative_path = (substr($relative_path, 1));
155 }
156 if (substr($relative_path, 0, 1) != '/')
157 {
158 $relative_path = '/' . $relative_path;
159 }
160 $htmlpath = ILIAS_HTTP_PATH . $relative_path;
161 return $htmlpath;
162 }
163
176 public static function getStyleSheetLocation($mode = "output", $a_css_name = "", $a_css_location = "")
177 {
178 global $ilias;
179
180 // add version as parameter to force reload for new releases
181 // use ilStyleDefinition instead of account to get the current style
182 require_once("./Services/Style/classes/class.ilStyleDefinition.php");
183 $stylesheet_name = (strlen($a_css_name))
184 ? $a_css_name
186 if (strlen($a_css_location) && (strcmp(substr($a_css_location, -1), "/") != 0))
187 {
188 $a_css_location = $a_css_location . "/";
189 }
190
191 $filename = "";
192 // use ilStyleDefinition instead of account to get the current skin
193 require_once("./Services/Style/classes/class.ilStyleDefinition.php");
194 if (ilStyleDefinition::getCurrentSkin() != "default")
195 {
196 $filename = "./Customizing/global/skin/".ilStyleDefinition::getCurrentSkin()."/".$a_css_location.$stylesheet_name;
197 }
198 if (strlen($filename) == 0 || !file_exists($filename))
199 {
200 $filename = "./" . $a_css_location . "templates/default/".$stylesheet_name;
201 }
202 $vers = "";
203 if ($mode != "filesystem")
204 {
205 $vers = str_replace(" ", "-", $ilias->getSetting("ilias_version"));
206 $vers = "?vers=".str_replace(".", "-", $vers);
207 $skin_version = ilStyleDefinition::getCurrentSkinVersion();
208 $vers .= ($skin_version != '' ? str_replace(".", "-", '-' . $skin_version) : '');
209 }
210 return $filename . $vers;
211 }
212
223 public static function getJSLocation($a_js_name, $a_js_location = "", $add_version = FALSE)
224 {
225 global $ilias;
226
227 // add version as parameter to force reload for new releases
228 $js_name = $a_js_name;
229 if (strlen($a_js_location) && (strcmp(substr($a_js_location, -1), "/") != 0)) $a_js_location = $a_js_location . "/";
230
231 $filename = "";
232 // use ilStyleDefinition instead of account to get the current skin
233 require_once("./Services/Style/classes/class.ilStyleDefinition.php");
234 if (ilStyleDefinition::getCurrentSkin() != "default")
235 {
236 $filename = "./Customizing/global/skin/".ilStyleDefinition::getCurrentSkin()."/".$a_js_location.$js_name;
237 }
238 if (strlen($filename) == 0 || !file_exists($filename))
239 {
240 $filename = "./" . $a_js_location . "templates/default/".$js_name;
241 }
242 $vers = "";
243 if ($add_version)
244 {
245 $vers = str_replace(" ", "-", $ilias->getSetting("ilias_version"));
246 $vers = "?vers=".str_replace(".", "-", $vers);
247 }
248 return $filename . $vers;
249 }
250
258 public static function getP3PLocation()
259 {
260 global $ilias;
261
262 if (defined("ILIAS_MODULE"))
263 {
264 $base = '';
265 for($i = 0;$i < count(explode('/',ILIAS_MODULE));$i++)
266 {
267 $base .= "../Services/Privacy/";
268 }
269 }
270 else
271 {
272 $base = "./Services/Privacy/";
273 }
274
275 if (is_file($base."w3c/p3p.xml"))
276 {
277 return ILIAS_HTTP_PATH."w3c/p3p.xml";
278 }
279 else
280 {
281 return ILIAS_HTTP_PATH."/w3c/p3p_template.xml";
282 }
283 }
284
292 public static function getNewContentStyleSheetLocation($mode = "output")
293 {
294 global $ilias;
295
296 // add version as parameter to force reload for new releases
297 if ($mode != "filesystem")
298 {
299 $vers = str_replace(" ", "-", $ilias->getSetting("ilias_version"));
300 $vers = "?vers=".str_replace(".", "-", $vers);
301 }
302
303 // use ilStyleDefinition instead of account to get the current skin and style
304 require_once("./Services/Style/classes/class.ilStyleDefinition.php");
305 if (ilStyleDefinition::getCurrentSkin() == "default")
306 {
307 $in_style = "./templates/".ilStyleDefinition::getCurrentSkin()."/"
308 .ilStyleDefinition::getCurrentStyle()."_cont.css";
309 }
310 else
311 {
312 $in_style = "./Customizing/global/skin/".ilStyleDefinition::getCurrentSkin()."/"
313 .ilStyleDefinition::getCurrentStyle()."_cont.css";
314 }
315
316 if (is_file("./".$in_style))
317 {
318 return $in_style.$vers;
319 }
320 else
321 {
322 return "templates/default/delos_cont.css".$vers;
323 }
324 }
325
344 public static function formSelect($selected,$varname,$options,$multiple = false,$direct_text = false, $size = "0",
345 $style_class = "", $attribs = "",$disabled = false)
346 {
347 global $lng;
348
349 if ($multiple == true)
350 {
351 $multiple = " multiple=\"multiple\"";
352 }
353 else
354 {
355 $multiple = "";
356 $size = 0;
357 }
358
359 $class = " class=\" form-control ".$style_class."\"";
360
361 // use form-inline!
362 // this is workaround the whole function should be set deprecated
363 // $attributes = " style='display:inline-block;' ";
364
365 if (is_array($attribs))
366 {
367 foreach ($attribs as $key => $val)
368 {
369 $attributes .= " ".$key."=\"".$val."\"";
370 }
371 }
372 if($disabled)
373 {
374 $disabled = ' disabled=\"disabled\"';
375 }
376
377 $str = "<select name=\"".$varname ."\"".$multiple." $class size=\"".$size."\" $attributes $disabled>\n";
378
379 foreach ((array) $options as $key => $val)
380 {
381 $style = "";
382 if (is_array($val))
383 {
384 $style = $val["style"];
385 $val = $val["text"]; // mus be last line, since we overwrite
386 }
387
388 $sty = ($style != "")
389 ? ' style="'.$style.'" '
390 : "";
391
392 if ($direct_text)
393 {
394 $str .= " <option $sty value=\"".$key."\"";
395 }
396 else
397 {
398 $str .= " <option $sty value=\"".$val."\"";
399 }
400 if (is_array($selected) )
401 {
402 if (in_array($key,$selected))
403 {
404 $str .= " selected=\"selected\"";
405 }
406 }
407 else if ($selected == $key)
408 {
409 $str .= " selected=\"selected\"";
410 }
411
412 if ($direct_text)
413 {
414 $str .= ">".$val."</option>\n";
415 }
416 else
417 {
418 $str .= ">".$lng->txt($val)."</option>\n";
419 }
420 }
421
422 $str .= "</select>\n";
423
424 return $str;
425 }
426
436 public static function getSelectName ($selected,$values)
437 {
438 return($values[$selected]);
439 }
440
452 public static function formCheckbox ($checked,$varname,$value,$disabled = false)
453 {
454 $str = "<input type=\"checkbox\" name=\"".$varname."\"";
455
456 if ($checked == 1)
457 {
458 $str .= " checked=\"checked\"";
459 }
460
461 if ($disabled)
462 {
463 $str .= " disabled=\"disabled\"";
464 }
465
466 $array_var = false;
467
468 if (substr($varname,-2) == "[]")
469 {
470 $array_var = true;
471 }
472
473 // if varname ends with [], use varname[-2] + _ + value as id tag (e.g. "user_id[]" => "user_id_15")
474 if ($array_var)
475 {
476 $varname_id = substr($varname,0,-2)."_".$value;
477 }
478 else
479 {
480 $varname_id = $varname;
481 }
482
483 // dirty removal of other "[]" in string
484 $varname_id = ereg_replace("\[","_",$varname_id);
485 $varname_id = ereg_replace("\]","",$varname_id);
486
487 $str .= " value=\"".$value."\" id=\"".$varname_id."\" />\n";
488
489 return $str;
490 }
491
503 public static function formDisabledRadioButton($checked,$varname,$value,$disabled)
504 {
505 if ($disabled) {
506 $str = "<input disabled type=\"radio\" name=\"".$varname."\"";
507 }
508 else {
509 $str = "<input type=\"radio\" name=\"".$varname."\"";
510 }
511 if ($checked == 1)
512 {
513 $str .= " checked=\"checked\"";
514 }
515
516 $str .= " value=\"".$value."\"";
517 $str .= " id=\"".$value."\" />\n";
518
519 return $str;
520
521 }
522
523
534 public static function formRadioButton($checked,$varname,$value,$onclick=null, $disabled = false)
535 {
536 $str = '<input ';
537
538 if($onclick)
539 {
540 $str .= ('onclick="'.$onclick.'"');
541 }
542
543 $str .= (" type=\"radio\" name=\"".$varname."\"");
544 if ($checked == 1)
545 {
546 $str .= " checked=\"checked\"";
547 }
548
549 if ($disabled)
550 {
551 $str .= " disabled=\"disabled\"";
552 }
553
554 $str .= " value=\"".$value."\"";
555
556 $str .= " id=\"".$value."\" />\n";
557
558 return $str;
559 }
560
561
571 public static function formInput($varname,$value,$disabled = false)
572 {
573
574 $str = "<input type=\"input\" name=\"".$varname."\"";
575 if ($disabled)
576 {
577 $str .= " disabled";
578 }
579
580 $str .= " value=\"".$value."\"";
581
582 $str .= " id=\"".$value."\" />\n";
583
584 return $str;
585 }
586
587
594 public static function checkInput ($vars)
595 {
596 // TO DO:
597 // Diese Funktion soll Formfeldeingaben berprfen (empty und required)
598 }
599
606 public static function setPathStr ($a_path)
607 {
608 if ("" != $a_path && "/" != substr($a_path, -1))
609 {
610 $a_path .= "/";
611 //$a_path = substr($a_path,1);
612 }
613
614 //return getcwd().$a_path;
615 return $a_path;
616 }
617
630 public static function switchColor ($a_num,$a_css1,$a_css2)
631 {
632 if (!($a_num % 2))
633 {
634 return $a_css1;
635 }
636 else
637 {
638 return $a_css2;
639 }
640 }
641
650 public static function checkFormEmpty ($emptyFields)
651 {
652
653 $feedback = "";
654
655 foreach ($emptyFields as $key => $val)
656 {
657 if ($val == "") {
658 if ($feedback != "") $feedback .= ", ";
659 $feedback .= $key;
660 }
661 }
662
663 return $feedback;
664 }
665
690 public static function Linkbar ($AScript,$AHits,$ALimit,$AOffset,$AParams = array(),$ALayout = array(), $prefix = '')
691 {
692 $LinkBar = "";
693
694 $layout_link = "";
695 $layout_prev = "&lt;&lt;";
696 $layout_next = "&gt;&gt;";
697
698 // layout options
699 if (count($ALayout > 0))
700 {
701 if ($ALayout["link"])
702 {
703 $layout_link = " class=\"".$ALayout["link"]."\"";
704 }
705
706 if ($ALayout["prev"])
707 {
708 $layout_prev = $ALayout["prev"];
709 }
710
711 if ($ALayout["next"])
712 {
713 $layout_next = $ALayout["next"];
714 }
715 }
716
717 // show links, if hits greater limit
718 // or offset > 0 (can be > 0 due to former setting)
719 if ($AHits > $ALimit || $AOffset > 0)
720 {
721 if (!empty($AParams))
722 {
723 foreach ($AParams as $key => $value)
724 {
725 $params.= $key."=".$value."&";
726 }
727 }
728 // if ($params) $params = substr($params,0,-1);
729 if(strpos($AScript,'&'))
730 {
731 $link = $AScript."&".$params.$prefix."offset=";
732 }
733 else
734 {
735 $link = $AScript."?".$params.$prefix."offset=";
736 }
737
738 // ?bergehe "zurck"-link, wenn offset 0 ist.
739 if ($AOffset >= 1)
740 {
741 $prevoffset = $AOffset - $ALimit;
742 if ($prevoffset < 0) $prevoffset = 0;
743 $LinkBar .= "<a".$layout_link." href=\"".$link.$prevoffset."\">".$layout_prev."&nbsp;</a>";
744 }
745
746 // Ben?tigte Seitenzahl kalkulieren
747 $pages=intval($AHits/$ALimit);
748
749 // Wenn ein Rest bleibt, addiere eine Seite
750 if (($AHits % $ALimit))
751 $pages++;
752
753 // Bei Offset = 0 keine Seitenzahlen anzeigen : DEAKTIVIERT
754 // if ($AOffset != 0) {
755
756 // ansonsten zeige Links zu den anderen Seiten an
757 for ($i = 1 ;$i <= $pages ; $i++)
758 {
759 $newoffset=$ALimit*($i-1);
760
761 if ($newoffset == $AOffset)
762 {
763 $LinkBar .= "[".$i."] ";
764 }
765 else
766 {
767 $LinkBar .= '<a '.$layout_link.' href="'.
768 $link.$newoffset.'">['.$i.']</a> ';
769 }
770 }
771 // }
772
773 // Checken, ob letze Seite erreicht ist
774 // Wenn nicht, gebe einen "Weiter"-Link aus
775 if (! ( ($AOffset/$ALimit)==($pages-1) ) && ($pages!=1) )
776 {
777 $newoffset=$AOffset+$ALimit;
778 $LinkBar .= "<a".$layout_link." href=\"".$link.$newoffset."\">&nbsp;".$layout_next."</a>";
779 }
780
781 return $LinkBar;
782 }
783 else
784 {
785 return false;
786 }
787 }
788
800 public static function makeClickable($a_text, $detectGotoLinks = false)
801 {
802 // New code, uses MediaWiki Sanitizer
803 $ret = $a_text;
804
805 // www-URL ohne ://-Angabe
806 $ret = eregi_replace("(^|[[:space:]]+)(www\.)([[:alnum:]#?/&=\.-]+)",
807 "\\1http://\\2\\3", $ret);
808
809 // ftp-URL ohne ://-Angabe
810 $ret = eregi_replace("(^|[[:space:]]+)(ftp\.)([[:alnum:]#?/&=\.-]+)",
811 "\\1ftp://\\2\\3", $ret);
812
813 // E-Mail (this does not work as expected, users must add mailto: manually)
814 //$ret = eregi_replace("(([a-z0-9_]|\\-|\\.)+@([^[:space:]]*)([[:alnum:]-]))",
815 // "mailto:\\1", $ret);
816
817 // mask existing image tags
818 $ret = str_replace('src="http://', '"***masked_im_start***', $ret);
819
820 include_once("./Services/Utilities/classes/class.ilMWParserAdapter.php");
821 $parser = new ilMWParserAdapter();
822 $ret = $parser->replaceFreeExternalLinks($ret);
823
824 // unmask existing image tags
825 $ret = str_replace('"***masked_im_start***', 'src="http://', $ret);
826
827 // Should be Safe
828
829 if ($detectGotoLinks)
830 // replace target blank with self and text with object title.
831 {
832 $regExp = "<a[^>]*href=\"(".str_replace("/","\/",ILIAS_HTTP_PATH)."\/goto.php\?target=\w+_(\d+)[^\"]*)\"[^>]*>[^<]*<\/a>";
833// echo htmlentities($regExp);
834 $ret = preg_replace_callback(
835 "/".$regExp."/i",
836 array("ilUtil", "replaceLinkProperties"),
837 $ret);
838
839 // Static links
840 $regExp = "<a[^>]*href=\"(".str_replace("/","\/",ILIAS_HTTP_PATH)."\/goto_.*[a-z0-9]+_([0-9]+)\.html)\"[^>]*>[^<]*<\/a>";
841// echo htmlentities($regExp);
842 $ret = preg_replace_callback(
843 "/".$regExp."/i",
844 array("ilUtil", "replaceLinkProperties"),
845 $ret);
846 }
847
848 return($ret);
849 }
850
864 public static function replaceLinkProperties ($matches)
865 {
866 $link = $matches[0];
867 $ref_id = $matches[2];
868
869 if ($ref_id > 0)
870 {
872 if ($obj_id > 0)
873 {
874 $title = ilObject::_lookupTitle($obj_id);
875 $link = "<a href=".$matches[1]." target=\"_self\">".$title."</a>";
876 }
877 }
878 return $link;
879 }
880
899 public static function makeDateSelect($prefix, $year = "", $month = "", $day = "", $startyear = "",$a_long_month = true,$a_further_options = array(), $emptyoption = false)
900 {
901 global $lng;
902
903 $disabled = '';
904 if(isset($a_further_options['disabled']) and $a_further_options['disabled'])
905 {
906 $disabled = 'disabled="disabled" ';
907 }
908
909 $now = getdate();
910 if (!$emptyoption)
911 {
912 if (!strlen($year)) $year = $now["year"];
913 if (!strlen($month)) $month = $now["mon"];
914 if (!strlen($day)) $day = $now["mday"];
915 }
916
917 $year = (int) $year;
918 $month = (int) $month;
919 $day = (int) $day;
920
921 // build day select
922
923 $sel_day .= '<select class="form-control" ';
924 if(isset($a_further_options['select_attributes']))
925 {
926 foreach($a_further_options['select_attributes'] as $name => $value)
927 {
928 $sel_day .= ($name.'="'.$value.'" ');
929 }
930 }
931
932 $sel_day .= $disabled."name=\"".$prefix."[d]\" id=\"".$prefix."_d\">\n";
933
934 if ($emptyoption) $sel_day .= "<option value=\"0\">--</option>\n";
935 for ($i = 1; $i <= 31; $i++)
936 {
937 $sel_day .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
938 }
939 $sel_day .= "</select>\n";
940 $sel_day = preg_replace("/(value\=\"$day\")/", "$1 selected=\"selected\"", $sel_day);
941
942 // build month select
943 $sel_month = '<select class="form-control" ';
944 if(isset($a_further_options['select_attributes']))
945 {
946 foreach($a_further_options['select_attributes'] as $name => $value)
947 {
948 $sel_month .= ($name.'="'.$value.'" ');
949 }
950 }
951 $sel_month .= $disabled."name=\"".$prefix."[m]\" id=\"".$prefix."_m\">\n";
952
953 if ($emptyoption) $sel_month .= "<option value=\"0\">--</option>\n";
954 for ($i = 1; $i <= 12; $i++)
955 {
956 if($a_long_month)
957 {
958 $sel_month .= "<option value=\"$i\">" . $lng->txt("month_" . sprintf("%02d", $i) . "_long") . "</option>\n";
959 }
960 else
961 {
962 $sel_month .= "<option value=\"$i\">" . $i . "</option>\n";
963 }
964 }
965 $sel_month .= "</select>\n";
966 $sel_month = preg_replace("/(value\=\"$month\")/", "$1 selected=\"selected\"", $sel_month);
967
968 // build year select
969 $sel_year = '<select class="form-control" ';
970 if(isset($a_further_options['select_attributes']))
971 {
972 foreach($a_further_options['select_attributes'] as $name => $value)
973 {
974 $sel_year .= ($name.'="'.$value.'" ');
975 }
976 }
977 $sel_year .= $disabled."name=\"".$prefix."[y]\" id=\"".$prefix."_y\">\n";
978 if ((strlen($startyear) == 0) || ($startyear > $year))
979 {
980 if (!$emptyoption || $year != 0) $startyear = $year - 5;
981 }
982
983 if(($year + 5) < (date('Y',time()) + 5))
984 {
985 $end_year = date('Y',time()) + 5;
986 }
987 else
988 {
989 $end_year = $year + 5;
990 }
991
992 if ($emptyoption) $sel_year .= "<option value=\"0\">----</option>\n";
993 for ($i = $startyear; $i <= $end_year; $i++)
994 {
995 $sel_year .= "<option value=\"$i\">" . sprintf("%04d", $i) . "</option>\n";
996 }
997 $sel_year .= "</select>\n";
998 $sel_year = preg_replace("/(value\=\"$year\")/", "$1 selected=\"selected\"", $sel_year);
999
1000 //$dateformat = $lng->text["lang_dateformat"];
1001 $dateformat = "d-m-Y";
1002 $dateformat = strtolower(preg_replace("/\W/", "", $dateformat));
1003 $dateformat = strtolower(preg_replace("/(\w)/", "%%$1", $dateformat));
1004 $dateformat = preg_replace("/%%d/", $sel_day, $dateformat);
1005 $dateformat = preg_replace("/%%m/", $sel_month, $dateformat);
1006 $dateformat = preg_replace("/%%y/", $sel_year, $dateformat);
1007 return $dateformat;
1008 }
1009
1028 public static function makeTimeSelect($prefix, $short = true, $hour = "", $minute = "", $second = "",$a_use_default = true,$a_further_options = array())
1029 {
1030 global $lng, $ilUser;
1031
1032 $minute_steps = 1;
1033 $disabled = '';
1034 if(count($a_further_options))
1035 {
1036 if(isset($a_further_options['minute_steps']))
1037 {
1038 $minute_steps = $a_further_options['minute_steps'];
1039 }
1040 if(isset($a_further_options['disabled']) and $a_further_options['disabled'])
1041 {
1042 $disabled = 'disabled="disabled" ';
1043 }
1044 }
1045
1046 if ($a_use_default and !strlen("$hour$minute$second")) {
1047 $now = localtime();
1048 $hour = $now[2];
1049 $minute = $now[1];
1050 $second = $now[0];
1051 } else {
1052 $hour = (int)$hour;
1053 $minute = (int)$minute;
1054 $second = (int)$second;
1055 }
1056 // build hour select
1057 $sel_hour = '<select ';
1058 if(isset($a_further_options['select_attributes']))
1059 {
1060 foreach($a_further_options['select_attributes'] as $name => $value)
1061 {
1062 $sel_hour .= $name.'='.$value.' ';
1063 }
1064 }
1065 $sel_hour .= " ".$disabled."name=\"".$prefix."[h]\" id=\"".$prefix."_h\" class=\"form-control\">\n";
1066
1067 $format = $ilUser->getTimeFormat();
1068 for ($i = 0; $i <= 23; $i++)
1069 {
1071 {
1072 $sel_hour .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
1073 }
1074 else
1075 {
1076 $sel_hour .= "<option value=\"$i\">" . date("ga", mktime($i, 0, 0)) . "</option>\n";
1077 }
1078 }
1079 $sel_hour .= "</select>\n";
1080 $sel_hour = preg_replace("/(value\=\"$hour\")/", "$1 selected=\"selected\"", $sel_hour);
1081
1082 // build minutes select
1083 $sel_minute .= "<select ".$disabled."name=\"".$prefix."[m]\" id=\"".$prefix."_m\" class=\"form-control\">\n";
1084
1085 for ($i = 0; $i <= 59; $i = $i + $minute_steps)
1086 {
1087 $sel_minute .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
1088 }
1089 $sel_minute .= "</select>\n";
1090 $sel_minute = preg_replace("/(value\=\"$minute\")/", "$1 selected=\"selected\"", $sel_minute);
1091
1092 if (!$short) {
1093 // build seconds select
1094 $sel_second .= "<select ".$disabled."name=\"".$prefix."[s]\" id=\"".$prefix."_s\" class=\"form-control\">\n";
1095
1096 for ($i = 0; $i <= 59; $i++)
1097 {
1098 $sel_second .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
1099 }
1100 $sel_second .= "</select>\n";
1101 $sel_second = preg_replace("/(value\=\"$second\")/", "$1 selected=\"selected\"", $sel_second);
1102 }
1103 $timeformat = $lng->text["lang_timeformat"];
1104 if (strlen($timeformat) == 0) $timeformat = "H:i:s";
1105 $timeformat = strtolower(preg_replace("/\W/", "", $timeformat));
1106 $timeformat = preg_replace("/(\w)/", "%%$1", $timeformat);
1107 $timeformat = preg_replace("/%%h/", $sel_hour, $timeformat);
1108 $timeformat = preg_replace("/%%i/", $sel_minute, $timeformat);
1109 if ($short) {
1110 $timeformat = preg_replace("/%%s/", "", $timeformat);
1111 } else {
1112 $timeformat = preg_replace("/%%s/", $sel_second, $timeformat);
1113 }
1114 return $timeformat;
1115 }
1116
1130 public static function is_email($a_email)
1131 {
1132 // BEGIN Mail: If possible, use PearMail to validate e-mail address
1133 global $ilErr;
1134
1135 // additional check for ilias object is needed,
1136 // otherwise setup will fail with this if branch
1137 if(is_object($ilErr)) // seems to work in Setup now
1138 {
1139 require_once './Services/PEAR/lib/Mail/RFC822.php';
1140 $parser = new Mail_RFC822();
1142 $addresses = $parser->parseAddressList($a_email, 'ilias', false, true);
1143 if(!is_a($addresses, 'PEAR_Error') &&
1144 count($addresses) == 1 && $addresses[0]->host != 'ilias'
1145 )
1146 {
1147 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($ilErr, "errorHandler"));
1148 return true;
1149 }
1150 else
1151 {
1152 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($ilErr, "errorHandler"));
1153 return false;
1154 }
1155 }
1156 else
1157 {
1158 $tlds = strtolower(
1159 "AC|AD|AE|AERO|AF|AG|AI|AL|AM|AN|AO|AQ|AR|ARPA|AS|ASIA|AT|AU|AW|AX|AZ|BA|BB|BD|BE|BF|BG|BH|BI|BIZ|BJ|BM|BN|BO|BR|BS|BT|BV|BW|BY|".
1160 "BZ|CA|CAT|CC|CD|CF|CG|CH|CI|CK|CL|CM|CN|CO|COM|COOP|CR|CU|CV|CX|CY|CZ|DE|DJ|DK|DM|DO|DZ|EC|EDU|EE|EG|".
1161 "ER|ES|ET|EU|FI|FJ|FK|FM|FO|FR|GA|GB|GD|GE|GF|GG|GH|GI|GL|GM|GN|GOV|GP|GQ|GR|GS|GT|GU|GW|GY|HK|HM|HN|HR|HT|".
1162 "HU|ID|IE|IL|IM|IN|INFO|INT|IO|IQ|IR|IS|IT|JE|JM|JO|JOBS|JP|KE|KG|KH|KI|KM|KN|KP|KR|KW|KY|KZ|LA|LB|LC|".
1163 "LI|LK|LR|LS|LT|LU|LV|LY|MA|MC|MD|ME|MG|MH|MIL|MK|ML|MM|MN|MO|MOBI|MP|MQ|MR|MS|MT|MU|MUSEUM|MV|MW|MX|".
1164 "MY|MZ|NA|NAME|NC|NE|NET|NF|NG|NI|NL|NO|NP|NR|NU|NZ|OM|ORG|PA|PE|PF|PG|PH|PK|PL|PM|PN|PR|PRO|PS|".
1165 "PT|PW|PY|QA|RE|RO|RS|RU|RW|SA|SB|SC|SD|SE|SG|SH|SI|SJ|SK|SL|SM|SN|SO|SR|ST|SU|SV|SY|SZ|TC|TD|TEL|".
1166 "TF|TG|TH|TJ|TK|TL|TM|TN|TO|TP|TR|TRAVEL|TT|TV|TW|TZ|UA|UG|UK|US|UY|UZ|VA|VC|VE|VG|VI|VN|VU|".
1167 "WF|WS|XN|YE|YT|YU|ZA|ZM|ZW");
1168
1169 return(preg_match("/^[-_.[:alnum:]]+@((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(".$tlds.")|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$a_email));
1170 }
1171 // END Mail: If possible, use PearMail to validate e-mail address
1172 }
1173
1182 public static function isPassword($a_passwd, &$customError = null)
1183 {
1184 global $lng;
1185
1186 include_once('./Services/PrivacySecurity/classes/class.ilSecuritySettings.php');
1188
1189 // check if password is empty
1190 if( empty($a_passwd) )
1191 {
1192 $customError = $lng->txt('password_empty');
1193 return false;
1194 }
1195
1196 $isPassword = true;
1197 $errors = array();
1198
1199 // check if password to short
1200 if( $security->getPasswordMinLength() > 0 && strlen($a_passwd) < $security->getPasswordMinLength() )
1201 {
1202 $errors[] = sprintf( $lng->txt('password_to_short'), $security->getPasswordMinLength() );
1203 $isPassword = false;
1204 }
1205
1206 // check if password not to long
1207 // Hmmmmm, maybe we should discuss this limitation. In my opinion it is stupid to limit the password length ;-). There should only be a technical limitation (field size in database).
1208 if( $security->getPasswordMaxLength() > 0 && strlen($a_passwd) > $security->getPasswordMaxLength() )
1209 {
1210 $errors[] = sprintf( $lng->txt('password_to_long'), $security->getPasswordMaxLength() );
1211 $isPassword = false;
1212 }
1213
1214 // if password must contains Chars and Numbers
1215 if( $security->isPasswordCharsAndNumbersEnabled() )
1216 {
1217 $hasCharsAndNumbers = true;
1218
1219 // check password for existing chars
1220 if( !preg_match('/[A-Za-z]+/',$a_passwd) )
1221 {
1222 $hasCharsAndNumbers = false;
1223 }
1224
1225 // check password for existing numbers
1226 if( !preg_match('/[0-9]+/',$a_passwd) )
1227 {
1228 $hasCharsAndNumbers = false;
1229 }
1230
1231 if( !$hasCharsAndNumbers )
1232 {
1233 $errors[] = $lng->txt('password_must_chars_and_numbers');
1234 $isPassword = false;
1235 }
1236 }
1237
1238 require_once 'Services/Utilities/classes/class.ilStr.php';
1239 if($security->getPasswordNumberOfUppercaseChars() > 0)
1240 {
1241 if(ilStr::strLen($a_passwd) - ilStr::strLen(preg_replace('/[A-Z]/', '', $a_passwd)) < $security->getPasswordNumberOfUppercaseChars())
1242 {
1243 $errors[] = sprintf($lng->txt('password_must_contain_ucase_chars'), $security->getPasswordNumberOfUppercaseChars());
1244 $isPassword = false;
1245 }
1246 }
1247
1248 if($security->getPasswordNumberOfLowercaseChars() > 0)
1249 {
1250 if(ilStr::strLen($a_passwd) - ilStr::strLen(preg_replace('/[a-z]/', '', $a_passwd)) < $security->getPasswordNumberOfLowercaseChars())
1251 {
1252 $errors[] = sprintf($lng->txt('password_must_contain_lcase_chars'), $security->getPasswordNumberOfLowercaseChars());
1253 $isPassword = false;
1254 }
1255 }
1256
1257 // if password must contains Special-Chars
1258 if( $security->isPasswordSpecialCharsEnabled() )
1259 {
1260 // check password for existing special-chars
1261 if( !preg_match( self::getPasswordValidChars(true, true) , $a_passwd) )
1262 {
1263 $errors[] = $lng->txt('password_must_special_chars');
1264 $isPassword = false;
1265 }
1266 }
1267
1268 // ensure password matches the positive list of chars/special-chars
1269 if( !preg_match( self::getPasswordValidChars() , $a_passwd) )
1270 {
1271 $errors[] = $lng->txt('password_contains_invalid_chars');
1272 $isPassword = false;
1273 }
1274
1275 // build custom error message
1276 if( count($errors) == 1 )
1277 {
1278 $customError = $errors[0];
1279 }
1280 elseif( count($errors) > 1 )
1281 {
1282 $customError = $lng->txt('password_multiple_errors');
1283 $customError .= '<br />'.implode('<br />', $errors);
1284 }
1285
1286 return $isPassword;
1287 }
1288
1295 public static function isPasswordValidForUserContext($clear_text_password, $user, &$error_language_variable = null)
1296 {
1297 include_once 'Services/PrivacySecurity/classes/class.ilSecuritySettings.php';
1299
1300 $login = null;
1301
1302 if(is_string($user))
1303 {
1304 $login = $user;
1305 }
1306 else if(is_array($user))
1307 {
1308 // Try to get loginname and user_id from array
1309 $login = $user['login'];
1310 $userId = $user['id'];
1311 }
1312 else if($user instanceof ilObjUser)
1313 {
1314 $login = $user->getLogin();
1315 $userId = $user->getId();
1316 }
1317
1318 // The user context (user instance or id) can be used for further validation (e.g. compare a password with the users' password history, etc.) in future releases.
1319
1320 if($login && (int)$security->getPasswordMustNotContainLoginnameStatus() &&
1321 strpos(strtolower($clear_text_password), strtolower($login)) !== false
1322 )
1323 {
1324 $error_language_variable = 'password_contains_parts_of_login_err';
1325 return false;
1326 }
1327
1328 return true;
1329 }
1330
1338 public static function getPasswordValidChars($a_as_regex = true, $a_only_special_chars = false)
1339 {
1340 if( $a_as_regex )
1341 {
1342 if( $a_only_special_chars )
1343 {
1344 return '/[_\.\+\?\#\-\*\@!\$\%\~\/\:\;]+/';
1345 }
1346 else
1347 {
1348 return '/^[A-Za-z0-9_\.\+\?\#\-\*\@!\$\%\~\/\:\;]+$/';
1349 }
1350 }
1351 else
1352 {
1353 return 'A-Z a-z 0-9 _.+?#-*@!$%~/:;';
1354 }
1355 }
1356
1364 public static function getPasswordRequirementsInfo()
1365 {
1366 global $lng;
1367
1368 include_once('./Services/PrivacySecurity/classes/class.ilSecuritySettings.php');
1370
1371 $infos = array(sprintf($lng->txt('password_allow_chars'), self::getPasswordValidChars(false)));
1372
1373 // check if password to short
1374 if( $security->getPasswordMinLength() > 0 )
1375 {
1376 $infos[] = sprintf( $lng->txt('password_to_short'), $security->getPasswordMinLength() );
1377 }
1378
1379 // check if password not to long
1380 if( $security->getPasswordMaxLength() > 0 )
1381 {
1382 $infos[] = sprintf( $lng->txt('password_to_long'), $security->getPasswordMaxLength() );
1383 }
1384
1385 // if password must contains Chars and Numbers
1386 if( $security->isPasswordCharsAndNumbersEnabled() )
1387 {
1388 $infos[] = $lng->txt('password_must_chars_and_numbers');
1389 }
1390
1391 // if password must contains Special-Chars
1392 if( $security->isPasswordSpecialCharsEnabled() )
1393 {
1394 $infos[] = $lng->txt('password_must_special_chars');
1395 }
1396
1397 if($security->getPasswordNumberOfUppercaseChars() > 0)
1398 {
1399 $infos[] = sprintf($lng->txt('password_must_contain_ucase_chars'), $security->getPasswordNumberOfUppercaseChars());
1400 }
1401
1402 if($security->getPasswordNumberOfLowercaseChars() > 0)
1403 {
1404 $infos[] = sprintf($lng->txt('password_must_contain_lcase_chars'), $security->getPasswordNumberOfLowercaseChars());
1405 }
1406
1407 return implode('<br />', $infos);
1408 }
1409
1410 /*
1411 * validates a login
1412 * @access public
1413 * @param string login
1414 * @return boolean true if valid
1415 */
1416 function isLogin($a_login)
1417 {
1418 if (empty($a_login))
1419 {
1420 return false;
1421 }
1422
1423 if (strlen($a_login) < 3)
1424 {
1425 return false;
1426 }
1427
1428 // FIXME - If ILIAS is configured to use RFC 822
1429 // compliant mail addresses we should not
1430 // allow the @ character.
1431 if (!ereg("^[A-Za-z0-9_\.\+\*\@!\$\%\~\-]+$", $a_login))
1432 {
1433 return false;
1434 }
1435
1436 return true;
1437 }
1438
1452 public static function shortenText ($a_str, $a_len, $a_dots = false, $a_next_blank = false,
1453 $a_keep_extension = false)
1454 {
1455 include_once("./Services/Utilities/classes/class.ilStr.php");
1456 if (ilStr::strLen($a_str) > $a_len)
1457 {
1458 if ($a_next_blank)
1459 {
1460 $len = ilStr::strPos($a_str, " ", $a_len);
1461 }
1462 else
1463 {
1464 $len = $a_len;
1465 }
1466 // BEGIN WebDAV
1467 // - Shorten names in the middle, before the filename extension
1468 // Workaround for Windows WebDAV Client:
1469 // Use the unicode ellipsis symbol for shortening instead of
1470 // three full stop characters.
1471 if ($a_keep_extension)
1472 {
1473 $p = strrpos($a_str, '.'); // this messes up normal shortening, see bug #6190
1474 }
1475 if ($p === false || $p == 0 || strlen($a_str) - $p > $a_len)
1476 {
1477 $a_str = ilStr::subStr($a_str,0,$len);
1478 if ($a_dots)
1479 {
1480 $a_str .= "\xe2\x80\xa6"; // UTF-8 encoding for Unicode ellipsis character.
1481 }
1482 }
1483 else
1484 {
1485 if ($a_dots)
1486 {
1487 $a_str = ilStr::subStr($a_str,0,$len - (strlen($a_str) - $p + 1))."\xe2\x80\xa6".substr($a_str, $p);
1488 }
1489 else
1490 {
1491 $a_str = ilStr::subStr($a_str,0,$len - (strlen($a_str) - $p + 1)).substr($a_str, $p);
1492 }
1493 }
1494 }
1495
1496 return $a_str;
1497 }
1498
1509 public static function shortenWords($a_str, $a_len = 30, $a_dots = true)
1510 {
1511 include_once("./Services/Utilities/classes/class.ilStr.php");
1512 $str_arr = explode(" ", $a_str);
1513
1514 for ($i = 0; $i < count($str_arr); $i++)
1515 {
1516 if (ilStr::strLen($str_arr[$i]) > $a_len)
1517 {
1518 $str_arr[$i] = ilStr::subStr($str_arr[$i], 0, $a_len);
1519 if ($a_dots)
1520 {
1521 $str_arr[$i].= "...";
1522 }
1523 }
1524 }
1525
1526 return implode($str_arr, " ");
1527 }
1528
1538 public static function attribsToArray($a_str)
1539 {
1540 $attribs = array();
1541 while (is_int(strpos($a_str, "=")))
1542 {
1543 $eq_pos = strpos($a_str, "=");
1544 $qu1_pos = strpos($a_str, "\"");
1545 $qu2_pos = strpos(substr($a_str, $qu1_pos + 1), "\"") + $qu1_pos + 1;
1546 if (is_int($eq_pos) && is_int($qu1_pos) && is_int($qu2_pos))
1547 {
1548 $var = trim(substr($a_str, 0, $eq_pos));
1549 $val = trim(substr($a_str, $qu1_pos + 1, ($qu2_pos - $qu1_pos) - 1));
1550 $attribs[$var] = $val;
1551 $a_str = substr($a_str, $qu2_pos + 1);
1552 }
1553 else
1554 {
1555 $a_str = "";
1556 }
1557 }
1558 return $attribs;
1559 }
1560
1572 public static function rCopy ($a_sdir, $a_tdir, $preserveTimeAttributes = false)
1573 {
1574 // check if arguments are directories
1575 if (!@is_dir($a_sdir) or
1576 !@is_dir($a_tdir))
1577 {
1578 return FALSE;
1579 }
1580
1581 // read a_sdir, copy files and copy directories recursively
1582 $dir = opendir($a_sdir);
1583
1584 while($file = readdir($dir))
1585 {
1586 if ($file != "." and
1587 $file != "..")
1588 {
1589 // directories
1590 if (@is_dir($a_sdir."/".$file))
1591 {
1592 if (!@is_dir($a_tdir."/".$file))
1593 {
1594 if (!ilUtil::makeDir($a_tdir."/".$file))
1595 return FALSE;
1596
1597 //chmod($a_tdir."/".$file, 0775);
1598 }
1599
1600 if (!ilUtil::rCopy($a_sdir."/".$file,$a_tdir."/".$file))
1601 {
1602 return FALSE;
1603 }
1604 }
1605
1606 // files
1607 if (@is_file($a_sdir."/".$file))
1608 {
1609 if (!copy($a_sdir."/".$file,$a_tdir."/".$file))
1610 {
1611 return FALSE;
1612 }
1613 if ($preserveTimeAttributes)
1614 touch($a_tdir."/".$file, filectime($a_sdir."/".$file));
1615 }
1616 }
1617 }
1618 return TRUE;
1619 }
1620
1629 public static function getWebspaceDir($mode = "filesystem")
1630 {
1631 global $ilias;
1632
1633 if ($mode == "filesystem")
1634 {
1635 return "./".ILIAS_WEB_DIR."/".$ilias->client_id;
1636 }
1637 else
1638 {
1639 if (defined("ILIAS_MODULE"))
1640 {
1641 return "../".ILIAS_WEB_DIR."/".$ilias->client_id;
1642 }
1643 else
1644 {
1645 return "./".ILIAS_WEB_DIR."/".$ilias->client_id;
1646 }
1647 }
1648
1649 //return $ilias->ini->readVariable("server","webspace_dir");
1650 }
1651
1658 public static function getDataDir()
1659 {
1660 return CLIENT_DATA_DIR;
1661 //global $ilias;
1662
1663 //return $ilias->ini->readVariable("server", "data_dir");
1664 }
1665
1675 public static function getUsersOnline($a_user_id = 0)
1676 {
1677 include_once("./Services/User/classes/class.ilObjUser.php");
1678 return ilObjUser::_getUsersOnline($a_user_id);
1679 }
1680
1691 public static function getAssociatedUsersOnline($a_user_id)
1692 {
1693 include_once("./Services/User/classes/class.ilObjUser.php");
1694 return ilObjUser::_getAssociatedUsersOnline($a_user_id);
1695 }
1696
1704 public static function ilTempnam($a_temp_path = null)
1705 {
1706 if($a_temp_path === null )
1707 {
1708 $temp_path = ilUtil::getDataDir() . "/temp";
1709 }
1710 else
1711 {
1712 $temp_path = $a_temp_path;
1713 }
1714
1715 if (!is_dir($temp_path))
1716 {
1717 ilUtil::createDirectory($temp_path);
1718 }
1719 $temp_name = tempnam($temp_path, "tmp");
1720 // --->
1721 // added the following line because tempnam creates a backslash on some
1722 // Windows systems which leads to problems, because the "...\tmp..." can be
1723 // interpreted as "...{TAB-CHARACTER}...". The normal slash works fine
1724 // even under windows (Helmut Schottmüller, 2005-08-31)
1725 $temp_name = str_replace("\\", "/", $temp_name);
1726 // --->
1727 unlink($temp_name);
1728 return $temp_name;
1729 }
1730
1739 public static function createDirectory($a_dir, $a_mod = 0755)
1740 {
1741 ilUtil::makeDir($a_dir);
1742 //@mkdir($a_dir);
1743 //@chmod($a_dir, $a_mod);
1744 }
1745
1746
1755 public static function unzip($a_file, $overwrite = false, $a_flat = false)
1756 {
1757 global $ilLog;
1758
1759 if (!is_file($a_file))
1760 {
1761 return;
1762 }
1763
1764 // if flat, move file to temp directory first
1765 if ($a_flat)
1766 {
1767 $tmpdir = ilUtil::ilTempnam();
1768 ilUtil::makeDir($tmpdir);
1769 copy($a_file, $tmpdir.DIRECTORY_SEPARATOR.basename($a_file));
1770 $orig_file = $a_file;
1771 $a_file = $tmpdir.DIRECTORY_SEPARATOR.basename($a_file);
1772 $origpathinfo = pathinfo($orig_file);
1773 }
1774
1775 $pathinfo = pathinfo($a_file);
1776 $dir = $pathinfo["dirname"];
1777 $file = $pathinfo["basename"];
1778
1779 // unzip
1780 $cdir = getcwd();
1781 chdir($dir);
1782 $unzip = PATH_TO_UNZIP;
1783
1784 // the following workaround has been removed due to bug
1785 // http://www.ilias.de/mantis/view.php?id=7578
1786 // since the workaround is quite old, it may not be necessary
1787 // anymore, alex 9 Oct 2012
1788/*
1789 // workaround for unzip problem (unzip of subdirectories fails, so
1790 // we create the subdirectories ourselves first)
1791 // get list
1792 $unzipcmd = "-Z -1 ".ilUtil::escapeShellArg($file);
1793 $arr = ilUtil::execQuoted($unzip, $unzipcmd);
1794 $zdirs = array();
1795
1796 foreach($arr as $line)
1797 {
1798 if(is_int(strpos($line, "/")))
1799 {
1800 $zdir = substr($line, 0, strrpos($line, "/"));
1801 $nr = substr_count($zdir, "/");
1802 //echo $zdir." ".$nr."<br>";
1803 while ($zdir != "")
1804 {
1805 $nr = substr_count($zdir, "/");
1806 $zdirs[$zdir] = $nr; // collect directories
1807 //echo $dir." ".$nr."<br>";
1808 $zdir = substr($zdir, 0, strrpos($zdir, "/"));
1809 }
1810 }
1811 }
1812
1813 asort($zdirs);
1814
1815 foreach($zdirs as $zdir => $nr) // create directories
1816 {
1817 ilUtil::createDirectory($zdir);
1818 }
1819*/
1820
1821 // real unzip
1822 if (!$overwrite)
1823 {
1824 $unzipcmd = ilUtil::escapeShellArg($file);
1825 }
1826 else
1827 {
1828 $unzipcmd = "-o ".ilUtil::escapeShellArg($file);
1829 }
1830 ilUtil::execQuoted($unzip, $unzipcmd);
1831
1832 chdir($cdir);
1833
1834 // remove all sym links
1835 clearstatcache(); // prevent is_link from using cache
1836 $dir_realpath = realpath($dir);
1837 foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)) as $name => $f)
1838 {
1839 if (is_link($name))
1840 {
1841 $target = readlink($name);
1842 if (substr($target, 0, strlen($dir_realpath)) != $dir_realpath)
1843 {
1844 unlink($name);
1845 $ilLog->write("Remove symlink ".$name);
1846 }
1847 }
1848 }
1849
1850 // if flat, get all files and move them to original directory
1851 if ($a_flat)
1852 {
1853 include_once("./Services/Utilities/classes/class.ilFileUtils.php");
1854 $filearray = array();
1855 ilFileUtils::recursive_dirscan($tmpdir, $filearray);
1856 if (is_array($filearray["file"]))
1857 {
1858 foreach ($filearray["file"] as $k => $f)
1859 {
1860 if (substr($f, 0, 1) != "." && $f != basename($orig_file))
1861 {
1862 copy($filearray["path"][$k].$f, $origpathinfo["dirname"].DIRECTORY_SEPARATOR.$f);
1863 }
1864 }
1865 }
1866 ilUtil::delDir($tmpdir);
1867 }
1868 }
1869
1876 public static function zip($a_dir, $a_file, $compress_content = false)
1877 {
1878 $cdir = getcwd();
1879
1880 if($compress_content)
1881 {
1882 $a_dir .="/*";
1883 $pathinfo = pathinfo($a_dir);
1884 chdir($pathinfo["dirname"]);
1885 }
1886
1887 $pathinfo = pathinfo($a_file);
1888 $dir = $pathinfo["dirname"];
1889 $file = $pathinfo["basename"];
1890
1891 if(!$compress_content)
1892 {
1893 chdir($dir);
1894 }
1895
1896 $zip = PATH_TO_ZIP;
1897
1898 if(!$zip)
1899 {
1900 chdir($cdir);
1901 return false;
1902 }
1903
1904 if (is_array($a_dir))
1905 {
1906 $source = "";
1907 foreach($a_dir as $dir)
1908 {
1909 $name = basename($dir);
1910 $source.= " ".ilUtil::escapeShellArg($name);
1911 }
1912 }
1913 else
1914 {
1915 $name = basename($a_dir);
1916 if (trim($name) != "*")
1917 {
1918 $source = ilUtil::escapeShellArg($name);
1919 }
1920 else
1921 {
1922 $source = $name;
1923 }
1924 }
1925
1926 $zipcmd = "-r ".ilUtil::escapeShellArg($a_file)." ".$source;
1927 ilUtil::execQuoted($zip, $zipcmd);
1928 chdir($cdir);
1929 return true;
1930 }
1931
1932 public static function CreateIsoFromFolder($a_dir, $a_file)
1933 {
1934 $cdir = getcwd();
1935
1936 $pathinfo = pathinfo($a_dir);
1937 chdir($pathinfo["dirname"]);
1938
1939 $pathinfo = pathinfo($a_file);
1940 $dir = $pathinfo["dirname"];
1941 $file = $pathinfo["basename"]; $zipcmd = "-r ".ilUtil::escapeShellArg($a_file)." ".$source;
1942
1943 $mkisofs = PATH_TO_MKISOFS;
1944 if(!$mkisofs)
1945 {
1946 chdir($cdir);
1947 return false;
1948 }
1949
1950 $name = basename($a_dir);
1951 $source = ilUtil::escapeShellArg($name);
1952
1953 $zipcmd = "-r -J -o ".$a_file." ".$source;
1954 ilUtil::execQuoted($mkisofs, $zipcmd);
1955 chdir($cdir);
1956 return true;
1957 }
1958
1967 public static function getConvertCmd()
1968 {
1969 return PATH_TO_CONVERT;
1970 }
1971
1979 public static function execConvert($args)
1980 {
1981 ilUtil::execQuoted(PATH_TO_CONVERT, $args);
1982 }
1983
1990 public static function isConvertVersionAtLeast($a_version)
1991 {
1992 $current_version = ilUtil::execQuoted(PATH_TO_CONVERT, "--version");
1993 $current_version = self::processConvertVersion($current_version[0]);
1994 $version = self::processConvertVersion($a_version);
1995 if($current_version >= $version)
1996 {
1997 return true;
1998 }
1999 return false;
2000 }
2001
2008 protected static function processConvertVersion($a_version)
2009 {
2010 if(preg_match("/([0-9]+)\.([0-9]+)\.([0-9]+)([\.|\-]([0-9]+))?/", $a_version, $match))
2011 {
2012 $version = str_pad($match[1], 2, 0, STR_PAD_LEFT).
2013 str_pad($match[2], 2, 0, STR_PAD_LEFT).
2014 str_pad($match[3], 2, 0, STR_PAD_LEFT).
2015 str_pad($match[5], 2, 0, STR_PAD_LEFT);
2016 return (int)$version;
2017 }
2018 }
2019
2029 public static function convertImage($a_from, $a_to, $a_target_format = "", $a_geometry = "",
2030 $a_background_color = "")
2031 {
2032 $format_str = ($a_target_format != "")
2033 ? strtoupper($a_target_format).":"
2034 : "";
2035 $geometry = "";
2036 if ($a_geometry != "")
2037 {
2038 if (is_int(strpos($a_geometry, "x")))
2039 {
2040 $geometry = " -geometry ".$a_geometry." ";
2041 }
2042 else
2043 {
2044 $geometry = " -geometry ".$a_geometry."x".$a_geometry." ";
2045 }
2046 }
2047
2048 $bg_color = ($a_background_color != "")
2049 ? " -background color ".$a_background_color." "
2050 : "";
2051 $convert_cmd = ilUtil::escapeShellArg($a_from)." ".$bg_color.$geometry.ilUtil::escapeShellArg($format_str.$a_to);
2052
2053 ilUtil::execConvert($convert_cmd);
2054 }
2055
2066 public static function resizeImage($a_from, $a_to, $a_width, $a_height, $a_constrain_prop = false)
2067 {
2068 if ($a_constrain_prop)
2069 {
2070 $size = " -geometry ".$a_width."x".$a_height." ";
2071 }
2072 else
2073 {
2074 $size = " -resize ".$a_width."x".$a_height."! ";
2075 }
2076 $convert_cmd = ilUtil::escapeShellArg($a_from)." ".$size.ilUtil::escapeShellArg($a_to);
2077
2078 ilUtil::execConvert($convert_cmd);
2079 }
2080
2087 public static function img($a_src, $a_alt = "", $a_width = "", $a_height = "", $a_border = 0, $a_id = "", $a_class = "")
2088 {
2089 $img = '<img src="'.$a_src.'"';
2090 if ($a_alt != "")
2091 {
2092 $img.= ' alt="'.htmlspecialchars($a_alt).'" title="'.htmlspecialchars($a_alt).'"';
2093 }
2094 if ($a_width != "")
2095 {
2096 $img.= ' width="'.htmlspecialchars($a_width).'"';
2097 }
2098 if ($a_height != "")
2099 {
2100 $img.= ' height="'.htmlspecialchars($a_height).'"';
2101 }
2102 if ($a_class != "")
2103 {
2104 $img.= ' class="'.$a_class.'"';
2105 }
2106 if ($a_id != "")
2107 {
2108 $img.= ' id="'.$a_id.'"';
2109 }
2110 $img.= ' border="'.(int) $a_border.'"/>';
2111
2112 return $img;
2113 }
2114
2122 public static function html2pdf($html, $pdf_file)
2123 {
2124 $html_file = str_replace(".pdf",".html",$pdf_file);
2125
2126 $fp = fopen( $html_file ,"wb");
2127 fwrite($fp, $html);
2128 fclose($fp);
2129
2130 ilUtil::htmlfile2pdf($html_file,$pdf_file);
2131 }
2132
2139 public static function htmlfile2pdf($html_file, $pdf_file)
2140 {
2141 $htmldoc_path = PATH_TO_HTMLDOC;
2142
2143 $htmldoc = "--no-toc ";
2144 $htmldoc .= "--no-jpeg ";
2145 $htmldoc .= "--webpage ";
2146 $htmldoc .= "--outfile " . ilUtil::escapeShellArg($pdf_file) . " ";
2147 $htmldoc .= "--bodyfont Arial ";
2148 $htmldoc .= "--charset iso-8859-15 ";
2149 $htmldoc .= "--color ";
2150 $htmldoc .= "--size A4 "; // --landscape
2151 $htmldoc .= "--format pdf ";
2152 $htmldoc .= "--footer ... ";
2153 $htmldoc .= "--header ... ";
2154 $htmldoc .= "--left 60 ";
2155 // $htmldoc .= "--right 200 ";
2156 $htmldoc .= $html_file;
2157 ilUtil::execQuoted($htmldoc_path, $htmldoc);
2158
2159 }
2160
2167 public static function deliverData($a_data, $a_filename, $mime = "application/octet-stream", $charset = "")
2168 {
2169 $disposition = "attachment"; // "inline" to view file in browser or "attachment" to download to hard disk
2170 // $mime = "application/octet-stream"; // or whatever the mime type is
2171
2172 include_once './Services/Http/classes/class.ilHTTPS.php';
2173
2174 //if($_SERVER['HTTPS'])
2175 if( ilHTTPS::getInstance()->isDetected() )
2176 {
2177
2178 // Added different handling for IE and HTTPS => send pragma after content informations
2182 #header("Pragma: ");
2183 #header("Cache-Control: ");
2184 #header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
2185 #header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
2186 #header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1
2187 #header("Cache-Control: post-check=0, pre-check=0", false);
2188 }
2189 else if ($disposition == "attachment")
2190 {
2191 header("Cache-control: private");
2192 }
2193 else
2194 {
2195 header("Cache-Control: no-cache, must-revalidate");
2196 header("Pragma: no-cache");
2197 }
2198
2199 $ascii_filename = ilUtil::getASCIIFilename($a_filename);
2200
2201 if (strlen($charset))
2202 {
2203 $charset = "; charset=$charset";
2204 }
2205 header("Content-Type: $mime$charset");
2206 header("Content-Disposition:$disposition; filename=\"".$ascii_filename."\"");
2207 header("Content-Description: ".$ascii_filename);
2208 header("Content-Length: ".(string)(strlen($a_data)));
2209
2210 //if($_SERVER['HTTPS'])
2211 if( ilHTTPS::getInstance()->isDetected() )
2212 {
2213 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
2214 header('Pragma: public');
2215 }
2216
2217 header("Connection: close");
2218 echo $a_data;
2219 exit;
2220 }
2221
2222 // BEGIN WebDAV: Show file in browser or provide it as attachment
2230 public static function deliverFile($a_file, $a_filename,$a_mime = '', $isInline = false, $removeAfterDelivery = false,
2231 $a_exit_after = true)
2232 {
2233 // should we fail silently?
2234 if(!file_exists($a_file))
2235 {
2236 return false;
2237 }
2238
2239 if ($isInline) {
2240 $disposition = "inline"; // "inline" to view file in browser
2241 } else {
2242 $disposition = "attachment"; // "attachment" to download to hard disk
2243 //$a_mime = "application/octet-stream"; // override mime type to ensure that no browser tries to show the file anyway.
2244 }
2245 // END WebDAV: Show file in browser or provide it as attachment
2246
2247 if(strlen($a_mime))
2248 {
2249 $mime = $a_mime;
2250 }
2251 else
2252 {
2253 $mime = "application/octet-stream"; // or whatever the mime type is
2254 }
2255 // BEGIN WebDAV: Removed broken HTTPS code.
2256 // END WebDAV: Removed broken HTTPS code.
2257 if ($disposition == "attachment")
2258 {
2259 header("Cache-control: private");
2260 }
2261 else
2262 {
2263 header("Cache-Control: no-cache, must-revalidate");
2264 header("Pragma: no-cache");
2265 }
2266
2267 $ascii_filename = ilUtil::getASCIIFilename($a_filename);
2268
2269 header("Content-Type: $mime");
2270 header("Content-Disposition:$disposition; filename=\"".$ascii_filename."\"");
2271 header("Content-Description: ".$ascii_filename);
2272
2273 // #7271: if notice gets thrown download will fail in IE
2274 $filesize = @filesize($a_file);
2275 if ($filesize)
2276 {
2277 header("Content-Length: ".(string)$filesize);
2278 }
2279
2280 include_once './Services/Http/classes/class.ilHTTPS.php';
2281 #if($_SERVER['HTTPS'])
2282 if(ilHTTPS::getInstance()->isDetected())
2283 {
2284 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
2285 header('Pragma: public');
2286 }
2287
2288 header("Connection: close");
2289 ilUtil::readFile( $a_file );
2290 if ($removeAfterDelivery)
2291 {
2292 unlink ($a_file);
2293 }
2294 if ($a_exit_after)
2295 {
2296 exit;
2297 }
2298 }
2299
2300
2310 public static function readFile($a_file)
2311 {
2312 $chunksize = 1*(1024*1024); // how many bytes per chunk
2313 $buffer = '';
2314 $handle = fopen($a_file, 'rb');
2315 if ($handle === false)
2316 {
2317 return false;
2318 }
2319 while (!feof($handle))
2320 {
2321 $buffer = fread($handle, $chunksize);
2322 print $buffer;
2323 }
2324 return fclose($handle);
2325 }
2326
2334 public static function getASCIIFilename($a_filename)
2335 {
2336 // The filename must be converted to ASCII, as of RFC 2183,
2337 // section 2.3.
2338
2350
2353
2354 // #15914 - try to fix german umlauts
2355 $umlauts = array("Ä"=>"Ae", "Ö"=>"Oe", "Ü"=>"Ue",
2356 "ä"=>"ae", "ö"=>"oe", "ü"=>"ue", "ß"=>"ss");
2357 foreach($umlauts as $src => $tgt)
2358 {
2359 $a_filename = str_replace($src, $tgt, $a_filename);
2360 }
2361
2362 $ascii_filename = htmlentities($a_filename, ENT_NOQUOTES, 'UTF-8');
2363 $ascii_filename = preg_replace('/\&(.)[^;]*;/', '\\1', $ascii_filename);
2364 $ascii_filename = preg_replace('/[\x7f-\xff]/', '_', $ascii_filename);
2365
2366 // OS do not allow the following characters in filenames: \/:*?"<>|
2367 $ascii_filename = preg_replace('/[:\x5c\/\*\?\"<>\|]/', '_', $ascii_filename);
2368 return $ascii_filename;
2369 }
2370
2377 public static function htmlentitiesOutsideHTMLTags($htmlText)
2378 {
2379 $matches = Array();
2380 $sep = '###HTMLTAG###';
2381
2382 preg_match_all("@<[^>]*>@", $htmlText, $matches);
2383 $tmp = preg_replace("@(<[^>]*>)@", $sep, $htmlText);
2384 $tmp = explode($sep, $tmp);
2385
2386 for ($i=0; $i<count($tmp); $i++)
2387 $tmp[$i] = htmlentities($tmp[$i], ENT_COMPAT, "UTF-8");
2388
2389 $tmp = join($sep, $tmp);
2390
2391 for ($i=0; $i<count($matches[0]); $i++)
2392 $tmp = preg_replace("@$sep@", $matches[0][$i], $tmp, 1);
2393
2394 return $tmp;
2395 }
2396
2403 public static function getJavaPath()
2404 {
2405 return PATH_TO_JAVA;
2406 //global $ilias;
2407
2408 //return $ilias->getSetting("java_path");
2409 }
2410
2418 public static function appendUrlParameterString($a_url, $a_par, $xml_style = false)
2419 {
2420 $amp = $xml_style
2421 ? "&amp;"
2422 : "&";
2423
2424 $url = (is_int(strpos($a_url, "?")))
2425 ? $a_url.$amp.$a_par
2426 : $a_url."?".$a_par;
2427
2428 return $url;
2429 }
2430
2446 public static function makeDir($a_dir)
2447 {
2448 $a_dir = trim($a_dir);
2449
2450 // remove trailing slash (bugfix for php 4.2.x)
2451 if (substr($a_dir,-1) == "/")
2452 {
2453 $a_dir = substr($a_dir,0,-1);
2454 }
2455
2456 // check if a_dir comes with a path
2457 if (!($path = substr($a_dir,0, strrpos($a_dir,"/") - strlen($a_dir))))
2458 {
2459 $path = ".";
2460 }
2461
2462 // create directory with file permissions of parent directory
2463 umask(0000);
2464 return @mkdir($a_dir,fileperms($path));
2465 }
2466
2467
2482 public static function makeDirParents($a_dir)
2483 {
2484 $dirs = array($a_dir);
2485 $a_dir = dirname($a_dir);
2486 $last_dirname = '';
2487
2488 while($last_dirname != $a_dir)
2489 {
2490 array_unshift($dirs, $a_dir);
2491 $last_dirname = $a_dir;
2492 $a_dir = dirname($a_dir);
2493 }
2494
2495 // find the first existing dir
2496 $reverse_paths = array_reverse($dirs, TRUE);
2497 $found_index = -1;
2498 foreach ($reverse_paths as $key => $value)
2499 {
2500 if ($found_index == -1)
2501 {
2502 if (is_dir($value))
2503 {
2504 $found_index = $key;
2505 }
2506 }
2507 }
2508
2509 umask(0000);
2510 foreach ($dirs as $dirindex => $dir)
2511 {
2512 // starting with the longest existing path
2513 if ($dirindex >= $found_index)
2514 {
2515 if (! file_exists($dir))
2516 {
2517 if (strcmp(substr($dir,strlen($dir)-1,1),"/") == 0)
2518 {
2519 // on some systems there is an error when there is a slash
2520 // at the end of a directory in mkdir, see Mantis #2554
2521 $dir = substr($dir,0,strlen($dir)-1);
2522 }
2523 if (! mkdir($dir, $umask))
2524 {
2525 error_log("Can't make directory: $dir");
2526 return false;
2527 }
2528 }
2529 elseif (! is_dir($dir))
2530 {
2531 error_log("$dir is not a directory");
2532 return false;
2533 }
2534 else
2535 {
2536 // get umask of the last existing parent directory
2537 $umask = fileperms($dir);
2538 }
2539 }
2540 }
2541 return true;
2542 }
2543
2553 public static function delDir($a_dir, $a_clean_only = false)
2554 {
2555 if (!is_dir($a_dir) || is_int(strpos($a_dir, "..")))
2556 {
2557 return;
2558 }
2559
2560 $current_dir = opendir($a_dir);
2561
2562 $files = array();
2563
2564 // this extra loop has been necessary because of a strange bug
2565 // at least on MacOS X. A looped readdir() didn't work
2566 // correctly with larger directories
2567 // when an unlink happened inside the loop. Getting all files
2568 // into the memory first solved the problem.
2569 while($entryname = readdir($current_dir))
2570 {
2571 $files[] = $entryname;
2572 }
2573
2574 foreach($files as $file)
2575 {
2576 if(is_dir($a_dir."/".$file) and ($file != "." and $file!=".."))
2577 {
2578 ilUtil::delDir(${a_dir}."/".${file});
2579 }
2580 elseif ($file != "." and $file != "..")
2581 {
2582 unlink(${a_dir}."/".${file});
2583 }
2584 }
2585
2586 closedir($current_dir);
2587 if (!$a_clean_only)
2588 {
2589 @rmdir(${a_dir});
2590 }
2591 }
2592
2593
2600 public static function getDir($a_dir, $a_rec = false, $a_sub_dir = "")
2601 {
2602 $current_dir = opendir($a_dir.$a_sub_dir);
2603
2604 $dirs = array();
2605 $files = array();
2606 $subitems = array();
2607 while($entry = readdir($current_dir))
2608 {
2609 if(is_dir($a_dir."/".$entry))
2610 {
2611 $dirs[$entry] = array("type" => "dir", "entry" => $entry,
2612 "subdir" => $a_sub_dir);
2613 if ($a_rec && $entry != "." && $entry != "..")
2614 {
2615 $si = ilUtil::getDir($a_dir, true, $a_sub_dir."/".$entry);
2616 $subitems = array_merge($subitems, $si);
2617 }
2618 }
2619 else
2620 {
2621 if ($entry != "." && $entry != "..")
2622 {
2623 $size = filesize($a_dir.$a_sub_dir."/".$entry);
2624 $files[$entry] = array("type" => "file", "entry" => $entry,
2625 "size" => $size, "subdir" => $a_sub_dir);
2626 }
2627 }
2628 }
2629 ksort($dirs);
2630 ksort($files);
2631
2632 return array_merge($dirs, $files, $subitems);
2633 }
2634
2641 public static function stripSlashesArray($a_arr, $a_strip_html = true, $a_allow = "")
2642 {
2643 if (is_array($a_arr))
2644 {
2645 foreach ($a_arr as $k => $v)
2646 {
2647 $a_arr[$k] = ilUtil::stripSlashes($v, $a_strip_html, $a_allow);
2648 }
2649 }
2650
2651 return $a_arr;
2652 }
2653
2660 public static function stripSlashesRecursive($a_data, $a_strip_html = true, $a_allow = "")
2661 {
2662 if (is_array($a_data))
2663 {
2664 foreach ($a_data as $k => $v)
2665 {
2666 if (is_array($v))
2667 {
2668 $a_data[$k] = ilUtil::stripSlashesRecursive($v, $a_strip_html, $a_allow);
2669 }
2670 else
2671 {
2672 $a_data[$k] = ilUtil::stripSlashes($v, $a_strip_html, $a_allow);
2673 }
2674 }
2675 }
2676 else
2677 {
2678 $a_data = ilUtil::stripSlashes($a_data, $a_strip_html, $a_allow);
2679 }
2680
2681 return $a_data;
2682 }
2683
2691 public static function stripSlashes($a_str, $a_strip_html = true, $a_allow = "")
2692 {
2693 if (ini_get("magic_quotes_gpc"))
2694 {
2695 $a_str = stripslashes($a_str);
2696 }
2697//echo "<br><br>-".$a_strip_html."-".htmlentities($a_str);
2698//echo "<br>-".htmlentities(ilUtil::secureString($a_str, $a_strip_html, $a_allow));
2699 return ilUtil::secureString($a_str, $a_strip_html, $a_allow);
2700 }
2701
2709 public static function stripOnlySlashes($a_str)
2710 {
2711 if (ini_get("magic_quotes_gpc"))
2712 {
2713 $a_str = stripslashes($a_str);
2714 }
2715
2716 return $a_str;
2717 }
2718
2725 public static function secureString($a_str, $a_strip_html = true, $a_allow = "")
2726 {
2727 // check whether all allowed tags can be made secure
2728 $only_secure = true;
2729 $allow_tags = explode(">", $a_allow);
2730 $sec_tags = ilUtil::getSecureTags();
2731 $allow_array = array();
2732 foreach($allow_tags as $allow)
2733 {
2734 if ($allow != "")
2735 {
2736 $allow = str_replace("<", "", $allow);
2737
2738 if (!in_array($allow, $sec_tags))
2739 {
2740 $only_secure = false;
2741 }
2742 $allow_array[] = $allow;
2743 }
2744 }
2745
2746 // default behaviour: allow only secure tags 1:1
2747 if (($only_secure || $a_allow == "") && $a_strip_html)
2748 {
2749 if ($a_allow == "")
2750 {
2751 $allow_array = array ("b", "i", "strong", "em", "code", "cite",
2752 "gap", "sub", "sup", "pre", "strike", "bdo");
2753 }
2754
2755 // this currently removes parts of strings like "a <= b"
2756 // because "a <= b" is treated like "<spam onclick='hurt()'>ss</spam>"
2757 $a_str = ilUtil::maskSecureTags($a_str, $allow_array);
2758 $a_str = strip_tags($a_str); // strip all other tags
2759 $a_str = ilUtil::unmaskSecureTags($a_str, $allow_array);
2760
2761 // a possible solution could be something like:
2762 // $a_str = str_replace("<", "&lt;", $a_str);
2763 // $a_str = str_replace(">", "&gt;", $a_str);
2764 // $a_str = ilUtil::unmaskSecureTags($a_str, $allow_array);
2765 //
2766 // output would be ok then, but input fields would show
2767 // "a &lt;= b" for input "a <= b" if data is brought back to a form
2768 }
2769 else
2770 {
2771 // only for scripts, that need to allow more/other tags and parameters
2772 if ($a_strip_html)
2773 {
2774 $a_str = ilUtil::stripScriptHTML($a_str, $a_allow);
2775 }
2776 }
2777
2778 return $a_str;
2779 }
2780
2781 public static function getSecureTags()
2782 {
2783 return array("strong", "em", "u", "strike", "ol", "li", "ul", "p", "div",
2784 "i", "b", "code", "sup", "sub", "pre", "gap", "a", "img", "bdo");
2785 }
2786
2787 public static function maskSecureTags($a_str, $allow_array)
2788 {
2789 foreach ($allow_array as $t)
2790 {
2791 switch($t)
2792 {
2793 case "a":
2794 $a_str = ilUtil::maskAttributeTag($a_str, "a", "href");
2795 break;
2796
2797 case "img":
2798 $a_str = ilUtil::maskAttributeTag($a_str, "img", "src");
2799 break;
2800
2801 case "p":
2802 case "div":
2803 $a_str = ilUtil::maskTag($a_str, $t, array(
2804 array("param" => "align", "value" => "left"),
2805 array("param" => "align", "value" => "center"),
2806 array("param" => "align", "value" => "justify"),
2807 array("param" => "align", "value" => "right")
2808 ));
2809 break;
2810
2811 default:
2812 $a_str = ilUtil::maskTag($a_str, $t);
2813 break;
2814 }
2815 }
2816
2817 return $a_str;
2818 }
2819
2820 public static function unmaskSecureTags($a_str, $allow_array)
2821 {
2822 foreach ($allow_array as $t)
2823 {
2824 switch($t)
2825 {
2826 case "a":
2827 $a_str = ilUtil::unmaskAttributeTag($a_str, "a", "href");
2828 break;
2829
2830 case "img":
2831 $a_str = ilUtil::unmaskAttributeTag($a_str, "img", "src");
2832 break;
2833
2834 case "p":
2835 case "div":
2836 $a_str = ilUtil::unmaskTag($a_str, $t, array(
2837 array("param" => "align", "value" => "left"),
2838 array("param" => "align", "value" => "center"),
2839 array("param" => "align", "value" => "justify"),
2840 array("param" => "align", "value" => "right")
2841 ));
2842 break;
2843
2844 default:
2845 $a_str = ilUtil::unmaskTag($a_str, $t);
2846 break;
2847 }
2848 }
2849
2850 return $a_str;
2851 }
2852
2860 public static function securePlainString($a_str)
2861 {
2862 if (ini_get("magic_quotes_gpc"))
2863 {
2864 return stripslashes($a_str);
2865 }
2866 else
2867 {
2868 return $a_str;
2869 }
2870 }
2887 public static function htmlencodePlainString($a_str, $a_make_links_clickable, $a_detect_goto_links = false)
2888 {
2889 $encoded = "";
2890
2891 if ($a_make_links_clickable)
2892 {
2893 // Find text sequences in the plain text string which match
2894 // the URI syntax rules, and pass them to ilUtil::makeClickable.
2895 // Encode all other text sequences in the plain text string using
2896 // htmlspecialchars and nl2br.
2897 // The following expressions matches URI's as specified in RFC 2396.
2898 //
2899 // The expression matches URI's, which start with some well known
2900 // schemes, like "http:", or with "www.". This must be followed
2901 // by at least one of the following RFC 2396 expressions:
2902 // - alphanum: [a-zA-Z0-9]
2903 // - reserved: [;\/?:|&=+$,]
2904 // - mark: [\\-_.!~*\'()]
2905 // - escaped: %[0-9a-fA-F]{2}
2906 // - fragment delimiter: #
2907 // - uric_no_slash: [;?:@&=+$,]
2908 $matches = array();
2909 $numberOfMatches = preg_match_all('/(?:(?:http|https|ftp|ftps|mailto):|www\.)(?:[a-zA-Z0-9]|[;\/?:|&=+$,]|[\\-_.!~*\'()]|%[0-9a-fA-F]{2}|#|[;?:@&=+$,])+/',$a_str, $matches, PREG_OFFSET_CAPTURE);
2910 $pos1 = 0;
2911 $encoded = "";
2912 foreach ($matches as $match)
2913 {
2914 }
2915 foreach ($matches[0] as $match)
2916 {
2917 $matched_text = $match[0];
2918 $pos2 = $match[1];
2919 if ($matched_offset != previous_offset)
2920 {
2921 // encode plain text
2922 $encoded .= nl2br(htmlspecialchars(substr($a_str, $pos1, $pos2 - $pos1)));
2923 }
2924 // encode URI
2925 $encoded .= ilUtil::makeClickable($matched_text, $a_detect_goto_links);
2926
2927
2928 $pos1 = $pos2 + strlen($matched_text);
2929 }
2930 if ($pos1 < strlen($a_str))
2931 {
2932 $encoded .= nl2br(htmlspecialchars(substr($a_str, $pos1)));
2933 }
2934 }
2935 else
2936 {
2937 $encoded = nl2br(htmlspecialchars($a_str));
2938 }
2939 return $encoded;
2940 }
2941
2942
2943 public static function maskAttributeTag($a_str, $tag, $tag_att)
2944 {
2945 global $ilLog;
2946
2947 $ws = "[ \t\r\f\v\n]*";
2948 $att = $ws."[^>]*".$ws;
2949
2950 while (eregi("<($tag$att($tag_att$ws=$ws\"(([\$@!*()~;,_0-9A-z/:=%\\.&#?+\\-])*)\")$att)>",
2951 $a_str, $found))
2952 {
2953 $un = array(".", "-", "+", "?", '$', "*", "(", ")");
2954 $esc = array();
2955 foreach($un as $v)
2956 {
2957 $esc[] = "\\".$v;
2958 }
2959 $ff = str_replace($un, $esc, $found[1]);
2960
2961 $old_str = $a_str;
2962 $a_str = eregi_replace("<".$ff.">",
2963 "&lt;$tag $tag_att$tag_att=\"".$found[3]."\"&gt;", $a_str);
2964 if ($old_str == $a_str)
2965 {
2966 $ilLog->write("ilUtil::maskA-".htmlentities($old_str)." == ".
2967 htmlentities($a_str));
2968 return $a_str;
2969 }
2970 }
2971 $a_str = str_ireplace("</$tag>",
2972 "&lt;/$tag&gt;", $a_str);
2973 return $a_str;
2974 }
2975
2976 public static function unmaskAttributeTag($a_str, $tag, $tag_att)
2977 {
2978 global $ilLog;
2979
2980 while (eregi("&lt;($tag $tag_att$tag_att=\"(([\$@!*()~;,_0-9A-z/:=%\\.&#?+\\-])*)\")&gt;",
2981 $a_str, $found))
2982 {
2983 $un = array(".", "-", "+", "?", '$', "*", "(", ")");
2984 $esc = array();
2985 foreach($un as $v)
2986 {
2987 $esc[] = "\\".$v;
2988 }
2989 $ff = str_replace($un, $esc, $found[1]);
2990
2991 $old_str = $a_str;
2992 $a_str = eregi_replace("&lt;".$ff."&gt;",
2993 "<$tag $tag_att=\"".ilUtil::secureLink($found[2])."\">", $a_str);
2994 if ($old_str == $a_str)
2995 {
2996 $ilLog->write("ilUtil::unmaskA-".htmlentities($old_str)." == ".
2997 htmlentities($a_str));
2998 return $a_str;
2999 }
3000 }
3001 $a_str = str_replace("&lt;/$tag&gt;", "</$tag>", $a_str);
3002 return $a_str;
3003 }
3004
3005 public static function maskTag($a_str, $t, $fix_param = "")
3006 {
3007 $a_str = str_replace(array("<$t>", "<".strtoupper($t).">"),
3008 "&lt;".$t."&gt;", $a_str);
3009 $a_str = str_replace(array("</$t>", "</".strtoupper($t).">"),
3010 "&lt;/".$t."&gt;", $a_str);
3011
3012 if (is_array($fix_param))
3013 {
3014 foreach ($fix_param as $p)
3015 {
3016 $k = $p["param"];
3017 $v = $p["value"];
3018 $a_str = str_replace("<$t $k=\"$v\">",
3019 "&lt;"."$t $k=\"$v\""."&gt;", $a_str);
3020 }
3021 }
3022
3023 return $a_str;
3024 }
3025
3026 public static function unmaskTag($a_str, $t, $fix_param = "")
3027 {
3028 $a_str = str_replace("&lt;".$t."&gt;", "<".$t.">", $a_str);
3029 $a_str = str_replace("&lt;/".$t."&gt;", "</".$t.">", $a_str);
3030
3031 if (is_array($fix_param))
3032 {
3033 foreach ($fix_param as $p)
3034 {
3035 $k = $p["param"];
3036 $v = $p["value"];
3037 $a_str = str_replace("&lt;$t $k=\"$v\"&gt;",
3038 "<"."$t $k=\"$v\"".">", $a_str);
3039 }
3040 }
3041 return $a_str;
3042 }
3043
3044 public static function secureLink($a_str)
3045 {
3046 $a_str = str_ireplace("javascript", "jvscrpt", $a_str);
3047 $a_str = str_ireplace(array("%00", "%0a", "%0d", "%1a", "&#00;", "&#x00;",
3048 "&#0;", "&#x0;", "&#x0a;", "&#x0d;", "&#10;", "&#13;"), "-", $a_str);
3049 return $a_str;
3050 }
3051
3065 public static function stripScriptHTML($a_str, $a_allow = "", $a_rm_js = true)
3066 {
3067 //$a_str = strip_tags($a_str, $a_allow);
3068
3069 $negativestr = "a,abbr,acronym,address,applet,area,base,basefont,".
3070 "big,blockquote,body,br,button,caption,center,cite,code,col,".
3071 "colgroup,dd,del,dfn,dir,div,dl,dt,em,fieldset,font,form,frame,".
3072 "frameset,h1,h2,h3,h4,h5,h6,head,hr,html,i,iframe,img,input,ins,isindex,kbd,".
3073 "label,legend,li,link,map,menu,meta,noframes,noscript,object,ol,".
3074 "optgroup,option,p,param,q,s,samp,script,select,small,span,".
3075 "strike,strong,style,sub,sup,table,tbody,td,textarea,tfoot,th,thead,".
3076 "title,tr,tt,u,ul,var";
3077 $a_allow = strtolower ($a_allow);
3078 $negatives = explode(",",$negativestr);
3079 $outer_old_str = "";
3080 while($outer_old_str != $a_str)
3081 {
3082 $outer_old_str = $a_str;
3083 foreach ($negatives as $item)
3084 {
3085 $pos = strpos($a_allow, "<$item>");
3086
3087 // remove complete tag, if not allowed
3088 if ($pos === false)
3089 {
3090 $old_str = "";
3091 while($old_str != $a_str)
3092 {
3093 $old_str = $a_str;
3094 $a_str = preg_replace("/<\/?\s*$item(\/?)\s*>/i", "", $a_str);
3095 $a_str = preg_replace("/<\/?\s*$item(\/?)\s+([^>]*)>/i", "", $a_str);
3096 }
3097 }
3098 }
3099 }
3100
3101 if ($a_rm_js)
3102 {
3103 // remove all attributes if an "on..." attribute is given
3104 $a_str = preg_replace("/<\s*\w*(\/?)(\s+[^>]*)?(\s+on[^>]*)>/i", "", $a_str);
3105
3106 // remove all attributes if a "javascript" is within tag
3107 $a_str = preg_replace("/<\s*\w*(\/?)\s+[^>]*javascript[^>]*>/i", "", $a_str);
3108
3109 // remove all attributes if an "expression" is within tag
3110 // (IE allows something like <b style='width:expression(alert(1))'>test</b>)
3111 $a_str = preg_replace("/<\s*\w*(\/?)\s+[^>]*expression[^>]*>/i", "", $a_str);
3112 }
3113
3114 return $a_str;
3115 }
3116
3128 public static function prepareFormOutput($a_str, $a_strip = false)
3129 {
3130 if($a_strip)
3131 {
3132 $a_str = ilUtil::stripSlashes($a_str);
3133 }
3134 $a_str = htmlspecialchars($a_str);
3135 // Added replacement of curly brackets to prevent
3136 // problems with PEAR templates, because {xyz} will
3137 // be removed as unused template variable
3138 $a_str = str_replace("{", "&#123;", $a_str);
3139 $a_str = str_replace("}", "&#125;", $a_str);
3140 // needed for LaTeX conversion \\ in LaTeX is a line break
3141 // but without this replacement, php changes \\ to \
3142 $a_str = str_replace("\\", "&#92;", $a_str);
3143 return $a_str;
3144 }
3145
3152 function secureUrl($url)
3153 {
3154 // check if url is valid (absolute or relative)
3155 if (filter_var($url, FILTER_VALIDATE_URL) === false &&
3156 filter_var("http://".$url, FILTER_VALIDATE_URL) === false &&
3157 filter_var("http:".$url, FILTER_VALIDATE_URL) === false &&
3158 filter_var("http://de.de".$url, FILTER_VALIDATE_URL) === false &&
3159 filter_var("http://de.de/".$url, FILTER_VALIDATE_URL) === false)
3160 {
3161 return "";
3162 }
3163 if (trim(strtolower(parse_url($url, PHP_URL_SCHEME))) == "javascript")
3164 {
3165 return "";
3166 }
3167 $url = htmlspecialchars($url, ENT_QUOTES);
3168 return $url;
3169 }
3170
3171
3172
3182 public static function prepareDBString($a_str)
3183 {
3184 return addslashes($a_str);
3185 }
3186
3187
3196 public static function removeItemFromDesktops($a_id)
3197 {
3199 }
3200
3201
3211 public static function extractParameterString($a_parstr)
3212 {
3213 // parse parameters in array
3214 $par = array();
3215 $ok=true;
3216 while(($spos=strpos($a_parstr,"=")) && $ok)
3217 {
3218 // extract parameter
3219 $cpar = substr($a_parstr,0,$spos);
3220 $a_parstr = substr($a_parstr,$spos,strlen($a_parstr)-$spos);
3221 while(substr($cpar,0,1)=="," ||substr($cpar,0,1)==" " || substr($cpar,0,1)==chr(13) || substr($cpar,0,1)==chr(10))
3222 $cpar = substr($cpar,1,strlen($cpar)-1);
3223 while(substr($cpar,strlen($cpar)-1,1)==" " || substr($cpar,strlen($cpar)-1,1)==chr(13) || substr($cpar,strlen($cpar)-1,1)==chr(10))
3224 $cpar = substr($cpar,0,strlen($cpar)-1);
3225
3226 // parameter name should only
3227 $cpar_old = "";
3228 while($cpar != $cpar_old)
3229 {
3230 $cpar_old = $cpar;
3231 $cpar = eregi_replace("[^a-zA-Z0-9_]", "", $cpar);
3232 }
3233
3234 // extract value
3235 if ($cpar != "")
3236 {
3237 if($spos=strpos($a_parstr,"\""))
3238 {
3239 $a_parstr = substr($a_parstr,$spos+1,strlen($a_parstr)-$spos);
3240 $spos=strpos($a_parstr,"\"");
3241 if(is_int($spos))
3242 {
3243 $cval = substr($a_parstr,0,$spos);
3244 $par[$cpar]=$cval;
3245 $a_parstr = substr($a_parstr,$spos+1,strlen($a_parstr)-$spos-1);
3246 }
3247 else
3248 $ok=false;
3249 }
3250 else
3251 $ok=false;
3252 }
3253 }
3254
3255 if($ok) return $par; else return false;
3256 }
3257
3258 public static function assembleParameterString($a_par_arr)
3259 {
3260 if (is_array($a_par_arr))
3261 {
3262 $target_arr = array();
3263 foreach ($a_par_arr as $par => $val)
3264 {
3265 $target_arr[] = "$par=\"$val\"";
3266 }
3267 $target_str = implode(", ", $target_arr);
3268 }
3269
3270 return $target_str;
3271 }
3272
3279 public static function dumpString($a_str)
3280 {
3281 $ret = $a_str.": ";
3282 for($i=0; $i<strlen($a_str); $i++)
3283 {
3284 $ret.= ord(substr($a_str,$i,1))." ";
3285 }
3286 return $ret;
3287 }
3288
3289
3296 public static function yn2tf($a_yn)
3297 {
3298 if(strtolower($a_yn) == "y")
3299 {
3300 return true;
3301 }
3302 else
3303 {
3304 return false;
3305 }
3306 }
3307
3314 public static function tf2yn($a_tf)
3315 {
3316 if($a_tf)
3317 {
3318 return "y";
3319 }
3320 else
3321 {
3322 return "n";
3323 }
3324 }
3325
3336 public static function sort_func ($a, $b)
3337 {
3338 global $array_sortby,$array_sortorder;
3339
3340 if(!isset($array_sortby))
3341 {
3342 // occured in: setup -> new client -> install languages -> sorting of languages
3343 $array_sortby = 0;
3344 }
3345
3346 // this comparison should give optimal results if
3347 // locale is provided and mb string functions are supported
3348 if ($array_sortorder == "asc")
3349 {
3350 return ilStr::strCmp($a[$array_sortby], $b[$array_sortby]);
3351 }
3352
3353 if ($array_sortorder == "desc")
3354 {
3355 return !ilStr::strCmp($a[$array_sortby], $b[$array_sortby]);
3356 return strcoll(ilStr::strToUpper($b[$array_sortby]), ilStr::strToUpper($a[$array_sortby]));
3357 }
3358 }
3359
3370 public static function sort_func_numeric ($a, $b)
3371 {
3372 global $array_sortby,$array_sortorder;
3373
3374 if ($array_sortorder == "asc")
3375 {
3376 return $a["$array_sortby"] > $b["$array_sortby"];
3377 }
3378
3379 if ($array_sortorder == "desc")
3380 {
3381 return $a["$array_sortby"] < $b["$array_sortby"];
3382 }
3383 }
3396 public static function sortArray($array,$a_array_sortby,$a_array_sortorder = 0,$a_numeric = false,
3397 $a_keep_keys = false)
3398 {
3399 include_once("./Services/Utilities/classes/class.ilStr.php");
3400
3401 // BEGIN WebDAV: Provide a 'stable' sort algorithm
3402 if (! $a_keep_keys) {
3403 return self::stableSortArray($array,$a_array_sortby,$a_array_sortorder,$a_numeric,$a_keep_keys);
3404 }
3405 // END WebDAV Provide a 'stable' sort algorithm
3406
3407 global $array_sortby,$array_sortorder;
3408
3409 $array_sortby = $a_array_sortby;
3410
3411 if ($a_array_sortorder == "desc")
3412 {
3413 $array_sortorder = "desc";
3414 }
3415 else
3416 {
3417 $array_sortorder = "asc";
3418 }
3419 if($a_numeric)
3420 {
3421 if ($a_keep_keys)
3422 {
3423 uasort($array, array("ilUtil", "sort_func_numeric"));
3424 }
3425 else
3426 {
3427 usort($array, array("ilUtil", "sort_func_numeric"));
3428 }
3429 }
3430 else
3431 {
3432 if ($a_keep_keys)
3433 {
3434 uasort($array, array("ilUtil", "sort_func"));
3435 }
3436 else
3437 {
3438 usort($array, array("ilUtil", "sort_func"));
3439 }
3440 }
3441 //usort($array,"ilUtil::sort_func");
3442
3443 return $array;
3444 }
3445 // BEGIN WebDAV: Provide a 'stable' sort algorithm
3460 public static function stableSortArray($array,$a_array_sortby,$a_array_sortorder = 0,$a_numeric = false)
3461 {
3462 global $array_sortby,$array_sortorder;
3463
3464 $array_sortby = $a_array_sortby;
3465
3466 if ($a_array_sortorder == "desc")
3467 {
3468 $array_sortorder = "desc";
3469 }
3470 else
3471 {
3472 $array_sortorder = "asc";
3473 }
3474
3475 // Create a copy of the array values for sorting
3476 $sort_array = array_values($array);
3477
3478 if($a_numeric)
3479 {
3480 ilUtil::mergesort($sort_array, array("ilUtil", "sort_func_numeric"));
3481 }
3482 else
3483 {
3484 ilUtil::mergesort($sort_array, array("ilUtil", "sort_func"));
3485 }
3486
3487 return $sort_array;
3488 }
3489 public static function mergesort(&$array, $cmp_function = 'strcmp') {
3490 // Arrays of size < 2 require no action.
3491 if (count($array) < 2) return;
3492
3493 // Split the array in half
3494 $halfway = count($array) / 2;
3495 $array1 = array_slice($array, 0, $halfway);
3496 $array2 = array_slice($array, $halfway);
3497
3498 // Recurse to sort the two halves
3499 ilUtil::mergesort($array1, $cmp_function);
3500 ilUtil::mergesort($array2, $cmp_function);
3501
3502 // If all of $array1 is <= all of $array2, just append them.
3503 if (call_user_func($cmp_function, end($array1), $array2[0]) < 1) {
3504 $array = array_merge($array1, $array2);
3505 return;
3506 }
3507
3508 // Merge the two sorted arrays into a single sorted array
3509 $array = array();
3510 $ptr1 = $ptr2 = 0;
3511 while ($ptr1 < count($array1) && $ptr2 < count($array2)) {
3512 if (call_user_func($cmp_function, $array1[$ptr1], $array2[$ptr2]) < 1) {
3513 $array[] = $array1[$ptr1++];
3514 }
3515 else {
3516 $array[] = $array2[$ptr2++];
3517 }
3518 }
3519
3520 // Merge the remainder
3521 while ($ptr1 < count($array1)) $array[] = $array1[$ptr1++];
3522 while ($ptr2 < count($array2)) $array[] = $array2[$ptr2++];
3523
3524 return;
3525 }
3526 // END WebDAV: Provide a 'stable' sort algorithm
3527
3539 public static function unique_multi_array($array, $sub_key)
3540 {
3541 $target = array();
3542 $existing_sub_key_values = array();
3543
3544 foreach ($array as $key=>$sub_array)
3545 {
3546 if (!in_array($sub_array[$sub_key], $existing_sub_key_values))
3547 {
3548 $existing_sub_key_values[] = $sub_array[$sub_key];
3549 $target[$key] = $sub_array;
3550 }
3551 }
3552
3553 return $target;
3554 }
3555
3556
3566 public static function getGDSupportedImageType($a_desired_type)
3567 {
3568 $a_desired_type = strtolower($a_desired_type);
3569 // get supported Image Types
3570 $im_types = ImageTypes();
3571
3572 switch($a_desired_type)
3573 {
3574 case "jpg":
3575 case "jpeg":
3576 if ($im_types & IMG_JPG) return "jpg";
3577 if ($im_types & IMG_GIF) return "gif";
3578 if ($im_types & IMG_PNG) return "png";
3579 break;
3580
3581 case "gif":
3582 if ($im_types & IMG_GIF) return "gif";
3583 if ($im_types & IMG_JPG) return "jpg";
3584 if ($im_types & IMG_PNG) return "png";
3585 break;
3586
3587 case "png":
3588 if ($im_types & IMG_PNG) return "png";
3589 if ($im_types & IMG_JPG) return "jpg";
3590 if ($im_types & IMG_GIF) return "gif";
3591 break;
3592
3593 case "svg":
3594 if ($im_types & IMG_PNG) return "png";
3595 if ($im_types & IMG_JPG) return "jpg";
3596 if ($im_types & IMG_GIF) return "gif";
3597 break;
3598 }
3599
3600 return "";
3601 }
3602
3612 public static function deducibleSize($a_mime)
3613 {
3614 if (($a_mime == "image/gif") || ($a_mime == "image/jpeg") ||
3615 ($a_mime == "image/png") || ($a_mime == "application/x-shockwave-flash") ||
3616 ($a_mime == "image/tiff") || ($a_mime == "image/x-ms-bmp") ||
3617 ($a_mime == "image/psd") || ($a_mime == "image/iff"))
3618 {
3619 return true;
3620 }
3621 else
3622 {
3623 return false;
3624 }
3625 }
3626
3627
3635 public static function redirect($a_script)
3636 {
3637 global $log, $PHP_SELF;
3638
3639//echo "<br>".$a_script;
3640 if (!is_int(strpos($a_script, "://")))
3641 {
3642 if (substr($a_script, 0, 1) != "/" && defined("ILIAS_HTTP_PATH"))
3643 {
3644 if (is_int(strpos($_SERVER["PHP_SELF"], "/setup/")))
3645 {
3646 $a_script = "setup/".$a_script;
3647 }
3648 $a_script = ILIAS_HTTP_PATH."/".$a_script;
3649 }
3650 }
3651//echo "<br>".$a_script; exit;
3652
3653 // include the user interface hook
3654 global $ilPluginAdmin;
3655 if (is_object($ilPluginAdmin))
3656 {
3657 $pl_names = $ilPluginAdmin->getActivePluginsForSlot(IL_COMP_SERVICE, "UIComponent", "uihk");
3658 foreach ($pl_names as $pl)
3659 {
3660 $ui_plugin = ilPluginAdmin::getPluginObject(IL_COMP_SERVICE, "UIComponent", "uihk", $pl);
3661 $gui_class = $ui_plugin->getUIClassInstance();
3662 $resp = $gui_class->getHTML("Services/Utilities", "redirect", array("html" => $a_script));
3663 if ($resp["mode"] != ilUIHookPluginGUI::KEEP)
3664 {
3665 $a_script = $gui_class->modifyHTML($a_script, $resp);
3666 }
3667 }
3668 }
3669
3670 header("Location: ".$a_script);
3671 exit();
3672 }
3673
3682 public static function insertInstIntoID($a_value)
3683 {
3684 if (substr($a_value, 0, 4) == "il__")
3685 {
3686 $a_value = "il_".IL_INST_ID."_".substr($a_value, 4, strlen($a_value) - 4);
3687 }
3688
3689 return $a_value;
3690 }
3691
3702 public static function groupNameExists($a_group_name,$a_id = 0)
3703 {
3704 global $ilDB,$ilErr;
3705
3706 if (empty($a_group_name))
3707 {
3708 $message = __METHOD__.": No groupname given!";
3709 $ilErr->raiseError($message,$ilErr->WARNING);
3710 }
3711
3712 $clause = ($a_id) ? " AND obj_id != ".$ilDB->quote($a_id)." " : "";
3713
3714 $q = "SELECT obj_id FROM object_data ".
3715 "WHERE title = ".$ilDB->quote($a_group_name, "text")." ".
3716 "AND type = ".$ilDB->quote("grp", "text").
3717 $clause;
3718
3719 $r = $ilDB->query($q);
3720
3721 if ($r->numRows())
3722 {
3723 return true;
3724 }
3725 else
3726 {
3727 return false;
3728 }
3729 }
3730
3737 public static function getMemString()
3738 {
3739 $my_pid = getmypid();
3740 return ("MEMORY USAGE (% KB PID ): ".`ps -eo%mem,rss,pid | grep $my_pid`);
3741 }
3742
3749 public static function isWindows()
3750 {
3751 if (strtolower(substr(php_uname(), 0, 3)) == "win")
3752 {
3753 return true;
3754 }
3755 return false;
3756 }
3757
3758
3759 public static function escapeShellArg($a_arg)
3760 {
3761 setlocale(LC_CTYPE, "UTF8", "en_US.UTF-8"); // fix for PHP escapeshellcmd bug. See: http://bugs.php.net/bug.php?id=45132
3762 // see also ilias bug 5630
3763 return escapeshellarg($a_arg);
3764 }
3765
3775 public static function escapeShellCmd($a_arg)
3776 {
3777 if(ini_get('safe_mode') == 1)
3778 {
3779 return $a_arg;
3780 }
3781 setlocale(LC_CTYPE, "UTF8", "en_US.UTF-8"); // fix for PHP escapeshellcmd bug. See: http://bugs.php.net/bug.php?id=45132
3782 return escapeshellcmd($a_arg);
3783 }
3784
3794 public static function execQuoted($cmd, $args = NULL)
3795 {
3796 global $ilLog;
3797
3798 if(ilUtil::isWindows() && strpos($cmd, " ") !== false && substr($cmd, 0, 1) !== '"')
3799 {
3800 // cmd won't work without quotes
3801 $cmd = '"'.$cmd.'"';
3802 if($args)
3803 {
3804 // args are also quoted, workaround is to quote the whole command AGAIN
3805 // was fixed in php 5.2 (see php bug #25361)
3806 if (version_compare(phpversion(), "5.2", "<") && strpos($args, '"') !== false)
3807 {
3808 $cmd = '"'.$cmd." ".$args.'"';
3809 }
3810 // args are not quoted or php is fixed, just append
3811 else
3812 {
3813 $cmd .= " ".$args;
3814 }
3815 }
3816 }
3817 // nothing todo, just append args
3818 else if($args)
3819 {
3820 $cmd .= " ".$args;
3821 }
3822//ilUtil::printBacktrace(5);
3823//echo "<br>".$cmd; exit;
3824 exec($cmd, $arr);
3825// $ilLog->write("ilUtil::execQuoted: ".$cmd.".");
3826 return $arr;
3827 }
3828
3851 public static function excelTime($year = "", $month = "", $day = "", $hour = "", $minute = "", $second = "")
3852 {
3853 $starting_time = mktime(0, 0, 0, 1, 2, 1970);
3854 if (strcmp("$year$month$day$hour$minute$second", "") == 0)
3855 {
3856 $target_time = time();
3857 }
3858 else
3859 {
3860 if ($year < 1970)
3861 {
3862 return 0;
3863 }
3864 }
3865 $target_time = mktime($hour, $minute, $second, $month, $day, $year);
3866 $difference = $target_time - $starting_time;
3867 $days = (($difference - ($difference % 86400)) / 86400);
3868 $difference = $difference - ($days * 86400) + 3600;
3869
3870 // #15343 - using a global locale leads to , instead of . for (implicit) floats
3871 return str_replace(",", ".", ($days + 25570 + ($difference / 86400)));
3872 }
3873
3880 public static function renameExecutables($a_dir)
3881 {
3882 $def_arr = explode(",", SUFFIX_REPL_DEFAULT);
3883 foreach ($def_arr as $def)
3884 {
3885 ilUtil::rRenameSuffix($a_dir, trim($def), "sec");
3886 }
3887
3888 $def_arr = explode(",", SUFFIX_REPL_ADDITIONAL);
3889 foreach ($def_arr as $def)
3890 {
3891 ilUtil::rRenameSuffix($a_dir, trim($def), "sec");
3892 }
3893 }
3894
3907 public static function rRenameSuffix ($a_dir, $a_old_suffix, $a_new_suffix)
3908 {
3909 if ($a_dir == "/" || $a_dir == "" || is_int(strpos($a_dir, ".."))
3910 || trim($a_old_suffix) == "")
3911 {
3912 return false;
3913 }
3914
3915 // check if argument is directory
3916 if (!@is_dir($a_dir))
3917 {
3918 return false;
3919 }
3920
3921 // read a_dir
3922 $dir = opendir($a_dir);
3923
3924 while($file = readdir($dir))
3925 {
3926 if ($file != "." and
3927 $file != "..")
3928 {
3929 // directories
3930 if (@is_dir($a_dir."/".$file))
3931 {
3932 ilUtil::rRenameSuffix($a_dir."/".$file, $a_old_suffix, $a_new_suffix);
3933 }
3934
3935 // files
3936 if (@is_file($a_dir."/".$file))
3937 {
3938 // first check for files with trailing dot
3939 if(strrpos($file,'.') == (strlen($file) - 1))
3940 {
3941 rename($a_dir.'/'.$file,substr($a_dir.'/'.$file,0,-1));
3942 $file = substr($file,0,-1);
3943 }
3944
3945 $path_info = pathinfo($a_dir."/".$file);
3946
3947 if (strtolower($path_info["extension"]) ==
3948 strtolower($a_old_suffix))
3949 {
3950 $pos = strrpos($a_dir."/".$file, ".");
3951 $new_name = substr($a_dir."/".$file, 0, $pos).".".$a_new_suffix;
3952 rename($a_dir."/".$file, $new_name);
3953 }
3954 }
3955 }
3956 }
3957 return true;
3958 }
3959
3960 public static function isAPICall () {
3961 return strpos($_SERVER["SCRIPT_FILENAME"],"api") !== false ||
3962 strpos($_SERVER["SCRIPT_FILENAME"],"dummy") !== false;
3963 }
3964
3965 public static function KT_replaceParam($qstring, $paramName, $paramValue) {
3966 if (preg_match("/&" . $paramName . "=/", $qstring)) {
3967 return preg_replace("/&" . $paramName . "=[^&]+/", "&" . $paramName . "=" . urlencode($paramValue), $qstring);
3968 } else {
3969 return $qstring . "&" . $paramName . "=" . urlencode($paramValue);
3970 }
3971 }
3972
3973 public static function replaceUrlParameterString ($url, $parametersArray) {
3974
3975 foreach ($parametersArray as $paramName => $paramValue ) {
3976 $url = ilUtil::KT_replaceParam($url, $paramName, $paramValue);
3977 }
3978 return $url;
3979 }
3980
3987 public static function generatePasswords ($a_number)
3988 {
3989 $ret = array();
3990 srand((double) microtime()*1000000);
3991
3992 include_once('./Services/PrivacySecurity/classes/class.ilSecuritySettings.php');
3994
3995 for ($i=1; $i<=$a_number; $i++)
3996 {
3997 $min = ($security->getPasswordMinLength() > 0)
3998 ? $security->getPasswordMinLength()
3999 : 6;
4000 $max = ($security->getPasswordMaxLength() > 0)
4001 ? $security->getPasswordMaxLength()
4002 : 10;
4003 if ($min > $max)
4004 {
4005 $max = $max + 1;
4006 }
4007 $length = rand($min,$max);
4008 $next = rand(1,2);
4009 $vowels = "aeiou";
4010 $vowels_uc = strtoupper($vowels);
4011 $consonants = "bcdfghjklmnpqrstvwxyz";
4012 $consonants_uc = strtoupper($consonants);
4013 $numbers = "1234567890";
4014 $special = "_.+?#-*@!$%~";
4015 $pw = "";
4016
4017 if($security->getPasswordNumberOfUppercaseChars() > 0)
4018 {
4019 for($j = 0; $j < $security->getPasswordNumberOfUppercaseChars(); $j++)
4020 {
4021 switch ($next)
4022 {
4023 case 1:
4024 $pw.= $consonants_uc[rand(0, strlen($consonants_uc) - 1)];
4025 $next = 2;
4026 break;
4027
4028 case 2:
4029 $pw.= $vowels_uc[rand(0, strlen($vowels_uc) - 1)];
4030 $next = 1;
4031 break;
4032 }
4033 }
4034 }
4035
4036 if($security->isPasswordCharsAndNumbersEnabled())
4037 {
4038 $pw.= $numbers[rand(0, strlen($numbers) - 1)];
4039 }
4040
4041 if($security->isPasswordSpecialCharsEnabled())
4042 {
4043 $pw.= $special[rand(0, strlen($special) - 1)];
4044 }
4045
4046 $num_lcase_chars = max($security->getPasswordNumberOfLowercaseChars(), $length - strlen($pw));
4047 for($j = 0; $j < $num_lcase_chars; $j++)
4048 {
4049 switch ($next)
4050 {
4051 case 1:
4052 $pw.= $consonants[rand(0, strlen($consonants) - 1)];
4053 $next = 2;
4054 break;
4055
4056 case 2:
4057 $pw.= $vowels[rand(0, strlen($vowels) - 1)];
4058 $next = 1;
4059 break;
4060 }
4061 }
4062
4063 $pw = str_shuffle($pw);
4064
4065 $ret[] = $pw;
4066 }
4067 return $ret;
4068 }
4069
4070 public static function removeTrailingPathSeparators($path)
4071 {
4072 $path = preg_replace("/[\/\\\]+$/", "", $path);
4073 return $path;
4074 }
4075
4086 public static function array_php2js($data)
4087 {
4088 if (empty($data))
4089 {
4090 $data = array();
4091 }
4092
4093 foreach($data as $k=>$datum)
4094 {
4095 if(is_null($datum)) $data[$k] = 'null';
4096 if(is_string($datum)) $data[$k] = "'" . $datum . "'";
4097 if(is_array($datum)) $data[$k] = array_php2js($datum);
4098 }
4099
4100 return "[" . implode(', ', $data) . "]";
4101 }
4102
4109 public static function virusHandling($a_file, $a_orig_name = "", $a_clean = true)
4110 {
4111 global $lng;
4112
4113 if (IL_VIRUS_SCANNER != "None")
4114 {
4115 require_once("./Services/VirusScanner/classes/class.ilVirusScannerFactory.php");
4117 if (($vs_txt = $vs->scanFile($a_file, $a_orig_name)) != "")
4118 {
4119 if ($a_clean && (IL_VIRUS_CLEAN_COMMAND != ""))
4120 {
4121 $clean_txt = $vs->cleanFile($a_file, $a_orig_name);
4122 if ($vs->fileCleaned())
4123 {
4124 $vs_txt.= "<br />".$lng->txt("cleaned_file").
4125 "<br />".$clean_txt;
4126 $vs_txt.= "<br />".$lng->txt("repeat_scan");
4127 if (($vs2_txt = $vs->scanFile($a_file, $a_orig_name)) != "")
4128 {
4129 return array(false, nl2br($vs_txt)."<br />".$lng->txt("repeat_scan_failed").
4130 "<br />".nl2br($vs2_txt));
4131 }
4132 else
4133 {
4134 return array(true, nl2br($vs_txt)."<br />".$lng->txt("repeat_scan_succeded"));
4135 }
4136 }
4137 else
4138 {
4139 return array(false, nl2br($vs_txt)."<br />".$lng->txt("cleaning_failed"));
4140 }
4141 }
4142 else
4143 {
4144 return array(false, nl2br($vs_txt));
4145 }
4146 }
4147 }
4148
4149 return array(true,"");
4150 }
4151
4152
4158 public static function moveUploadedFile($a_file, $a_name, $a_target, $a_raise_errors = true,
4159 $a_mode = "move_uploaded")
4160 {
4161 global $lng, $ilias;
4162
4163 if (!is_file($a_file))
4164 {
4165 if ($a_raise_errors)
4166 {
4167 $ilias->raiseError($lng->txt("upload_error_file_not_found"), $ilias->error_obj->MESSAGE);
4168 }
4169 else
4170 {
4171 ilUtil::sendFailure($lng->txt("upload_error_file_not_found"), true);
4172 }
4173 return false;
4174 }
4175
4176 // virus handling
4177 $vir = ilUtil::virusHandling($a_file, $a_name);
4178 if (!$vir[0])
4179 {
4180 unlink($a_file);
4181 if ($a_raise_errors)
4182 {
4183 $ilias->raiseError($lng->txt("file_is_infected")."<br />".
4184 $vir[1],
4185 $ilias->error_obj->MESSAGE);
4186 }
4187 else
4188 {
4189 ilUtil::sendFailure($lng->txt("file_is_infected")."<br />".
4190 $vir[1], true);
4191 }
4192 return false;
4193 }
4194 else
4195 {
4196 if ($vir[1] != "")
4197 {
4198 ilUtil::sendInfo($vir[1], true);
4199 }
4200 include_once("./Services/Utilities/classes/class.ilFileUtils.php");
4201 $a_target = ilFileUtils::getValidFilename($a_target);
4202 switch ($a_mode)
4203 {
4204 case "rename":
4205 return rename($a_file, $a_target);
4206 break;
4207
4208 case "copy":
4209 return copy($a_file, $a_target);
4210 break;
4211
4212 default:
4213 return move_uploaded_file($a_file, $a_target);
4214 break;
4215 }
4216 }
4217 }
4218
4219
4226 public static function date_mysql2time($mysql_date_time) {
4227 list($datum, $uhrzeit) = explode (" ",$mysql_date_time);
4228 list($jahr, $monat, $tag) = explode("-", $datum);
4229 list($std, $min, $sec) = explode(":", $uhrzeit);
4230 return mktime ((int) $std, (int) $min, (int) $sec, (int) $monat, (int) $tag, (int) $jahr);
4231 }
4232
4239 public static function now()
4240 {
4241 return date("Y-m-d H:i:s");
4242 }
4243
4259 public static function &processCSVRow(&$row, $quoteAll = FALSE, $separator = ";", $outUTF8 = FALSE, $compatibleWithMSExcel = TRUE)
4260 {
4261 $resultarray = array();
4262 foreach ($row as $rowindex => $entry)
4263 {
4264 $surround = FALSE;
4265 if ($quoteAll)
4266 {
4267 $surround = TRUE;
4268 }
4269 if (strpos($entry, "\"") !== FALSE)
4270 {
4271 $entry = str_replace("\"", "\"\"", $entry);
4272 $surround = TRUE;
4273 }
4274 if (strpos($entry, $separator) !== FALSE)
4275 {
4276 $surround = TRUE;
4277 }
4278 if ($compatibleWithMSExcel)
4279 {
4280 // replace all CR LF with LF (for Excel for Windows compatibility
4281 $entry = str_replace(chr(13).chr(10), chr(10), $entry);
4282 }
4283 if ($surround)
4284 {
4285 if ($outUTF8)
4286 {
4287 $resultarray[$rowindex] = "\"" . $entry . "\"";
4288 }
4289 else
4290 {
4291 $resultarray[$rowindex] = utf8_decode("\"" . $entry . "\"");
4292 }
4293 }
4294 else
4295 {
4296 if ($outUTF8)
4297 {
4298 $resultarray[$rowindex] = $entry;
4299 }
4300 else
4301 {
4302 $resultarray[$rowindex] = utf8_decode($entry);
4303 }
4304 }
4305 }
4306 return $resultarray;
4307 }
4308
4309 // validates a domain name (example: www.ilias.de)
4310 public static function isDN($a_str)
4311 {
4312 return(preg_match("/^[a-z]+([a-z0-9-]*[a-z0-9]+)?(\.([a-z]+([a-z0-9-]*[a-z0-9]+)?)+)*$/",$a_str));
4313 }
4314
4315 // validates an IP address (example: 192.168.1.1)
4316 public static function isIPv4($a_str)
4317 {
4318 return(preg_match("/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.".
4319 "(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/",$a_str));
4320 }
4321
4322
4351 public static function _getObjectsByOperations($a_obj_type,$a_operation,$a_usr_id = 0,$limit = 0)
4352 {
4353 global $ilDB,$rbacreview,$ilAccess,$ilUser,$ilias,$tree;
4354
4355 if(!is_array($a_obj_type))
4356 {
4357 $where = "WHERE type = ".$ilDB->quote($a_obj_type, "text")." ";
4358 }
4359 else
4360 {
4361 $where = "WHERE ".$ilDB->in("type", $a_obj_type, false, "text")." ";
4362 }
4363
4364 // limit number of results default is search result limit
4365 if(!$limit)
4366 {
4367 $limit = $ilias->getSetting('search_max_hits',100);
4368 }
4369 if($limit == -1)
4370 {
4371 $limit = 10000;
4372 }
4373
4374 // default to logged in usr
4375 $a_usr_id = $a_usr_id ? $a_usr_id : $ilUser->getId();
4376 $a_roles = $rbacreview->assignedRoles($a_usr_id);
4377
4378 // Since no rbac_pa entries are available for the system role. This function returns !all! ref_ids in the case the user
4379 // is assigned to the system role
4380 if($rbacreview->isAssigned($a_usr_id,SYSTEM_ROLE_ID))
4381 {
4382 $query = "SELECT ref_id FROM object_reference obr LEFT JOIN object_data obd ON obr.obj_id = obd.obj_id ".
4383 "LEFT JOIN tree ON obr.ref_id = tree.child ".
4384 $where.
4385 "AND tree = 1";
4386
4387 $res = $ilDB->query($query);
4388 $counter = 0;
4389 while($row = $ilDB->fetchObject($res))
4390 {
4391 // Filter recovery folder
4392 if($tree->isGrandChild(RECOVERY_FOLDER_ID, $row->ref_id))
4393 {
4394 continue;
4395 }
4396
4397 if($counter++ >= $limit)
4398 {
4399 break;
4400 }
4401
4402 $ref_ids[] = $row->ref_id;
4403 }
4404 return $ref_ids ? $ref_ids : array();
4405 } // End Administrators
4406
4407 // Check ownership if it is not asked for edit_permission or a create permission
4408 if($a_operation == 'edit_permissions' or strpos($a_operation,'create') !== false)
4409 {
4410 $check_owner = ") ";
4411 }
4412 else
4413 {
4414 $check_owner = "OR owner = ".$ilDB->quote($a_usr_id, "integer").") ";
4415 }
4416
4417 $ops_ids = ilRbacReview::_getOperationIdsByName(array($a_operation));
4418 $ops_id = $ops_ids[0];
4419
4420 $and = "AND ((".$ilDB->in("rol_id", $a_roles, false, "integer")." ";
4421
4422 $query = "SELECT DISTINCT(obr.ref_id),obr.obj_id,type FROM object_reference obr ".
4423 "JOIN object_data obd ON obd.obj_id = obr.obj_id ".
4424 "LEFT JOIN rbac_pa ON obr.ref_id = rbac_pa.ref_id ".
4425 $where.
4426 $and.
4427 "AND (".$ilDB->like("ops_id", "text","%i:".$ops_id."%"). " ".
4428 "OR ".$ilDB->like("ops_id", "text", "%:\"".$ops_id."\";%").")) ".
4429 $check_owner;
4430
4431 $res = $ilDB->query($query);
4432 $counter = 0;
4433 while($row = $res->fetchRow(DB_FETCHMODE_OBJECT))
4434 {
4435 if($counter >= $limit)
4436 {
4437 break;
4438 }
4439
4440 // Filter objects in recovery folder
4441 if($tree->isGrandChild(RECOVERY_FOLDER_ID, $row->ref_id))
4442 {
4443 continue;
4444 }
4445
4446 // Check deleted, hierarchical access ...
4447 if($ilAccess->checkAccessOfUser($a_usr_id,$a_operation,'',$row->ref_id,$row->type,$row->obj_id))
4448 {
4449 $counter++;
4450 $ref_ids[] = $row->ref_id;
4451 }
4452 }
4453 return $ref_ids ? $ref_ids : array();
4454 }
4455
4456
4463 function includeMathjax($a_tpl = null)
4464 {
4465 global $tpl;
4466
4467 if ($a_tpl == null)
4468 {
4469 $a_tpl = $tpl;
4470 }
4471
4472 // - take care of html exports (-> see buildLatexImages)
4473 include_once "./Services/Administration/classes/class.ilSetting.php";
4474 $mathJaxSetting = new ilSetting("MathJax");
4475 $use_mathjax = $mathJaxSetting->get("enable");
4476 if ($use_mathjax)
4477 {
4478 $a_tpl->addJavaScript($mathJaxSetting->get("path_to_mathjax"));
4479 }
4480 }
4481
4482
4492 public static function insertLatexImages($a_text, $a_start = "\[tex\]", $a_end = "\[\/tex\]")
4493 {
4494 global $tpl, $lng, $ilUser;
4495
4496 $cgi = URL_TO_LATEX;
4497
4498 // - take care of html exports (-> see buildLatexImages)
4499 include_once "./Services/Administration/classes/class.ilSetting.php";
4500 $mathJaxSetting = new ilSetting("MathJax");
4501 $use_mathjax = $mathJaxSetting->get("enable");
4502 if ($use_mathjax)
4503 {
4504 $a_text = preg_replace("/\\\\([RZN])([^a-zA-Z]|<\/span>)/", "\\mathbb{"."$1"."}"."$2", $a_text);
4505 $tpl->addJavaScript($mathJaxSetting->get("path_to_mathjax"));
4506 }
4507
4508 // this is a fix for bug5362
4509 $cpos = 0;
4510 $o_start = $a_start;
4511 $o_end = $a_end;
4512 $a_start = str_replace("\\", "", $a_start);
4513 $a_end = str_replace("\\", "", $a_end);
4514
4515 while (is_int($spos = stripos($a_text, $a_start, $cpos))) // find next start
4516 {
4517 if (is_int ($epos = stripos($a_text, $a_end, $spos + 1)))
4518 {
4519 $tex = substr($a_text, $spos + strlen($a_start), $epos - $spos - strlen($a_start));
4520
4521 // replace, if tags do not go across div borders
4522 if (!is_int(strpos($tex, "</div>")))
4523 {
4524 if (!$use_mathjax)
4525 {
4526 $a_text = substr($a_text, 0, $spos).
4527 "<img alt=\"".htmlentities($tex)."\" src=\"".$cgi."?".
4528 rawurlencode(str_replace('&amp;', '&', str_replace('&gt;', '>', str_replace('&lt;', '<', $tex))))."\" ".
4529 " />".
4530 substr($a_text, $epos + strlen($a_end));
4531 }
4532 else
4533 {
4534 $tex = $a_start.$tex.$a_end;
4535
4536 switch ((int) $mathJaxSetting->get("limiter"))
4537 {
4538 case 1:
4539 $mj_start = "[tex]";
4540 $mj_end = "[/tex]";
4541 break;
4542
4543 case 2:
4544 $mj_start = '<span class="math">';
4545 $mj_end = '</span>';
4546 break;
4547
4548 default:
4549 $mj_start = "\‍(";
4550 $mj_end = "\‍)";
4551 break;
4552 }
4553
4554 $replacement =
4555 preg_replace('/' . $o_start . '(.*?)' . $o_end . '/ie',
4556 "'".$mj_start."' . preg_replace('/[\\\\\\\\\\]{2}/', '\\cr', str_replace('<', '&lt;', str_replace('<br/>', '', str_replace('<br />', '', str_replace('<br>', '', '$1'))))) . '".$mj_end."'", $tex);
4557 // added special handling for \\ -> \cr, < -> $lt; and removal of <br/> tags in jsMath expressions, H. Schottmüller, 2007-09-09
4558 $a_text = substr($a_text, 0, $spos).
4559 $replacement.
4560 substr($a_text, $epos + strlen($a_end));
4561 }
4562 }
4563 }
4564 $cpos = $spos + 1;
4565 }
4566
4567 $result_text = $a_text;
4568
4569 return $result_text;
4570 }
4571
4581 public static function buildLatexImages($a_text, $a_dir)
4582 {
4583 $result_text = $a_text;
4584
4585 $start = "\[tex\]";
4586 $end = "\[\/tex\]";
4587
4588 $cgi = URL_TO_LATEX;
4589
4590 if ($cgi != "")
4591 {
4592 while (preg_match('/' . $start . '(.*?)' . $end . '/ie', $result_text, $found))
4593 {
4594 $cnt = (int) $GLOBALS["teximgcnt"]++;
4595 // get image from cgi and write it to file
4596 $fpr = @fopen($cgi."?".rawurlencode($found[1]), "r");
4597 $lcnt = 0;
4598 if ($fpr)
4599 {
4600 while(!feof($fpr))
4601 {
4602 $buf = fread($fpr, 1024);
4603 if ($lcnt == 0)
4604 {
4605 if (is_int(strpos(strtoupper(substr($buf, 0, 5)), "GIF")))
4606 {
4607 $suffix = "gif";
4608 }
4609 else
4610 {
4611 $suffix = "png";
4612 }
4613 $fpw = fopen($a_dir."/teximg/img".$cnt.".".$suffix, "w");
4614 }
4615 $lcnt++;
4616 fwrite($fpw, $buf);
4617 }
4618 fclose($fpw);
4619 fclose($fpr);
4620 }
4621
4622 // replace tex-tag
4623 $img_str = "./teximg/img".$cnt.".".$suffix;
4624 $result_text = str_replace($found[0],
4625 '<img alt="'.$found[1].'" src="'.$img_str.'" />', $result_text);
4626 }
4627 }
4628
4629 return $result_text;
4630 }
4631
4640 public static function prepareTextareaOutput($txt_output, $prepare_for_latex_output = FALSE, $omitNl2BrWhenTextArea = false)
4641 {
4642 $result = $txt_output;
4643 $is_html = self::isHTML($result);
4644
4645 if ($prepare_for_latex_output)
4646 {
4647 $result = ilUtil::insertLatexImages($result, "<span class\=\"latex\">", "<\/span>");
4648 $result = ilUtil::insertLatexImages($result, "\[tex\]", "\[\/tex\]");
4649 }
4650
4651 // removed: did not work with magic_quotes_gpc = On
4652 if (!$is_html )
4653 {
4654 if(!$omitNl2BrWhenTextArea)
4655 {
4656 // if the string does not contain HTML code, replace the newlines with HTML line breaks
4657 $result = preg_replace("/[\n]/", "<br />", $result);
4658 }
4659 }
4660 else
4661 {
4662 // patch for problems with the <pre> tags in tinyMCE
4663 if (preg_match_all("/(<pre>.*?<\/pre>)/ims", $result, $matches))
4664 {
4665 foreach ($matches[0] as $found)
4666 {
4667 $replacement = "";
4668 if (strpos("\n", $found) === FALSE)
4669 {
4670 $replacement = "\n";
4671 }
4672 $removed = preg_replace("/<br\s*?\/>/ims", $replacement, $found);
4673 $result = str_replace($found, $removed, $result);
4674 }
4675 }
4676 }
4677 if ($prepare_for_latex_output)
4678 {
4679 // replace special characters to prevent problems with the ILIAS template system
4680 // eg. if someone uses {1} as an answer, nothing will be shown without the replacement
4681 $result = str_replace("{", "&#123;", $result);
4682 $result = str_replace("}", "&#125;", $result);
4683 $result = str_replace("\\", "&#92;", $result);
4684 }
4685
4686 return $result;
4687 }
4688
4697 public static function isHTML($a_text)
4698 {
4699 if( strlen(strip_tags($a_text)) < strlen($a_text) )
4700 {
4701 return true;
4702 }
4703
4704 return false;
4705 }
4706
4716 public static function period2String(ilDateTime $a_from, $a_to = null)
4717 {
4718 global $lng;
4719
4720 if (!$a_to)
4721 {
4722 $a_to = new ilDateTime(time(), IL_CAL_UNIX);
4723 }
4724
4725 $from = new DateTime($a_from->get(IL_CAL_DATETIME));
4726 $to = new DateTime($a_to->get(IL_CAL_DATETIME));
4727 $diff = $to->diff($from);
4728
4729 $periods = array();
4730 $periods["years"] = $diff->format("%y");
4731 $periods["months"] = $diff->format("%m");
4732 $periods["days"] = $diff->format("%d");
4733 $periods["hours"] = $diff->format("%h");
4734 $periods["minutes"] = $diff->format("%i");
4735 $periods["seconds"] = $diff->format("%s");
4736
4737 if (!array_sum($periods))
4738 {
4739 return;
4740 }
4741
4742 foreach ($periods as $key => $value)
4743 {
4744 if($value)
4745 {
4746 $segment_name = ($value > 1)
4747 ? $key
4748 : substr($key, 0, -1);
4749 $array[] = $value . ' ' . $lng->txt($segment_name);
4750 }
4751 }
4752
4753 $len = sizeof($array);
4754 if ($len > 3)
4755 {
4756 $array = array_slice($array, 0, (3-$len));
4757 }
4758
4759 return implode(', ', $array);
4760 }
4761
4762 public static function getFileSizeInfo()
4763 {
4764 $max_filesize = self::formatBytes(
4765 self::getUploadSizeLimitBytes()
4766 );
4767
4768 global $lng;
4769 /*
4770 // get the value for the maximal uploadable filesize from the php.ini (if available)
4771 $umf=get_cfg_var("upload_max_filesize");
4772 // get the value for the maximal post data from the php.ini (if available)
4773 $pms=get_cfg_var("post_max_size");
4774
4775 // use the smaller one as limit
4776 $max_filesize=min($umf, $pms);
4777 if (!$max_filesize) $max_filesize=max($umf, $pms);
4778 */
4779 return $lng->txt("file_notice")." $max_filesize.";
4780 }
4781
4782 public static function formatBytes($size, $decimals = 0)
4783 {
4784 $unit = array('', 'K', 'M', 'G', 'T', 'P');
4785
4786 for($i = 0, $maxUnits = count($unit); $size >= 1024 && $i <= $maxUnits; $i++)
4787 {
4788 $size /= 1024;
4789 }
4790
4791 return round($size, $decimals).$unit[$i];
4792 }
4793
4794 public static function getUploadSizeLimitBytes()
4795 {
4796 $uploadSizeLimitBytes = min(
4797 self::convertPhpIniSizeValueToBytes(ini_get('post_max_size')),
4798 self::convertPhpIniSizeValueToBytes(ini_get('upload_max_filesize'))
4799 );
4800
4801 return $uploadSizeLimitBytes;
4802 }
4803
4804 public static function convertPhpIniSizeValueToBytes($phpIniSizeValue)
4805 {
4806 if( is_numeric($phpIniSizeValue) )
4807 {
4808 return $phpIniSizeValue;
4809 }
4810
4811 $suffix = substr($phpIniSizeValue, -1);
4812 $value = substr($phpIniSizeValue, 0, -1);
4813
4814 switch( strtoupper($suffix) )
4815 {
4816 case 'P':
4817 $value *= 1024;
4818 case 'T':
4819 $value *= 1024;
4820 case 'G':
4821 $value *= 1024;
4822 case 'M':
4823 $value *= 1024;
4824 case 'K':
4825 $value *= 1024;
4826 break;
4827 }
4828
4829 return $value;
4830 }
4831
4840 public static function __extractRefId($role_title)
4841 {
4842
4843 $test_str = explode('_',$role_title);
4844
4845 if ($test_str[0] == 'il')
4846 {
4847 $test2 = (int) $test_str[3];
4848 return is_numeric ($test2) ? (int) $test2 : false;
4849 }
4850 return false;
4851 }
4852
4863 public static function __extractId($ilias_id, $inst_id)
4864 {
4865
4866 $test_str = explode('_',$ilias_id);
4867
4868 if ($test_str[0] == 'il' && $test_str[1] == $inst_id && count($test_str) == 4)
4869 {
4870 $test2 = (int) $test_str[3];
4871 return is_numeric ($test2) ? (int) $test2 : false;
4872 }
4873 return false;
4874 }
4875
4890 public static function _sortIds($a_ids,$a_table,$a_field,$a_id_name)
4891 {
4892 global $ilDB;
4893
4894 if(!$a_ids)
4895 {
4896 return array();
4897 }
4898
4899 // use database to sort user array
4900 $where = "WHERE ".$a_id_name." IN (";
4901 $where .= implode(",", ilUtil::quoteArray($a_ids));
4902 $where .= ") ";
4903
4904 $query = "SELECT ".$a_id_name." FROM ".$a_table." ".
4905 $where.
4906 "ORDER BY ".$a_field;
4907
4908 $res = $ilDB->query($query);
4909 while($row = $res->fetchRow(DB_FETCHMODE_OBJECT))
4910 {
4911 $ids[] = $row->$a_id_name;
4912 }
4913 return $ids ? $ids : array();
4914 }
4915
4925 public static function getMySQLTimestamp($a_ts)
4926 {
4927 global $ilDB;
4928
4929 return $a_ts;
4930 }
4931
4938 public static function quoteArray($a_array)
4939 {
4940 global $ilDB;
4941
4942
4943 if(!is_array($a_array) or !count($a_array))
4944 {
4945 return array("''");
4946 }
4947
4948 foreach($a_array as $k => $item)
4949 {
4950 $a_array[$k] = $ilDB->quote($item);
4951 }
4952
4953 return $a_array;
4954 }
4955
4964 public static function sendInfo($a_info = "",$a_keep = false)
4965 {
4966 global $tpl;
4967 $tpl->setMessage("info", $a_info, $a_keep);
4968 }
4969
4978 public static function sendFailure($a_info = "",$a_keep = false)
4979 {
4980 global $tpl;
4981
4982 if(is_object($tpl))
4983 {
4984 $tpl->setMessage("failure", $a_info, $a_keep);
4985 }
4986 }
4987
4994 public static function sendQuestion($a_info = "",$a_keep = false)
4995 {
4996 global $tpl;
4997 $tpl->setMessage("question", $a_info, $a_keep);
4998 }
4999
5008 public static function sendSuccess($a_info = "",$a_keep = false)
5009 {
5010 global $tpl;
5011 $tpl->setMessage("success", $a_info, $a_keep);
5012 }
5013
5014 public static function infoPanel($a_keep = true)
5015 {
5016 global $tpl,$ilias,$lng;
5017
5018 if (!empty($_SESSION["infopanel"]) and is_array($_SESSION["infopanel"]))
5019 {
5020 $tpl->addBlockFile("INFOPANEL", "infopanel", "tpl.infopanel.html",
5021 "Services/Utilities");
5022 $tpl->setCurrentBlock("infopanel");
5023
5024 if (!empty($_SESSION["infopanel"]["text"]))
5025 {
5026 $link = "<a href=\"".$dir.$_SESSION["infopanel"]["link"]."\" target=\"".
5027 ilFrameTargetInfo::_getFrame("MainContent").
5028 "\">";
5029 $link .= $lng->txt($_SESSION["infopanel"]["text"]);
5030 $link .= "</a>";
5031 }
5032
5033 // deactivated
5034 if (!empty($_SESSION["infopanel"]["img"]))
5035 {
5036 $link .= "<td><a href=\"".$_SESSION["infopanel"]["link"]."\" target=\"".
5037 ilFrameTargetInfo::_getFrame("MainContent").
5038 "\">";
5039 $link .= "<img src=\"".$ilias->tplPath.$ilias->account->prefs["skin"]."/images/".
5040 $_SESSION["infopanel"]["img"]."\" border=\"0\" vspace=\"0\"/>";
5041 $link .= "</a></td>";
5042 }
5043
5044 $tpl->setVariable("INFO_ICONS",$link);
5045 $tpl->parseCurrentBlock();
5046 }
5047
5048 //if (!$a_keep)
5049 //{
5050 ilSession::clear("infopanel");
5051 //}
5052 }
5053
5054
5063 public static function dirsize($directory)
5064 {
5065 $size = 0;
5066 if (!is_dir($directory))
5067 {
5068 // BEGIN DiskQuota Suppress PHP warning when attempting to determine
5069 // dirsize of non-existing directory
5070 $size = @filesize($directory);
5071 // END DiskQuota Suppress PHP warning.
5072 return ($size === false) ? -1 : $size;
5073 }
5074 if ($DIR = opendir($directory))
5075 {
5076 while (($dirfile = readdir($DIR)) !== false)
5077 {
5078 if (is_link($directory . DIRECTORY_SEPARATOR . $dirfile) || $dirfile == '.' || $dirfile == '..')
5079 continue;
5080 if (is_file($directory . DIRECTORY_SEPARATOR . $dirfile))
5081 $size += filesize($directory . DIRECTORY_SEPARATOR . $dirfile);
5082 else if (is_dir($directory . DIRECTORY_SEPARATOR . $dirfile))
5083 {
5084 // BEGIN DiskQuota: dirsize is not a global function anymore
5085 $dirSize = ilUtil::dirsize($directory . DIRECTORY_SEPARATOR . $dirfile);
5086 // END DiskQuota: dirsize is not a global function anymore
5087 if ($dirSize >= 0)
5088 $size += $dirSize;
5089 else return -1;
5090 }
5091 }
5092 closedir($DIR);
5093 }
5094 return $size;
5095 }
5096
5097 public static function randomhash()
5098 {
5099 return md5(rand(1,9999999) + str_replace(" ", "", (string) microtime()));
5100 }
5101
5102 public static function setCookie($a_cookie_name,$a_cookie_value = '', $a_also_set_super_global = true, $a_set_cookie_invalid = false)
5103 {
5104 /*
5105 if(!(bool)$a_set_cookie_invalid) $expire = IL_COOKIE_EXPIRE;
5106 else $expire = time() - (365*24*60*60);
5107 */
5108 // Temporary fix for feed.php
5109 if(!(bool)$a_set_cookie_invalid) $expire = 0;
5110 else $expire = time() - (365*24*60*60);
5111
5112 setcookie( $a_cookie_name, $a_cookie_value, $expire,
5113 IL_COOKIE_PATH, IL_COOKIE_DOMAIN, IL_COOKIE_SECURE, IL_COOKIE_HTTPONLY
5114 );
5115
5116 if((bool)$a_also_set_super_global) $_COOKIE[$a_cookie_name] = $a_cookie_value;
5117 }
5118
5119 public static function _sanitizeFilemame($a_filename)
5120 {
5121 return strip_tags(self::stripSlashes($a_filename));
5122 }
5123
5124 public static function _getHttpPath()
5125 {
5126 global $ilIliasIniFile;
5127
5128 if($_SERVER['SHELL'] || php_sapi_name() == 'cli' ||
5129 // fallback for windows systems, useful in crons
5130 (class_exists("ilContext") && !ilContext::usesHTTP()))
5131 {
5132 return $ilIliasIniFile->readVariable('server', 'http_path');
5133 }
5134 else
5135 {
5136 return ILIAS_HTTP_PATH;
5137 }
5138 }
5139
5145 public static function printBacktrace($a_limit = 0)
5146 {
5147 $bt = debug_backtrace();
5148 $cnt = 0;
5149 foreach ($bt as $t)
5150 {
5151 if ($cnt != 0 && ($a_limit == 0 || $cnt <= $a_limit))
5152 {
5153 echo "<br>".$t["file"].", ".$t["function"]." [".$t["line"]."]";
5154 }
5155 $cnt++;
5156 }
5157 echo "<br>";
5158 }
5159
5174 public static function parseImportId($a_import_id)
5175 {
5176 $exploded = explode('_',$a_import_id);
5177
5178 $parsed['orig'] = $a_import_id;
5179 if($exploded[0] == 'il')
5180 {
5181 $parsed['prefix'] = $exploded[0];
5182 }
5183 if(is_numeric($exploded[1]))
5184 {
5185 $parsed['inst_id'] = (int) $exploded[1];
5186 }
5187 $parsed['type'] = $exploded[2];
5188
5189 if(is_numeric($exploded[3]))
5190 {
5191 $parsed['id'] = (int) $exploded[3];
5192 }
5193 return $parsed;
5194 }
5195
5202 public static function unserializeSession($data)
5203 {
5204 $vars = preg_split(
5205 '/([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff^|]*)\|/',
5206 $data,
5207 -1,
5208 PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE
5209 );
5210
5211 $result = array();
5212
5213 for($i = 0; $vars[$i]; $i++)
5214 {
5215 $result[$vars[$i++]] = unserialize($vars[$i]);
5216 }
5217
5218 return $result;
5219 }
5220
5221
5235
5236 $fp = @fopen($file, 'rb');
5237
5238 $size = filesize($file); // File size
5239 $length = $size; // Content length
5240 $start = 0; // Start byte
5241 $end = $size - 1; // End byte
5242 // Now that we've gotten so far without errors we send the accept range header
5243 /* At the moment we only support single ranges.
5244 * Multiple ranges requires some more work to ensure it works correctly
5245 * and comply with the spesifications: http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.2
5246 *
5247 * Multirange support annouces itself with:
5248 * header('Accept-Ranges: bytes');
5249 *
5250 * Multirange content must be sent with multipart/byteranges mediatype,
5251 * (mediatype = mimetype)
5252 * as well as a boundry header to indicate the various chunks of data.
5253 */
5254 header("Accept-Ranges: 0-$length");
5255 // header('Accept-Ranges: bytes');
5256 // multipart/byteranges
5257 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.2
5258 if (isset($_SERVER['HTTP_RANGE'])) {
5259
5260 $c_start = $start;
5261 $c_end = $end;
5262 // Extract the range string
5263 list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
5264 // Make sure the client hasn't sent us a multibyte range
5265 if (strpos($range, ',') !== false) {
5266
5267 // (?) Shoud this be issued here, or should the first
5268 // range be used? Or should the header be ignored and
5269 // we output the whole content?
5270 header('HTTP/1.1 416 Requested Range Not Satisfiable');
5271 header("Content-Range: bytes $start-$end/$size");
5272 // (?) Echo some info to the client?
5273 exit;
5274 }
5275 // If the range starts with an '-' we start from the beginning
5276 // If not, we forward the file pointer
5277 // And make sure to get the end byte if spesified
5278 if ($range == '-') {
5279
5280 // The n-number of the last bytes is requested
5281 $c_start = $size - substr($range, 1);
5282 }
5283 else {
5284
5285 $range = explode('-', $range);
5286 $c_start = $range[0];
5287 $c_end = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size;
5288 }
5289 /* Check the range and make sure it's treated according to the specs.
5290 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
5291 */
5292 // End bytes can not be larger than $end.
5293 $c_end = ($c_end > $end) ? $end : $c_end;
5294 // Validate the requested range and return an error if it's not correct.
5295 if ($c_start > $c_end || $c_start > $size - 1 || $c_end >= $size) {
5296
5297 header('HTTP/1.1 416 Requested Range Not Satisfiable');
5298 header("Content-Range: bytes $start-$end/$size");
5299 // (?) Echo some info to the client?
5300 exit;
5301 }
5302 $start = $c_start;
5303 $end = $c_end;
5304 $length = $end - $start + 1; // Calculate new content length
5305 fseek($fp, $start);
5306 header('HTTP/1.1 206 Partial Content');
5307 }
5308 // Notify the client the byte range we'll be outputting
5309 header("Content-Range: bytes $start-$end/$size");
5310 header("Content-Length: $length");
5311
5312 // Start buffered download
5313 $buffer = 1024 * 8;
5314 while(!feof($fp) && ($p = ftell($fp)) <= $end) {
5315
5316 if ($p + $buffer > $end) {
5317
5318 // In case we're only outputtin a chunk, make sure we don't
5319 // read past the length
5320 $buffer = $end - $p + 1;
5321 }
5322 set_time_limit(0); // Reset time limit for big files
5323 echo fread($fp, $buffer);
5324 flush(); // Free up memory. Otherwise large files will trigger PHP's memory limit.
5325 }
5326
5327 fclose($fp);
5328
5329 }
5330
5331
5332} // END class.ilUtil
5333
5334
5335?>
$result
print $file
const PEAR_ERROR_RETURN
#+ ERROR constants
Definition: PEAR.php:31
const PEAR_ERROR_CALLBACK
Definition: PEAR.php:35
$size
Definition: RandomTest.php:79
global $tpl
Definition: ilias.php:8
$filename
Definition: buildRTE.php:89
$_SESSION["AccountId"]
setErrorHandling($mode=null, $options=null)
Sets how errors generated by this object should be handled.
Definition: PEAR.php:335
const IL_COMP_SERVICE
const DB_FETCHMODE_OBJECT
Definition: class.ilDB.php:11
const IL_CAL_UNIX
const IL_CAL_DATETIME
static usesHTTP()
Uses HTTP aka browser.
@classDescription Date and time handling
get($a_format, $a_format_str='', $a_tz='')
get formatted date
static getValidFilename($a_filename)
Get valid filename.
recursive_dirscan($dir, &$arr)
Recursively scans a given directory and writes path and filename into referenced array.
static _getFrame($a_class, $a_type='')
Get content frame name.
static getInstance()
Get https instance.
static _getAssociatedUsersOnline($a_user_id, $a_no_anonymous=false)
static _removeItemFromDesktops($a_id)
removes object from all user's desktops @access public
static _lookupObjId($a_id)
static _lookupTitle($a_id)
lookup object title
static _getIcon($a_obj_id="", $a_size="big", $a_type="", $a_offline=false)
Get icon for repository item.
static getPluginObject($a_ctype, $a_cname, $a_slot_id, $a_pname)
Get Plugin Object.
static _getOperationIdsByName($operations)
get ops_id's by name.
static _getInstance()
Get instance of ilSecuritySettings.
static clear($a_var)
Unset a value.
ILIAS Setting Class.
static strPos($a_haystack, $a_needle, $a_offset=NULL)
Definition: class.ilStr.php:34
static strCmp($a, $b)
Compare two strings.
static strToUpper($a_string)
static strLen($a_string)
Definition: class.ilStr.php:79
static subStr($a_str, $a_start, $a_length=NULL)
Definition: class.ilStr.php:15
static getCurrentMasterStyle()
get the current style
static getCurrentStyle()
get the current style
Util class various functions, usage as namespace.
static getPasswordValidChars($a_as_regex=true, $a_only_special_chars=false)
All valid chars for password.
static is_email($a_email)
This preg-based function checks whether an e-mail address is formally valid.
static CreateIsoFromFolder($a_dir, $a_file)
static getDataDir()
get data directory (outside webspace)
static moveUploadedFile($a_file, $a_name, $a_target, $a_raise_errors=true, $a_mode="move_uploaded")
move uploaded file
static getJSLocation($a_js_name, $a_js_location="", $add_version=FALSE)
get full javascript file name (path inclusive) of current user
static delDir($a_dir, $a_clean_only=false)
removes a dir and all its content (subdirs and files) recursively
static getMySQLTimestamp($a_ts)
Get MySQL timestamp in 4.1.x or higher format (yyyy-mm-dd hh:mm:ss) This function converts a timestam...
static assembleParameterString($a_par_arr)
static dumpString($a_str)
dumps ord values of every character of string $a_str
static appendUrlParameterString($a_url, $a_par, $xml_style=false)
append URL parameter string ("par1=value1&par2=value2...") to given URL string
isLogin($a_login)
static prepareDBString($a_str)
prepare a string for db writing (insert/update)
static getMemString()
get current memory usage as string
static _sanitizeFilemame($a_filename)
static formRadioButton($checked, $varname, $value, $onclick=null, $disabled=false)
??? @access public
static checkInput($vars)
???
static secureString($a_str, $a_strip_html=true, $a_allow="")
Remove unsecure tags.
static unmaskSecureTags($a_str, $allow_array)
static formCheckbox($checked, $varname, $value, $disabled=false)
??? @access public
static isConvertVersionAtLeast($a_version)
Compare convert version numbers.
static formDisabledRadioButton($checked, $varname, $value, $disabled)
??? @accesspublic @paramstring @paramstring @paramstring
static excelTime($year="", $month="", $day="", $hour="", $minute="", $second="")
Calculates a Microsoft Excel date/time value.
static formatBytes($size, $decimals=0)
static getUploadSizeLimitBytes()
static _sortIds($a_ids, $a_table, $a_field, $a_id_name)
Function that sorts ids by a given table field using WHERE IN E.g: __sort(array(6,...
static checkFormEmpty($emptyFields)
??? @access public
static convertPhpIniSizeValueToBytes($phpIniSizeValue)
static isHTML($a_text)
Checks if a given string contains HTML or not.
static getGDSupportedImageType($a_desired_type)
returns the best supported image type by this PHP build
static setCookie($a_cookie_name, $a_cookie_value='', $a_also_set_super_global=true, $a_set_cookie_invalid=false)
static stripOnlySlashes($a_str)
strip slashes if magic qoutes is enabled
static sendQuestion($a_info="", $a_keep=false)
Send Question to Screen.
static replaceUrlParameterString($url, $parametersArray)
static insertInstIntoID($a_value)
inserts installation id into ILIAS id
static __extractRefId($role_title)
extract ref id from role title, e.g.
static KT_replaceParam($qstring, $paramName, $paramValue)
static shortenText($a_str, $a_len, $a_dots=false, $a_next_blank=false, $a_keep_extension=false)
shorten a string to given length.
static isIPv4($a_str)
static tf2yn($a_tf)
convert true/false to "y"/"n"
static replaceLinkProperties($matches)
replaces target _blank with _self and the link text with the according object title.
static Linkbar($AScript, $AHits, $ALimit, $AOffset, $AParams=array(), $ALayout=array(), $prefix='')
Linkbar Diese Funktion erzeugt einen typischen Navigationsbalken mit "Previous"- und "Next"-Links und...
static parseImportId($a_import_id)
Parse an ilias import id Typically of type il_[IL_INST_ID]_[OBJ_TYPE]_[OBJ_ID] returns array( 'orig' ...
static prepareTextareaOutput($txt_output, $prepare_for_latex_output=FALSE, $omitNl2BrWhenTextArea=false)
Prepares a string for a text area output where latex code may be in it If the text is HTML-free,...
static sortArray($array, $a_array_sortby, $a_array_sortorder=0, $a_numeric=false, $a_keep_keys=false)
sortArray
static getJavaPath()
get full java path (dir + java command)
static escapeShellArg($a_arg)
static setPathStr($a_path)
??? @access public
static getImageTagByType($a_type, $a_path, $a_big=false)
Builds an html image tag TODO: function still in use, but in future use getImagePath and move HTML-Co...
static readFile($a_file)
there are some known problems with the original readfile method, which sometimes truncates delivered ...
static getWebspaceDir($mode="filesystem")
get webspace directory
static unmaskAttributeTag($a_str, $tag, $tag_att)
static sendSuccess($a_info="", $a_keep=false)
Send Success Message to Screen.
rangeDownload($file)
Send a file via range request, see http://mobiforge.com/design-development/content-delivery-mobile-de...
static execConvert($args)
execute convert command
static rCopy($a_sdir, $a_tdir, $preserveTimeAttributes=false)
Copies content of a directory $a_sdir recursively to a directory $a_tdir.
static getStyleSheetLocation($mode="output", $a_css_name="", $a_css_location="")
get full style sheet file name (path inclusive) of current user
static redirect($a_script)
http redirect to other script
static resizeImage($a_from, $a_to, $a_width, $a_height, $a_constrain_prop=false)
resize image
static isPassword($a_passwd, &$customError=null)
validates a password @access public
static sendFailure($a_info="", $a_keep=false)
Send Failure Message to Screen.
static stripSlashesRecursive($a_data, $a_strip_html=true, $a_allow="")
Strip slashes from array and sub-arrays.
static _getHttpPath()
static makeClickable($a_text, $detectGotoLinks=false)
makeClickable In Texten enthaltene URLs und Mail-Adressen klickbar machen
static groupNameExists($a_group_name, $a_id=0)
checks if group name already exists.
static virusHandling($a_file, $a_orig_name="", $a_clean=true)
scan file for viruses and clean files if possible
static buildLatexImages($a_text, $a_dir)
replace [text]...[/tex] tags with formula image code //////// added additional parameters to make thi...
static printBacktrace($a_limit=0)
printBacktrace
static getAssociatedUsersOnline($a_user_id)
static deliverData($a_data, $a_filename, $mime="application/octet-stream", $charset="")
deliver data for download via browser.
static maskSecureTags($a_str, $allow_array)
static unmaskTag($a_str, $t, $fix_param="")
static zip($a_dir, $a_file, $compress_content=false)
static isWindows()
check wether the current client system is a windows system
static switchColor($a_num, $a_css1, $a_css2)
switches style sheets for each even $a_num (used for changing colors of different result rows)
static rRenameSuffix($a_dir, $a_old_suffix, $a_new_suffix)
Renames all files with certain suffix and gives them a new suffix.
static extractParameterString($a_parstr)
extracts parameter value pairs from a string into an array
static period2String(ilDateTime $a_from, $a_to=null)
Return a string of time period.
static execQuoted($cmd, $args=NULL)
exec command and fix spaces on windows
static getDir($a_dir, $a_rec=false, $a_sub_dir="")
get directory
static _getObjectsByOperations($a_obj_type, $a_operation, $a_usr_id=0, $limit=0)
Get all objects of a specific type and check access This function is not recursive,...
static img($a_src, $a_alt="", $a_width="", $a_height="", $a_border=0, $a_id="", $a_class="")
Build img tag.
static now()
Return current timestamp in Y-m-d H:i:s format.
static getConvertCmd()
get convert command
static getP3PLocation()
Get p3p file path.
static escapeShellCmd($a_arg)
escape shell cmd
static maskAttributeTag($a_str, $tag, $tag_att)
static htmlfile2pdf($html_file, $pdf_file)
static shortenWords($a_str, $a_len=30, $a_dots=true)
Ensure that the maximum word lenght within a text is not longer than $a_len.
static processConvertVersion($a_version)
Parse convert version string, e.g.
static getNewContentStyleSheetLocation($mode="output")
get full style sheet file name (path inclusive) of current user
static getSecureTags()
static securePlainString($a_str)
Remove unsecure characters from a plain text string.
static ilTempnam($a_temp_path=null)
Create a temporary file in an ILIAS writable directory.
static getASCIIFilename($a_filename)
convert utf8 to ascii filename
static htmlentitiesOutsideHTMLTags($htmlText)
Encodes HTML entities outside of HTML tags.
static getHtmlPath($relative_path)
get url of path
static insertLatexImages($a_text, $a_start="\[tex\]", $a_end="\[\/tex\]")
replace [text]...[/tex] tags with formula image code
static convertImage($a_from, $a_to, $a_target_format="", $a_geometry="", $a_background_color="")
convert image
static getPasswordRequirementsInfo()
static stripScriptHTML($a_str, $a_allow="", $a_rm_js=true)
strip only html tags (4.0) from text $allowed contains tags to be allowed, in format tags a and b ar...
static html2pdf($html, $pdf_file)
static unzip($a_file, $overwrite=false, $a_flat=false)
unzip file
static htmlencodePlainString($a_str, $a_make_links_clickable, $a_detect_goto_links=false)
Encodes a plain text string into HTML for display in a browser.
static array_php2js($data)
convert php arrays to javascript arrays
includeMathjax($a_tpl=null)
Include Mathjax.
static unique_multi_array($array, $sub_key)
Make a multi-dimensional array to have only DISTINCT values for a certain "column".
static makeDateSelect($prefix, $year="", $month="", $day="", $startyear="", $a_long_month=true, $a_further_options=array(), $emptyoption=false)
Creates a combination of HTML selects for date inputs.
static generatePasswords($a_number)
Generate a number of passwords.
static getSelectName($selected, $values)
???
static randomhash()
static stripSlashes($a_str, $a_strip_html=true, $a_allow="")
strip slashes if magic qoutes is enabled
static date_mysql2time($mysql_date_time)
static getFileSizeInfo()
secureUrl($url)
Prepare secure href attribute.
static yn2tf($a_yn)
convert "y"/"n" to true/false
static quoteArray($a_array)
Quotes all members of an array for usage in DB query statement.
static secureLink($a_str)
static makeDirParents($a_dir)
Create a new directory and all parent directories.
static isPasswordValidForUserContext($clear_text_password, $user, &$error_language_variable=null)
static sort_func_numeric($a, $b)
sub-function to sort an array
static stableSortArray($array, $a_array_sortby, $a_array_sortorder=0, $a_numeric=false)
static & processCSVRow(&$row, $quoteAll=FALSE, $separator=";", $outUTF8=FALSE, $compatibleWithMSExcel=TRUE)
Convertes an array for CSV usage.
static removeItemFromDesktops($a_id)
removes object from all user's desktops @access public
static sendInfo($a_info="", $a_keep=false)
Send Info Message to Screen.
static formSelect($selected, $varname, $options, $multiple=false, $direct_text=false, $size="0", $style_class="", $attribs="", $disabled=false)
Builds a select form field with options and shows the selected option first.
static __extractId($ilias_id, $inst_id)
extract ref id from role title, e.g.
static getTypeIconPath($a_type, $a_obj_id, $a_size='small')
Get type icon path path Return image path for icon_xxx.pngs Or (if enabled) path to custom icon Depre...
static getImagePath($img, $module_path="", $mode="output", $offline=false)
get image path (for images located in a template directory)
static deducibleSize($a_mime)
checks if mime type is provided by getimagesize()
static isDN($a_str)
static attribsToArray($a_str)
converts a string of format var1 = "val1" var2 = "val2" ... into an array
static maskTag($a_str, $t, $fix_param="")
static removeTrailingPathSeparators($path)
static infoPanel($a_keep=true)
static deliverFile($a_file, $a_filename, $a_mime='', $isInline=false, $removeAfterDelivery=false, $a_exit_after=true)
deliver file for download via browser.
static unserializeSession($data)
Returns the unserialized ILIAS session data.
static prepareFormOutput($a_str, $a_strip=false)
prepares string output for html forms @access public
static createDirectory($a_dir, $a_mod=0755)
create directory
static makeDir($a_dir)
creates a new directory and inherits all filesystem permissions of the parent directory You may pass ...
static formInput($varname, $value, $disabled=false)
create html input area
static getUsersOnline($a_user_id=0)
reads all active sessions from db and returns users that are online OR returns only one active user i...
static renameExecutables($a_dir)
Rename uploaded executables for security reasons.
static dirsize($directory)
get size of a directory or a file.
static stripSlashesArray($a_arr, $a_strip_html=true, $a_allow="")
Strip slashes from array.
static isAPICall()
static makeTimeSelect($prefix, $short=true, $hour="", $minute="", $second="", $a_use_default=true, $a_further_options=array())
Creates a combination of HTML selects for time inputs.
static sort_func($a, $b)
sub-function to sort an array
static mergesort(&$array, $cmp_function='strcmp')
& _getInstance()
Constructor @access public.
if(!file_exists(getcwd().'/ilias.ini.php')) if(isset( $_GET["client_id"]))
registration confirmation script for ilias
Definition: confirmReg.php:20
$_COOKIE["ilClientId"]
Definition: cron.php:11
$html
Definition: example_001.php:87
$data
$style
Definition: example_012.php:70
$r
Definition: example_031.php:79
$params
Definition: example_049.php:96
$target_arr
Definition: goto.php:86
$GLOBALS['PHPCAS_CLIENT']
This global variable is used by the interface class phpCAS.
Definition: CAS.php:276
global $ilCtrl
Definition: ilias.php:18
$separator
if(! $in) print
exit
Definition: login.php:54
const ILIAS_MODULE
Definition: payment.php:15
global $lng
Definition: privfeed.php:40
$cmd
Definition: sahs_server.php:35
$ref_id
Definition: sahs_server.php:39
echo;exit;}function LogoutNotification($SessionID) { global $ilDB; $q="SELECT session_id, data FROM usr_session WHERE expires > (\w+)\|/" PREG_SPLIT_NO_EMPTY PREG_SPLIT_DELIM_CAPTURE
$url
Definition: shib_logout.php:72
$path
Definition: index.php:22
const IL_COOKIE_PATH
Definition: index.php:6
global $ilDB
$errors
if(!is_array($argv)) $options
if((!isset($_SERVER['DOCUMENT_ROOT'])) OR(empty($_SERVER['DOCUMENT_ROOT']))) $_SERVER['DOCUMENT_ROOT']
global $ilIliasIniFile
global $ilUser
Definition: imgupload.php:15
if(strpos( $jquery_path, './')===0) else if(strpos($jquery_path, '.')===0) $mathJaxSetting
Definition: latex.php:34
$dirs