ILIAS  release_7 Revision v7.30-3-g800a261c036
class.ilUtil.php
Go to the documentation of this file.
1<?php
24
26require_once './include/Unicode/UtfNormal.php';
27
38class ilUtil
39{
41
52 public static function getImageTagByType($a_type, $a_path, $a_big = false)
53 {
54 global $DIC;
55
56 $lng = $DIC->language();
57
58 $size = ($a_big)
59 ? "big"
60 : "small";
61
62 include_once("./Services/Object/classes/class.ilObject.php");
63 $filename = ilObject::_getIcon("", $size, $a_type);
64
65 return "<img src=\"" . $filename . "\" alt=\"" . $lng->txt("obj_" . $a_type) . "\" title=\"" . $lng->txt("obj_" . $a_type) . "\" border=\"0\" vspace=\"0\"/>";
66 }
67
80 public static function getTypeIconPath($a_type, $a_obj_id, $a_size = 'small')
81 {
82 include_once("./Services/Object/classes/class.ilObject.php");
83 return ilObject::_getIcon($a_obj_id, $a_size, $a_type);
84 }
85
96 public static function getImagePath($img, $module_path = "", $mode = "output", $offline = false)
97 {
98 global $DIC;
99
100 $styleDefinition = null;
101 if (isset($DIC["styleDefinition"])) {
102 $styleDefinition = $DIC["styleDefinition"];
103 }
104
105 if (is_int(strpos($_SERVER["PHP_SELF"], "setup.php"))) {
106 $module_path = "..";
107 }
108 if ($module_path != "") {
109 $module_path = "/" . $module_path;
110 }
111
112 // default image
113 $default_img = "." . $module_path . "/templates/default/images/" . $img;
114
115 // use ilStyleDefinition instead of account to get the current skin and style
116 require_once("./Services/Style/System/classes/class.ilStyleDefinition.php");
117 $current_skin = ilStyleDefinition::getCurrentSkin();
118 $current_style = ilStyleDefinition::getCurrentStyle();
119
120 if (is_object($styleDefinition)) {
121 $image_dir = $styleDefinition->getImageDirectory($current_style);
122 }
123 $skin_img = "";
124 if ($current_skin == "default") {
125 $user_img = "." . $module_path . "/templates/default/" . $image_dir . "/" . $img;
126 $skin_img = "." . $module_path . "/templates/default/images/" . $img;
127 } elseif (is_object($styleDefinition) && $current_skin != "default") {
128 $user_img = "./Customizing/global/skin/" .
129 $current_skin . $module_path . "/" . $image_dir . "/" . $img;
130 $skin_img = "./Customizing/global/skin/" .
131 $current_skin . $module_path . "/images/" . $img;
132 }
133
134 // temp svg patch
135 /*
136 $pi = pathinfo($img);
137 if ($pi["dirname"] != "") {
138 $pi["dirname"] = $pi["dirname"]."/";
139 }
140 $svg_img = ".".$module_path."/templates/default/images/".$pi["dirname"].$pi["filename"].".svg";
141 if (file_exists($svg_img))
142 {
143 return $svg_img;
144 }*/
145
146
147 if ($offline) {
148 return "./images/" . $img;
149 } elseif (@file_exists($user_img) && $image_dir != "") {
150 return $user_img; // found image for skin and style
151 } elseif (file_exists($skin_img)) {
152 return $skin_img; // found image in skin/images
153 }
154
155 return $default_img; // take image in default
156 }
157
168 public static function getHtmlPath($relative_path)
169 {
170 if (substr($relative_path, 0, 2) == './') {
171 $relative_path = (substr($relative_path, 1));
172 }
173 if (substr($relative_path, 0, 1) != '/') {
174 $relative_path = '/' . $relative_path;
175 }
176 $htmlpath = ILIAS_HTTP_PATH . $relative_path;
177 return $htmlpath;
178 }
179
192 public static function getStyleSheetLocation($mode = "output", $a_css_name = "", $a_css_location = "")
193 {
194 global $DIC;
195
196 $ilSetting = $DIC->settings();
197
198 // add version as parameter to force reload for new releases
199 // use ilStyleDefinition instead of account to get the current style
200 require_once("./Services/Style/System/classes/class.ilStyleDefinition.php");
201 $stylesheet_name = (strlen($a_css_name))
202 ? $a_css_name
204 if (strlen($a_css_location) && (strcmp(substr($a_css_location, -1), "/") != 0)) {
205 $a_css_location = $a_css_location . "/";
206 }
207
208 $filename = "";
209 // use ilStyleDefinition instead of account to get the current skin
210 require_once("./Services/Style/System/classes/class.ilStyleDefinition.php");
211 if (ilStyleDefinition::getCurrentSkin() != "default") {
212 $filename = "./Customizing/global/skin/" . ilStyleDefinition::getCurrentSkin() . "/" . $a_css_location . $stylesheet_name;
213 }
214 if (strlen($filename) == 0 || !file_exists($filename)) {
215 $filename = "./" . $a_css_location . "templates/default/" . $stylesheet_name;
216 }
217 $skin_version_appendix = "";
218 if ($mode !== "filesystem") {
219 // use version from template xml to force reload on changes
221 $skin_version = $skin->getVersion();
222 $skin_version_appendix .= ($skin_version !== '' ? str_replace(".", "-", $skin_version) : '0');
223 $skin_version_appendix = "?skin_version=" . $skin_version_appendix;
224 }
225 return $filename . $skin_version_appendix;
226 }
227
238 public static function getJSLocation($a_js_name, $a_js_location = "", $add_version = false)
239 {
240 global $DIC;
241
242 $ilSetting = $DIC->settings();
243
244 // add version as parameter to force reload for new releases
245 $js_name = $a_js_name;
246 if (strlen($a_js_location) && (strcmp(substr($a_js_location, -1), "/") != 0)) {
247 $a_js_location = $a_js_location . "/";
248 }
249
250 $filename = "";
251 // use ilStyleDefinition instead of account to get the current skin
252 require_once("./Services/Style/System/classes/class.ilStyleDefinition.php");
253 if (ilStyleDefinition::getCurrentSkin() != "default") {
254 $filename = "./Customizing/global/skin/" . ilStyleDefinition::getCurrentSkin() . "/" . $a_js_location . $js_name;
255 }
256 if (strlen($filename) == 0 || !file_exists($filename)) {
257 $filename = "./" . $a_js_location . "templates/default/" . $js_name;
258 }
259 return $filename;
260 }
261
269 public static function getP3PLocation()
270 {
271 if (defined("ILIAS_MODULE")) {
272 $base = '';
273 for ($i = 0;$i < count(explode('/', ILIAS_MODULE));$i++) {
274 $base .= "../Services/Privacy/";
275 }
276 } else {
277 $base = "./Services/Privacy/";
278 }
279
280 if (is_file($base . "w3c/p3p.xml")) {
281 return ILIAS_HTTP_PATH . "w3c/p3p.xml";
282 } else {
283 return ILIAS_HTTP_PATH . "/w3c/p3p_template.xml";
284 }
285 }
286
294 public static function getNewContentStyleSheetLocation($mode = "output")
295 {
296 global $DIC;
297
298 $ilSetting = $DIC->settings();
299
300 // use ilStyleDefinition instead of account to get the current skin and style
301 require_once("./Services/Style/System/classes/class.ilStyleDefinition.php");
302 if (ilStyleDefinition::getCurrentSkin() == "default") {
303 $in_style = "./templates/" . ilStyleDefinition::getCurrentSkin() . "/"
304 . ilStyleDefinition::getCurrentStyle() . "_cont.css";
305 } else {
306 $in_style = "./Customizing/global/skin/" . ilStyleDefinition::getCurrentSkin() . "/"
307 . ilStyleDefinition::getCurrentStyle() . "_cont.css";
308 }
309
310 if (is_file("./" . $in_style)) {
311 return $in_style;
312 } else {
313 return "templates/default/delos_cont.css";
314 }
315 }
316
335 public static function formSelect(
336 $selected,
337 $varname,
338 $options,
339 $multiple = false,
340 $direct_text = false,
341 $size = "0",
342 $style_class = "",
343 $attribs = "",
344 $disabled = false
345 ) {
346 global $DIC;
347
348 $lng = $DIC->language();
349
350 if ($multiple == true) {
351 $multiple = " multiple=\"multiple\"";
352 } else {
353 $multiple = "";
354 $size = 0;
355 }
356
357 $class = " class=\" form-control " . $style_class . "\"";
358
359 // use form-inline!
360 // this is workaround the whole function should be set deprecated
361 // $attributes = " style='display:inline-block;' ";
362
363 if (is_array($attribs)) {
364 foreach ($attribs as $key => $val) {
365 $attributes .= " " . $key . "=\"" . $val . "\"";
366 }
367 }
368 if ($disabled) {
369 $disabled = ' disabled=\"disabled\"';
370 }
371
372 $size_str = "";
373 if ($size > 0) {
374 $size_str = ' size="' . $size . '" ';
375 }
376 $str = "<select name=\"" . $varname . "\"" . $multiple . " $class " . $size_str . " $attributes $disabled>\n";
377
378 foreach ((array) $options as $key => $val) {
379 $style = "";
380 if (is_array($val)) {
381 $style = $val["style"];
382 $val = $val["text"]; // mus be last line, since we overwrite
383 }
384
385 $sty = ($style != "")
386 ? ' style="' . $style . '" '
387 : "";
388
389 if ($direct_text) {
390 $str .= " <option $sty value=\"" . $key . "\"";
391 } else {
392 $str .= " <option $sty value=\"" . $val . "\"";
393 }
394 if (is_array($selected)) {
395 if (in_array($key, $selected)) {
396 $str .= " selected=\"selected\"";
397 }
398 } elseif ($selected == $key) {
399 $str .= " selected=\"selected\"";
400 }
401
402 if ($direct_text) {
403 $str .= ">" . $val . "</option>\n";
404 } else {
405 $str .= ">" . $lng->txt($val) . "</option>\n";
406 }
407 }
408
409 $str .= "</select>\n";
410
411 return $str;
412 }
413
423 public static function getSelectName($selected, $values)
424 {
425 return($values[$selected]);
426 }
427
439 public static function formCheckbox($checked, $varname, $value, $disabled = false)
440 {
441 $str = "<input type=\"checkbox\" name=\"" . $varname . "\"";
442
443 if ($checked == 1) {
444 $str .= " checked=\"checked\"";
445 }
446
447 if ($disabled) {
448 $str .= " disabled=\"disabled\"";
449 }
450
451 $array_var = false;
452
453 if (substr($varname, -2) == "[]") {
454 $array_var = true;
455 }
456
457 // if varname ends with [], use varname[-2] + _ + value as id tag (e.g. "user_id[]" => "user_id_15")
458 if ($array_var) {
459 $varname_id = substr($varname, 0, -2) . "_" . $value;
460 } else {
461 $varname_id = $varname;
462 }
463
464 // dirty removal of other "[]" in string
465 $varname_id = str_replace("[", "_", $varname_id);
466 $varname_id = str_replace("]", "", $varname_id);
467
468 $str .= " value=\"" . $value . "\" id=\"" . $varname_id . "\" />\n";
469
470 return $str;
471 }
472
484 public static function formDisabledRadioButton($checked, $varname, $value, $disabled)
485 {
486 if ($disabled) {
487 $str = "<input disabled type=\"radio\" name=\"" . $varname . "\"";
488 } else {
489 $str = "<input type=\"radio\" name=\"" . $varname . "\"";
490 }
491 if ($checked == 1) {
492 $str .= " checked=\"checked\"";
493 }
494
495 $str .= " value=\"" . $value . "\"";
496 $str .= " id=\"" . $value . "\" />\n";
497
498 return $str;
499 }
500
501
512 public static function formRadioButton($checked, $varname, $value, $onclick = null, $disabled = false)
513 {
514 $str = '<input ';
515
516 if ($onclick) {
517 $str .= ('onclick="' . $onclick . '"');
518 }
519
520 $str .= (" type=\"radio\" name=\"" . $varname . "\"");
521 if ($checked == 1) {
522 $str .= " checked=\"checked\"";
523 }
524
525 if ($disabled) {
526 $str .= " disabled=\"disabled\"";
527 }
528
529 $str .= " value=\"" . $value . "\"";
530
531 $str .= " id=\"" . $value . "\" />\n";
532
533 return $str;
534 }
535
536
546 public static function formInput($varname, $value, $disabled = false)
547 {
548 $str = "<input type=\"input\" name=\"" . $varname . "\"";
549 if ($disabled) {
550 $str .= " disabled";
551 }
552
553 $str .= " value=\"" . $value . "\"";
554
555 $str .= " id=\"" . $value . "\" />\n";
556
557 return $str;
558 }
559
560
567 public static function checkInput($vars)
568 {
569 // TO DO:
570 // Diese Funktion soll Formfeldeingaben berprfen (empty und required)
571 }
572
579 public static function setPathStr($a_path)
580 {
581 if ("" != $a_path && "/" != substr($a_path, -1)) {
582 $a_path .= "/";
583 //$a_path = substr($a_path,1);
584 }
585
586 //return getcwd().$a_path;
587 return $a_path;
588 }
589
602 public static function switchColor($a_num, $a_css1, $a_css2)
603 {
604 if (!($a_num % 2)) {
605 return $a_css1;
606 } else {
607 return $a_css2;
608 }
609 }
610
619 public static function checkFormEmpty($emptyFields)
620 {
621 $feedback = "";
622
623 foreach ($emptyFields as $key => $val) {
624 if ($val == "") {
625 if ($feedback != "") {
626 $feedback .= ", ";
627 }
628 $feedback .= $key;
629 }
630 }
631
632 return $feedback;
633 }
634
659 public static function Linkbar($AScript, $AHits, $ALimit, $AOffset, $AParams = array(), $ALayout = array(), $prefix = '')
660 {
661 $LinkBar = "";
662
663 $layout_link = "";
664 $layout_prev = "&lt;&lt;";
665 $layout_next = "&gt;&gt;";
666
667 // layout options
668 if ((is_array($ALayout) && (count($ALayout) > 0))) {
669 if ($ALayout["link"]) {
670 $layout_link = " class=\"" . $ALayout["link"] . "\"";
671 }
672
673 if ($ALayout["prev"]) {
674 $layout_prev = $ALayout["prev"];
675 }
676
677 if ($ALayout["next"]) {
678 $layout_next = $ALayout["next"];
679 }
680 }
681
682 // show links, if hits greater limit
683 // or offset > 0 (can be > 0 due to former setting)
684 if ($AHits > $ALimit || $AOffset > 0) {
685 if (!empty($AParams)) {
686 foreach ($AParams as $key => $value) {
687 $params .= $key . "=" . $value . "&";
688 }
689 }
690 // if ($params) $params = substr($params,0,-1);
691 if (strpos($AScript, '&')) {
692 $link = $AScript . "&" . $params . $prefix . "offset=";
693 } else {
694 $link = $AScript . "?" . $params . $prefix . "offset=";
695 }
696
697 // ?bergehe "zurck"-link, wenn offset 0 ist.
698 if ($AOffset >= 1) {
699 $prevoffset = $AOffset - $ALimit;
700 if ($prevoffset < 0) {
701 $prevoffset = 0;
702 }
703 $LinkBar .= "<a" . $layout_link . " href=\"" . $link . $prevoffset . "\">" . $layout_prev . "&nbsp;</a>";
704 }
705
706 // Ben?tigte Seitenzahl kalkulieren
707 $pages = intval($AHits / $ALimit);
708
709 // Wenn ein Rest bleibt, addiere eine Seite
710 if (($AHits % $ALimit)) {
711 $pages++;
712 }
713
714 // Bei Offset = 0 keine Seitenzahlen anzeigen : DEAKTIVIERT
715 // if ($AOffset != 0) {
716
717 // ansonsten zeige Links zu den anderen Seiten an
718 for ($i = 1 ;$i <= $pages ; $i++) {
719 $newoffset = $ALimit * ($i - 1);
720
721 if ($newoffset == $AOffset) {
722 $LinkBar .= "[" . $i . "] ";
723 } else {
724 $LinkBar .= '<a ' . $layout_link . ' href="' .
725 $link . $newoffset . '">[' . $i . ']</a> ';
726 }
727 }
728 // }
729
730 // Checken, ob letze Seite erreicht ist
731 // Wenn nicht, gebe einen "Weiter"-Link aus
732 if (!(($AOffset / $ALimit) == ($pages - 1)) && ($pages != 1)) {
733 $newoffset = $AOffset + $ALimit;
734 $LinkBar .= "<a" . $layout_link . " href=\"" . $link . $newoffset . "\">&nbsp;" . $layout_next . "</a>";
735 }
736
737 return $LinkBar;
738 } else {
739 return false;
740 }
741 }
742
754 public static function makeClickable($a_text, $detectGotoLinks = false)
755 {
756 // New code, uses MediaWiki Sanitizer
757 $ret = $a_text;
758 // www-URL ohne ://-Angabe
759 $ret = preg_replace(
760 "/(^|[\s]+)(www\.)([A-Za-z0-9#&=?.\/\-]+)/i",
761 "$1http://$2$3",
762 $ret
763 );
764
765 // ftp-URL ohne ://-Angabe
766 $ret = preg_replace(
767 "/(^|[\s]+)(ftp\.)([A-Za-z0-9#&=?.\/\-]+)/i",
768 "$1ftp://$2$3",
769 $ret
770 );
771
772 // E-Mail (this does not work as expected, users must add mailto: manually)
773 //$ret = preg_replace("/(([a-z0-9_]|\-|\.)+@([^[\s]*)([A-Za-z0-9\-]))/i",
774 // "mailto:$1", $ret);
775
776 // mask existing image tags
777 $ret = str_replace('src="http://', '"***masked_im_start***', $ret);
778
779 include_once("./Services/Utilities/classes/class.ilMWParserAdapter.php");
780 $global_wgContLang = $GLOBALS["wgContLang"];
781 $GLOBALS["wgContLang"] = new ilMWFakery();
782 $parser = new ilMWParserAdapter();
783 $ret = $parser->replaceFreeExternalLinks($ret);
784
785 // unmask existing image tags
786 $ret = str_replace('"***masked_im_start***', 'src="http://', $ret);
787
788 // Should be Safe
789
790 if ($detectGotoLinks) {
791 // replace target blank with self and text with object title.
792 $regExp = "<a[^>]*href=\"(" . str_replace("/", "\/", ILIAS_HTTP_PATH) . "\/goto.php\?target=\w+_(\d+)[^\"]*)\"[^>]*>[^<]*<\/a>";
793 // echo htmlentities($regExp);
794 $ret = preg_replace_callback(
795 "/" . $regExp . "/i",
796 array("ilUtil", "replaceLinkProperties"),
797 $ret
798 );
799
800 // Static links
801 $regExp = "<a[^>]*href=\"(" . str_replace("/", "\/", ILIAS_HTTP_PATH) . "\/goto_.*[a-z0-9]+_([0-9]+)\.html)\"[^>]*>[^<]*<\/a>";
802 // echo htmlentities($regExp);
803 $ret = preg_replace_callback(
804 "/" . $regExp . "/i",
805 array("ilUtil", "replaceLinkProperties"),
806 $ret
807 );
808 }
809 $GLOBALS["wgContLang"] = $global_wgContLang;
810 return($ret);
811 }
812
826 public static function replaceLinkProperties($matches)
827 {
828 $link = $matches[0];
829 $ref_id = $matches[2];
830
831 if ($ref_id > 0) {
832 $obj_id = ilObject::_lookupObjId($ref_id);
833 if ($obj_id > 0) {
834 $title = ilObject::_lookupTitle($obj_id);
835 $link = "<a href=" . $matches[1] . " target=\"_self\">" . $title . "</a>";
836 }
837 }
838 return $link;
839 }
840
859 public static function makeDateSelect($prefix, $year = "", $month = "", $day = "", $startyear = "", $a_long_month = true, $a_further_options = array(), $emptyoption = false)
860 {
861 global $DIC;
862
863 $lng = $DIC->language();
864
865 $disabled = '';
866 if (isset($a_further_options['disabled']) and $a_further_options['disabled']) {
867 $disabled = 'disabled="disabled" ';
868 }
869
870 $now = getdate();
871 if (!$emptyoption) {
872 if (!strlen($year)) {
873 $year = $now["year"];
874 }
875 if (!strlen($month)) {
876 $month = $now["mon"];
877 }
878 if (!strlen($day)) {
879 $day = $now["mday"];
880 }
881 }
882
883 $year = (int) $year;
884 $month = (int) $month;
885 $day = (int) $day;
886
887 // build day select
888
889 $sel_day .= '<select class="form-control" ';
890 if (isset($a_further_options['select_attributes'])) {
891 foreach ($a_further_options['select_attributes'] as $name => $value) {
892 $sel_day .= ($name . '="' . $value . '" ');
893 }
894 }
895
896 $sel_day .= $disabled . "name=\"" . $prefix . "[d]\" id=\"" . $prefix . "_d\">\n";
897
898 if ($emptyoption) {
899 $sel_day .= "<option value=\"0\">--</option>\n";
900 }
901 for ($i = 1; $i <= 31; $i++) {
902 $sel_day .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
903 }
904 $sel_day .= "</select>\n";
905 $sel_day = preg_replace("/(value\=\"$day\")/", "$1 selected=\"selected\"", $sel_day);
906
907 // build month select
908 $sel_month = '<select class="form-control" ';
909 if (isset($a_further_options['select_attributes'])) {
910 foreach ($a_further_options['select_attributes'] as $name => $value) {
911 $sel_month .= ($name . '="' . $value . '" ');
912 }
913 }
914 $sel_month .= $disabled . "name=\"" . $prefix . "[m]\" id=\"" . $prefix . "_m\">\n";
915
916 if ($emptyoption) {
917 $sel_month .= "<option value=\"0\">--</option>\n";
918 }
919 for ($i = 1; $i <= 12; $i++) {
920 if ($a_long_month) {
921 $sel_month .= "<option value=\"$i\">" . $lng->txt("month_" . sprintf("%02d", $i) . "_long") . "</option>\n";
922 } else {
923 $sel_month .= "<option value=\"$i\">" . $i . "</option>\n";
924 }
925 }
926 $sel_month .= "</select>\n";
927 $sel_month = preg_replace("/(value\=\"$month\")/", "$1 selected=\"selected\"", $sel_month);
928
929 // build year select
930 $sel_year = '<select class="form-control" ';
931 if (isset($a_further_options['select_attributes'])) {
932 foreach ($a_further_options['select_attributes'] as $name => $value) {
933 $sel_year .= ($name . '="' . $value . '" ');
934 }
935 }
936 $sel_year .= $disabled . "name=\"" . $prefix . "[y]\" id=\"" . $prefix . "_y\">\n";
937 if ((strlen($startyear) == 0) || ($startyear > $year)) {
938 if (!$emptyoption || $year != 0) {
939 $startyear = $year - 5;
940 }
941 }
942
943 if (($year + 5) < (date('Y', time()) + 5)) {
944 $end_year = date('Y', time()) + 5;
945 } else {
946 $end_year = $year + 5;
947 }
948
949 if ($emptyoption) {
950 $sel_year .= "<option value=\"0\">----</option>\n";
951 }
952 for ($i = $startyear; $i <= $end_year; $i++) {
953 $sel_year .= "<option value=\"$i\">" . sprintf("%04d", $i) . "</option>\n";
954 }
955 $sel_year .= "</select>\n";
956 $sel_year = preg_replace("/(value\=\"$year\")/", "$1 selected=\"selected\"", $sel_year);
957
958 //$dateformat = $lng->text["lang_dateformat"];
959 $dateformat = "d-m-Y";
960 $dateformat = strtolower(preg_replace("/\W/", "", $dateformat));
961 $dateformat = strtolower(preg_replace("/(\w)/", "%%$1", $dateformat));
962 $dateformat = preg_replace("/%%d/", $sel_day, $dateformat);
963 $dateformat = preg_replace("/%%m/", $sel_month, $dateformat);
964 $dateformat = preg_replace("/%%y/", $sel_year, $dateformat);
965 return $dateformat;
966 }
967
986 public static function makeTimeSelect($prefix, $short = true, $hour = "", $minute = "", $second = "", $a_use_default = true, $a_further_options = array())
987 {
988 global $DIC;
989
990 $lng = $DIC->language();
991 $ilUser = $DIC->user();
992
993 $minute_steps = 1;
994 $disabled = '';
995 if (count($a_further_options)) {
996 if (isset($a_further_options['minute_steps'])) {
997 $minute_steps = $a_further_options['minute_steps'];
998 }
999 if (isset($a_further_options['disabled']) and $a_further_options['disabled']) {
1000 $disabled = 'disabled="disabled" ';
1001 }
1002 }
1003
1004 if ($a_use_default and !strlen("$hour$minute$second")) {
1005 $now = localtime();
1006 $hour = $now[2];
1007 $minute = $now[1];
1008 $second = $now[0];
1009 } else {
1010 $hour = (int) $hour;
1011 $minute = (int) $minute;
1012 $second = (int) $second;
1013 }
1014 // build hour select
1015 $sel_hour = '<select ';
1016 if (isset($a_further_options['select_attributes'])) {
1017 foreach ($a_further_options['select_attributes'] as $name => $value) {
1018 $sel_hour .= $name . '=' . $value . ' ';
1019 }
1020 }
1021 $sel_hour .= " " . $disabled . "name=\"" . $prefix . "[h]\" id=\"" . $prefix . "_h\" class=\"form-control\">\n";
1022
1023 $format = $ilUser->getTimeFormat();
1024 for ($i = 0; $i <= 23; $i++) {
1026 $sel_hour .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
1027 } else {
1028 $sel_hour .= "<option value=\"$i\">" . date("ga", mktime($i, 0, 0)) . "</option>\n";
1029 }
1030 }
1031 $sel_hour .= "</select>\n";
1032 $sel_hour = preg_replace("/(value\=\"$hour\")/", "$1 selected=\"selected\"", $sel_hour);
1033
1034 // build minutes select
1035 $sel_minute .= "<select " . $disabled . "name=\"" . $prefix . "[m]\" id=\"" . $prefix . "_m\" class=\"form-control\">\n";
1036
1037 for ($i = 0; $i <= 59; $i = $i + $minute_steps) {
1038 $sel_minute .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
1039 }
1040 $sel_minute .= "</select>\n";
1041 $sel_minute = preg_replace("/(value\=\"$minute\")/", "$1 selected=\"selected\"", $sel_minute);
1042
1043 if (!$short) {
1044 // build seconds select
1045 $sel_second .= "<select " . $disabled . "name=\"" . $prefix . "[s]\" id=\"" . $prefix . "_s\" class=\"form-control\">\n";
1046
1047 for ($i = 0; $i <= 59; $i++) {
1048 $sel_second .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
1049 }
1050 $sel_second .= "</select>\n";
1051 $sel_second = preg_replace("/(value\=\"$second\")/", "$1 selected=\"selected\"", $sel_second);
1052 }
1053 $timeformat = $lng->text["lang_timeformat"];
1054 if (strlen($timeformat) == 0) {
1055 $timeformat = "H:i:s";
1056 }
1057 $timeformat = strtolower(preg_replace("/\W/", "", $timeformat));
1058 $timeformat = preg_replace("/(\w)/", "%%$1", $timeformat);
1059 $timeformat = preg_replace("/%%h/", $sel_hour, $timeformat);
1060 $timeformat = preg_replace("/%%i/", $sel_minute, $timeformat);
1061 if ($short) {
1062 $timeformat = preg_replace("/%%s/", "", $timeformat);
1063 } else {
1064 $timeformat = preg_replace("/%%s/", $sel_second, $timeformat);
1065 }
1066 return $timeformat;
1067 }
1068
1082 public static function is_email($a_email, ilMailRfc822AddressParserFactory $mailAddressParserFactory = null)
1083 {
1084 if (null === $a_email || !is_string($a_email)) {
1085 return false;
1086 }
1087
1088 if ($mailAddressParserFactory === null) {
1089 $mailAddressParserFactory = new ilMailRfc822AddressParserFactory();
1090 }
1091
1092 try {
1093 $parser = $mailAddressParserFactory->getParser((string) $a_email);
1094 $addresses = $parser->parse();
1095 return count($addresses) == 1 && $addresses[0]->getHost() != ilMail::ILIAS_HOST;
1096 } catch (ilException $e) {
1097 return false;
1098 }
1099 }
1100
1109 public static function isPassword($a_passwd, &$customError = null)
1110 {
1111 global $DIC;
1112
1113 $lng = $DIC->language();
1114
1115 include_once('./Services/PrivacySecurity/classes/class.ilSecuritySettings.php');
1117
1118 // check if password is empty
1119 if (empty($a_passwd)) {
1120 $customError = $lng->txt('password_empty');
1121 return false;
1122 }
1123
1124 $isPassword = true;
1125 $errors = array();
1126
1127 // check if password to short
1128 if ($security->getPasswordMinLength() > 0 && strlen($a_passwd) < $security->getPasswordMinLength()) {
1129 $errors[] = sprintf($lng->txt('password_to_short'), $security->getPasswordMinLength());
1130 $isPassword = false;
1131 }
1132
1133 // check if password not to long
1134 // 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).
1135 if ($security->getPasswordMaxLength() > 0 && strlen($a_passwd) > $security->getPasswordMaxLength()) {
1136 $errors[] = sprintf($lng->txt('password_to_long'), $security->getPasswordMaxLength());
1137 $isPassword = false;
1138 }
1139
1140 // if password must contains Chars and Numbers
1141 if ($security->isPasswordCharsAndNumbersEnabled()) {
1142 $hasCharsAndNumbers = true;
1143
1144 // check password for existing chars
1145 if (!preg_match('/[A-Za-z]+/', $a_passwd)) {
1146 $hasCharsAndNumbers = false;
1147 }
1148
1149 // check password for existing numbers
1150 if (!preg_match('/[0-9]+/', $a_passwd)) {
1151 $hasCharsAndNumbers = false;
1152 }
1153
1154 if (!$hasCharsAndNumbers) {
1155 $errors[] = $lng->txt('password_must_chars_and_numbers');
1156 $isPassword = false;
1157 }
1158 }
1159
1160 require_once 'Services/Utilities/classes/class.ilStr.php';
1161 if ($security->getPasswordNumberOfUppercaseChars() > 0) {
1162 if (ilStr::strLen($a_passwd) - ilStr::strLen(preg_replace('/[A-Z]/', '', $a_passwd)) < $security->getPasswordNumberOfUppercaseChars()) {
1163 $errors[] = sprintf($lng->txt('password_must_contain_ucase_chars'), $security->getPasswordNumberOfUppercaseChars());
1164 $isPassword = false;
1165 }
1166 }
1167
1168 if ($security->getPasswordNumberOfLowercaseChars() > 0) {
1169 if (ilStr::strLen($a_passwd) - ilStr::strLen(preg_replace('/[a-z]/', '', $a_passwd)) < $security->getPasswordNumberOfLowercaseChars()) {
1170 $errors[] = sprintf($lng->txt('password_must_contain_lcase_chars'), $security->getPasswordNumberOfLowercaseChars());
1171 $isPassword = false;
1172 }
1173 }
1174
1175 // if password must contains Special-Chars
1176 if ($security->isPasswordSpecialCharsEnabled()) {
1177 // check password for existing special-chars
1178 if (!preg_match(self::getPasswordValidChars(true, true), $a_passwd)) {
1179 $errors[] = $lng->txt('password_must_special_chars');
1180 $isPassword = false;
1181 }
1182 }
1183
1184 // ensure password matches the positive list of chars/special-chars
1185 if (!preg_match(self::getPasswordValidChars(), $a_passwd)) {
1186 $errors[] = $lng->txt('password_contains_invalid_chars');
1187 $isPassword = false;
1188 }
1189
1190 // build custom error message
1191 if (count($errors) == 1) {
1192 $customError = $errors[0];
1193 } elseif (count($errors) > 1) {
1194 $customError = $lng->txt('password_multiple_errors');
1195 $customError .= '<br />' . implode('<br />', $errors);
1196 }
1197
1198 return $isPassword;
1199 }
1200
1207 public static function isPasswordValidForUserContext($clear_text_password, $user, &$error_language_variable = null)
1208 {
1209 include_once 'Services/PrivacySecurity/classes/class.ilSecuritySettings.php';
1211
1212 $login = null;
1213
1214 if (is_string($user)) {
1215 $login = $user;
1216 } elseif (is_array($user)) {
1217 // Try to get loginname and user_id from array
1218 $login = $user['login'];
1219 $userId = $user['id'];
1220 } elseif ($user instanceof ilObjUser) {
1221 $login = $user->getLogin();
1222 $userId = $user->getId();
1223 }
1224
1225 // 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.
1226
1227 if ($login && (int) $security->getPasswordMustNotContainLoginnameStatus() &&
1228 strpos(strtolower($clear_text_password), strtolower($login)) !== false
1229 ) {
1230 $error_language_variable = 'password_contains_parts_of_login_err';
1231 return false;
1232 }
1233
1234 return true;
1235 }
1236
1244 public static function getPasswordValidChars($a_as_regex = true, $a_only_special_chars = false)
1245 {
1246 if ($a_as_regex) {
1247 if ($a_only_special_chars) {
1248 return '/[_\.\+\?\#\-\*\@!\$\%\~\/\:\;]+/';
1249 } else {
1250 return '/^[A-Za-z0-9_\.\+\?\#\-\*\@!\$\%\~\/\:\;]+$/';
1251 }
1252 } else {
1253 return 'A-Z a-z 0-9 _.+?#-*@!$%~/:;';
1254 }
1255 }
1256
1264 public static function getPasswordRequirementsInfo()
1265 {
1266 global $DIC;
1267
1268 $lng = $DIC->language();
1269
1270 include_once('./Services/PrivacySecurity/classes/class.ilSecuritySettings.php');
1272
1273 $infos = array(sprintf($lng->txt('password_allow_chars'), self::getPasswordValidChars(false)));
1274
1275 // check if password to short
1276 if ($security->getPasswordMinLength() > 0) {
1277 $infos[] = sprintf($lng->txt('password_to_short'), $security->getPasswordMinLength());
1278 }
1279
1280 // check if password not to long
1281 if ($security->getPasswordMaxLength() > 0) {
1282 $infos[] = sprintf($lng->txt('password_to_long'), $security->getPasswordMaxLength());
1283 }
1284
1285 // if password must contains Chars and Numbers
1286 if ($security->isPasswordCharsAndNumbersEnabled()) {
1287 $infos[] = $lng->txt('password_must_chars_and_numbers');
1288 }
1289
1290 // if password must contains Special-Chars
1291 if ($security->isPasswordSpecialCharsEnabled()) {
1292 $infos[] = $lng->txt('password_must_special_chars');
1293 }
1294
1295 if ($security->getPasswordNumberOfUppercaseChars() > 0) {
1296 $infos[] = sprintf($lng->txt('password_must_contain_ucase_chars'), $security->getPasswordNumberOfUppercaseChars());
1297 }
1298
1299 if ($security->getPasswordNumberOfLowercaseChars() > 0) {
1300 $infos[] = sprintf($lng->txt('password_must_contain_lcase_chars'), $security->getPasswordNumberOfLowercaseChars());
1301 }
1302
1303 return implode('<br />', $infos);
1304 }
1305
1306 /*
1307 * validates a login
1308 * @access public
1309 * @param string login
1310 * @return boolean true if valid
1311 */
1312 public static function isLogin($a_login)
1313 {
1314 if (empty($a_login)) {
1315 return false;
1316 }
1317
1318 if (strlen($a_login) < 3) {
1319 return false;
1320 }
1321
1322 // FIXME - If ILIAS is configured to use RFC 822
1323 // compliant mail addresses we should not
1324 // allow the @ character.
1325 if (!preg_match("/^[A-Za-z0-9_\.\+\*\@!\$\%\~\-]+$/", $a_login)) {
1326 return false;
1327 }
1328
1329 return true;
1330 }
1331
1345 public static function shortenText(
1346 $a_str,
1347 $a_len,
1348 $a_dots = false,
1349 $a_next_blank = false,
1350 $a_keep_extension = false
1351 ) {
1352 include_once("./Services/Utilities/classes/class.ilStr.php");
1353 if (ilStr::strLen($a_str) > $a_len) {
1354 if ($a_next_blank) {
1355 $len = ilStr::strPos($a_str, " ", $a_len);
1356 } else {
1357 $len = $a_len;
1358 }
1359 // BEGIN WebDAV
1360 // - Shorten names in the middle, before the filename extension
1361 // Workaround for Windows WebDAV Client:
1362 // Use the unicode ellipsis symbol for shortening instead of
1363 // three full stop characters.
1364 if ($a_keep_extension) {
1365 $p = strrpos($a_str, '.'); // this messes up normal shortening, see bug #6190
1366 }
1367 if ($p === false || $p == 0 || strlen($a_str) - $p > $a_len) {
1368 $a_str = ilStr::subStr($a_str, 0, $len);
1369 if ($a_dots) {
1370 $a_str .= "\xe2\x80\xa6"; // UTF-8 encoding for Unicode ellipsis character.
1371 }
1372 } else {
1373 if ($a_dots) {
1374 $a_str = ilStr::subStr($a_str, 0, $len - (strlen($a_str) - $p + 1)) . "\xe2\x80\xa6" . substr($a_str, $p);
1375 } else {
1376 $a_str = ilStr::subStr($a_str, 0, $len - (strlen($a_str) - $p + 1)) . substr($a_str, $p);
1377 }
1378 }
1379 }
1380
1381 return $a_str;
1382 }
1383
1384
1397 public static function shortenWords($a_str, $a_len = 30, $a_dots = true)
1398 {
1399 include_once("./Services/Utilities/classes/class.ilStr.php");
1400 $str_arr = explode(" ", $a_str);
1401
1402 for ($i = 0; $i < count($str_arr); $i++) {
1403 if (ilStr::strLen($str_arr[$i]) > $a_len) {
1404 $str_arr[$i] = ilStr::subStr($str_arr[$i], 0, $a_len);
1405 if ($a_dots) {
1406 $str_arr[$i] .= "...";
1407 }
1408 }
1409 }
1410
1411 return implode(" ", $str_arr);
1412 }
1413
1423 public static function attribsToArray($a_str)
1424 {
1425 $attribs = array();
1426 while (is_int(strpos($a_str, "="))) {
1427 $eq_pos = strpos($a_str, "=");
1428 $qu1_pos = strpos($a_str, "\"");
1429 $qu2_pos = strpos(substr($a_str, $qu1_pos + 1), "\"") + $qu1_pos + 1;
1430 if (is_int($eq_pos) && is_int($qu1_pos) && is_int($qu2_pos)) {
1431 $var = trim(substr($a_str, 0, $eq_pos));
1432 $val = trim(substr($a_str, $qu1_pos + 1, ($qu2_pos - $qu1_pos) - 1));
1433 $attribs[$var] = $val;
1434 $a_str = substr($a_str, $qu2_pos + 1);
1435 } else {
1436 $a_str = "";
1437 }
1438 }
1439 return $attribs;
1440 }
1441
1442
1460 public static function rCopy($a_sdir, $a_tdir, $preserveTimeAttributes = false)
1461 {
1462 $sourceFS = LegacyPathHelper::deriveFilesystemFrom($a_sdir);
1463 $targetFS = LegacyPathHelper::deriveFilesystemFrom($a_tdir);
1464
1465 $sourceDir = LegacyPathHelper::createRelativePath($a_sdir);
1466 $targetDir = LegacyPathHelper::createRelativePath($a_tdir);
1467
1468 // check if arguments are directories
1469 if (!$sourceFS->hasDir($sourceDir)) {
1470 return false;
1471 }
1472
1473 $sourceList = $sourceFS->listContents($sourceDir, true);
1474
1475 foreach ($sourceList as $item) {
1476 if ($item->isDir()) {
1477 continue;
1478 }
1479 try {
1480 $itemPath = $targetDir . '/' . substr($item->getPath(), strlen($sourceDir));
1481 $stream = $sourceFS->readStream($item->getPath());
1482 $targetFS->writeStream($itemPath, $stream);
1483 } catch (\ILIAS\Filesystem\Exception\FileAlreadyExistsException $e) {
1484 // Do nothing with that type of exception
1485 }
1486 }
1487
1488 return true;
1489 }
1490
1491
1507 public static function getWebspaceDir($mode = "filesystem")
1508 {
1509 if ($mode == "filesystem") {
1510 return "./" . ILIAS_WEB_DIR . "/" . CLIENT_ID;
1511 } else {
1512 if (defined("ILIAS_MODULE")) {
1513 return "../" . ILIAS_WEB_DIR . "/" . CLIENT_ID;
1514 } else {
1515 return "./" . ILIAS_WEB_DIR . "/" . CLIENT_ID;
1516 }
1517 }
1518 }
1519
1530 public static function getDataDir()
1531 {
1532 return CLIENT_DATA_DIR;
1533 }
1534
1544 public static function getUsersOnline($a_user_id = 0)
1545 {
1546 include_once("./Services/User/classes/class.ilObjUser.php");
1547 return ilObjUser::_getUsersOnline($a_user_id);
1548 }
1549
1550
1558 public static function ilTempnam($a_temp_path = null)
1559 {
1560 if ($a_temp_path === null) {
1561 $temp_path = ilUtil::getDataDir() . "/temp";
1562 } else {
1563 $temp_path = $a_temp_path;
1564 }
1565
1566 if (!is_dir($temp_path)) {
1567 ilUtil::createDirectory($temp_path);
1568 }
1569 $temp_name = $temp_path . "/" . uniqid("tmp");
1570
1571 return $temp_name;
1572 }
1573
1574
1587 public static function createDirectory($a_dir, $a_mod = 0755)
1588 {
1589 ilUtil::makeDir($a_dir);
1590 //@mkdir($a_dir);
1591 //@chmod($a_dir, $a_mod);
1592 }
1593
1594 public static function unzip(
1595 string $path_to_zip_file,
1596 bool $overwrite_existing = false,
1597 bool $unpack_flat = false
1598 ) {
1599 global $DIC;
1600
1601 $log = $DIC->logger()->root();
1602
1603 if (!is_file($path_to_zip_file)) {
1604 return;
1605 }
1606
1607 // we unpack the zip always in a temp directory
1608 $temporary_unzip_directory = ilUtil::ilTempnam();
1609 ilUtil::makeDir($temporary_unzip_directory);
1610 copy($path_to_zip_file, $temporary_unzip_directory . DIRECTORY_SEPARATOR . basename($path_to_zip_file));
1611 $original_path_to_zip_file = $path_to_zip_file;
1612 $path_to_zip_file = $temporary_unzip_directory . DIRECTORY_SEPARATOR . basename($path_to_zip_file);
1613 $original_zip_path_info = pathinfo($original_path_to_zip_file);
1614 $unzippable_zip_path_info = pathinfo($path_to_zip_file);
1615
1616 $unzippable_zip_directory = $unzippable_zip_path_info["dirname"];
1617 $unzippable_zip_filename = $unzippable_zip_path_info["basename"];
1618
1619 // unzip
1620 $current_directory = getcwd();
1621 chdir($unzippable_zip_directory);
1622 $unzip_command = PATH_TO_UNZIP;
1623
1624 // real unzip
1625 if (!$overwrite_existing) {
1626 $unzip_parameters = ilUtil::escapeShellArg($unzippable_zip_filename);
1627 } else {
1628 $unzip_parameters = "-o " . ilUtil::escapeShellArg($unzippable_zip_filename);
1629 }
1630 ilUtil::execQuoted($unzip_command, $unzip_parameters);
1631 // move back
1632 chdir($current_directory);
1633
1634 // remove all sym links
1635 clearstatcache(); // prevent is_link from using cache
1636
1637 // sanitize filenames
1638 $dir_realpath = realpath($unzippable_zip_directory);
1639 foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($unzippable_zip_directory)) as $name => $f) {
1640 if (is_link($name)) {
1641 $target = readlink($name);
1642 if (substr($target, 0, strlen($dir_realpath)) != $dir_realpath) {
1643 unlink($name);
1644 $log->info("Removed symlink " . $name);
1645 }
1646 }
1647 if (is_file($name) && $name !== ilFileUtils::getValidFilename($name)) {
1648 // rename file if it contains invalid suffix
1650 rename($name, $new_name);
1651 }
1652 }
1653
1654 // rename executables
1655 self::renameExecutables($unzippable_zip_directory);
1656
1657 // now we have to move the files to the original directory.
1658 // if $a_flat is true, we move the files only without directories, otherwise we move the whole directory.
1659 // since some provide a realtive path here, we have to get the absolute path first
1660 $target_dir_name = $original_zip_path_info["dirname"];
1661 $target_dir_name = realpath($target_dir_name);
1662 if ($unpack_flat) {
1663 $file_array = [];
1664 ilFileUtils::recursive_dirscan($temporary_unzip_directory, $file_array);
1665 if (is_array($file_array["file"])) {
1666 foreach ($file_array["file"] as $k => $f) {
1667 if (
1668 substr($f, 0, 1) !== "."
1669 && $f !== basename($original_path_to_zip_file)
1670 ) {
1671 copy(
1672 $file_array["path"][$k] . $f,
1673 $target_dir_name . DIRECTORY_SEPARATOR . $f
1674 );
1675 }
1676 }
1677 }
1678 } else {
1679 $target_directory = $target_dir_name;
1681 $temporary_unzip_directory,
1682 $target_directory
1683 );
1684 }
1685
1686 ilUtil::delDir($temporary_unzip_directory);
1687 }
1688
1695 public static function zip($a_dir, $a_file, $compress_content = false)
1696 {
1697 $cdir = getcwd();
1698
1699 if ($compress_content) {
1700 $a_dir .= "/*";
1701 $pathinfo = pathinfo($a_dir);
1702 chdir($pathinfo["dirname"]);
1703 }
1704
1705 $pathinfo = pathinfo($a_file);
1706 $dir = $pathinfo["dirname"];
1707 $file = $pathinfo["basename"];
1708
1709 if (!$compress_content) {
1710 chdir($dir);
1711 }
1712
1713 $zip = PATH_TO_ZIP;
1714
1715 if (!$zip) {
1716 chdir($cdir);
1717 return false;
1718 }
1719
1720 if (is_array($a_dir)) {
1721 $source = "";
1722 foreach ($a_dir as $dir) {
1723 $name = basename($dir);
1725 }
1726 } else {
1727 $name = basename($a_dir);
1728 if (trim($name) != "*") {
1730 } else {
1731 $source = $name;
1732 }
1733 }
1734
1735 $zipcmd = "-r " . ilUtil::escapeShellArg($a_file) . " " . $source;
1736 ilUtil::execQuoted($zip, $zipcmd);
1737 chdir($cdir);
1738 return true;
1739 }
1740
1741 public static function CreateIsoFromFolder($a_dir, $a_file)
1742 {
1743 $cdir = getcwd();
1744
1745 $pathinfo = pathinfo($a_dir);
1746 chdir($pathinfo["dirname"]);
1747
1748 $pathinfo = pathinfo($a_file);
1749 $dir = $pathinfo["dirname"];
1750 $file = $pathinfo["basename"];
1751 $zipcmd = "-r " . ilUtil::escapeShellArg($a_file) . " " . $source;
1752
1753 $mkisofs = PATH_TO_MKISOFS;
1754 if (!$mkisofs) {
1755 chdir($cdir);
1756 return false;
1757 }
1758
1759 $name = basename($a_dir);
1761
1762 $zipcmd = "-r -J -o " . $a_file . " " . $source;
1763 ilUtil::execQuoted($mkisofs, $zipcmd);
1764 chdir($cdir);
1765 return true;
1766 }
1767
1776 public static function getConvertCmd()
1777 {
1778 return PATH_TO_CONVERT;
1779 }
1780
1788 public static function execConvert($args)
1789 {
1790 $args = self::escapeShellCmd($args);
1791 ilUtil::execQuoted(PATH_TO_CONVERT, $args);
1792 }
1793
1800 public static function isConvertVersionAtLeast($a_version)
1801 {
1802 $current_version = ilUtil::execQuoted(PATH_TO_CONVERT, "--version");
1803 $current_version = self::processConvertVersion($current_version[0]);
1804 $version = self::processConvertVersion($a_version);
1805 if ($current_version >= $version) {
1806 return true;
1807 }
1808 return false;
1809 }
1810
1817 protected static function processConvertVersion($a_version)
1818 {
1819 if (preg_match("/([0-9]+)\.([0-9]+)\.([0-9]+)([\.|\-]([0-9]+))?/", $a_version, $match)) {
1820 $version = str_pad($match[1], 2, 0, STR_PAD_LEFT) .
1821 str_pad($match[2], 2, 0, STR_PAD_LEFT) .
1822 str_pad($match[3], 2, 0, STR_PAD_LEFT) .
1823 str_pad($match[5], 2, 0, STR_PAD_LEFT);
1824 return (int) $version;
1825 }
1826 }
1827
1837 public static function convertImage(
1838 $a_from,
1839 $a_to,
1840 $a_target_format = "",
1841 $a_geometry = "",
1842 $a_background_color = ""
1843 ) {
1844 $format_str = ($a_target_format != "")
1845 ? strtoupper($a_target_format) . ":"
1846 : "";
1847 $geometry = "";
1848 if ($a_geometry != "") {
1849 if (is_int(strpos($a_geometry, "x"))) {
1850 $geometry = " -geometry " . $a_geometry . " ";
1851 } else {
1852 $geometry = " -geometry " . $a_geometry . "x" . $a_geometry . " ";
1853 }
1854 }
1855
1856 $bg_color = ($a_background_color != "")
1857 ? " -background color " . $a_background_color . " "
1858 : "";
1859 $convert_cmd = ilUtil::escapeShellArg($a_from) . " " . $bg_color . $geometry . ilUtil::escapeShellArg($format_str . $a_to);
1860
1861 ilUtil::execConvert($convert_cmd);
1862 }
1863
1874 public static function resizeImage($a_from, $a_to, $a_width, $a_height, $a_constrain_prop = false)
1875 {
1876 if ($a_constrain_prop) {
1877 $size = " -geometry " . $a_width . "x" . $a_height . " ";
1878 } else {
1879 $size = " -resize " . $a_width . "x" . $a_height . "! ";
1880 }
1881 $convert_cmd = ilUtil::escapeShellArg($a_from) . " " . $size . ilUtil::escapeShellArg($a_to);
1882
1883 ilUtil::execConvert($convert_cmd);
1884 }
1885
1892 public static function img($a_src, $a_alt = null, $a_width = "", $a_height = "", $a_border = 0, $a_id = "", $a_class = "")
1893 {
1894 $img = '<img src="' . $a_src . '"';
1895 if (!is_null($a_alt)) {
1896 $img .= ' alt="' . htmlspecialchars($a_alt) . '"';
1897 }
1898 if ($a_width != "") {
1899 $img .= ' width="' . htmlspecialchars($a_width) . '"';
1900 }
1901 if ($a_height != "") {
1902 $img .= ' height="' . htmlspecialchars($a_height) . '"';
1903 }
1904 if ($a_class != "") {
1905 $img .= ' class="' . $a_class . '"';
1906 }
1907 if ($a_id != "") {
1908 $img .= ' id="' . $a_id . '"';
1909 }
1910 $img .= ' />';
1911
1912 return $img;
1913 }
1914
1921 public static function deliverData($a_data, $a_filename, $mime = "application/octet-stream", $charset = "")
1922 {
1923 $disposition = "attachment"; // "inline" to view file in browser or "attachment" to download to hard disk
1924 // $mime = "application/octet-stream"; // or whatever the mime type is
1925
1926 include_once './Services/Http/classes/class.ilHTTPS.php';
1927
1928 //if($_SERVER['HTTPS'])
1929 if (ilHTTPS::getInstance()->isDetected()) {
1930
1931 // Added different handling for IE and HTTPS => send pragma after content informations
1935 #header("Pragma: ");
1936 #header("Cache-Control: ");
1937 #header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
1938 #header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
1939 #header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1
1940 #header("Cache-Control: post-check=0, pre-check=0", false);
1941 } elseif ($disposition == "attachment") {
1942 header("Cache-control: private");
1943 } else {
1944 header("Cache-Control: no-cache, must-revalidate");
1945 header("Pragma: no-cache");
1946 }
1947
1949
1950 if (strlen($charset)) {
1951 $charset = "; charset=$charset";
1952 }
1953 header("Content-Type: $mime$charset");
1954 header("Content-Disposition:$disposition; filename=\"" . $ascii_filename . "\"");
1955 header("Content-Description: " . $ascii_filename);
1956 header("Content-Length: " . (string) (strlen($a_data)));
1957
1958 //if($_SERVER['HTTPS'])
1959 if (ilHTTPS::getInstance()->isDetected()) {
1960 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
1961 header('Pragma: public');
1962 }
1963
1964 header("Connection: close");
1965 echo $a_data;
1966 exit;
1967 }
1968
1976 public static function deliverFile(
1977 $a_file,
1978 $a_filename,
1979 $a_mime = '',
1980 $isInline = false,
1981 $removeAfterDelivery = false,
1982 $a_exit_after = true
1983 ) {
1984 global $DIC;
1985 // should we fail silently?
1986 if (!file_exists($a_file)) {
1987 return false;
1988 }
1989 $delivery = new ilFileDelivery($a_file);
1990
1991 if ($isInline) {
1992 $delivery->setDisposition(ilFileDelivery::DISP_INLINE);
1993 } else {
1994 $delivery->setDisposition(ilFileDelivery::DISP_ATTACHMENT);
1995 }
1996
1997 if (strlen($a_mime)) {
1998 $delivery->setMimeType($a_mime);
1999 }
2000
2001 $delivery->setDownloadFileName($a_filename);
2002 $delivery->setConvertFileNameToAsci((bool) !$DIC->clientIni()->readVariable('file_access', 'disable_ascii'));
2003 $delivery->setDeleteFile($removeAfterDelivery);
2004 $delivery->deliver();
2005 }
2006
2007
2017 public static function readFile($a_file)
2018 {
2019 $chunksize = 1 * (1024 * 1024); // how many bytes per chunk
2020 $buffer = '';
2021 $handle = fopen($a_file, 'rb');
2022 if ($handle === false) {
2023 return false;
2024 }
2025 while (!feof($handle)) {
2026 $buffer = fread($handle, $chunksize);
2027 print $buffer;
2028 }
2029 return fclose($handle);
2030 }
2031
2039 public static function getASCIIFilename($a_filename)
2040 {
2041 // The filename must be converted to ASCII, as of RFC 2183,
2042 // section 2.3.
2043
2055
2058
2059 // #15914 - try to fix german umlauts
2060 $umlauts = [
2061 "Ä" => "Ae",
2062 "Ö" => "Oe",
2063 "Ü" => "Ue",
2064 "ä" => "ae",
2065 "ö" => "oe",
2066 "ü" => "ue",
2067 "é" => "e",
2068 "è" => "e",
2069 "é" => "e",
2070 "ê" => "e",
2071 "ß" => "ss"
2072 ];
2073 foreach ($umlauts as $src => $tgt) {
2074 $a_filename = str_replace($src, $tgt, $a_filename);
2075 }
2076
2077 $ascii_filename = htmlentities($a_filename, ENT_NOQUOTES, 'UTF-8');
2078 $ascii_filename = preg_replace('/\&(.)[^;]*;/', '\\1', $ascii_filename);
2079 $ascii_filename = preg_replace('/[\x7f-\xff]/', '_', $ascii_filename);
2080
2081 // OS do not allow the following characters in filenames: \/:*?"<>|
2082 $ascii_filename = preg_replace('/[:\x5c\/\*\?\"<>\|]/', '_', $ascii_filename);
2083 return $ascii_filename;
2084 }
2085
2092 public static function htmlentitiesOutsideHTMLTags($htmlText)
2093 {
2094 $matches = array();
2095 $sep = '###HTMLTAG###';
2096
2097 preg_match_all("@<[^>]*>@", $htmlText, $matches);
2098 $tmp = preg_replace("@(<[^>]*>)@", $sep, $htmlText);
2099 $tmp = explode($sep, $tmp);
2100
2101 for ($i = 0; $i < count($tmp); $i++) {
2102 $tmp[$i] = htmlentities($tmp[$i], ENT_COMPAT, "UTF-8");
2103 }
2104
2105 $tmp = join($sep, $tmp);
2106
2107 for ($i = 0; $i < count($matches[0]); $i++) {
2108 $tmp = preg_replace("@$sep@", $matches[0][$i], $tmp, 1);
2109 }
2110
2111 return $tmp;
2112 }
2113
2120 public static function getJavaPath()
2121 {
2122 return PATH_TO_JAVA;
2123 //global $ilias;
2124
2125 //return $ilias->getSetting("java_path");
2126 }
2127
2135 public static function appendUrlParameterString($a_url, $a_par, $xml_style = false)
2136 {
2137 $amp = $xml_style
2138 ? "&amp;"
2139 : "&";
2140
2141 $url = (is_int(strpos($a_url, "?")))
2142 ? $a_url . $amp . $a_par
2143 : $a_url . "?" . $a_par;
2144
2145 return $url;
2146 }
2147
2166 public static function makeDir($a_dir)
2167 {
2168 $a_dir = trim($a_dir);
2169
2170 // remove trailing slash (bugfix for php 4.2.x)
2171 if (substr($a_dir, -1) == "/") {
2172 $a_dir = substr($a_dir, 0, -1);
2173 }
2174
2175 // check if a_dir comes with a path
2176 if (!($path = substr($a_dir, 0, strrpos($a_dir, "/") - strlen($a_dir)))) {
2177 $path = ".";
2178 }
2179
2180 // create directory with file permissions of parent directory
2181 umask(0000);
2182 return @mkdir($a_dir, fileperms($path));
2183 }
2184
2185
2205 public static function makeDirParents($a_dir)
2206 {
2207 $dirs = array($a_dir);
2208 $a_dir = dirname($a_dir);
2209 $last_dirname = '';
2210
2211 while ($last_dirname != $a_dir) {
2212 array_unshift($dirs, $a_dir);
2213 $last_dirname = $a_dir;
2214 $a_dir = dirname($a_dir);
2215 }
2216
2217 // find the first existing dir
2218 $reverse_paths = array_reverse($dirs, true);
2219 $found_index = -1;
2220 foreach ($reverse_paths as $key => $value) {
2221 if ($found_index == -1) {
2222 if (is_dir($value)) {
2223 $found_index = $key;
2224 }
2225 }
2226 }
2227
2228 umask(0000);
2229 foreach ($dirs as $dirindex => $dir) {
2230 // starting with the longest existing path
2231 if ($dirindex >= $found_index) {
2232 if (!file_exists($dir)) {
2233 if (strcmp(substr($dir, strlen($dir) - 1, 1), "/") == 0) {
2234 // on some systems there is an error when there is a slash
2235 // at the end of a directory in mkdir, see Mantis #2554
2236 $dir = substr($dir, 0, strlen($dir) - 1);
2237 }
2238 if (!mkdir($dir, $umask)) {
2239 error_log("Can't make directory: $dir");
2240 return false;
2241 }
2242 } elseif (!is_dir($dir)) {
2243 error_log("$dir is not a directory");
2244 return false;
2245 } else {
2246 // get umask of the last existing parent directory
2247 $umask = fileperms($dir);
2248 }
2249 }
2250 }
2251 return true;
2252 }
2253
2254
2270 public static function delDir($a_dir, $a_clean_only = false)
2271 {
2272 if (!is_dir($a_dir) || is_int(strpos($a_dir, ".."))) {
2273 return;
2274 }
2275
2276 $current_dir = opendir($a_dir);
2277
2278 $files = array();
2279
2280 // this extra loop has been necessary because of a strange bug
2281 // at least on MacOS X. A looped readdir() didn't work
2282 // correctly with larger directories
2283 // when an unlink happened inside the loop. Getting all files
2284 // into the memory first solved the problem.
2285 while ($entryname = readdir($current_dir)) {
2286 $files[] = $entryname;
2287 }
2288
2289 foreach ($files as $file) {
2290 if (is_dir($a_dir . "/" . $file) and ($file != "." and $file != "..")) {
2291 ilUtil::delDir($a_dir . "/" . $file);
2292 } elseif ($file != "." and $file != "..") {
2293 unlink($a_dir . "/" . $file);
2294 }
2295 }
2296
2297 closedir($current_dir);
2298 if (!$a_clean_only) {
2299 @rmdir($a_dir);
2300 }
2301 }
2302
2303
2319 public static function getDir($a_dir, $a_rec = false, $a_sub_dir = "")
2320 {
2321 $current_dir = opendir($a_dir . $a_sub_dir);
2322
2323 $dirs = array();
2324 $files = array();
2325 $subitems = array();
2326 while ($entry = readdir($current_dir)) {
2327 if (is_dir($a_dir . "/" . $entry)) {
2328 $dirs[$entry] = array("type" => "dir", "entry" => $entry,
2329 "subdir" => $a_sub_dir);
2330 if ($a_rec && $entry != "." && $entry != "..") {
2331 $si = ilUtil::getDir($a_dir, true, $a_sub_dir . "/" . $entry);
2332 $subitems = array_merge($subitems, $si);
2333 }
2334 } else {
2335 if ($entry != "." && $entry != "..") {
2336 $size = filesize($a_dir . $a_sub_dir . "/" . $entry);
2337 $files[$entry] = array("type" => "file", "entry" => $entry,
2338 "size" => $size, "subdir" => $a_sub_dir);
2339 }
2340 }
2341 }
2342 ksort($dirs);
2343 ksort($files);
2344
2345 return array_merge($dirs, $files, $subitems);
2346 }
2347
2354 public static function stripSlashesArray($a_arr, $a_strip_html = true, $a_allow = "")
2355 {
2356 if (is_array($a_arr)) {
2357 foreach ($a_arr as $k => $v) {
2358 $a_arr[$k] = ilUtil::stripSlashes($v, $a_strip_html, $a_allow);
2359 }
2360 }
2361
2362 return $a_arr;
2363 }
2364
2369 public static function getClientIdByString(string $clientId) : \ILIAS\Data\ClientId
2370 {
2371 $df = new \ILIAS\Data\Factory;
2372
2373 return $df->clientId($clientId);
2374 }
2375
2382 public static function stripSlashesRecursive($a_data, $a_strip_html = true, $a_allow = "")
2383 {
2384 if (is_array($a_data)) {
2385 foreach ($a_data as $k => $v) {
2386 if (is_array($v)) {
2387 $a_data[$k] = ilUtil::stripSlashesRecursive($v, $a_strip_html, $a_allow);
2388 } else {
2389 $a_data[$k] = ilUtil::stripSlashes($v, $a_strip_html, $a_allow);
2390 }
2391 }
2392 } else {
2393 $a_data = ilUtil::stripSlashes($a_data, $a_strip_html, $a_allow);
2394 }
2395
2396 return $a_data;
2397 }
2398
2406 public static function stripSlashes($a_str, $a_strip_html = true, $a_allow = "")
2407 {
2408 if (ini_get("magic_quotes_gpc")) {
2409 $a_str = stripslashes($a_str);
2410 }
2411 //echo "<br><br>-".$a_strip_html."-".htmlentities($a_str);
2412 //echo "<br>-".htmlentities(ilUtil::secureString($a_str, $a_strip_html, $a_allow));
2413 return ilUtil::secureString($a_str, $a_strip_html, $a_allow);
2414 }
2415
2423 public static function stripOnlySlashes($a_str)
2424 {
2425 if (ini_get("magic_quotes_gpc")) {
2426 $a_str = stripslashes($a_str);
2427 }
2428
2429 return $a_str;
2430 }
2431
2438 public static function secureString($a_str, $a_strip_html = true, $a_allow = "")
2439 {
2440 // check whether all allowed tags can be made secure
2441 $only_secure = true;
2442 $allow_tags = explode(">", $a_allow);
2443 $sec_tags = ilUtil::getSecureTags();
2444 $allow_array = array();
2445 foreach ($allow_tags as $allow) {
2446 if ($allow != "") {
2447 $allow = str_replace("<", "", $allow);
2448
2449 if (!in_array($allow, $sec_tags)) {
2450 $only_secure = false;
2451 }
2452 $allow_array[] = $allow;
2453 }
2454 }
2455
2456 // default behaviour: allow only secure tags 1:1
2457 if (($only_secure || $a_allow == "") && $a_strip_html) {
2458 if ($a_allow == "") {
2459 $allow_array = array("b", "i", "strong", "em", "code", "cite",
2460 "gap", "sub", "sup", "pre", "strike", "bdo");
2461 }
2462
2463 // this currently removes parts of strings like "a <= b"
2464 // because "a <= b" is treated like "<spam onclick='hurt()'>ss</spam>"
2465 $a_str = ilUtil::maskSecureTags($a_str, $allow_array);
2466 $a_str = strip_tags($a_str); // strip all other tags
2467 $a_str = ilUtil::unmaskSecureTags($a_str, $allow_array);
2468
2469 // a possible solution could be something like:
2470 // $a_str = str_replace("<", "&lt;", $a_str);
2471 // $a_str = str_replace(">", "&gt;", $a_str);
2472 // $a_str = ilUtil::unmaskSecureTags($a_str, $allow_array);
2473 //
2474 // output would be ok then, but input fields would show
2475 // "a &lt;= b" for input "a <= b" if data is brought back to a form
2476 } else {
2477 // only for scripts, that need to allow more/other tags and parameters
2478 if ($a_strip_html) {
2479 $a_str = ilUtil::stripScriptHTML($a_str, $a_allow);
2480 }
2481 }
2482
2483 return $a_str;
2484 }
2485
2486 public static function getSecureTags()
2487 {
2488 return array("strong", "em", "u", "strike", "ol", "li", "ul", "p", "div",
2489 "i", "b", "code", "sup", "sub", "pre", "gap", "a", "img", "bdo");
2490 }
2491
2492 public static function maskSecureTags($a_str, $allow_array)
2493 {
2494 foreach ($allow_array as $t) {
2495 switch ($t) {
2496 case "a":
2497 $a_str = ilUtil::maskAttributeTag($a_str, "a", "href");
2498 break;
2499
2500 case "img":
2501 $a_str = ilUtil::maskAttributeTag($a_str, "img", "src");
2502 break;
2503
2504 case "p":
2505 case "div":
2506 $a_str = ilUtil::maskTag($a_str, $t, array(
2507 array("param" => "align", "value" => "left"),
2508 array("param" => "align", "value" => "center"),
2509 array("param" => "align", "value" => "justify"),
2510 array("param" => "align", "value" => "right")
2511 ));
2512 break;
2513
2514 default:
2515 $a_str = ilUtil::maskTag($a_str, $t);
2516 break;
2517 }
2518 }
2519
2520 return $a_str;
2521 }
2522
2523 public static function unmaskSecureTags($a_str, $allow_array)
2524 {
2525 foreach ($allow_array as $t) {
2526 switch ($t) {
2527 case "a":
2528 $a_str = ilUtil::unmaskAttributeTag($a_str, "a", "href");
2529 break;
2530
2531 case "img":
2532 $a_str = ilUtil::unmaskAttributeTag($a_str, "img", "src");
2533 break;
2534
2535 case "p":
2536 case "div":
2537 $a_str = ilUtil::unmaskTag($a_str, $t, array(
2538 array("param" => "align", "value" => "left"),
2539 array("param" => "align", "value" => "center"),
2540 array("param" => "align", "value" => "justify"),
2541 array("param" => "align", "value" => "right")
2542 ));
2543 break;
2544
2545 default:
2546 $a_str = ilUtil::unmaskTag($a_str, $t);
2547 break;
2548 }
2549 }
2550
2551 return $a_str;
2552 }
2553
2561 public static function securePlainString($a_str)
2562 {
2563 if (ini_get("magic_quotes_gpc")) {
2564 return stripslashes($a_str);
2565 } else {
2566 return $a_str;
2567 }
2568 }
2585 public static function htmlencodePlainString($a_str, $a_make_links_clickable, $a_detect_goto_links = false)
2586 {
2587 $encoded = "";
2588
2589 if ($a_make_links_clickable) {
2590 // Find text sequences in the plain text string which match
2591 // the URI syntax rules, and pass them to ilUtil::makeClickable.
2592 // Encode all other text sequences in the plain text string using
2593 // htmlspecialchars and nl2br.
2594 // The following expressions matches URI's as specified in RFC 2396.
2595 //
2596 // The expression matches URI's, which start with some well known
2597 // schemes, like "http:", or with "www.". This must be followed
2598 // by at least one of the following RFC 2396 expressions:
2599 // - alphanum: [a-zA-Z0-9]
2600 // - reserved: [;\/?:|&=+$,]
2601 // - mark: [\\-_.!~*\'()]
2602 // - escaped: %[0-9a-fA-F]{2}
2603 // - fragment delimiter: #
2604 // - uric_no_slash: [;?:@&=+$,]
2605 $matches = array();
2606 $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);
2607 $pos1 = 0;
2608 $encoded = "";
2609
2610 foreach ($matches[0] as $match) {
2611 $matched_text = $match[0];
2612 $pos2 = $match[1];
2613
2614 // encode plain text
2615 $encoded .= nl2br(htmlspecialchars(substr($a_str, $pos1, $pos2 - $pos1)));
2616
2617 // encode URI
2618 $encoded .= ilUtil::makeClickable($matched_text, $a_detect_goto_links);
2619
2620
2621 $pos1 = $pos2 + strlen($matched_text);
2622 }
2623 if ($pos1 < strlen($a_str)) {
2624 $encoded .= nl2br(htmlspecialchars(substr($a_str, $pos1)));
2625 }
2626 } else {
2627 $encoded = nl2br(htmlspecialchars($a_str));
2628 }
2629 return $encoded;
2630 }
2631
2632
2633 public static function maskAttributeTag($a_str, $tag, $tag_att)
2634 {
2635 global $DIC;
2636
2637 $ilLog = $DIC["ilLog"];
2638
2639 $ws = "[\s]*";
2640 $att = $ws . "[^>]*" . $ws;
2641
2642 while (preg_match(
2643 '/<(' . $tag . $att . '(' . $tag_att . $ws . '="' . $ws . '(([$@!*()~;,_0-9A-z\/:=%.&#?+\-])*)")' . $att . ')>/i',
2644 $a_str,
2645 $found
2646 )) {
2647 $old_str = $a_str;
2648 $a_str = preg_replace(
2649 "/<" . preg_quote($found[1], "/") . ">/i",
2650 '&lt;' . $tag . ' ' . $tag_att . $tag_att . '="' . $found[3] . '"&gt;',
2651 $a_str
2652 );
2653 if ($old_str == $a_str) {
2654 $ilLog->write("ilUtil::maskA-" . htmlentities($old_str) . " == " .
2655 htmlentities($a_str));
2656 return $a_str;
2657 }
2658 }
2659 $a_str = str_ireplace(
2660 "</$tag>",
2661 "&lt;/$tag&gt;",
2662 $a_str
2663 );
2664 return $a_str;
2665 }
2666
2667 public static function unmaskAttributeTag($a_str, $tag, $tag_att)
2668 {
2669 global $DIC;
2670
2671 $ilLog = $DIC["ilLog"];
2672
2673 while (preg_match(
2674 '/&lt;(' . $tag . ' ' . $tag_att . $tag_att . '="(([$@!*()~;,_0-9A-z\/:=%.&#?+\-])*)")&gt;/i',
2675 $a_str,
2676 $found
2677 )) {
2678 $old_str = $a_str;
2679 $a_str = preg_replace(
2680 "/&lt;" . preg_quote($found[1], "/") . "&gt;/i",
2681 '<' . $tag . ' ' . $tag_att . '="' . ilUtil::secureLink($found[2]) . '">',
2682 $a_str
2683 );
2684 if ($old_str == $a_str) {
2685 $ilLog->write("ilUtil::unmaskA-" . htmlentities($old_str) . " == " .
2686 htmlentities($a_str));
2687 return $a_str;
2688 }
2689 }
2690 $a_str = str_replace('&lt;/' . $tag . '&gt;', '</' . $tag . '>', $a_str);
2691 return $a_str;
2692 }
2693
2694 public static function maskTag($a_str, $t, $fix_param = "")
2695 {
2696 $a_str = str_replace(
2697 array("<$t>", "<" . strtoupper($t) . ">"),
2698 "&lt;" . $t . "&gt;",
2699 $a_str
2700 );
2701 $a_str = str_replace(
2702 array("</$t>", "</" . strtoupper($t) . ">"),
2703 "&lt;/" . $t . "&gt;",
2704 $a_str
2705 );
2706
2707 if (is_array($fix_param)) {
2708 foreach ($fix_param as $p) {
2709 $k = $p["param"];
2710 $v = $p["value"];
2711 $a_str = str_replace(
2712 "<$t $k=\"$v\">",
2713 "&lt;" . "$t $k=\"$v\"" . "&gt;",
2714 $a_str
2715 );
2716 }
2717 }
2718
2719 return $a_str;
2720 }
2721
2722 public static function unmaskTag($a_str, $t, $fix_param = "")
2723 {
2724 $a_str = str_replace("&lt;" . $t . "&gt;", "<" . $t . ">", $a_str);
2725 $a_str = str_replace("&lt;/" . $t . "&gt;", "</" . $t . ">", $a_str);
2726
2727 if (is_array($fix_param)) {
2728 foreach ($fix_param as $p) {
2729 $k = $p["param"];
2730 $v = $p["value"];
2731 $a_str = str_replace(
2732 "&lt;$t $k=\"$v\"&gt;",
2733 "<" . "$t $k=\"$v\"" . ">",
2734 $a_str
2735 );
2736 }
2737 }
2738 return $a_str;
2739 }
2740
2741 public static function secureLink($a_str)
2742 {
2743 $a_str = str_ireplace("javascript", "jvscrpt", $a_str);
2744 $a_str = str_ireplace(array("%00", "%0a", "%0d", "%1a", "&#00;", "&#x00;",
2745 "&#0;", "&#x0;", "&#x0a;", "&#x0d;", "&#10;", "&#13;"), "-", $a_str);
2746 return $a_str;
2747 }
2748
2762 public static function stripScriptHTML($a_str, $a_allow = "", $a_rm_js = true)
2763 {
2764 //$a_str = strip_tags($a_str, $a_allow);
2765
2766 $negativestr = "a,abbr,acronym,address,applet,area,base,basefont," .
2767 "big,blockquote,body,br,button,caption,center,cite,code,col," .
2768 "colgroup,dd,del,dfn,dir,div,dl,dt,em,fieldset,font,form,frame," .
2769 "frameset,h1,h2,h3,h4,h5,h6,head,hr,html,i,iframe,img,input,ins,isindex,kbd," .
2770 "label,legend,li,link,map,menu,meta,noframes,noscript,object,ol," .
2771 "optgroup,option,p,param,q,s,samp,script,select,small,span," .
2772 "strike,strong,style,sub,sup,table,tbody,td,textarea,tfoot,th,thead," .
2773 "title,tr,tt,u,ul,var";
2774 $a_allow = strtolower($a_allow);
2775 $negatives = explode(",", $negativestr);
2776 $outer_old_str = "";
2777 while ($outer_old_str != $a_str) {
2778 $outer_old_str = $a_str;
2779 foreach ($negatives as $item) {
2780 $pos = strpos($a_allow, "<$item>");
2781
2782 // remove complete tag, if not allowed
2783 if ($pos === false) {
2784 $old_str = "";
2785 while ($old_str != $a_str) {
2786 $old_str = $a_str;
2787 $a_str = preg_replace("/<\/?\s*$item(\/?)\s*>/i", "", $a_str);
2788 $a_str = preg_replace("/<\/?\s*$item(\/?)\s+([^>]*)>/i", "", $a_str);
2789 }
2790 }
2791 }
2792 }
2793
2794 if ($a_rm_js) {
2795 // remove all attributes if an "on..." attribute is given
2796 $a_str = preg_replace("/<\s*\w*(\/?)(\s+[^>]*)?(\s+on[^>]*)>/i", "", $a_str);
2797
2798 // remove all attributes if a "javascript" is within tag
2799 $a_str = preg_replace("/<\s*\w*(\/?)\s+[^>]*javascript[^>]*>/i", "", $a_str);
2800
2801 // remove all attributes if an "expression" is within tag
2802 // (IE allows something like <b style='width:expression(alert(1))'>test</b>)
2803 $a_str = preg_replace("/<\s*\w*(\/?)\s+[^>]*expression[^>]*>/i", "", $a_str);
2804 }
2805
2806 return $a_str;
2807 }
2808
2820 public static function prepareFormOutput($a_str, $a_strip = false)
2821 {
2822 if ($a_strip) {
2823 $a_str = ilUtil::stripSlashes($a_str);
2824 }
2825 $a_str = htmlspecialchars($a_str);
2826 // Added replacement of curly brackets to prevent
2827 // problems with PEAR templates, because {xyz} will
2828 // be removed as unused template variable
2829 $a_str = str_replace("{", "&#123;", $a_str);
2830 $a_str = str_replace("}", "&#125;", $a_str);
2831 // needed for LaTeX conversion \\ in LaTeX is a line break
2832 // but without this replacement, php changes \\ to \
2833 $a_str = str_replace("\\", "&#92;", $a_str);
2834 return $a_str;
2835 }
2836
2843 public static function secureUrl($url)
2844 {
2845 // check if url is valid (absolute or relative)
2846 if (filter_var($url, FILTER_VALIDATE_URL) === false &&
2847 filter_var("http://" . $url, FILTER_VALIDATE_URL) === false &&
2848 filter_var("http:" . $url, FILTER_VALIDATE_URL) === false &&
2849 filter_var("http://de.de" . $url, FILTER_VALIDATE_URL) === false &&
2850 filter_var("http://de.de/" . $url, FILTER_VALIDATE_URL) === false) {
2851 return "";
2852 }
2853 if (trim(strtolower(parse_url($url, PHP_URL_SCHEME))) == "javascript") {
2854 return "";
2855 }
2856 $url = htmlspecialchars($url, ENT_QUOTES);
2857 return $url;
2858 }
2859
2860
2861
2871 public static function prepareDBString($a_str)
2872 {
2873 return addslashes($a_str);
2874 }
2875
2876
2886 public static function extractParameterString($a_parstr)
2887 {
2888 // parse parameters in array
2889 $par = array();
2890 $ok = true;
2891 while (($spos = strpos($a_parstr, "=")) && $ok) {
2892 // extract parameter
2893 $cpar = substr($a_parstr, 0, $spos);
2894 $a_parstr = substr($a_parstr, $spos, strlen($a_parstr) - $spos);
2895 while (substr($cpar, 0, 1) == "," || substr($cpar, 0, 1) == " " || substr($cpar, 0, 1) == chr(13) || substr($cpar, 0, 1) == chr(10)) {
2896 $cpar = substr($cpar, 1, strlen($cpar) - 1);
2897 }
2898 while (substr($cpar, strlen($cpar) - 1, 1) == " " || substr($cpar, strlen($cpar) - 1, 1) == chr(13) || substr($cpar, strlen($cpar) - 1, 1) == chr(10)) {
2899 $cpar = substr($cpar, 0, strlen($cpar) - 1);
2900 }
2901
2902 // parameter name should only
2903 $cpar_old = "";
2904 while ($cpar != $cpar_old) {
2905 $cpar_old = $cpar;
2906 $cpar = preg_replace("/[^a-zA-Z0-9_]/i", "", $cpar);
2907 }
2908
2909 // extract value
2910 if ($cpar != "") {
2911 if ($spos = strpos($a_parstr, "\"")) {
2912 $a_parstr = substr($a_parstr, $spos + 1, strlen($a_parstr) - $spos);
2913 $spos = strpos($a_parstr, "\"");
2914 if (is_int($spos)) {
2915 $cval = substr($a_parstr, 0, $spos);
2916 $par[$cpar] = $cval;
2917 $a_parstr = substr($a_parstr, $spos + 1, strlen($a_parstr) - $spos - 1);
2918 } else {
2919 $ok = false;
2920 }
2921 } else {
2922 $ok = false;
2923 }
2924 }
2925 }
2926
2927 if ($ok) {
2928 return $par;
2929 } else {
2930 return false;
2931 }
2932 }
2933
2934 public static function assembleParameterString($a_par_arr)
2935 {
2936 if (is_array($a_par_arr)) {
2937 $target_arr = array();
2938 foreach ($a_par_arr as $par => $val) {
2939 $target_arr[] = "$par=\"$val\"";
2940 }
2941 $target_str = implode(", ", $target_arr);
2942 }
2943
2944 return $target_str;
2945 }
2946
2953 public static function dumpString($a_str)
2954 {
2955 $ret = $a_str . ": ";
2956 for ($i = 0; $i < strlen($a_str); $i++) {
2957 $ret .= ord(substr($a_str, $i, 1)) . " ";
2958 }
2959 return $ret;
2960 }
2961
2962
2969 public static function yn2tf($a_yn)
2970 {
2971 if (strtolower($a_yn) == "y") {
2972 return true;
2973 } else {
2974 return false;
2975 }
2976 }
2977
2984 public static function tf2yn($a_tf)
2985 {
2986 if ($a_tf) {
2987 return "y";
2988 } else {
2989 return "n";
2990 }
2991 }
2992
3003 public static function sort_func($a, $b)
3004 {
3005 global $array_sortby,$array_sortorder;
3006
3007 if (!isset($array_sortby)) {
3008 // occured in: setup -> new client -> install languages -> sorting of languages
3009 $array_sortby = 0;
3010 }
3011
3012 // this comparison should give optimal results if
3013 // locale is provided and mb string functions are supported
3014 if ($array_sortorder == "asc") {
3015 return ilStr::strCmp($a[$array_sortby], $b[$array_sortby]);
3016 }
3017
3018 if ($array_sortorder == "desc") {
3019 return !ilStr::strCmp($a[$array_sortby], $b[$array_sortby]);
3020 return strcoll(ilStr::strToUpper($b[$array_sortby]), ilStr::strToUpper($a[$array_sortby]));
3021 }
3022 }
3023
3034 public static function sort_func_numeric($a, $b)
3035 {
3036 global $array_sortby,$array_sortorder;
3037
3038 if ($array_sortorder == "asc") {
3039 return $a["$array_sortby"] > $b["$array_sortby"];
3040 }
3041
3042 if ($array_sortorder == "desc") {
3043 return $a["$array_sortby"] < $b["$array_sortby"];
3044 }
3045 }
3058 public static function sortArray(
3059 $array,
3060 $a_array_sortby,
3061 $a_array_sortorder = 0,
3062 $a_numeric = false,
3063 $a_keep_keys = false
3064 ) {
3065 include_once("./Services/Utilities/classes/class.ilStr.php");
3066
3067 if (!$a_keep_keys) {
3068 return self::stableSortArray($array, $a_array_sortby, $a_array_sortorder, $a_numeric, $a_keep_keys);
3069 }
3070
3071 global $array_sortby,$array_sortorder;
3072 $array_sortby = $a_array_sortby;
3073
3074 if ($a_array_sortorder == "desc") {
3075 $array_sortorder = "desc";
3076 } else {
3077 $array_sortorder = "asc";
3078 }
3079 if ($a_numeric) {
3080 if ($a_keep_keys) {
3081 uasort($array, array("ilUtil", "sort_func_numeric"));
3082 } else {
3083 usort($array, array("ilUtil", "sort_func_numeric"));
3084 }
3085 } else {
3086 if ($a_keep_keys) {
3087 uasort($array, array("ilUtil", "sort_func"));
3088 } else {
3089 usort($array, array("ilUtil", "sort_func"));
3090 }
3091 }
3092 //usort($array,"ilUtil::sort_func");
3093
3094 return $array;
3095 }
3096
3111 public static function stableSortArray($array, $a_array_sortby, $a_array_sortorder = 0, $a_numeric = false)
3112 {
3113 global $array_sortby,$array_sortorder;
3114
3115 $array_sortby = $a_array_sortby;
3116
3117 if ($a_array_sortorder == "desc") {
3118 $array_sortorder = "desc";
3119 } else {
3120 $array_sortorder = "asc";
3121 }
3122
3123 // Create a copy of the array values for sorting
3124 $sort_array = array_values($array);
3125
3126 if ($a_numeric) {
3127 ilUtil::mergesort($sort_array, array("ilUtil", "sort_func_numeric"));
3128 } else {
3129 ilUtil::mergesort($sort_array, array("ilUtil", "sort_func"));
3130 }
3131
3132 return $sort_array;
3133 }
3134
3135 public static function mergesort(&$array, $cmp_function = 'strcmp')
3136 {
3137 // Arrays of size < 2 require no action.
3138 if (count($array) < 2) {
3139 return;
3140 }
3141
3142 // Split the array in half
3143 $halfway = count($array) / 2;
3144 $array1 = array_slice($array, 0, $halfway);
3145 $array2 = array_slice($array, $halfway);
3146
3147 // Recurse to sort the two halves
3148 ilUtil::mergesort($array1, $cmp_function);
3149 ilUtil::mergesort($array2, $cmp_function);
3150
3151 // If all of $array1 is <= all of $array2, just append them.
3152 if (call_user_func($cmp_function, end($array1), $array2[0]) < 1) {
3153 $array = array_merge($array1, $array2);
3154 return;
3155 }
3156
3157 // Merge the two sorted arrays into a single sorted array
3158 $array = array();
3159 $ptr1 = $ptr2 = 0;
3160 while ($ptr1 < count($array1) && $ptr2 < count($array2)) {
3161 if (call_user_func($cmp_function, $array1[$ptr1], $array2[$ptr2]) < 1) {
3162 $array[] = $array1[$ptr1++];
3163 } else {
3164 $array[] = $array2[$ptr2++];
3165 }
3166 }
3167
3168 // Merge the remainder
3169 while ($ptr1 < count($array1)) {
3170 $array[] = $array1[$ptr1++];
3171 }
3172 while ($ptr2 < count($array2)) {
3173 $array[] = $array2[$ptr2++];
3174 }
3175
3176 return;
3177 }
3178
3190 public static function unique_multi_array($array, $sub_key)
3191 {
3192 $target = array();
3193 $existing_sub_key_values = array();
3194
3195 foreach ($array as $key => $sub_array) {
3196 if (!in_array($sub_array[$sub_key], $existing_sub_key_values)) {
3197 $existing_sub_key_values[] = $sub_array[$sub_key];
3198 $target[$key] = $sub_array;
3199 }
3200 }
3201
3202 return $target;
3203 }
3204
3205
3215 public static function getGDSupportedImageType($a_desired_type)
3216 {
3217 $a_desired_type = strtolower($a_desired_type);
3218 // get supported Image Types
3219 $im_types = ImageTypes();
3220
3221 switch ($a_desired_type) {
3222 case "jpg":
3223 case "jpeg":
3224 if ($im_types & IMG_JPG) {
3225 return "jpg";
3226 }
3227 if ($im_types & IMG_GIF) {
3228 return "gif";
3229 }
3230 if ($im_types & IMG_PNG) {
3231 return "png";
3232 }
3233 break;
3234
3235 case "gif":
3236 if ($im_types & IMG_GIF) {
3237 return "gif";
3238 }
3239 if ($im_types & IMG_JPG) {
3240 return "jpg";
3241 }
3242 if ($im_types & IMG_PNG) {
3243 return "png";
3244 }
3245 break;
3246
3247 case "png":
3248 if ($im_types & IMG_PNG) {
3249 return "png";
3250 }
3251 if ($im_types & IMG_JPG) {
3252 return "jpg";
3253 }
3254 if ($im_types & IMG_GIF) {
3255 return "gif";
3256 }
3257 break;
3258
3259 case "svg":
3260 if ($im_types & IMG_PNG) {
3261 return "png";
3262 }
3263 if ($im_types & IMG_JPG) {
3264 return "jpg";
3265 }
3266 if ($im_types & IMG_GIF) {
3267 return "gif";
3268 }
3269 break;
3270 }
3271
3272 return "";
3273 }
3274
3284 public static function deducibleSize($a_mime)
3285 {
3286 if (($a_mime == "image/gif") || ($a_mime == "image/jpeg") ||
3287 ($a_mime == "image/png") || ($a_mime == "application/x-shockwave-flash") ||
3288 ($a_mime == "image/tiff") || ($a_mime == "image/x-ms-bmp") ||
3289 ($a_mime == "image/psd") || ($a_mime == "image/iff")) {
3290 return true;
3291 } else {
3292 return false;
3293 }
3294 }
3295
3296
3302 public static function redirect($a_script)
3303 {
3304 global $DIC;
3305
3306 if (!isset($DIC['ilCtrl']) || !$DIC['ilCtrl'] instanceof ilCtrl) {
3307 $ctrl = new ilCtrl();
3308 } else {
3309 $ctrl = $DIC->ctrl();
3310 }
3311 $ctrl->redirectToURL($a_script);
3312 }
3313
3322 public static function insertInstIntoID($a_value)
3323 {
3324 if (substr($a_value, 0, 4) == "il__") {
3325 $a_value = "il_" . IL_INST_ID . "_" . substr($a_value, 4, strlen($a_value) - 4);
3326 }
3327
3328 return $a_value;
3329 }
3330
3341 public static function groupNameExists($a_group_name, $a_id = 0)
3342 {
3343 global $DIC;
3344
3345 $ilDB = $DIC->database();
3346
3347 $ilErr = null;
3348 if (isset($DIC["ilErr"])) {
3349 $ilErr = $DIC["ilErr"];
3350 }
3351
3352 if (empty($a_group_name)) {
3353 $message = __METHOD__ . ": No groupname given!";
3354 $ilErr->raiseError($message, $ilErr->WARNING);
3355 }
3356
3357 $clause = ($a_id) ? " AND obj_id != " . $ilDB->quote($a_id) . " " : "";
3358
3359 $q = "SELECT obj_id FROM object_data " .
3360 "WHERE title = " . $ilDB->quote($a_group_name, "text") . " " .
3361 "AND type = " . $ilDB->quote("grp", "text") .
3362 $clause;
3363
3364 $r = $ilDB->query($q);
3365
3366 if ($r->numRows()) {
3367 return true;
3368 } else {
3369 return false;
3370 }
3371 }
3372
3379 public static function getMemString()
3380 {
3381 $my_pid = getmypid();
3382 return ("MEMORY USAGE (% KB PID ): " . `ps -eo%mem,rss,pid | grep $my_pid`);
3383 }
3384
3391 public static function isWindows()
3392 {
3393 if (strtolower(substr(php_uname(), 0, 3)) == "win") {
3394 return true;
3395 }
3396 return false;
3397 }
3398
3399
3400 public static function escapeShellArg($a_arg)
3401 {
3402 setlocale(LC_CTYPE, "UTF8", "en_US.UTF-8"); // fix for PHP escapeshellcmd bug. See: http://bugs.php.net/bug.php?id=45132
3403 // see also ilias bug 5630
3404 return escapeshellarg($a_arg);
3405 }
3406
3416 public static function escapeShellCmd($a_arg)
3417 {
3418 if (ini_get('safe_mode') == 1) {
3419 return $a_arg;
3420 }
3421 setlocale(LC_CTYPE, "UTF8", "en_US.UTF-8"); // fix for PHP escapeshellcmd bug. See: http://bugs.php.net/bug.php?id=45132
3422 return escapeshellcmd($a_arg);
3423 }
3424
3434 public static function execQuoted($cmd, $args = null)
3435 {
3436 global $DIC;
3437
3438 if (ilUtil::isWindows() && strpos($cmd, " ") !== false && substr($cmd, 0, 1) !== '"') {
3439 // cmd won't work without quotes
3440 $cmd = '"' . $cmd . '"';
3441 if ($args) {
3442 // args are also quoted, workaround is to quote the whole command AGAIN
3443 // was fixed in php 5.2 (see php bug #25361)
3444 if (version_compare(phpversion(), "5.2", "<") && strpos($args, '"') !== false) {
3445 $cmd = '"' . $cmd . " " . $args . '"';
3446 }
3447 // args are not quoted or php is fixed, just append
3448 else {
3449 $cmd .= " " . $args;
3450 }
3451 }
3452 }
3453 // nothing todo, just append args
3454 elseif ($args) {
3455 $cmd .= " " . $args;
3456 }
3457 exec($cmd, $arr);
3458
3459 $DIC->logger()->root()->debug("ilUtil::execQuoted: " . $cmd . ".");
3460
3461 return $arr;
3462 }
3463
3486 public static function excelTime($year = "", $month = "", $day = "", $hour = "", $minute = "", $second = "")
3487 {
3488 $starting_time = mktime(0, 0, 0, 1, 2, 1970);
3489 if (strcmp("$year$month$day$hour$minute$second", "") == 0) {
3490 $target_time = time();
3491 } else {
3492 if ($year < 1970) {
3493 return 0;
3494 }
3495 }
3496 $target_time = mktime($hour, $minute, $second, $month, $day, $year);
3497 $difference = $target_time - $starting_time;
3498 $days = (($difference - ($difference % 86400)) / 86400);
3499 $difference = $difference - ($days * 86400) + 3600;
3500
3501 // #15343 - using a global locale leads to , instead of . for (implicit) floats
3502 return str_replace(",", ".", ($days + 25570 + ($difference / 86400)));
3503 }
3504
3511 public static function renameExecutables($a_dir)
3512 {
3513 $def_arr = explode(",", SUFFIX_REPL_DEFAULT);
3514 foreach ($def_arr as $def) {
3515 ilUtil::rRenameSuffix($a_dir, trim($def), "sec");
3516 }
3517
3518 $def_arr = explode(",", SUFFIX_REPL_ADDITIONAL);
3519 foreach ($def_arr as $def) {
3520 ilUtil::rRenameSuffix($a_dir, trim($def), "sec");
3521 }
3522 }
3523
3528 public static function getSafeFilename($a_initial_filename)
3529 {
3530 $file_peaces = explode('.', $a_initial_filename);
3531
3532 $file_extension = array_pop($file_peaces);
3533
3534 if (SUFFIX_REPL_ADDITIONAL) {
3535 $string_extensions = SUFFIX_REPL_DEFAULT . "," . SUFFIX_REPL_ADDITIONAL;
3536 } else {
3537 $string_extensions = SUFFIX_REPL_DEFAULT;
3538 }
3539
3540 $sufixes = explode(",", $string_extensions);
3541
3542 if (in_array($file_extension, $sufixes)) {
3543 $file_extension = "sec";
3544 }
3545
3546 array_push($file_peaces, $file_extension);
3547
3548 $safe_filename = "";
3549 foreach ($file_peaces as $piece) {
3550 $safe_filename .= "$piece";
3551 if ($piece != end($file_peaces)) {
3552 $safe_filename .= ".";
3553 }
3554 }
3555
3556 return $safe_filename;
3557 }
3558
3571 public static function rRenameSuffix(string $a_dir, string $a_old_suffix, string $a_new_suffix) : bool
3572 {
3573 if ($a_dir === "/"
3574 || $a_dir === ""
3575 || strpos($a_dir, "..") !== false
3576 || trim($a_old_suffix) === "") {
3577 return false;
3578 }
3579
3580 // check if argument is directory
3581 if (!@is_dir($a_dir)) {
3582 return false;
3583 }
3584
3585 // read a_dir
3586 $dir = opendir($a_dir);
3587 if ($dir === false) {
3588 return false;
3589 }
3590
3591 $prohibited = [
3592 '...'
3593 ];
3594
3595 while ($file = readdir($dir)) {
3596 if (
3597 $file !== "."
3598 && $file !== ".."
3599 ) {
3600 // triple dot is not allowed in filenames
3601 if (in_array($file, $prohibited)) {
3602 unlink($a_dir . "/" . $file);
3603 continue;
3604 }
3605
3606 // directories
3607 if (@is_dir($a_dir . "/" . $file)) {
3608 self::rRenameSuffix($a_dir . "/" . $file, $a_old_suffix, $a_new_suffix);
3609 }
3610
3611 // files
3612 if (@is_file($a_dir . "/" . $file)) {
3613 // first check for files with trailing dot
3614 if (strrpos($file, '.') == (strlen($file) - 1)) {
3615 try {
3616 rename($a_dir . '/' . $file, substr($a_dir . '/' . $file, 0, -1));
3617 } catch (Throwable $t) {
3618 // to avoid exploits we do delete this file and continue renaming
3619 unlink($a_dir . '/' . $file);
3620 continue;
3621 }
3622
3623 $file = substr($file, 0, -1);
3624 }
3625
3626 $path_info = pathinfo($a_dir . "/" . $file);
3627
3628 if (strtolower($path_info["extension"]) === strtolower($a_old_suffix)) {
3629 $pos = strrpos($a_dir . "/" . $file, ".");
3630 $new_name = substr($a_dir . "/" . $file, 0, $pos) . "." . $a_new_suffix;
3631 // check if file exists
3632 if (file_exists($new_name)) {
3633 if (is_dir($new_name)) {
3634 ilUtil::delDir($new_name);
3635 } else {
3636 unlink($new_name);
3637 }
3638 }
3639 rename($a_dir . "/" . $file, $new_name);
3640 }
3641 }
3642 }
3643 }
3644 return true;
3645 }
3646
3647 public static function isAPICall()
3648 {
3649 return strpos($_SERVER["SCRIPT_FILENAME"], "api") !== false ||
3650 strpos($_SERVER["SCRIPT_FILENAME"], "dummy") !== false;
3651 }
3652
3653 public static function KT_replaceParam($qstring, $paramName, $paramValue)
3654 {
3655 if (preg_match("/&" . $paramName . "=/", $qstring)) {
3656 return preg_replace("/&" . $paramName . "=[^&]+/", "&" . $paramName . "=" . urlencode($paramValue), $qstring);
3657 } else {
3658 return $qstring . "&" . $paramName . "=" . urlencode($paramValue);
3659 }
3660 }
3661
3662 public static function replaceUrlParameterString($url, $parametersArray)
3663 {
3664 foreach ($parametersArray as $paramName => $paramValue) {
3665 $url = ilUtil::KT_replaceParam($url, $paramName, $paramValue);
3666 }
3667 return $url;
3668 }
3669
3676 public static function generatePasswords($a_number)
3677 {
3678 $ret = array();
3679 srand((double) microtime() * 1000000);
3680
3681 include_once('./Services/PrivacySecurity/classes/class.ilSecuritySettings.php');
3683
3684 for ($i = 1; $i <= $a_number; $i++) {
3685 $min = ($security->getPasswordMinLength() > 0)
3686 ? $security->getPasswordMinLength()
3687 : 6;
3688 $max = ($security->getPasswordMaxLength() > 0)
3689 ? $security->getPasswordMaxLength()
3690 : 10;
3691 if ($min > $max) {
3692 $max = $min + 1;
3693 }
3694 $random = new \ilRandom();
3695 $length = $random->int($min, $max);
3696 $next = $random->int(1, 2);
3697 $vowels = "aeiou";
3698 $vowels_uc = strtoupper($vowels);
3699 $consonants = "bcdfghjklmnpqrstvwxyz";
3700 $consonants_uc = strtoupper($consonants);
3701 $numbers = "1234567890";
3702 $special = "_.+?#-*@!$%~";
3703 $pw = "";
3704
3705 if ($security->getPasswordNumberOfUppercaseChars() > 0) {
3706 for ($j = 0; $j < $security->getPasswordNumberOfUppercaseChars(); $j++) {
3707 switch ($next) {
3708 case 1:
3709 $pw .= $consonants_uc[$random->int(0, strlen($consonants_uc) - 1)];
3710 $next = 2;
3711 break;
3712
3713 case 2:
3714 $pw .= $vowels_uc[$random->int(0, strlen($vowels_uc) - 1)];
3715 $next = 1;
3716 break;
3717 }
3718 }
3719 }
3720
3721 if ($security->isPasswordCharsAndNumbersEnabled()) {
3722 $pw .= $numbers[$random->int(0, strlen($numbers) - 1)];
3723 }
3724
3725 if ($security->isPasswordSpecialCharsEnabled()) {
3726 $pw .= $special[$random->int(0, strlen($special) - 1)];
3727 }
3728
3729 $num_lcase_chars = max($security->getPasswordNumberOfLowercaseChars(), $length - strlen($pw));
3730 for ($j = 0; $j < $num_lcase_chars; $j++) {
3731 switch ($next) {
3732 case 1:
3733 $pw .= $consonants[$random->int(0, strlen($consonants) - 1)];
3734 $next = 2;
3735 break;
3736
3737 case 2:
3738 $pw .= $vowels[$random->int(0, strlen($vowels) - 1)];
3739 $next = 1;
3740 break;
3741 }
3742 }
3743
3744 $pw = str_shuffle($pw);
3745
3746 $ret[] = $pw;
3747 }
3748 return $ret;
3749 }
3750
3751 public static function removeTrailingPathSeparators($path)
3752 {
3753 $path = preg_replace("/[\/\\\]+$/", "", $path);
3754 return $path;
3755 }
3756
3767 public static function array_php2js($data)
3768 {
3769 if (empty($data)) {
3770 $data = array();
3771 }
3772
3773 foreach ($data as $k => $datum) {
3774 if (is_null($datum)) {
3775 $data[$k] = 'null';
3776 }
3777 if (is_string($datum)) {
3778 $data[$k] = "'" . $datum . "'";
3779 }
3780 if (is_array($datum)) {
3781 $data[$k] = array_php2js($datum);
3782 }
3783 }
3784
3785 return "[" . implode(', ', $data) . "]";
3786 }
3787
3794 public static function virusHandling($a_file, $a_orig_name = "", $a_clean = true)
3795 {
3796 global $DIC;
3797
3798 $lng = $DIC->language();
3799
3800 if ((defined('IL_VIRUS_SCANNER') && IL_VIRUS_SCANNER != "None") || (defined('IL_ICAP_HOST') && strlen(IL_ICAP_HOST) !== 0)) {
3801 require_once("./Services/VirusScanner/classes/class.ilVirusScannerFactory.php");
3803 if (($vs_txt = $vs->scanFile($a_file, $a_orig_name)) != "") {
3804 if ($a_clean && (IL_VIRUS_CLEAN_COMMAND != "")) {
3805 $clean_txt = $vs->cleanFile($a_file, $a_orig_name);
3806 if ($vs->fileCleaned()) {
3807 $vs_txt .= "<br />" . $lng->txt("cleaned_file") .
3808 "<br />" . $clean_txt;
3809 $vs_txt .= "<br />" . $lng->txt("repeat_scan");
3810 if (($vs2_txt = $vs->scanFile($a_file, $a_orig_name)) != "") {
3811 return array(false, nl2br($vs_txt) . "<br />" . $lng->txt("repeat_scan_failed") .
3812 "<br />" . nl2br($vs2_txt));
3813 } else {
3814 return array(true, nl2br($vs_txt) . "<br />" . $lng->txt("repeat_scan_succeded"));
3815 }
3816 } else {
3817 return array(false, nl2br($vs_txt) . "<br />" . $lng->txt("cleaning_failed"));
3818 }
3819 } else {
3820 return array(false, nl2br($vs_txt));
3821 }
3822 }
3823 }
3824
3825 return array(true,"");
3826 }
3827
3828
3848 public static function moveUploadedFile($a_file, $a_name, $a_target, $a_raise_errors = true, $a_mode = "move_uploaded")
3849 {
3850 global $DIC;
3851 $target_filename = basename($a_target);
3852
3853 include_once("./Services/Utilities/classes/class.ilFileUtils.php");
3854 $target_filename = ilFileUtils::getValidFilename($target_filename);
3855
3856 // Make sure the target is in a valid subfolder. (e.g. no uploads to ilias/setup/....)
3857 list($target_filesystem, $target_dir) = self::sanitateTargetPath($a_target);
3858
3859 $upload = $DIC->upload();
3860
3861 // If the upload has not yet been processed make sure he gets processed now.
3862 if (!$upload->hasBeenProcessed()) {
3863 $upload->process();
3864 }
3865
3866 try {
3867 if (!$upload->hasUploads()) {
3868 throw new ilException($DIC->language()->txt("upload_error_file_not_found"));
3869 }
3870 $upload_result = $upload->getResults()[$a_file] ?? null;
3871 if ($upload_result instanceof UploadResult) {
3872 $processing_status = $upload_result->getStatus();
3873 if ($processing_status->getCode() === ProcessingStatus::REJECTED
3874 || $processing_status->getCode() === ProcessingStatus::DENIED) {
3875 throw new ilException($processing_status->getMessage());
3876 }
3877 } else {
3878 return false;
3879 }
3880 } catch (ilException $e) {
3881 if (!$a_raise_errors) {
3882 ilUtil::sendFailure($e->getMessage(), true);
3883 } else {
3884 throw $e;
3885 }
3886
3887 return false;
3888 }
3889
3890 $upload->moveOneFileTo($upload_result, $target_dir, $target_filesystem, $target_filename, true);
3891
3892 return true;
3893 }
3894
3895
3902 public static function date_mysql2time($mysql_date_time)
3903 {
3904 list($datum, $uhrzeit) = explode(" ", $mysql_date_time);
3905 list($jahr, $monat, $tag) = explode("-", $datum);
3906 list($std, $min, $sec) = explode(":", $uhrzeit);
3907 return mktime((int) $std, (int) $min, (int) $sec, (int) $monat, (int) $tag, (int) $jahr);
3908 }
3909
3916 public static function now()
3917 {
3918 return date("Y-m-d H:i:s");
3919 }
3920
3936 public static function &processCSVRow(&$row, $quoteAll = false, $separator = ";", $outUTF8 = false, $compatibleWithMSExcel = true)
3937 {
3938 $resultarray = array();
3939 foreach ($row as $rowindex => $entry) {
3940 $surround = false;
3941 if ($quoteAll) {
3942 $surround = true;
3943 }
3944 if (strpos($entry, "\"") !== false) {
3945 $entry = str_replace("\"", "\"\"", $entry);
3946 $surround = true;
3947 }
3948 if (strpos($entry, $separator) !== false) {
3949 $surround = true;
3950 }
3951 if ($compatibleWithMSExcel) {
3952 // replace all CR LF with LF (for Excel for Windows compatibility
3953 $entry = str_replace(chr(13) . chr(10), chr(10), $entry);
3954 }
3955 if ($surround) {
3956 if ($outUTF8) {
3957 $resultarray[$rowindex] = "\"" . $entry . "\"";
3958 } else {
3959 $resultarray[$rowindex] = utf8_decode("\"" . $entry . "\"");
3960 }
3961 } else {
3962 if ($outUTF8) {
3963 $resultarray[$rowindex] = $entry;
3964 } else {
3965 $resultarray[$rowindex] = utf8_decode($entry);
3966 }
3967 }
3968 }
3969 return $resultarray;
3970 }
3971
3972 // validates a domain name (example: www.ilias.de)
3973 public static function isDN($a_str)
3974 {
3975 return(preg_match("/^[a-z]+([a-z0-9-]*[a-z0-9]+)?(\.([a-z]+([a-z0-9-]*[a-z0-9]+)?)+)*$/", $a_str));
3976 }
3977
3978 // validates an IP address (example: 192.168.1.1)
3979 public static function isIPv4($a_str)
3980 {
3981 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])\." .
3982 "(\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));
3983 }
3984
3985
4014 public static function _getObjectsByOperations($a_obj_type, $a_operation, $a_usr_id = 0, $limit = 0)
4015 {
4016 global $DIC;
4017
4018 $ilDB = $DIC->database();
4019 $rbacreview = $DIC->rbac()->review();
4020 $ilAccess = $DIC->access();
4021 $ilUser = $DIC->user();
4022 $ilSetting = $DIC->settings();
4023 $tree = $DIC->repositoryTree();
4024
4025 if (!is_array($a_obj_type)) {
4026 $where = "WHERE type = " . $ilDB->quote($a_obj_type, "text") . " ";
4027 } else {
4028 $where = "WHERE " . $ilDB->in("type", $a_obj_type, false, "text") . " ";
4029 }
4030
4031 // limit number of results default is search result limit
4032 if (!$limit) {
4033 $limit = $ilSetting->get('search_max_hits', 100);
4034 }
4035 if ($limit == -1) {
4036 $limit = 10000;
4037 }
4038
4039 // default to logged in usr
4040 $a_usr_id = $a_usr_id ? $a_usr_id : $ilUser->getId();
4041 $a_roles = $rbacreview->assignedRoles($a_usr_id);
4042
4043 // Since no rbac_pa entries are available for the system role. This function returns !all! ref_ids in the case the user
4044 // is assigned to the system role
4045 if ($rbacreview->isAssigned($a_usr_id, SYSTEM_ROLE_ID)) {
4046 $query = "SELECT ref_id FROM object_reference obr LEFT JOIN object_data obd ON obr.obj_id = obd.obj_id " .
4047 "LEFT JOIN tree ON obr.ref_id = tree.child " .
4048 $where .
4049 "AND tree = 1";
4050
4051 $res = $ilDB->query($query);
4052 $counter = 0;
4053 while ($row = $ilDB->fetchObject($res)) {
4054 // Filter recovery folder
4055 if ($tree->isGrandChild(RECOVERY_FOLDER_ID, $row->ref_id)) {
4056 continue;
4057 }
4058
4059 if ($counter++ >= $limit) {
4060 break;
4061 }
4062
4063 $ref_ids[] = $row->ref_id;
4064 }
4065 return $ref_ids ? $ref_ids : array();
4066 } // End Administrators
4067
4068 // Check ownership if it is not asked for edit_permission or a create permission
4069 if ($a_operation == 'edit_permissions' or strpos($a_operation, 'create') !== false) {
4070 $check_owner = ") ";
4071 } else {
4072 $check_owner = "OR owner = " . $ilDB->quote($a_usr_id, "integer") . ") ";
4073 }
4074
4075 $ops_ids = ilRbacReview::_getOperationIdsByName(array($a_operation));
4076 $ops_id = $ops_ids[0];
4077
4078 $and = "AND ((" . $ilDB->in("rol_id", $a_roles, false, "integer") . " ";
4079
4080 $query = "SELECT DISTINCT(obr.ref_id),obr.obj_id,type FROM object_reference obr " .
4081 "JOIN object_data obd ON obd.obj_id = obr.obj_id " .
4082 "LEFT JOIN rbac_pa ON obr.ref_id = rbac_pa.ref_id " .
4083 $where .
4084 $and .
4085 "AND (" . $ilDB->like("ops_id", "text", "%i:" . $ops_id . "%") . " " .
4086 "OR " . $ilDB->like("ops_id", "text", "%:\"" . $ops_id . "\";%") . ")) " .
4087 $check_owner;
4088
4089 $res = $ilDB->query($query);
4090 $counter = 0;
4091 while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) {
4092 if ($counter >= $limit) {
4093 break;
4094 }
4095
4096 // Filter objects in recovery folder
4097 if ($tree->isGrandChild(RECOVERY_FOLDER_ID, $row->ref_id)) {
4098 continue;
4099 }
4100
4101 // Check deleted, hierarchical access ...
4102 if ($ilAccess->checkAccessOfUser($a_usr_id, $a_operation, '', $row->ref_id, $row->type, $row->obj_id)) {
4103 $counter++;
4104 $ref_ids[] = $row->ref_id;
4105 }
4106 }
4107 return $ref_ids ? $ref_ids : array();
4108 }
4109
4110
4116 protected static function sanitateTargetPath($a_target)
4117 {
4118 switch (true) {
4119 case strpos($a_target, ILIAS_WEB_DIR . '/' . CLIENT_ID) === 0:
4120 case strpos($a_target, './' . ILIAS_WEB_DIR . '/' . CLIENT_ID) === 0:
4121 case strpos($a_target, CLIENT_WEB_DIR) === 0:
4122 $targetFilesystem = \ILIAS\FileUpload\Location::WEB;
4123 break;
4124 case strpos($a_target, CLIENT_DATA_DIR . "/temp") === 0:
4125 $targetFilesystem = \ILIAS\FileUpload\Location::TEMPORARY;
4126 break;
4127 case strpos($a_target, CLIENT_DATA_DIR) === 0:
4128 $targetFilesystem = \ILIAS\FileUpload\Location::STORAGE;
4129 break;
4130 case strpos($a_target, ILIAS_ABSOLUTE_PATH . '/Customizing') === 0:
4131 $targetFilesystem = \ILIAS\FileUpload\Location::CUSTOMIZING;
4132 break;
4133 default:
4134 throw new InvalidArgumentException("Can not move files to \"$a_target\" because path can not be mapped to web, storage or customizing location.");
4135 }
4136
4137 $absTargetDir = dirname($a_target);
4138 $targetDir = LegacyPathHelper::createRelativePath($absTargetDir);
4139
4140 return array( $targetFilesystem, $targetDir );
4141 }
4142
4143
4148 public function includeMathjax($a_tpl = null)
4149 {
4150 include_once './Services/MathJax/classes/class.ilMathJax.php';
4151 ilMathJax::getInstance()->includeMathJax($a_tpl);
4152 }
4153
4158 public static function insertLatexImages($a_text, $a_start = '[tex]', $a_end = '[/tex]')
4159 {
4160 include_once './Services/MathJax/classes/class.ilMathJax.php';
4161 return ilMathJax::getInstance()->insertLatexImages($a_text, $a_start, $a_end);
4162 }
4163
4168 public static function buildLatexImages($a_text, $a_dir)
4169 {
4170 include_once './Services/MathJax/classes/class.ilMathJax.php';
4171 return ilMathJax::getInstance()->insertLatexImages($a_text, '[tex]', '[/tex]', $a_dir . '/teximg', './teximg');
4172 }
4173
4182 public static function prepareTextareaOutput($txt_output, $prepare_for_latex_output = false, $omitNl2BrWhenTextArea = false)
4183 {
4184 $result = $txt_output;
4185 $is_html = self::isHTML($result);
4186
4187 // removed: did not work with magic_quotes_gpc = On
4188 if (!$is_html) {
4189 if (!$omitNl2BrWhenTextArea) {
4190 // if the string does not contain HTML code, replace the newlines with HTML line breaks
4191 $result = preg_replace("/[\n]/", "<br />", $result);
4192 }
4193 } else {
4194 // patch for problems with the <pre> tags in tinyMCE
4195 if (preg_match_all("/(<pre>.*?<\/pre>)/ims", $result, $matches)) {
4196 foreach ($matches[0] as $found) {
4197 $replacement = "";
4198 if (strpos("\n", $found) === false) {
4199 $replacement = "\n";
4200 }
4201 $removed = preg_replace("/<br\s*?\/>/ims", $replacement, $found);
4202 $result = str_replace($found, $removed, $result);
4203 }
4204 }
4205 }
4206
4207 // since server side mathjax rendering does include svg-xml structures that indeed have linebreaks,
4208 // do latex conversion AFTER replacing linebreaks with <br>. <svg> tag MUST NOT contain any <br> tags.
4209 if ($prepare_for_latex_output) {
4210 include_once './Services/MathJax/classes/class.ilMathJax.php';
4211 $result = ilMathJax::getInstance()->insertLatexImages($result, "<span class\=\"latex\">", "<\/span>");
4212 $result = ilMathJax::getInstance()->insertLatexImages($result, "\[tex\]", "\[\/tex\]");
4213 }
4214
4215 if ($prepare_for_latex_output) {
4216 // replace special characters to prevent problems with the ILIAS template system
4217 // eg. if someone uses {1} as an answer, nothing will be shown without the replacement
4218 $result = str_replace("{", "&#123;", $result);
4219 $result = str_replace("}", "&#125;", $result);
4220 $result = str_replace("\\", "&#92;", $result);
4221 }
4222
4223 return $result;
4224 }
4225
4234 public static function isHTML($a_text)
4235 {
4236 if (strlen(strip_tags($a_text)) < strlen($a_text)) {
4237 return true;
4238 }
4239
4240 return false;
4241 }
4242
4252 public static function period2String(ilDateTime $a_from, $a_to = null)
4253 {
4254 global $DIC;
4255
4256 $lng = $DIC->language();
4257
4258 if (!$a_to) {
4259 $a_to = new ilDateTime(time(), IL_CAL_UNIX);
4260 }
4261
4262 $from = new DateTime($a_from->get(IL_CAL_DATETIME));
4263 $to = new DateTime($a_to->get(IL_CAL_DATETIME));
4264 $diff = $to->diff($from);
4265
4266 $periods = array();
4267 $periods["years"] = $diff->format("%y");
4268 $periods["months"] = $diff->format("%m");
4269 $periods["days"] = $diff->format("%d");
4270 $periods["hours"] = $diff->format("%h");
4271 $periods["minutes"] = $diff->format("%i");
4272 $periods["seconds"] = $diff->format("%s");
4273
4274 if (!array_sum($periods)) {
4275 return;
4276 }
4277
4278 foreach ($periods as $key => $value) {
4279 if ($value) {
4280 $segment_name = ($value > 1)
4281 ? $key
4282 : substr($key, 0, -1);
4283 $array[] = $value . ' ' . $lng->txt($segment_name);
4284 }
4285 }
4286
4287 $len = sizeof($array);
4288 if ($len > 3) {
4289 $array = array_slice($array, 0, (3 - $len));
4290 }
4291
4292 return implode(', ', $array);
4293 }
4294
4295 public static function getFileSizeInfo()
4296 {
4297 $max_filesize = self::formatBytes(
4298 self::getUploadSizeLimitBytes()
4299 );
4300
4301 global $DIC;
4302
4303 $lng = $DIC->language();
4304 /*
4305 // get the value for the maximal uploadable filesize from the php.ini (if available)
4306 $umf=get_cfg_var("upload_max_filesize");
4307 // get the value for the maximal post data from the php.ini (if available)
4308 $pms=get_cfg_var("post_max_size");
4309
4310 // use the smaller one as limit
4311 $max_filesize=min($umf, $pms);
4312 if (!$max_filesize) $max_filesize=max($umf, $pms);
4313 */
4314 return $lng->txt("file_notice") . " $max_filesize.";
4315 }
4316
4317 public static function formatBytes($size, $decimals = 0)
4318 {
4319 $unit = array('', 'K', 'M', 'G', 'T', 'P');
4320
4321 for ($i = 0, $maxUnits = count($unit); $size >= 1024 && $i <= $maxUnits; $i++) {
4322 $size /= 1024;
4323 }
4324
4325 return round($size, $decimals) . $unit[$i];
4326 }
4327
4328 public static function getUploadSizeLimitBytes()
4329 {
4330 $uploadSizeLimitBytes = min(
4331 self::convertPhpIniSizeValueToBytes(ini_get('post_max_size')),
4332 self::convertPhpIniSizeValueToBytes(ini_get('upload_max_filesize'))
4333 );
4334
4335 return $uploadSizeLimitBytes;
4336 }
4337
4338 public static function convertPhpIniSizeValueToBytes($phpIniSizeValue)
4339 {
4340 if (is_numeric($phpIniSizeValue)) {
4341 return $phpIniSizeValue;
4342 }
4343
4344 $suffix = substr($phpIniSizeValue, -1);
4345 $value = substr($phpIniSizeValue, 0, -1);
4346
4347 switch (strtoupper($suffix)) {
4348 case 'P':
4349 $value *= 1024;
4350 // no break
4351 case 'T':
4352 $value *= 1024;
4353 // no break
4354 case 'G':
4355 $value *= 1024;
4356 // no break
4357 case 'M':
4358 $value *= 1024;
4359 // no break
4360 case 'K':
4361 $value *= 1024;
4362 break;
4363 }
4364
4365 return $value;
4366 }
4367
4376 public static function __extractRefId($role_title)
4377 {
4378 $test_str = explode('_', $role_title);
4379
4380 if ($test_str[0] == 'il') {
4381 $test2 = (int) $test_str[3];
4382 return is_numeric($test2) ? (int) $test2 : false;
4383 }
4384 return false;
4385 }
4386
4397 public static function __extractId($ilias_id, $inst_id)
4398 {
4399 $test_str = explode('_', $ilias_id);
4400
4401 if ($test_str[0] == 'il' && $test_str[1] == $inst_id && count($test_str) == 4) {
4402 $test2 = (int) $test_str[3];
4403 return is_numeric($test2) ? (int) $test2 : false;
4404 }
4405 return false;
4406 }
4407
4422 public static function _sortIds($a_ids, $a_table, $a_field, $a_id_name)
4423 {
4424 global $DIC;
4425
4426 $ilDB = $DIC->database();
4427
4428 if (!$a_ids) {
4429 return array();
4430 }
4431
4432 // use database to sort user array
4433 $where = "WHERE " . $a_id_name . " IN (";
4434 $where .= implode(",", ilUtil::quoteArray($a_ids));
4435 $where .= ") ";
4436
4437 $query = "SELECT " . $a_id_name . " FROM " . $a_table . " " .
4438 $where .
4439 "ORDER BY " . $a_field;
4440
4441 $res = $ilDB->query($query);
4442 while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) {
4443 $ids[] = $row->$a_id_name;
4444 }
4445 return $ids ? $ids : array();
4446 }
4447
4457 public static function getMySQLTimestamp($a_ts)
4458 {
4459 global $DIC;
4460
4461 $ilDB = $DIC->database();
4462
4463 return $a_ts;
4464 }
4465
4472 public static function quoteArray($a_array)
4473 {
4474 global $DIC;
4475
4476 $ilDB = $DIC->database();
4477
4478
4479 if (!is_array($a_array) or !count($a_array)) {
4480 return array("''");
4481 }
4482
4483 foreach ($a_array as $k => $item) {
4484 $a_array[$k] = $ilDB->quote($item);
4485 }
4486
4487 return $a_array;
4488 }
4489
4496 public static function getSystemMessageHTML($a_txt, $a_type = "info")
4497 {
4498 global $DIC;
4499
4500 $lng = $DIC->language();
4501 $mtpl = new ilTemplate("tpl.message.html", true, true, "Services/Utilities");
4502 $mtpl->setCurrentBlock($a_type . "_message");
4503 $mtpl->setVariable("TEXT", $a_txt);
4504 $mtpl->setVariable("MESSAGE_HEADING", $lng->txt($a_type . "_message"));
4505 $mtpl->parseCurrentBlock();
4506
4507 return $mtpl->get();
4508 }
4509
4518 public static function sendInfo($a_info = "", $a_keep = false)
4519 {
4520 global $DIC;
4521
4522 $tpl = $DIC["tpl"];
4523 $tpl->setOnScreenMessage("info", $a_info, $a_keep);
4524 }
4525
4534 public static function sendFailure($a_info = "", $a_keep = false)
4535 {
4536 global $DIC;
4537
4538 if (isset($DIC["tpl"])) {
4539 $tpl = $DIC["tpl"];
4540 $tpl->setOnScreenMessage("failure", $a_info, $a_keep);
4541 }
4542 }
4543
4550 public static function sendQuestion($a_info = "", $a_keep = false)
4551 {
4552 global $DIC;
4553
4554 $tpl = $DIC["tpl"];
4555 $tpl->setOnScreenMessage("question", $a_info, $a_keep);
4556 }
4557
4566 public static function sendSuccess($a_info = "", $a_keep = false)
4567 {
4568 global $DIC;
4569
4571 $tpl = $DIC["tpl"];
4572 $tpl->setOnScreenMessage("success", $a_info, $a_keep);
4573 }
4574
4575 public static function infoPanel($a_keep = true)
4576 {
4577 global $DIC;
4578
4579 $tpl = $DIC["tpl"];
4580 $lng = $DIC->language();
4581 $ilUser = $DIC->user();
4582
4583 if (!empty($_SESSION["infopanel"]) and is_array($_SESSION["infopanel"])) {
4584 $tpl->addBlockFile(
4585 "INFOPANEL",
4586 "infopanel",
4587 "tpl.infopanel.html",
4588 "Services/Utilities"
4589 );
4590 $tpl->setCurrentBlock("infopanel");
4591
4592 if (!empty($_SESSION["infopanel"]["text"])) {
4593 $link = "<a href=\"" . $_SESSION["infopanel"]["link"] . "\" target=\"" .
4594 ilFrameTargetInfo::_getFrame("MainContent") .
4595 "\">";
4596 $link .= $lng->txt($_SESSION["infopanel"]["text"]);
4597 $link .= "</a>";
4598 }
4599
4600 // deactivated
4601 if (!empty($_SESSION["infopanel"]["img"])) {
4602 $link .= "<td><a href=\"" . $_SESSION["infopanel"]["link"] . "\" target=\"" .
4603 ilFrameTargetInfo::_getFrame("MainContent") .
4604 "\">";
4605 $link .= "<img src=\"" . "./templates/" . $ilUser->prefs["skin"] . "/images/" .
4606 $_SESSION["infopanel"]["img"] . "\" border=\"0\" vspace=\"0\"/>";
4607 $link .= "</a></td>";
4608 }
4609
4610 $tpl->setVariable("INFO_ICONS", $link);
4611 $tpl->parseCurrentBlock();
4612 }
4613
4614 //if (!$a_keep)
4615 //{
4616 ilSession::clear("infopanel");
4617 //}
4618 }
4619
4620
4629 public static function dirsize($directory)
4630 {
4631 $size = 0;
4632 if (!is_dir($directory)) {
4633 // dirsize of non-existing directory
4634 $size = @filesize($directory);
4635 return ($size === false) ? -1 : $size;
4636 }
4637 if ($DIR = opendir($directory)) {
4638 while (($dirfile = readdir($DIR)) !== false) {
4639 if (is_link($directory . DIRECTORY_SEPARATOR . $dirfile) || $dirfile == '.' || $dirfile == '..') {
4640 continue;
4641 }
4642 if (is_file($directory . DIRECTORY_SEPARATOR . $dirfile)) {
4643 $size += filesize($directory . DIRECTORY_SEPARATOR . $dirfile);
4644 } elseif (is_dir($directory . DIRECTORY_SEPARATOR . $dirfile)) {
4645 $dirSize = ilUtil::dirsize($directory . DIRECTORY_SEPARATOR . $dirfile);
4646 if ($dirSize >= 0) {
4647 $size += $dirSize;
4648 } else {
4649 return -1;
4650 }
4651 }
4652 }
4653 closedir($DIR);
4654 }
4655 return $size;
4656 }
4657
4658 public static function randomhash()
4659 {
4660 $random = new \ilRandom();
4661 return md5($random->int(1, 9999999) + str_replace(" ", "", (string) microtime()));
4662 }
4663
4664 public static function setCookie($a_cookie_name, $a_cookie_value = '', $a_also_set_super_global = true, $a_set_cookie_invalid = false)
4665 {
4666 /*
4667 if(!(bool)$a_set_cookie_invalid) $expire = IL_COOKIE_EXPIRE;
4668 else $expire = time() - (365*24*60*60);
4669 */
4670 // Temporary fix for feed.php
4671 if (!(bool) $a_set_cookie_invalid) {
4672 $expire = 0;
4673 } else {
4674 $expire = time() - (365 * 24 * 60 * 60);
4675 }
4676 /* We MUST NOT set the global constant here, because this affects the session_set_cookie_params() call as well
4677 if(!defined('IL_COOKIE_SECURE'))
4678 {
4679 define('IL_COOKIE_SECURE', false);
4680 }
4681 */
4682 $secure = false;
4683 if (defined('IL_COOKIE_SECURE')) {
4684 $secure = IL_COOKIE_SECURE;
4685 }
4686
4687 $cookie_parameters = [
4688 'expires' => $expire,
4689 'path' => IL_COOKIE_PATH,
4690 'domain' => IL_COOKIE_DOMAIN,
4691 'secure' => $secure,
4692 'httponly' => IL_COOKIE_HTTPONLY,
4693 ];
4694
4695 if (
4696 $secure &&
4697 (!isset(session_get_cookie_params()['samesite']) || strtolower(session_get_cookie_params()['samesite']) !== 'strict')
4698 ) {
4699 $cookie_parameters['samesite'] = 'Lax';
4700 }
4701
4702 setcookie(
4703 $a_cookie_name,
4704 $a_cookie_value,
4705 $cookie_parameters
4706 );
4707
4708 if ((bool) $a_also_set_super_global) {
4709 $_COOKIE[$a_cookie_name] = $a_cookie_value;
4710 }
4711 }
4712
4713 public static function _sanitizeFilemame($a_filename)
4714 {
4715 return strip_tags(self::stripSlashes($a_filename));
4716 }
4717
4718 public static function _getHttpPath()
4719 {
4720 global $DIC;
4721
4722 $ilIliasIniFile = $DIC["ilIliasIniFile"];
4723
4724 if ($_SERVER['SHELL'] || php_sapi_name() == 'cli' ||
4725 // fallback for windows systems, useful in crons
4726 (class_exists("ilContext") && !ilContext::usesHTTP())) {
4727 return $ilIliasIniFile->readVariable('server', 'http_path');
4728 } else {
4729 return ILIAS_HTTP_PATH;
4730 }
4731 }
4732
4738 public static function printBacktrace($a_limit = 0)
4739 {
4740 $bt = debug_backtrace();
4741 $cnt = 0;
4742 foreach ($bt as $t) {
4743 if ($cnt != 0 && ($a_limit == 0 || $cnt <= $a_limit)) {
4744 echo "<br>" . $t["file"] . ", " . $t["function"] . " [" . $t["line"] . "]";
4745 }
4746 $cnt++;
4747 }
4748 echo "<br>";
4749 }
4750
4765 public static function parseImportId($a_import_id)
4766 {
4767 $exploded = explode('_', $a_import_id);
4768
4769 $parsed['orig'] = $a_import_id;
4770 if ($exploded[0] == 'il') {
4771 $parsed['prefix'] = $exploded[0];
4772 }
4773 if (is_numeric($exploded[1])) {
4774 $parsed['inst_id'] = (int) $exploded[1];
4775 }
4776 $parsed['type'] = $exploded[2];
4777
4778 if (is_numeric($exploded[3])) {
4779 $parsed['id'] = (int) $exploded[3];
4780 }
4781 return $parsed;
4782 }
4783
4790 public static function unserializeSession($data)
4791 {
4792 $vars = preg_split(
4793 '/([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff^|]*)\|/',
4794 $data,
4795 -1,
4796 PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE
4797 );
4798
4799 $result = array();
4800
4801 for ($i = 0; $vars[$i]; $i++) {
4802 $result[$vars[$i++]] = unserialize($vars[$i]);
4803 }
4804
4805 return $result;
4806 }
4807
4808
4821 public function rangeDownload($file)
4822 {
4823 $fp = @fopen($file, 'rb');
4824
4825 $size = filesize($file); // File size
4826 $length = $size; // Content length
4827 $start = 0; // Start byte
4828 $end = $size - 1; // End byte
4829 // Now that we've gotten so far without errors we send the accept range header
4830 /* At the moment we only support single ranges.
4831 * Multiple ranges requires some more work to ensure it works correctly
4832 * and comply with the spesifications: http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.2
4833 *
4834 * Multirange support annouces itself with:
4835 * header('Accept-Ranges: bytes');
4836 *
4837 * Multirange content must be sent with multipart/byteranges mediatype,
4838 * (mediatype = mimetype)
4839 * as well as a boundry header to indicate the various chunks of data.
4840 */
4841 header("Accept-Ranges: 0-$length");
4842 // header('Accept-Ranges: bytes');
4843 // multipart/byteranges
4844 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.2
4845 if (isset($_SERVER['HTTP_RANGE'])) {
4846 $c_start = $start;
4847 $c_end = $end;
4848 // Extract the range string
4849 list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
4850 // Make sure the client hasn't sent us a multibyte range
4851 if (strpos($range, ',') !== false) {
4852
4853 // (?) Shoud this be issued here, or should the first
4854 // range be used? Or should the header be ignored and
4855 // we output the whole content?
4856 header('HTTP/1.1 416 Requested Range Not Satisfiable');
4857 header("Content-Range: bytes $start-$end/$size");
4858 // (?) Echo some info to the client?
4859 exit;
4860 }
4861 // If the range starts with an '-' we start from the beginning
4862 // If not, we forward the file pointer
4863 // And make sure to get the end byte if spesified
4864 if ($range == '-') {
4865
4866 // The n-number of the last bytes is requested
4867 $c_start = $size - substr($range, 1);
4868 } else {
4869 $range = explode('-', $range);
4870 $c_start = $range[0];
4871 $c_end = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size;
4872 }
4873 /* Check the range and make sure it's treated according to the specs.
4874 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
4875 */
4876 // End bytes can not be larger than $end.
4877 $c_end = ($c_end > $end) ? $end : $c_end;
4878 // Validate the requested range and return an error if it's not correct.
4879 if ($c_start > $c_end || $c_start > $size - 1 || $c_end >= $size) {
4880 header('HTTP/1.1 416 Requested Range Not Satisfiable');
4881 header("Content-Range: bytes $start-$end/$size");
4882 // (?) Echo some info to the client?
4883 exit;
4884 }
4885 $start = $c_start;
4886 $end = $c_end;
4887 $length = $end - $start + 1; // Calculate new content length
4888 fseek($fp, $start);
4889 header('HTTP/1.1 206 Partial Content');
4890 }
4891 // Notify the client the byte range we'll be outputting
4892 header("Content-Range: bytes $start-$end/$size");
4893 header("Content-Length: $length");
4894
4895 // Start buffered download
4896 $buffer = 1024 * 8;
4897 while (!feof($fp) && ($p = ftell($fp)) <= $end) {
4898 if ($p + $buffer > $end) {
4899
4900 // In case we're only outputtin a chunk, make sure we don't
4901 // read past the length
4902 $buffer = $end - $p + 1;
4903 }
4904 set_time_limit(0); // Reset time limit for big files
4905 echo fread($fp, $buffer);
4906 flush(); // Free up memory. Otherwise large files will trigger PHP's memory limit.
4907 }
4908
4909 fclose($fp);
4910 }
4911
4912
4913 //
4914 // used to be in ilFormat
4915 //
4916
4929 protected static function _getSizeMagnitude()
4930 {
4931 return 1024;
4932 }
4933
4947 protected static function fmtFloat($a_float, $a_decimals = 0, $a_dec_point = null, $a_thousands_sep = null, $a_suppress_dot_zero = false)
4948 {
4949 global $DIC;
4950
4951 $lng = $DIC->language();
4952
4953 if ($a_dec_point == null) {
4954 {
4955 $a_dec_point = ".";
4956 }
4957 }
4958 if ($a_dec_point == '-lang_sep_decimal-') {
4959 $a_dec_point = ".";
4960 }
4961
4962 if ($a_thousands_sep == null) {
4963 $a_thousands_sep = $lng->txt('lang_sep_thousand');
4964 }
4965 if ($a_thousands_sep == '-lang_sep_thousand-') {
4966 $a_thousands_sep = ",";
4967 }
4968
4969 $txt = number_format($a_float, $a_decimals, $a_dec_point, $a_thousands_sep);
4970
4971 // remove trailing ".0"
4972 if (($a_suppress_dot_zero == 0 || $a_decimals == 0)
4973 && substr($txt, -2) == $a_dec_point . '0'
4974 ) {
4975 $txt = substr($txt, 0, strlen($txt) - 2);
4976 }
4977 if ($a_float == 0 and $txt == "") {
4978 $txt = "0";
4979 }
4980
4981 return $txt;
4982 }
4983
5000 public static function formatSize($size, $a_mode = 'short', $a_lng = null)
5001 {
5002 global $DIC;
5003
5004 $lng = $DIC->language();
5005 if ($a_lng == null) {
5006 $a_lng = $lng;
5007 }
5008
5009 $mag = self::_getSizeMagnitude();
5010
5011 if ($size >= $mag * $mag * $mag) {
5012 $scaled_size = $size / $mag / $mag / $mag;
5013 $scaled_unit = 'lang_size_gb';
5014 } else {
5015 if ($size >= $mag * $mag) {
5016 $scaled_size = $size / $mag / $mag;
5017 $scaled_unit = 'lang_size_mb';
5018 } else {
5019 if ($size >= $mag) {
5020 $scaled_size = $size / $mag;
5021 $scaled_unit = 'lang_size_kb';
5022 } else {
5023 $scaled_size = $size;
5024 $scaled_unit = 'lang_size_bytes';
5025 }
5026 }
5027 }
5028
5029 $result = self::fmtFloat($scaled_size, ($scaled_unit
5030 == 'lang_size_bytes') ? 0 : 1, $a_lng->txt('lang_sep_decimal'), $a_lng->txt('lang_sep_thousand'), true)
5031 . ' ' . $a_lng->txt($scaled_unit);
5032 if ($a_mode == 'long' && $size > $mag) {
5033 $result .= ' (' . self::fmtFloat($size, 0, $a_lng->txt('lang_sep_decimal'), $a_lng->txt('lang_sep_thousand')) . ' '
5034 . $a_lng->txt('lang_size_bytes') . ')';
5035 }
5036
5037 return $result;
5038 }
5039
5040
5041 //
5042 // used for disk quotas
5043 //
5044
5045 public static function MB2Bytes($a_value)
5046 {
5047 return ((int) $a_value) * pow(self::_getSizeMagnitude(), 2);
5048 }
5049
5050 public static function Bytes2MB($a_value)
5051 {
5052 return ((int) $a_value) / (pow(self::_getSizeMagnitude(), 2));
5053 }
5054
5062 public static function dbSupportsDisctinctUmlauts()
5063 {
5064 global $DIC;
5065
5066 if (!isset(self::$db_supports_distinct_umlauts)) {
5067 $ilDB = $DIC->database();
5068 $set = $ilDB->query("SELECT (" . $ilDB->quote("A", "text") . " = " . $ilDB->quote("Ä", "text") . ") t FROM DUAL ");
5069 $rec = $ilDB->fetchAssoc($set);
5070 self::$db_supports_distinct_umlauts = !(bool) $rec["t"];
5071 }
5072
5074 }
5075
5081 public static function dumpVar($mixed = null)
5082 {
5083 echo '<pre>';
5084 var_dump($mixed);
5085 echo '</pre>';
5086 }
5087} // END class.ilUtil
$result
if(!defined('PATH_SEPARATOR')) $GLOBALS['_PEAR_default_error_mode']
Definition: PEAR.php:64
$size
Definition: RandomTest.php:84
if(! $in) print
$filename
Definition: buildRTE.php:89
$_SESSION["AccountId"]
An exception for terminatinating execution or to throw for unit testing.
Class LegacyPathHelper The legacy path helper provides convenient functions for the integration of th...
const IL_CAL_UNIX
const IL_CAL_DATETIME
static usesHTTP()
Uses HTTP aka browser.
This class provides processing control methods.
@classDescription Date and time handling
get($a_format, $a_format_str='', $a_tz='')
get formatted date
This file is part of ILIAS, a powerful learning management system published by ILIAS open source e-Le...
Class ilFileDelivery.
static getValidFilename($a_filename)
Get valid filename.
static 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.
Class ilMailRfc822AddressParserFactory.
const ILIAS_HOST
static getInstance()
Singleton: get instance.
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 _getOperationIdsByName($operations)
get ops_id's by name.
static _getInstance()
Get instance of ilSecuritySettings.
static clear($a_var)
Unset a value.
static strPos($a_haystack, $a_needle, $a_offset=null)
Definition: class.ilStr.php:30
static subStr($a_str, $a_start, $a_length=null)
Definition: class.ilStr.php:15
static strCmp($a, $b)
Compare two strings.
static strToUpper($a_string)
Definition: class.ilStr.php:96
static strLen($a_string)
Definition: class.ilStr.php:78
static getCurrentSkin()
get the current skin
static getCurrentStyle()
get the current style or sub style
special template class to simplify handling of ITX/PEAR
@noRector
static getPasswordValidChars($a_as_regex=true, $a_only_special_chars=false)
All valid chars for password.
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 _getSizeMagnitude()
Returns the magnitude used for size units.
static delDir($a_dir, $a_clean_only=false)
removes a dir and all its content (subdirs and files) recursively
static getJSLocation($a_js_name, $a_js_location="", $add_version=false)
get full javascript file name (path inclusive) of current user
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 convertImage( $a_from, $a_to, $a_target_format="", $a_geometry="", $a_background_color="")
convert image
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
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 insertLatexImages($a_text, $a_start='[tex]', $a_end='[/tex]')
replace [tex]...[/tex] tags with formula image code
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 sortArray( $array, $a_array_sortby, $a_array_sortorder=0, $a_numeric=false, $a_keep_keys=false)
sortArray
static stripOnlySlashes($a_str)
strip slashes if magic qoutes is enabled
static sendQuestion($a_info="", $a_keep=false)
Send Question to Screen.
static execQuoted($cmd, $args=null)
exec command and fix spaces on windows
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 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 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)
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 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 getStyleSheetLocation($mode="output", $a_css_name="", $a_css_location="")
get full style sheet file name (path inclusive) of current user
static sanitateTargetPath($a_target)
static redirect($a_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 getClientIdByString(string $clientId)
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 [tex]...[/tex] tags with formula image code for offline use
static printBacktrace($a_limit=0)
printBacktrace
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)
zips given directory/file into given zip.file
static isWindows()
check wether the current client system is a windows system
static img($a_src, $a_alt=null, $a_width="", $a_height="", $a_border=0, $a_id="", $a_class="")
Build img tag.
static dumpVar($mixed=null)
Dump var.
static getSafeFilename($a_initial_filename)
static fmtFloat($a_float, $a_decimals=0, $a_dec_point=null, $a_thousands_sep=null, $a_suppress_dot_zero=false)
format a float
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 formatSize($size, $a_mode='short', $a_lng=null)
Returns the specified file size value in a human friendly form.
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 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 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 rRenameSuffix(string $a_dir, string $a_old_suffix, string $a_new_suffix)
Renames all files with certain suffix and gives them a new suffix.
static unzip(string $path_to_zip_file, bool $overwrite_existing=false, bool $unpack_flat=false)
static maskAttributeTag($a_str, $tag, $tag_att)
static is_email($a_email, ilMailRfc822AddressParserFactory $mailAddressParserFactory=null)
This preg-based function checks whether an e-mail address is formally valid.
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 isLogin($a_login)
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 dbSupportsDisctinctUmlauts()
Only temp fix for #8603, should go to db classes.
static ilTempnam($a_temp_path=null)
Returns a unique and non existing Path for e temporary file or directory.
static deliverFile( $a_file, $a_filename, $a_mime='', $isInline=false, $removeAfterDelivery=false, $a_exit_after=true)
deliver file for download via browser.
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 $db_supports_distinct_umlauts
static getPasswordRequirementsInfo()
infotext for ilPasswordInputGUI setInfo()
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 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)
make time object from mysql_date_time
static getFileSizeInfo()
static MB2Bytes($a_value)
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 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 stableSortArray($array, $a_array_sortby, $a_array_sortorder=0, $a_numeric=false)
Sort an aray using a stable sort algorithm, which preveserves the sequence of array elements which ha...
static sendInfo($a_info="", $a_keep=false)
Send Info Message to Screen.
static getSystemMessageHTML($a_txt, $a_type="info")
Get HTML for a system message.
static shortenText( $a_str, $a_len, $a_dots=false, $a_next_blank=false, $a_keep_extension=false)
shorten a string to given length.
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 & processCSVRow(&$row, $quoteAll=false, $separator=";", $outUTF8=false, $compatibleWithMSExcel=true)
Convertes an array for CSV usage.
static secureUrl($url)
Prepare secure href attribute.
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 Bytes2MB($a_value)
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')
const CLIENT_ID
Definition: constants.php:39
const RECOVERY_FOLDER_ID
Definition: constants.php:35
const SYSTEM_ROLE_ID
Definition: constants.php:27
const ILIAS_WEB_DIR
Definition: constants.php:43
const CLIENT_WEB_DIR
Definition: constants.php:45
const CLIENT_DATA_DIR
Definition: constants.php:44
const IL_INST_ID
Definition: constants.php:38
$login
Definition: cron.php:13
$txt
Definition: error.php:13
global $DIC
Definition: goto.php:24
$target_arr
Definition: goto.php:49
$ilIliasIniFile
Definition: imgupload.php:16
$img
Definition: imgupload.php:57
$errors
Definition: imgupload.php:49
$ilUser
Definition: imgupload.php:18
const TEMPORARY
The ILIAS temporary directory.
Definition: Location.php:38
const CUSTOMIZING
The filesystem within the web root where all the skins and plugins are saved.
Definition: Location.php:33
const WEB
The filesystem within the ilias web root.
Definition: Location.php:23
const STORAGE
The filesystem outside of the ilias web root.
Definition: Location.php:28
if($DIC->http() ->request() ->getMethod()=="GET" &&isset($DIC->http() ->request() ->getQueryParams()['tex'])) $tpl
Definition: latex.php:41
exit
Definition: login.php:29
if($format !==null) $name
Definition: metadata.php:230
$format
Definition: metadata.php:218
$ascii_filename
Definition: metadata.php:361
$i
Definition: metadata.php:24
$source
Definition: metadata.php:76
const IL_COOKIE_PATH(isset($_GET["client_id"]))
Definition: metadata.php:47
$attributes
Definition: metadata.php:231
Class FlySystemFileAccessTest \Provider\FlySystem @runTestsInSeparateProcesses @preserveGlobalState d...
Class ChatMainBarProvider \MainMenu\Provider.
$a
thx to https://mlocati.github.io/php-cs-fixer-configurator for the examples
$base
Definition: index.php:4
$ret
Definition: parser.php:6
global $ilSetting
Definition: privfeed.php:17
$query
$url
$_SERVER['HTTP_HOST']
Definition: raiseError.php:10
$ilErr
Definition: raiseError.php:18
$log
Definition: result.php:15
$lng
foreach($_POST as $key=> $value) $res
global $ilDB
$data
Definition: storeScorm.php:23
const ILIAS_MODULE
Definition: server.php:14
$message
Definition: xapiexit.php:14
$_COOKIE[session_name()]
Definition: xapitoken.php:37