ILIAS  release_6 Revision v6.24-5-g0c8bfefb3b8
class.ilUtil.php
Go to the documentation of this file.
1<?php
2/* Copyright (c) 1998-2010 ILIAS open source, Extended GPL, see docs/LICENSE */
3
11
22class ilUtil
23{
25
36 public static function getImageTagByType($a_type, $a_path, $a_big = false)
37 {
38 global $DIC;
39
40 $lng = $DIC->language();
41
42 $size = ($a_big)
43 ? "big"
44 : "small";
45
46 include_once("./Services/Object/classes/class.ilObject.php");
47 $filename = ilObject::_getIcon("", $size, $a_type);
48
49 return "<img src=\"" . $filename . "\" alt=\"" . $lng->txt("obj_" . $a_type) . "\" title=\"" . $lng->txt("obj_" . $a_type) . "\" border=\"0\" vspace=\"0\"/>";
50 }
51
64 public static function getTypeIconPath($a_type, $a_obj_id, $a_size = 'small')
65 {
66 include_once("./Services/Object/classes/class.ilObject.php");
67 return ilObject::_getIcon($a_obj_id, $a_size, $a_type);
68 }
69
80 public static function getImagePath($img, $module_path = "", $mode = "output", $offline = false)
81 {
82 global $DIC;
83
84 $styleDefinition = null;
85 if (isset($DIC["styleDefinition"])) {
86 $styleDefinition = $DIC["styleDefinition"];
87 }
88
89 if (is_int(strpos($_SERVER["PHP_SELF"], "setup.php"))) {
90 $module_path = "..";
91 }
92 if ($module_path != "") {
93 $module_path = "/" . $module_path;
94 }
95
96 // default image
97 $default_img = "." . $module_path . "/templates/default/images/" . $img;
98
99 // use ilStyleDefinition instead of account to get the current skin and style
100 require_once("./Services/Style/System/classes/class.ilStyleDefinition.php");
101 $current_skin = ilStyleDefinition::getCurrentSkin();
102 $current_style = ilStyleDefinition::getCurrentStyle();
103
104 if (is_object($styleDefinition)) {
105 $image_dir = $styleDefinition->getImageDirectory($current_style);
106 }
107 if ($current_skin == "default") {
108 $user_img = "." . $module_path . "/templates/default/" . $image_dir . "/" . $img;
109 $skin_img = "." . $module_path . "/templates/default/images/" . $img;
110 } elseif (is_object($styleDefinition) && $current_skin != "default") {
111 $user_img = "./Customizing/global/skin/" .
112 $current_skin . $module_path . "/" . $image_dir . "/" . $img;
113 $skin_img = "./Customizing/global/skin/" .
114 $current_skin . $module_path . "/images/" . $img;
115 }
116
117 // temp svg patch
118 /*
119 $pi = pathinfo($img);
120 if ($pi["dirname"] != "") {
121 $pi["dirname"] = $pi["dirname"]."/";
122 }
123 $svg_img = ".".$module_path."/templates/default/images/".$pi["dirname"].$pi["filename"].".svg";
124 if (file_exists($svg_img))
125 {
126 return $svg_img;
127 }*/
128
129
130 if ($offline) {
131 return "./images/" . $img;
132 } elseif (@file_exists($user_img) && $image_dir != "") {
133 return $user_img; // found image for skin and style
134 } elseif (file_exists($skin_img)) {
135 return $skin_img; // found image in skin/images
136 }
137
138 return $default_img; // take image in default
139 }
140
151 public static function getHtmlPath($relative_path)
152 {
153 if (substr($relative_path, 0, 2) == './') {
154 $relative_path = (substr($relative_path, 1));
155 }
156 if (substr($relative_path, 0, 1) != '/') {
157 $relative_path = '/' . $relative_path;
158 }
159 $htmlpath = ILIAS_HTTP_PATH . $relative_path;
160 return $htmlpath;
161 }
162
175 public static function getStyleSheetLocation($mode = "output", $a_css_name = "", $a_css_location = "")
176 {
177 global $DIC;
178
179 $ilSetting = $DIC->settings();
180
181 // add version as parameter to force reload for new releases
182 // use ilStyleDefinition instead of account to get the current style
183 require_once("./Services/Style/System/classes/class.ilStyleDefinition.php");
184 $stylesheet_name = (strlen($a_css_name))
185 ? $a_css_name
187 if (strlen($a_css_location) && (strcmp(substr($a_css_location, -1), "/") != 0)) {
188 $a_css_location = $a_css_location . "/";
189 }
190
191 $filename = "";
192 // use ilStyleDefinition instead of account to get the current skin
193 require_once("./Services/Style/System/classes/class.ilStyleDefinition.php");
194 if (ilStyleDefinition::getCurrentSkin() != "default") {
195 $filename = "./Customizing/global/skin/" . ilStyleDefinition::getCurrentSkin() . "/" . $a_css_location . $stylesheet_name;
196 }
197 if (strlen($filename) == 0 || !file_exists($filename)) {
198 $filename = "./" . $a_css_location . "templates/default/" . $stylesheet_name;
199 }
200 $vers = "";
201 if ($mode != "filesystem") {
202 $vers = str_replace(" ", "-", $ilSetting->get("ilias_version"));
203 $vers = "?vers=" . str_replace(".", "-", $vers);
204 // use version from template xml to force reload on changes
206 $vers .= ($skin->getVersion() != '' ? str_replace(".", "-", '-' . $skin->getVersion()) : '');
207 }
208 return $filename . $vers;
209 }
210
221 public static function getJSLocation($a_js_name, $a_js_location = "", $add_version = false)
222 {
223 global $DIC;
224
225 $ilSetting = $DIC->settings();
226
227 // add version as parameter to force reload for new releases
228 $js_name = $a_js_name;
229 if (strlen($a_js_location) && (strcmp(substr($a_js_location, -1), "/") != 0)) {
230 $a_js_location = $a_js_location . "/";
231 }
232
233 $filename = "";
234 // use ilStyleDefinition instead of account to get the current skin
235 require_once("./Services/Style/System/classes/class.ilStyleDefinition.php");
236 if (ilStyleDefinition::getCurrentSkin() != "default") {
237 $filename = "./Customizing/global/skin/" . ilStyleDefinition::getCurrentSkin() . "/" . $a_js_location . $js_name;
238 }
239 if (strlen($filename) == 0 || !file_exists($filename)) {
240 $filename = "./" . $a_js_location . "templates/default/" . $js_name;
241 }
242 $vers = "";
243 if ($add_version) {
244 $vers = str_replace(" ", "-", $ilSetting->get("ilias_version"));
245 $vers = "?vers=" . str_replace(".", "-", $vers);
246 }
247 return $filename . $vers;
248 }
249
257 public static function getP3PLocation()
258 {
259 if (defined("ILIAS_MODULE")) {
260 $base = '';
261 for ($i = 0;$i < count(explode('/', ILIAS_MODULE));$i++) {
262 $base .= "../Services/Privacy/";
263 }
264 } else {
265 $base = "./Services/Privacy/";
266 }
267
268 if (is_file($base . "w3c/p3p.xml")) {
269 return ILIAS_HTTP_PATH . "w3c/p3p.xml";
270 } else {
271 return ILIAS_HTTP_PATH . "/w3c/p3p_template.xml";
272 }
273 }
274
282 public static function getNewContentStyleSheetLocation($mode = "output")
283 {
284 global $DIC;
285
286 $ilSetting = $DIC->settings();
287
288 // add version as parameter to force reload for new releases
289 if ($mode != "filesystem") {
290 $vers = str_replace(" ", "-", $ilSetting->get("ilias_version"));
291 $vers = "?vers=" . str_replace(".", "-", $vers);
292 }
293
294 // use ilStyleDefinition instead of account to get the current skin and style
295 require_once("./Services/Style/System/classes/class.ilStyleDefinition.php");
296 if (ilStyleDefinition::getCurrentSkin() == "default") {
297 $in_style = "./templates/" . ilStyleDefinition::getCurrentSkin() . "/"
298 . ilStyleDefinition::getCurrentStyle() . "_cont.css";
299 } else {
300 $in_style = "./Customizing/global/skin/" . ilStyleDefinition::getCurrentSkin() . "/"
301 . ilStyleDefinition::getCurrentStyle() . "_cont.css";
302 }
303
304 if (is_file("./" . $in_style)) {
305 return $in_style . $vers;
306 } else {
307 return "templates/default/delos_cont.css" . $vers;
308 }
309 }
310
329 public static function formSelect(
330 $selected,
331 $varname,
332 $options,
333 $multiple = false,
334 $direct_text = false,
335 $size = "0",
336 $style_class = "",
337 $attribs = "",
338 $disabled = false
339 ) {
340 global $DIC;
341
342 $lng = $DIC->language();
343
344 if ($multiple == true) {
345 $multiple = " multiple=\"multiple\"";
346 } else {
347 $multiple = "";
348 $size = 0;
349 }
350
351 $class = " class=\" form-control " . $style_class . "\"";
352
353 // use form-inline!
354 // this is workaround the whole function should be set deprecated
355 // $attributes = " style='display:inline-block;' ";
356
357 if (is_array($attribs)) {
358 foreach ($attribs as $key => $val) {
359 $attributes .= " " . $key . "=\"" . $val . "\"";
360 }
361 }
362 if ($disabled) {
363 $disabled = ' disabled=\"disabled\"';
364 }
365
366 $size_str = "";
367 if ($size > 0) {
368 $size_str = ' size="'.$size.'" ';
369 }
370 $str = "<select name=\"" . $varname . "\"" . $multiple . " $class " . $size_str . " $attributes $disabled>\n";
371
372 foreach ((array) $options as $key => $val) {
373 $style = "";
374 if (is_array($val)) {
375 $style = $val["style"];
376 $val = $val["text"]; // mus be last line, since we overwrite
377 }
378
379 $sty = ($style != "")
380 ? ' style="' . $style . '" '
381 : "";
382
383 if ($direct_text) {
384 $str .= " <option $sty value=\"" . $key . "\"";
385 } else {
386 $str .= " <option $sty value=\"" . $val . "\"";
387 }
388 if (is_array($selected)) {
389 if (in_array($key, $selected)) {
390 $str .= " selected=\"selected\"";
391 }
392 } elseif ($selected == $key) {
393 $str .= " selected=\"selected\"";
394 }
395
396 if ($direct_text) {
397 $str .= ">" . $val . "</option>\n";
398 } else {
399 $str .= ">" . $lng->txt($val) . "</option>\n";
400 }
401 }
402
403 $str .= "</select>\n";
404
405 return $str;
406 }
407
417 public static function getSelectName($selected, $values)
418 {
419 return($values[$selected]);
420 }
421
433 public static function formCheckbox($checked, $varname, $value, $disabled = false)
434 {
435 $str = "<input type=\"checkbox\" name=\"" . $varname . "\"";
436
437 if ($checked == 1) {
438 $str .= " checked=\"checked\"";
439 }
440
441 if ($disabled) {
442 $str .= " disabled=\"disabled\"";
443 }
444
445 $array_var = false;
446
447 if (substr($varname, -2) == "[]") {
448 $array_var = true;
449 }
450
451 // if varname ends with [], use varname[-2] + _ + value as id tag (e.g. "user_id[]" => "user_id_15")
452 if ($array_var) {
453 $varname_id = substr($varname, 0, -2) . "_" . $value;
454 } else {
455 $varname_id = $varname;
456 }
457
458 // dirty removal of other "[]" in string
459 $varname_id = str_replace("[", "_", $varname_id);
460 $varname_id = str_replace("]", "", $varname_id);
461
462 $str .= " value=\"" . $value . "\" id=\"" . $varname_id . "\" />\n";
463
464 return $str;
465 }
466
478 public static function formDisabledRadioButton($checked, $varname, $value, $disabled)
479 {
480 if ($disabled) {
481 $str = "<input disabled type=\"radio\" name=\"" . $varname . "\"";
482 } else {
483 $str = "<input type=\"radio\" name=\"" . $varname . "\"";
484 }
485 if ($checked == 1) {
486 $str .= " checked=\"checked\"";
487 }
488
489 $str .= " value=\"" . $value . "\"";
490 $str .= " id=\"" . $value . "\" />\n";
491
492 return $str;
493 }
494
495
506 public static function formRadioButton($checked, $varname, $value, $onclick = null, $disabled = false)
507 {
508 $str = '<input ';
509
510 if ($onclick) {
511 $str .= ('onclick="' . $onclick . '"');
512 }
513
514 $str .= (" type=\"radio\" name=\"" . $varname . "\"");
515 if ($checked == 1) {
516 $str .= " checked=\"checked\"";
517 }
518
519 if ($disabled) {
520 $str .= " disabled=\"disabled\"";
521 }
522
523 $str .= " value=\"" . $value . "\"";
524
525 $str .= " id=\"" . $value . "\" />\n";
526
527 return $str;
528 }
529
530
540 public static function formInput($varname, $value, $disabled = false)
541 {
542 $str = "<input type=\"input\" name=\"" . $varname . "\"";
543 if ($disabled) {
544 $str .= " disabled";
545 }
546
547 $str .= " value=\"" . $value . "\"";
548
549 $str .= " id=\"" . $value . "\" />\n";
550
551 return $str;
552 }
553
554
561 public static function checkInput($vars)
562 {
563 // TO DO:
564 // Diese Funktion soll Formfeldeingaben berprfen (empty und required)
565 }
566
573 public static function setPathStr($a_path)
574 {
575 if ("" != $a_path && "/" != substr($a_path, -1)) {
576 $a_path .= "/";
577 //$a_path = substr($a_path,1);
578 }
579
580 //return getcwd().$a_path;
581 return $a_path;
582 }
583
596 public static function switchColor($a_num, $a_css1, $a_css2)
597 {
598 if (!($a_num % 2)) {
599 return $a_css1;
600 } else {
601 return $a_css2;
602 }
603 }
604
613 public static function checkFormEmpty($emptyFields)
614 {
615 $feedback = "";
616
617 foreach ($emptyFields as $key => $val) {
618 if ($val == "") {
619 if ($feedback != "") {
620 $feedback .= ", ";
621 }
622 $feedback .= $key;
623 }
624 }
625
626 return $feedback;
627 }
628
653 public static function Linkbar($AScript, $AHits, $ALimit, $AOffset, $AParams = array(), $ALayout = array(), $prefix = '')
654 {
655 $LinkBar = "";
656
657 $layout_link = "";
658 $layout_prev = "&lt;&lt;";
659 $layout_next = "&gt;&gt;";
660
661 // layout options
662 if ((is_array($ALayout) && (count($ALayout) > 0))) {
663 if ($ALayout["link"]) {
664 $layout_link = " class=\"" . $ALayout["link"] . "\"";
665 }
666
667 if ($ALayout["prev"]) {
668 $layout_prev = $ALayout["prev"];
669 }
670
671 if ($ALayout["next"]) {
672 $layout_next = $ALayout["next"];
673 }
674 }
675
676 // show links, if hits greater limit
677 // or offset > 0 (can be > 0 due to former setting)
678 if ($AHits > $ALimit || $AOffset > 0) {
679 if (!empty($AParams)) {
680 foreach ($AParams as $key => $value) {
681 $params .= $key . "=" . $value . "&";
682 }
683 }
684 // if ($params) $params = substr($params,0,-1);
685 if (strpos($AScript, '&')) {
686 $link = $AScript . "&" . $params . $prefix . "offset=";
687 } else {
688 $link = $AScript . "?" . $params . $prefix . "offset=";
689 }
690
691 // ?bergehe "zurck"-link, wenn offset 0 ist.
692 if ($AOffset >= 1) {
693 $prevoffset = $AOffset - $ALimit;
694 if ($prevoffset < 0) {
695 $prevoffset = 0;
696 }
697 $LinkBar .= "<a" . $layout_link . " href=\"" . $link . $prevoffset . "\">" . $layout_prev . "&nbsp;</a>";
698 }
699
700 // Ben?tigte Seitenzahl kalkulieren
701 $pages = intval($AHits / $ALimit);
702
703 // Wenn ein Rest bleibt, addiere eine Seite
704 if (($AHits % $ALimit)) {
705 $pages++;
706 }
707
708 // Bei Offset = 0 keine Seitenzahlen anzeigen : DEAKTIVIERT
709 // if ($AOffset != 0) {
710
711 // ansonsten zeige Links zu den anderen Seiten an
712 for ($i = 1 ;$i <= $pages ; $i++) {
713 $newoffset = $ALimit * ($i - 1);
714
715 if ($newoffset == $AOffset) {
716 $LinkBar .= "[" . $i . "] ";
717 } else {
718 $LinkBar .= '<a ' . $layout_link . ' href="' .
719 $link . $newoffset . '">[' . $i . ']</a> ';
720 }
721 }
722 // }
723
724 // Checken, ob letze Seite erreicht ist
725 // Wenn nicht, gebe einen "Weiter"-Link aus
726 if (!(($AOffset / $ALimit) == ($pages - 1)) && ($pages != 1)) {
727 $newoffset = $AOffset + $ALimit;
728 $LinkBar .= "<a" . $layout_link . " href=\"" . $link . $newoffset . "\">&nbsp;" . $layout_next . "</a>";
729 }
730
731 return $LinkBar;
732 } else {
733 return false;
734 }
735 }
736
748 public static function makeClickable($a_text, $detectGotoLinks = false)
749 {
750 // New code, uses MediaWiki Sanitizer
751 $ret = $a_text;
752
753 // www-URL ohne ://-Angabe
754 $ret = preg_replace(
755 "/(^|[\s]+)(www\.)([A-Za-z0-9#&=?.\/\-]+)/i",
756 "$1http://$2$3",
757 $ret
758 );
759
760 // ftp-URL ohne ://-Angabe
761 $ret = preg_replace(
762 "/(^|[\s]+)(ftp\.)([A-Za-z0-9#&=?.\/\-]+)/i",
763 "$1ftp://$2$3",
764 $ret
765 );
766
767 // E-Mail (this does not work as expected, users must add mailto: manually)
768 //$ret = preg_replace("/(([a-z0-9_]|\-|\.)+@([^[\s]*)([A-Za-z0-9\-]))/i",
769 // "mailto:$1", $ret);
770
771 // mask existing image tags
772 $ret = str_replace('src="http://', '"***masked_im_start***', $ret);
773
774 include_once("./Services/Utilities/classes/class.ilMWParserAdapter.php");
776 $ret = $parser->replaceFreeExternalLinks($ret);
777
778 // unmask existing image tags
779 $ret = str_replace('"***masked_im_start***', 'src="http://', $ret);
780
781 // Should be Safe
782
783 if ($detectGotoLinks) {
784 // replace target blank with self and text with object title.
785 $regExp = "<a[^>]*href=\"(" . str_replace("/", "\/", ILIAS_HTTP_PATH) . "\/goto.php\?target=\w+_(\d+)[^\"]*)\"[^>]*>[^<]*<\/a>";
786 // echo htmlentities($regExp);
787 $ret = preg_replace_callback(
788 "/" . $regExp . "/i",
789 array("ilUtil", "replaceLinkProperties"),
790 $ret
791 );
792
793 // Static links
794 $regExp = "<a[^>]*href=\"(" . str_replace("/", "\/", ILIAS_HTTP_PATH) . "\/goto_.*[a-z0-9]+_([0-9]+)\.html)\"[^>]*>[^<]*<\/a>";
795 // echo htmlentities($regExp);
796 $ret = preg_replace_callback(
797 "/" . $regExp . "/i",
798 array("ilUtil", "replaceLinkProperties"),
799 $ret
800 );
801 }
802
803 return($ret);
804 }
805
819 public static function replaceLinkProperties($matches)
820 {
821 $link = $matches[0];
822 $ref_id = $matches[2];
823
824 if ($ref_id > 0) {
825 $obj_id = ilObject::_lookupObjId($ref_id);
826 if ($obj_id > 0) {
827 $title = ilObject::_lookupTitle($obj_id);
828 $link = "<a href=" . $matches[1] . " target=\"_self\">" . $title . "</a>";
829 }
830 }
831 return $link;
832 }
833
852 public static function makeDateSelect($prefix, $year = "", $month = "", $day = "", $startyear = "", $a_long_month = true, $a_further_options = array(), $emptyoption = false)
853 {
854 global $DIC;
855
856 $lng = $DIC->language();
857
858 $disabled = '';
859 if (isset($a_further_options['disabled']) and $a_further_options['disabled']) {
860 $disabled = 'disabled="disabled" ';
861 }
862
863 $now = getdate();
864 if (!$emptyoption) {
865 if (!strlen($year)) {
866 $year = $now["year"];
867 }
868 if (!strlen($month)) {
869 $month = $now["mon"];
870 }
871 if (!strlen($day)) {
872 $day = $now["mday"];
873 }
874 }
875
876 $year = (int) $year;
877 $month = (int) $month;
878 $day = (int) $day;
879
880 // build day select
881
882 $sel_day .= '<select class="form-control" ';
883 if (isset($a_further_options['select_attributes'])) {
884 foreach ($a_further_options['select_attributes'] as $name => $value) {
885 $sel_day .= ($name . '="' . $value . '" ');
886 }
887 }
888
889 $sel_day .= $disabled . "name=\"" . $prefix . "[d]\" id=\"" . $prefix . "_d\">\n";
890
891 if ($emptyoption) {
892 $sel_day .= "<option value=\"0\">--</option>\n";
893 }
894 for ($i = 1; $i <= 31; $i++) {
895 $sel_day .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
896 }
897 $sel_day .= "</select>\n";
898 $sel_day = preg_replace("/(value\=\"$day\")/", "$1 selected=\"selected\"", $sel_day);
899
900 // build month select
901 $sel_month = '<select class="form-control" ';
902 if (isset($a_further_options['select_attributes'])) {
903 foreach ($a_further_options['select_attributes'] as $name => $value) {
904 $sel_month .= ($name . '="' . $value . '" ');
905 }
906 }
907 $sel_month .= $disabled . "name=\"" . $prefix . "[m]\" id=\"" . $prefix . "_m\">\n";
908
909 if ($emptyoption) {
910 $sel_month .= "<option value=\"0\">--</option>\n";
911 }
912 for ($i = 1; $i <= 12; $i++) {
913 if ($a_long_month) {
914 $sel_month .= "<option value=\"$i\">" . $lng->txt("month_" . sprintf("%02d", $i) . "_long") . "</option>\n";
915 } else {
916 $sel_month .= "<option value=\"$i\">" . $i . "</option>\n";
917 }
918 }
919 $sel_month .= "</select>\n";
920 $sel_month = preg_replace("/(value\=\"$month\")/", "$1 selected=\"selected\"", $sel_month);
921
922 // build year select
923 $sel_year = '<select class="form-control" ';
924 if (isset($a_further_options['select_attributes'])) {
925 foreach ($a_further_options['select_attributes'] as $name => $value) {
926 $sel_year .= ($name . '="' . $value . '" ');
927 }
928 }
929 $sel_year .= $disabled . "name=\"" . $prefix . "[y]\" id=\"" . $prefix . "_y\">\n";
930 if ((strlen($startyear) == 0) || ($startyear > $year)) {
931 if (!$emptyoption || $year != 0) {
932 $startyear = $year - 5;
933 }
934 }
935
936 if (($year + 5) < (date('Y', time()) + 5)) {
937 $end_year = date('Y', time()) + 5;
938 } else {
939 $end_year = $year + 5;
940 }
941
942 if ($emptyoption) {
943 $sel_year .= "<option value=\"0\">----</option>\n";
944 }
945 for ($i = $startyear; $i <= $end_year; $i++) {
946 $sel_year .= "<option value=\"$i\">" . sprintf("%04d", $i) . "</option>\n";
947 }
948 $sel_year .= "</select>\n";
949 $sel_year = preg_replace("/(value\=\"$year\")/", "$1 selected=\"selected\"", $sel_year);
950
951 //$dateformat = $lng->text["lang_dateformat"];
952 $dateformat = "d-m-Y";
953 $dateformat = strtolower(preg_replace("/\W/", "", $dateformat));
954 $dateformat = strtolower(preg_replace("/(\w)/", "%%$1", $dateformat));
955 $dateformat = preg_replace("/%%d/", $sel_day, $dateformat);
956 $dateformat = preg_replace("/%%m/", $sel_month, $dateformat);
957 $dateformat = preg_replace("/%%y/", $sel_year, $dateformat);
958 return $dateformat;
959 }
960
979 public static function makeTimeSelect($prefix, $short = true, $hour = "", $minute = "", $second = "", $a_use_default = true, $a_further_options = array())
980 {
981 global $DIC;
982
983 $lng = $DIC->language();
984 $ilUser = $DIC->user();
985
986 $minute_steps = 1;
987 $disabled = '';
988 if (count($a_further_options)) {
989 if (isset($a_further_options['minute_steps'])) {
990 $minute_steps = $a_further_options['minute_steps'];
991 }
992 if (isset($a_further_options['disabled']) and $a_further_options['disabled']) {
993 $disabled = 'disabled="disabled" ';
994 }
995 }
996
997 if ($a_use_default and !strlen("$hour$minute$second")) {
998 $now = localtime();
999 $hour = $now[2];
1000 $minute = $now[1];
1001 $second = $now[0];
1002 } else {
1003 $hour = (int) $hour;
1004 $minute = (int) $minute;
1005 $second = (int) $second;
1006 }
1007 // build hour select
1008 $sel_hour = '<select ';
1009 if (isset($a_further_options['select_attributes'])) {
1010 foreach ($a_further_options['select_attributes'] as $name => $value) {
1011 $sel_hour .= $name . '=' . $value . ' ';
1012 }
1013 }
1014 $sel_hour .= " " . $disabled . "name=\"" . $prefix . "[h]\" id=\"" . $prefix . "_h\" class=\"form-control\">\n";
1015
1016 $format = $ilUser->getTimeFormat();
1017 for ($i = 0; $i <= 23; $i++) {
1019 $sel_hour .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
1020 } else {
1021 $sel_hour .= "<option value=\"$i\">" . date("ga", mktime($i, 0, 0)) . "</option>\n";
1022 }
1023 }
1024 $sel_hour .= "</select>\n";
1025 $sel_hour = preg_replace("/(value\=\"$hour\")/", "$1 selected=\"selected\"", $sel_hour);
1026
1027 // build minutes select
1028 $sel_minute .= "<select " . $disabled . "name=\"" . $prefix . "[m]\" id=\"" . $prefix . "_m\" class=\"form-control\">\n";
1029
1030 for ($i = 0; $i <= 59; $i = $i + $minute_steps) {
1031 $sel_minute .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
1032 }
1033 $sel_minute .= "</select>\n";
1034 $sel_minute = preg_replace("/(value\=\"$minute\")/", "$1 selected=\"selected\"", $sel_minute);
1035
1036 if (!$short) {
1037 // build seconds select
1038 $sel_second .= "<select " . $disabled . "name=\"" . $prefix . "[s]\" id=\"" . $prefix . "_s\" class=\"form-control\">\n";
1039
1040 for ($i = 0; $i <= 59; $i++) {
1041 $sel_second .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
1042 }
1043 $sel_second .= "</select>\n";
1044 $sel_second = preg_replace("/(value\=\"$second\")/", "$1 selected=\"selected\"", $sel_second);
1045 }
1046 $timeformat = $lng->text["lang_timeformat"];
1047 if (strlen($timeformat) == 0) {
1048 $timeformat = "H:i:s";
1049 }
1050 $timeformat = strtolower(preg_replace("/\W/", "", $timeformat));
1051 $timeformat = preg_replace("/(\w)/", "%%$1", $timeformat);
1052 $timeformat = preg_replace("/%%h/", $sel_hour, $timeformat);
1053 $timeformat = preg_replace("/%%i/", $sel_minute, $timeformat);
1054 if ($short) {
1055 $timeformat = preg_replace("/%%s/", "", $timeformat);
1056 } else {
1057 $timeformat = preg_replace("/%%s/", $sel_second, $timeformat);
1058 }
1059 return $timeformat;
1060 }
1061
1075 public static function is_email($a_email, ilMailRfc822AddressParserFactory $mailAddressParserFactory = null)
1076 {
1077 if (null === $a_email || !is_string($a_email)) {
1078 return false;
1079 }
1080
1081 if ($mailAddressParserFactory === null) {
1082 $mailAddressParserFactory = new ilMailRfc822AddressParserFactory();
1083 }
1084
1085 try {
1086 $parser = $mailAddressParserFactory->getParser((string) $a_email);
1087 $addresses = $parser->parse();
1088 return count($addresses) == 1 && $addresses[0]->getHost() != ilMail::ILIAS_HOST;
1089 } catch (ilException $e) {
1090 return false;
1091 }
1092 }
1093
1102 public static function isPassword($a_passwd, &$customError = null)
1103 {
1104 global $DIC;
1105
1106 $lng = $DIC->language();
1107
1108 include_once('./Services/PrivacySecurity/classes/class.ilSecuritySettings.php');
1110
1111 // check if password is empty
1112 if (empty($a_passwd)) {
1113 $customError = $lng->txt('password_empty');
1114 return false;
1115 }
1116
1117 $isPassword = true;
1118 $errors = array();
1119
1120 // check if password to short
1121 if ($security->getPasswordMinLength() > 0 && strlen($a_passwd) < $security->getPasswordMinLength()) {
1122 $errors[] = sprintf($lng->txt('password_to_short'), $security->getPasswordMinLength());
1123 $isPassword = false;
1124 }
1125
1126 // check if password not to long
1127 // 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).
1128 if ($security->getPasswordMaxLength() > 0 && strlen($a_passwd) > $security->getPasswordMaxLength()) {
1129 $errors[] = sprintf($lng->txt('password_to_long'), $security->getPasswordMaxLength());
1130 $isPassword = false;
1131 }
1132
1133 // if password must contains Chars and Numbers
1134 if ($security->isPasswordCharsAndNumbersEnabled()) {
1135 $hasCharsAndNumbers = true;
1136
1137 // check password for existing chars
1138 if (!preg_match('/[A-Za-z]+/', $a_passwd)) {
1139 $hasCharsAndNumbers = false;
1140 }
1141
1142 // check password for existing numbers
1143 if (!preg_match('/[0-9]+/', $a_passwd)) {
1144 $hasCharsAndNumbers = false;
1145 }
1146
1147 if (!$hasCharsAndNumbers) {
1148 $errors[] = $lng->txt('password_must_chars_and_numbers');
1149 $isPassword = false;
1150 }
1151 }
1152
1153 require_once 'Services/Utilities/classes/class.ilStr.php';
1154 if ($security->getPasswordNumberOfUppercaseChars() > 0) {
1155 if (ilStr::strLen($a_passwd) - ilStr::strLen(preg_replace('/[A-Z]/', '', $a_passwd)) < $security->getPasswordNumberOfUppercaseChars()) {
1156 $errors[] = sprintf($lng->txt('password_must_contain_ucase_chars'), $security->getPasswordNumberOfUppercaseChars());
1157 $isPassword = false;
1158 }
1159 }
1160
1161 if ($security->getPasswordNumberOfLowercaseChars() > 0) {
1162 if (ilStr::strLen($a_passwd) - ilStr::strLen(preg_replace('/[a-z]/', '', $a_passwd)) < $security->getPasswordNumberOfLowercaseChars()) {
1163 $errors[] = sprintf($lng->txt('password_must_contain_lcase_chars'), $security->getPasswordNumberOfLowercaseChars());
1164 $isPassword = false;
1165 }
1166 }
1167
1168 // if password must contains Special-Chars
1169 if ($security->isPasswordSpecialCharsEnabled()) {
1170 // check password for existing special-chars
1171 if (!preg_match(self::getPasswordValidChars(true, true), $a_passwd)) {
1172 $errors[] = $lng->txt('password_must_special_chars');
1173 $isPassword = false;
1174 }
1175 }
1176
1177 // ensure password matches the positive list of chars/special-chars
1178 if (!preg_match(self::getPasswordValidChars(), $a_passwd)) {
1179 $errors[] = $lng->txt('password_contains_invalid_chars');
1180 $isPassword = false;
1181 }
1182
1183 // build custom error message
1184 if (count($errors) == 1) {
1185 $customError = $errors[0];
1186 } elseif (count($errors) > 1) {
1187 $customError = $lng->txt('password_multiple_errors');
1188 $customError .= '<br />' . implode('<br />', $errors);
1189 }
1190
1191 return $isPassword;
1192 }
1193
1200 public static function isPasswordValidForUserContext($clear_text_password, $user, &$error_language_variable = null)
1201 {
1202 include_once 'Services/PrivacySecurity/classes/class.ilSecuritySettings.php';
1204
1205 $login = null;
1206
1207 if (is_string($user)) {
1208 $login = $user;
1209 } elseif (is_array($user)) {
1210 // Try to get loginname and user_id from array
1211 $login = $user['login'];
1212 $userId = $user['id'];
1213 } elseif ($user instanceof ilObjUser) {
1214 $login = $user->getLogin();
1215 $userId = $user->getId();
1216 }
1217
1218 // 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.
1219
1220 if ($login && (int) $security->getPasswordMustNotContainLoginnameStatus() &&
1221 strpos(strtolower($clear_text_password), strtolower($login)) !== false
1222 ) {
1223 $error_language_variable = 'password_contains_parts_of_login_err';
1224 return false;
1225 }
1226
1227 return true;
1228 }
1229
1237 public static function getPasswordValidChars($a_as_regex = true, $a_only_special_chars = false)
1238 {
1239 if ($a_as_regex) {
1240 if ($a_only_special_chars) {
1241 return '/[_\.\+\?\#\-\*\@!\$\%\~\/\:\;]+/';
1242 } else {
1243 return '/^[A-Za-z0-9_\.\+\?\#\-\*\@!\$\%\~\/\:\;]+$/';
1244 }
1245 } else {
1246 return 'A-Z a-z 0-9 _.+?#-*@!$%~/:;';
1247 }
1248 }
1249
1257 public static function getPasswordRequirementsInfo()
1258 {
1259 global $DIC;
1260
1261 $lng = $DIC->language();
1262
1263 include_once('./Services/PrivacySecurity/classes/class.ilSecuritySettings.php');
1265
1266 $infos = array(sprintf($lng->txt('password_allow_chars'), self::getPasswordValidChars(false)));
1267
1268 // check if password to short
1269 if ($security->getPasswordMinLength() > 0) {
1270 $infos[] = sprintf($lng->txt('password_to_short'), $security->getPasswordMinLength());
1271 }
1272
1273 // check if password not to long
1274 if ($security->getPasswordMaxLength() > 0) {
1275 $infos[] = sprintf($lng->txt('password_to_long'), $security->getPasswordMaxLength());
1276 }
1277
1278 // if password must contains Chars and Numbers
1279 if ($security->isPasswordCharsAndNumbersEnabled()) {
1280 $infos[] = $lng->txt('password_must_chars_and_numbers');
1281 }
1282
1283 // if password must contains Special-Chars
1284 if ($security->isPasswordSpecialCharsEnabled()) {
1285 $infos[] = $lng->txt('password_must_special_chars');
1286 }
1287
1288 if ($security->getPasswordNumberOfUppercaseChars() > 0) {
1289 $infos[] = sprintf($lng->txt('password_must_contain_ucase_chars'), $security->getPasswordNumberOfUppercaseChars());
1290 }
1291
1292 if ($security->getPasswordNumberOfLowercaseChars() > 0) {
1293 $infos[] = sprintf($lng->txt('password_must_contain_lcase_chars'), $security->getPasswordNumberOfLowercaseChars());
1294 }
1295
1296 return implode('<br />', $infos);
1297 }
1298
1299 /*
1300 * validates a login
1301 * @access public
1302 * @param string login
1303 * @return boolean true if valid
1304 */
1305 public static function isLogin($a_login)
1306 {
1307 if (empty($a_login)) {
1308 return false;
1309 }
1310
1311 if (strlen($a_login) < 3) {
1312 return false;
1313 }
1314
1315 // FIXME - If ILIAS is configured to use RFC 822
1316 // compliant mail addresses we should not
1317 // allow the @ character.
1318 if (!preg_match("/^[A-Za-z0-9_\.\+\*\@!\$\%\~\-]+$/", $a_login)) {
1319 return false;
1320 }
1321
1322 return true;
1323 }
1324
1338 public static function shortenText(
1339 $a_str,
1340 $a_len,
1341 $a_dots = false,
1342 $a_next_blank = false,
1343 $a_keep_extension = false
1344 ) {
1345 include_once("./Services/Utilities/classes/class.ilStr.php");
1346 if (ilStr::strLen($a_str) > $a_len) {
1347 if ($a_next_blank) {
1348 $len = ilStr::strPos($a_str, " ", $a_len);
1349 } else {
1350 $len = $a_len;
1351 }
1352 // BEGIN WebDAV
1353 // - Shorten names in the middle, before the filename extension
1354 // Workaround for Windows WebDAV Client:
1355 // Use the unicode ellipsis symbol for shortening instead of
1356 // three full stop characters.
1357 if ($a_keep_extension) {
1358 $p = strrpos($a_str, '.'); // this messes up normal shortening, see bug #6190
1359 }
1360 if ($p === false || $p == 0 || strlen($a_str) - $p > $a_len) {
1361 $a_str = ilStr::subStr($a_str, 0, $len);
1362 if ($a_dots) {
1363 $a_str .= "\xe2\x80\xa6"; // UTF-8 encoding for Unicode ellipsis character.
1364 }
1365 } else {
1366 if ($a_dots) {
1367 $a_str = ilStr::subStr($a_str, 0, $len - (strlen($a_str) - $p + 1)) . "\xe2\x80\xa6" . substr($a_str, $p);
1368 } else {
1369 $a_str = ilStr::subStr($a_str, 0, $len - (strlen($a_str) - $p + 1)) . substr($a_str, $p);
1370 }
1371 }
1372 }
1373
1374 return $a_str;
1375 }
1376
1377
1390 public static function shortenWords($a_str, $a_len = 30, $a_dots = true)
1391 {
1392 include_once("./Services/Utilities/classes/class.ilStr.php");
1393 $str_arr = explode(" ", $a_str);
1394
1395 for ($i = 0; $i < count($str_arr); $i++) {
1396 if (ilStr::strLen($str_arr[$i]) > $a_len) {
1397 $str_arr[$i] = ilStr::subStr($str_arr[$i], 0, $a_len);
1398 if ($a_dots) {
1399 $str_arr[$i] .= "...";
1400 }
1401 }
1402 }
1403
1404 return implode(" ", $str_arr);
1405 }
1406
1416 public static function attribsToArray($a_str)
1417 {
1418 $attribs = array();
1419 while (is_int(strpos($a_str, "="))) {
1420 $eq_pos = strpos($a_str, "=");
1421 $qu1_pos = strpos($a_str, "\"");
1422 $qu2_pos = strpos(substr($a_str, $qu1_pos + 1), "\"") + $qu1_pos + 1;
1423 if (is_int($eq_pos) && is_int($qu1_pos) && is_int($qu2_pos)) {
1424 $var = trim(substr($a_str, 0, $eq_pos));
1425 $val = trim(substr($a_str, $qu1_pos + 1, ($qu2_pos - $qu1_pos) - 1));
1426 $attribs[$var] = $val;
1427 $a_str = substr($a_str, $qu2_pos + 1);
1428 } else {
1429 $a_str = "";
1430 }
1431 }
1432 return $attribs;
1433 }
1434
1435
1453 public static function rCopy($a_sdir, $a_tdir, $preserveTimeAttributes = false)
1454 {
1455 $sourceFS = LegacyPathHelper::deriveFilesystemFrom($a_sdir);
1456 $targetFS = LegacyPathHelper::deriveFilesystemFrom($a_tdir);
1457
1458 $sourceDir = LegacyPathHelper::createRelativePath($a_sdir);
1459 $targetDir = LegacyPathHelper::createRelativePath($a_tdir);
1460
1461 // check if arguments are directories
1462 if (!$sourceFS->hasDir($sourceDir)) {
1463 return false;
1464 }
1465
1466 $sourceList = $sourceFS->listContents($sourceDir, true);
1467
1468 foreach ($sourceList as $item) {
1469 if ($item->isDir()) {
1470 continue;
1471 }
1472 try {
1473 $itemPath = $targetDir . '/' . substr($item->getPath(), strlen($sourceDir));
1474 $stream = $sourceFS->readStream($item->getPath());
1475 $targetFS->writeStream($itemPath, $stream);
1476 } catch (\ILIAS\Filesystem\Exception\FileAlreadyExistsException $e) {
1477 // Do nothing with that type of exception
1478 }
1479 }
1480
1481 return true;
1482 }
1483
1484
1500 public static function getWebspaceDir($mode = "filesystem")
1501 {
1502 if ($mode == "filesystem") {
1503 return "./" . ILIAS_WEB_DIR . "/" . CLIENT_ID;
1504 } else {
1505 if (defined("ILIAS_MODULE")) {
1506 return "../" . ILIAS_WEB_DIR . "/" . CLIENT_ID;
1507 } else {
1508 return "./" . ILIAS_WEB_DIR . "/" . CLIENT_ID;
1509 }
1510 }
1511 }
1512
1523 public static function getDataDir()
1524 {
1525 return CLIENT_DATA_DIR;
1526 }
1527
1537 public static function getUsersOnline($a_user_id = 0)
1538 {
1539 include_once("./Services/User/classes/class.ilObjUser.php");
1540 return ilObjUser::_getUsersOnline($a_user_id);
1541 }
1542
1543
1551 public static function ilTempnam($a_temp_path = null)
1552 {
1553 if ($a_temp_path === null) {
1554 $temp_path = ilUtil::getDataDir() . "/temp";
1555 } else {
1556 $temp_path = $a_temp_path;
1557 }
1558
1559 if (!is_dir($temp_path)) {
1560 ilUtil::createDirectory($temp_path);
1561 }
1562 $temp_name = $temp_path . "/" . uniqid("tmp");
1563
1564 return $temp_name;
1565 }
1566
1567
1580 public static function createDirectory($a_dir, $a_mod = 0755)
1581 {
1582 ilUtil::makeDir($a_dir);
1583 //@mkdir($a_dir);
1584 //@chmod($a_dir, $a_mod);
1585 }
1586
1587
1596 public static function unzip($a_file, $overwrite = false, $a_flat = false)
1597 {
1598 global $DIC;
1599
1600 $log = $DIC->logger()->root();
1601
1602 if (!is_file($a_file)) {
1603 return;
1604 }
1605
1606 // if flat, move file to temp directory first
1607 if ($a_flat) {
1608 $tmpdir = ilUtil::ilTempnam();
1609 ilUtil::makeDir($tmpdir);
1610 copy($a_file, $tmpdir . DIRECTORY_SEPARATOR . basename($a_file));
1611 $orig_file = $a_file;
1612 $a_file = $tmpdir . DIRECTORY_SEPARATOR . basename($a_file);
1613 $origpathinfo = pathinfo($orig_file);
1614 }
1615
1616 $pathinfo = pathinfo($a_file);
1617 $dir = $pathinfo["dirname"];
1618 $file = $pathinfo["basename"];
1619
1620 // unzip
1621 $cdir = getcwd();
1622 chdir($dir);
1623 $unzip = PATH_TO_UNZIP;
1624
1625 // the following workaround has been removed due to bug
1626 // http://www.ilias.de/mantis/view.php?id=7578
1627 // since the workaround is quite old, it may not be necessary
1628 // anymore, alex 9 Oct 2012
1629 /*
1630 // workaround for unzip problem (unzip of subdirectories fails, so
1631 // we create the subdirectories ourselves first)
1632 // get list
1633 $unzipcmd = "-Z -1 ".ilUtil::escapeShellArg($file);
1634 $arr = ilUtil::execQuoted($unzip, $unzipcmd);
1635 $zdirs = array();
1636
1637 foreach($arr as $line)
1638 {
1639 if(is_int(strpos($line, "/")))
1640 {
1641 $zdir = substr($line, 0, strrpos($line, "/"));
1642 $nr = substr_count($zdir, "/");
1643 //echo $zdir." ".$nr."<br>";
1644 while ($zdir != "")
1645 {
1646 $nr = substr_count($zdir, "/");
1647 $zdirs[$zdir] = $nr; // collect directories
1648 //echo $dir." ".$nr."<br>";
1649 $zdir = substr($zdir, 0, strrpos($zdir, "/"));
1650 }
1651 }
1652 }
1653
1654 asort($zdirs);
1655
1656 foreach($zdirs as $zdir => $nr) // create directories
1657 {
1658 ilUtil::createDirectory($zdir);
1659 }
1660 */
1661
1662 // real unzip
1663 if (!$overwrite) {
1664 $unzipcmd = ilUtil::escapeShellArg($file);
1665 } else {
1666 $unzipcmd = "-o " . ilUtil::escapeShellArg($file);
1667 }
1668 ilUtil::execQuoted($unzip, $unzipcmd);
1669
1670 chdir($cdir);
1671
1672 // remove all sym links
1673 clearstatcache(); // prevent is_link from using cache
1674 $dir_realpath = realpath($dir);
1675 foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)) as $name => $f) {
1676 if (is_link($name)) {
1677 $target = readlink($name);
1678 if (substr($target, 0, strlen($dir_realpath)) != $dir_realpath) {
1679 unlink($name);
1680 $log->info("Removed symlink " . $name);
1681 }
1682 }
1683 }
1684
1685 // if flat, get all files and move them to original directory
1686 if ($a_flat) {
1687 include_once("./Services/Utilities/classes/class.ilFileUtils.php");
1688 $filearray = array();
1689 ilFileUtils::recursive_dirscan($tmpdir, $filearray);
1690 if (is_array($filearray["file"])) {
1691 foreach ($filearray["file"] as $k => $f) {
1692 if (substr($f, 0, 1) != "." && $f != basename($orig_file)) {
1693 copy($filearray["path"][$k] . $f, $origpathinfo["dirname"] . DIRECTORY_SEPARATOR . $f);
1694 }
1695 }
1696 }
1697 ilUtil::delDir($tmpdir);
1698 }
1699 }
1700
1707 public static function zip($a_dir, $a_file, $compress_content = false)
1708 {
1709 $cdir = getcwd();
1710
1711 if ($compress_content) {
1712 $a_dir .= "/*";
1713 $pathinfo = pathinfo($a_dir);
1714 chdir($pathinfo["dirname"]);
1715 }
1716
1717 $pathinfo = pathinfo($a_file);
1718 $dir = $pathinfo["dirname"];
1719 $file = $pathinfo["basename"];
1720
1721 if (!$compress_content) {
1722 chdir($dir);
1723 }
1724
1725 $zip = PATH_TO_ZIP;
1726
1727 if (!$zip) {
1728 chdir($cdir);
1729 return false;
1730 }
1731
1732 if (is_array($a_dir)) {
1733 $source = "";
1734 foreach ($a_dir as $dir) {
1735 $name = basename($dir);
1737 }
1738 } else {
1739 $name = basename($a_dir);
1740 if (trim($name) != "*") {
1742 } else {
1743 $source = $name;
1744 }
1745 }
1746
1747 $zipcmd = "-r " . ilUtil::escapeShellArg($a_file) . " " . $source;
1748 ilUtil::execQuoted($zip, $zipcmd);
1749 chdir($cdir);
1750 return true;
1751 }
1752
1753 public static function CreateIsoFromFolder($a_dir, $a_file)
1754 {
1755 $cdir = getcwd();
1756
1757 $pathinfo = pathinfo($a_dir);
1758 chdir($pathinfo["dirname"]);
1759
1760 $pathinfo = pathinfo($a_file);
1761 $dir = $pathinfo["dirname"];
1762 $file = $pathinfo["basename"];
1763 $zipcmd = "-r " . ilUtil::escapeShellArg($a_file) . " " . $source;
1764
1765 $mkisofs = PATH_TO_MKISOFS;
1766 if (!$mkisofs) {
1767 chdir($cdir);
1768 return false;
1769 }
1770
1771 $name = basename($a_dir);
1773
1774 $zipcmd = "-r -J -o " . $a_file . " " . $source;
1775 ilUtil::execQuoted($mkisofs, $zipcmd);
1776 chdir($cdir);
1777 return true;
1778 }
1779
1788 public static function getConvertCmd()
1789 {
1790 return PATH_TO_CONVERT;
1791 }
1792
1800 public static function execConvert($args)
1801 {
1802 $args = self::escapeShellCmd($args);
1803 ilUtil::execQuoted(PATH_TO_CONVERT, $args);
1804 }
1805
1812 public static function isConvertVersionAtLeast($a_version)
1813 {
1814 $current_version = ilUtil::execQuoted(PATH_TO_CONVERT, "--version");
1815 $current_version = self::processConvertVersion($current_version[0]);
1816 $version = self::processConvertVersion($a_version);
1817 if ($current_version >= $version) {
1818 return true;
1819 }
1820 return false;
1821 }
1822
1829 protected static function processConvertVersion($a_version)
1830 {
1831 if (preg_match("/([0-9]+)\.([0-9]+)\.([0-9]+)([\.|\-]([0-9]+))?/", $a_version, $match)) {
1832 $version = str_pad($match[1], 2, 0, STR_PAD_LEFT) .
1833 str_pad($match[2], 2, 0, STR_PAD_LEFT) .
1834 str_pad($match[3], 2, 0, STR_PAD_LEFT) .
1835 str_pad($match[5], 2, 0, STR_PAD_LEFT);
1836 return (int) $version;
1837 }
1838 }
1839
1849 public static function convertImage(
1850 $a_from,
1851 $a_to,
1852 $a_target_format = "",
1853 $a_geometry = "",
1854 $a_background_color = ""
1855 ) {
1856 $format_str = ($a_target_format != "")
1857 ? strtoupper($a_target_format) . ":"
1858 : "";
1859 $geometry = "";
1860 if ($a_geometry != "") {
1861 if (is_int(strpos($a_geometry, "x"))) {
1862 $geometry = " -geometry " . $a_geometry . " ";
1863 } else {
1864 $geometry = " -geometry " . $a_geometry . "x" . $a_geometry . " ";
1865 }
1866 }
1867
1868 $bg_color = ($a_background_color != "")
1869 ? " -background color " . $a_background_color . " "
1870 : "";
1871 $convert_cmd = ilUtil::escapeShellArg($a_from) . " " . $bg_color . $geometry . ilUtil::escapeShellArg($format_str . $a_to);
1872
1873 ilUtil::execConvert($convert_cmd);
1874 }
1875
1886 public static function resizeImage($a_from, $a_to, $a_width, $a_height, $a_constrain_prop = false)
1887 {
1888 if ($a_constrain_prop) {
1889 $size = " -geometry " . $a_width . "x" . $a_height . " ";
1890 } else {
1891 $size = " -resize " . $a_width . "x" . $a_height . "! ";
1892 }
1893 $convert_cmd = ilUtil::escapeShellArg($a_from) . " " . $size . ilUtil::escapeShellArg($a_to);
1894
1895 ilUtil::execConvert($convert_cmd);
1896 }
1897
1904 public static function img($a_src, $a_alt = null, $a_width = "", $a_height = "", $a_border = 0, $a_id = "", $a_class = "")
1905 {
1906 $img = '<img src="' . $a_src . '"';
1907 if (!is_null($a_alt)) {
1908 $img .= ' alt="' . htmlspecialchars($a_alt) . '"';
1909 }
1910 if ($a_width != "") {
1911 $img .= ' width="' . htmlspecialchars($a_width) . '"';
1912 }
1913 if ($a_height != "") {
1914 $img .= ' height="' . htmlspecialchars($a_height) . '"';
1915 }
1916 if ($a_class != "") {
1917 $img .= ' class="' . $a_class . '"';
1918 }
1919 if ($a_id != "") {
1920 $img .= ' id="' . $a_id . '"';
1921 }
1922 $img .= ' />';
1923
1924 return $img;
1925 }
1926
1933 public static function deliverData($a_data, $a_filename, $mime = "application/octet-stream", $charset = "")
1934 {
1935 $disposition = "attachment"; // "inline" to view file in browser or "attachment" to download to hard disk
1936 // $mime = "application/octet-stream"; // or whatever the mime type is
1937
1938 include_once './Services/Http/classes/class.ilHTTPS.php';
1939
1940 //if($_SERVER['HTTPS'])
1941 if (ilHTTPS::getInstance()->isDetected()) {
1942
1943 // Added different handling for IE and HTTPS => send pragma after content informations
1947 #header("Pragma: ");
1948 #header("Cache-Control: ");
1949 #header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
1950 #header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
1951 #header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1
1952 #header("Cache-Control: post-check=0, pre-check=0", false);
1953 } elseif ($disposition == "attachment") {
1954 header("Cache-control: private");
1955 } else {
1956 header("Cache-Control: no-cache, must-revalidate");
1957 header("Pragma: no-cache");
1958 }
1959
1961
1962 if (strlen($charset)) {
1963 $charset = "; charset=$charset";
1964 }
1965 header("Content-Type: $mime$charset");
1966 header("Content-Disposition:$disposition; filename=\"" . $ascii_filename . "\"");
1967 header("Content-Description: " . $ascii_filename);
1968 header("Content-Length: " . (string) (strlen($a_data)));
1969
1970 //if($_SERVER['HTTPS'])
1971 if (ilHTTPS::getInstance()->isDetected()) {
1972 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
1973 header('Pragma: public');
1974 }
1975
1976 header("Connection: close");
1977 echo $a_data;
1978 exit;
1979 }
1980
1981 // BEGIN WebDAV: Show file in browser or provide it as attachment
1989 public static function deliverFile(
1990 $a_file,
1991 $a_filename,
1992 $a_mime = '',
1993 $isInline = false,
1994 $removeAfterDelivery = false,
1995 $a_exit_after = true
1996 ) {
1997 global $DIC;
1998 // should we fail silently?
1999 if (!file_exists($a_file)) {
2000 return false;
2001 }
2002 $delivery = new ilFileDelivery($a_file);
2003
2004 if ($isInline) {
2005 $delivery->setDisposition(ilFileDelivery::DISP_INLINE);
2006 } else {
2007 $delivery->setDisposition(ilFileDelivery::DISP_ATTACHMENT);
2008 }
2009
2010 if (strlen($a_mime)) {
2011 $delivery->setMimeType($a_mime);
2012 }
2013
2014 $delivery->setDownloadFileName($a_filename);
2015 $delivery->setConvertFileNameToAsci((bool) !$DIC->clientIni()->readVariable('file_access', 'disable_ascii'));
2016 $delivery->setDeleteFile($removeAfterDelivery);
2017 $delivery->deliver();
2018 }
2019
2020
2030 public static function readFile($a_file)
2031 {
2032 $chunksize = 1 * (1024 * 1024); // how many bytes per chunk
2033 $buffer = '';
2034 $handle = fopen($a_file, 'rb');
2035 if ($handle === false) {
2036 return false;
2037 }
2038 while (!feof($handle)) {
2039 $buffer = fread($handle, $chunksize);
2040 print $buffer;
2041 }
2042 return fclose($handle);
2043 }
2044
2052 public static function getASCIIFilename($a_filename)
2053 {
2054 // The filename must be converted to ASCII, as of RFC 2183,
2055 // section 2.3.
2056
2068
2071
2072 // #15914 - try to fix german umlauts
2073 $umlauts = array("Ä" => "Ae", "Ö" => "Oe", "Ü" => "Ue",
2074 "ä" => "ae", "ö" => "oe", "ü" => "ue", "ß" => "ss");
2075 foreach ($umlauts as $src => $tgt) {
2076 $a_filename = str_replace($src, $tgt, $a_filename);
2077 }
2078
2079 $ascii_filename = htmlentities($a_filename, ENT_NOQUOTES, 'UTF-8');
2080 $ascii_filename = preg_replace('/\&(.)[^;]*;/', '\\1', $ascii_filename);
2081 $ascii_filename = preg_replace('/[\x7f-\xff]/', '_', $ascii_filename);
2082
2083 // OS do not allow the following characters in filenames: \/:*?"<>|
2084 $ascii_filename = preg_replace('/[:\x5c\/\*\?\"<>\|]/', '_', $ascii_filename);
2085 return $ascii_filename;
2086 }
2087
2094 public static function htmlentitiesOutsideHTMLTags($htmlText)
2095 {
2096 $matches = array();
2097 $sep = '###HTMLTAG###';
2098
2099 preg_match_all("@<[^>]*>@", $htmlText, $matches);
2100 $tmp = preg_replace("@(<[^>]*>)@", $sep, $htmlText);
2101 $tmp = explode($sep, $tmp);
2102
2103 for ($i = 0; $i < count($tmp); $i++) {
2104 $tmp[$i] = htmlentities($tmp[$i], ENT_COMPAT, "UTF-8");
2105 }
2106
2107 $tmp = join($sep, $tmp);
2108
2109 for ($i = 0; $i < count($matches[0]); $i++) {
2110 $tmp = preg_replace("@$sep@", $matches[0][$i], $tmp, 1);
2111 }
2112
2113 return $tmp;
2114 }
2115
2122 public static function getJavaPath()
2123 {
2124 return PATH_TO_JAVA;
2125 //global $ilias;
2126
2127 //return $ilias->getSetting("java_path");
2128 }
2129
2137 public static function appendUrlParameterString($a_url, $a_par, $xml_style = false)
2138 {
2139 $amp = $xml_style
2140 ? "&amp;"
2141 : "&";
2142
2143 $url = (is_int(strpos($a_url, "?")))
2144 ? $a_url . $amp . $a_par
2145 : $a_url . "?" . $a_par;
2146
2147 return $url;
2148 }
2149
2168 public static function makeDir($a_dir)
2169 {
2170 $a_dir = trim($a_dir);
2171
2172 // remove trailing slash (bugfix for php 4.2.x)
2173 if (substr($a_dir, -1) == "/") {
2174 $a_dir = substr($a_dir, 0, -1);
2175 }
2176
2177 // check if a_dir comes with a path
2178 if (!($path = substr($a_dir, 0, strrpos($a_dir, "/") - strlen($a_dir)))) {
2179 $path = ".";
2180 }
2181
2182 // create directory with file permissions of parent directory
2183 umask(0000);
2184 return @mkdir($a_dir, fileperms($path));
2185 }
2186
2187
2207 public static function makeDirParents($a_dir)
2208 {
2209 $dirs = array($a_dir);
2210 $a_dir = dirname($a_dir);
2211 $last_dirname = '';
2212
2213 while ($last_dirname != $a_dir) {
2214 array_unshift($dirs, $a_dir);
2215 $last_dirname = $a_dir;
2216 $a_dir = dirname($a_dir);
2217 }
2218
2219 // find the first existing dir
2220 $reverse_paths = array_reverse($dirs, true);
2221 $found_index = -1;
2222 foreach ($reverse_paths as $key => $value) {
2223 if ($found_index == -1) {
2224 if (is_dir($value)) {
2225 $found_index = $key;
2226 }
2227 }
2228 }
2229
2230 umask(0000);
2231 foreach ($dirs as $dirindex => $dir) {
2232 // starting with the longest existing path
2233 if ($dirindex >= $found_index) {
2234 if (!file_exists($dir)) {
2235 if (strcmp(substr($dir, strlen($dir) - 1, 1), "/") == 0) {
2236 // on some systems there is an error when there is a slash
2237 // at the end of a directory in mkdir, see Mantis #2554
2238 $dir = substr($dir, 0, strlen($dir) - 1);
2239 }
2240 if (!mkdir($dir, $umask)) {
2241 error_log("Can't make directory: $dir");
2242 return false;
2243 }
2244 } elseif (!is_dir($dir)) {
2245 error_log("$dir is not a directory");
2246 return false;
2247 } else {
2248 // get umask of the last existing parent directory
2249 $umask = fileperms($dir);
2250 }
2251 }
2252 }
2253 return true;
2254 }
2255
2256
2272 public static function delDir($a_dir, $a_clean_only = false)
2273 {
2274 if (!is_dir($a_dir) || is_int(strpos($a_dir, ".."))) {
2275 return;
2276 }
2277
2278 $current_dir = opendir($a_dir);
2279
2280 $files = array();
2281
2282 // this extra loop has been necessary because of a strange bug
2283 // at least on MacOS X. A looped readdir() didn't work
2284 // correctly with larger directories
2285 // when an unlink happened inside the loop. Getting all files
2286 // into the memory first solved the problem.
2287 while ($entryname = readdir($current_dir)) {
2288 $files[] = $entryname;
2289 }
2290
2291 foreach ($files as $file) {
2292 if (is_dir($a_dir . "/" . $file) and ($file != "." and $file != "..")) {
2293 ilUtil::delDir($a_dir . "/" . $file);
2294 } elseif ($file != "." and $file != "..") {
2295 unlink($a_dir . "/" . $file);
2296 }
2297 }
2298
2299 closedir($current_dir);
2300 if (!$a_clean_only) {
2301 @rmdir($a_dir);
2302 }
2303 }
2304
2305
2321 public static function getDir($a_dir, $a_rec = false, $a_sub_dir = "")
2322 {
2323 $current_dir = opendir($a_dir . $a_sub_dir);
2324
2325 $dirs = array();
2326 $files = array();
2327 $subitems = array();
2328 while ($entry = readdir($current_dir)) {
2329 if (is_dir($a_dir . "/" . $entry)) {
2330 $dirs[$entry] = array("type" => "dir", "entry" => $entry,
2331 "subdir" => $a_sub_dir);
2332 if ($a_rec && $entry != "." && $entry != "..") {
2333 $si = ilUtil::getDir($a_dir, true, $a_sub_dir . "/" . $entry);
2334 $subitems = array_merge($subitems, $si);
2335 }
2336 } else {
2337 if ($entry != "." && $entry != "..") {
2338 $size = filesize($a_dir . $a_sub_dir . "/" . $entry);
2339 $files[$entry] = array("type" => "file", "entry" => $entry,
2340 "size" => $size, "subdir" => $a_sub_dir);
2341 }
2342 }
2343 }
2344 ksort($dirs);
2345 ksort($files);
2346
2347 return array_merge($dirs, $files, $subitems);
2348 }
2349
2356 public static function stripSlashesArray($a_arr, $a_strip_html = true, $a_allow = "")
2357 {
2358 if (is_array($a_arr)) {
2359 foreach ($a_arr as $k => $v) {
2360 $a_arr[$k] = ilUtil::stripSlashes($v, $a_strip_html, $a_allow);
2361 }
2362 }
2363
2364 return $a_arr;
2365 }
2366
2371 public static function getClientIdByString(string $clientId) : \ILIAS\Data\ClientId
2372 {
2373 $df = new \ILIAS\Data\Factory;
2374
2375 return $df->clientId($clientId);
2376 }
2377
2384 public static function stripSlashesRecursive($a_data, $a_strip_html = true, $a_allow = "")
2385 {
2386 if (is_array($a_data)) {
2387 foreach ($a_data as $k => $v) {
2388 if (is_array($v)) {
2389 $a_data[$k] = ilUtil::stripSlashesRecursive($v, $a_strip_html, $a_allow);
2390 } else {
2391 $a_data[$k] = ilUtil::stripSlashes($v, $a_strip_html, $a_allow);
2392 }
2393 }
2394 } else {
2395 $a_data = ilUtil::stripSlashes($a_data, $a_strip_html, $a_allow);
2396 }
2397
2398 return $a_data;
2399 }
2400
2408 public static function stripSlashes($a_str, $a_strip_html = true, $a_allow = "")
2409 {
2410 if (ini_get("magic_quotes_gpc")) {
2411 $a_str = stripslashes($a_str);
2412 }
2413 //echo "<br><br>-".$a_strip_html."-".htmlentities($a_str);
2414 //echo "<br>-".htmlentities(ilUtil::secureString($a_str, $a_strip_html, $a_allow));
2415 return ilUtil::secureString($a_str, $a_strip_html, $a_allow);
2416 }
2417
2425 public static function stripOnlySlashes($a_str)
2426 {
2427 if (ini_get("magic_quotes_gpc")) {
2428 $a_str = stripslashes($a_str);
2429 }
2430
2431 return $a_str;
2432 }
2433
2440 public static function secureString($a_str, $a_strip_html = true, $a_allow = "")
2441 {
2442 // check whether all allowed tags can be made secure
2443 $only_secure = true;
2444 $allow_tags = explode(">", $a_allow);
2445 $sec_tags = ilUtil::getSecureTags();
2446 $allow_array = array();
2447 foreach ($allow_tags as $allow) {
2448 if ($allow != "") {
2449 $allow = str_replace("<", "", $allow);
2450
2451 if (!in_array($allow, $sec_tags)) {
2452 $only_secure = false;
2453 }
2454 $allow_array[] = $allow;
2455 }
2456 }
2457
2458 // default behaviour: allow only secure tags 1:1
2459 if (($only_secure || $a_allow == "") && $a_strip_html) {
2460 if ($a_allow == "") {
2461 $allow_array = array("b", "i", "strong", "em", "code", "cite",
2462 "gap", "sub", "sup", "pre", "strike", "bdo");
2463 }
2464
2465 // this currently removes parts of strings like "a <= b"
2466 // because "a <= b" is treated like "<spam onclick='hurt()'>ss</spam>"
2467 $a_str = ilUtil::maskSecureTags($a_str, $allow_array);
2468 $a_str = strip_tags($a_str); // strip all other tags
2469 $a_str = ilUtil::unmaskSecureTags($a_str, $allow_array);
2470
2471 // a possible solution could be something like:
2472 // $a_str = str_replace("<", "&lt;", $a_str);
2473 // $a_str = str_replace(">", "&gt;", $a_str);
2474 // $a_str = ilUtil::unmaskSecureTags($a_str, $allow_array);
2475 //
2476 // output would be ok then, but input fields would show
2477 // "a &lt;= b" for input "a <= b" if data is brought back to a form
2478 } else {
2479 // only for scripts, that need to allow more/other tags and parameters
2480 if ($a_strip_html) {
2481 $a_str = ilUtil::stripScriptHTML($a_str, $a_allow);
2482 }
2483 }
2484
2485 return $a_str;
2486 }
2487
2488 public static function getSecureTags()
2489 {
2490 return array("strong", "em", "u", "strike", "ol", "li", "ul", "p", "div",
2491 "i", "b", "code", "sup", "sub", "pre", "gap", "a", "img", "bdo");
2492 }
2493
2494 public static function maskSecureTags($a_str, $allow_array)
2495 {
2496 foreach ($allow_array as $t) {
2497 switch ($t) {
2498 case "a":
2499 $a_str = ilUtil::maskAttributeTag($a_str, "a", "href");
2500 break;
2501
2502 case "img":
2503 $a_str = ilUtil::maskAttributeTag($a_str, "img", "src");
2504 break;
2505
2506 case "p":
2507 case "div":
2508 $a_str = ilUtil::maskTag($a_str, $t, array(
2509 array("param" => "align", "value" => "left"),
2510 array("param" => "align", "value" => "center"),
2511 array("param" => "align", "value" => "justify"),
2512 array("param" => "align", "value" => "right")
2513 ));
2514 break;
2515
2516 default:
2517 $a_str = ilUtil::maskTag($a_str, $t);
2518 break;
2519 }
2520 }
2521
2522 return $a_str;
2523 }
2524
2525 public static function unmaskSecureTags($a_str, $allow_array)
2526 {
2527 foreach ($allow_array as $t) {
2528 switch ($t) {
2529 case "a":
2530 $a_str = ilUtil::unmaskAttributeTag($a_str, "a", "href");
2531 break;
2532
2533 case "img":
2534 $a_str = ilUtil::unmaskAttributeTag($a_str, "img", "src");
2535 break;
2536
2537 case "p":
2538 case "div":
2539 $a_str = ilUtil::unmaskTag($a_str, $t, array(
2540 array("param" => "align", "value" => "left"),
2541 array("param" => "align", "value" => "center"),
2542 array("param" => "align", "value" => "justify"),
2543 array("param" => "align", "value" => "right")
2544 ));
2545 break;
2546
2547 default:
2548 $a_str = ilUtil::unmaskTag($a_str, $t);
2549 break;
2550 }
2551 }
2552
2553 return $a_str;
2554 }
2555
2563 public static function securePlainString($a_str)
2564 {
2565 if (ini_get("magic_quotes_gpc")) {
2566 return stripslashes($a_str);
2567 } else {
2568 return $a_str;
2569 }
2570 }
2587 public static function htmlencodePlainString($a_str, $a_make_links_clickable, $a_detect_goto_links = false)
2588 {
2589 $encoded = "";
2590
2591 if ($a_make_links_clickable) {
2592 // Find text sequences in the plain text string which match
2593 // the URI syntax rules, and pass them to ilUtil::makeClickable.
2594 // Encode all other text sequences in the plain text string using
2595 // htmlspecialchars and nl2br.
2596 // The following expressions matches URI's as specified in RFC 2396.
2597 //
2598 // The expression matches URI's, which start with some well known
2599 // schemes, like "http:", or with "www.". This must be followed
2600 // by at least one of the following RFC 2396 expressions:
2601 // - alphanum: [a-zA-Z0-9]
2602 // - reserved: [;\/?:|&=+$,]
2603 // - mark: [\\-_.!~*\'()]
2604 // - escaped: %[0-9a-fA-F]{2}
2605 // - fragment delimiter: #
2606 // - uric_no_slash: [;?:@&=+$,]
2607 $matches = array();
2608 $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);
2609 $pos1 = 0;
2610 $encoded = "";
2611
2612 foreach ($matches[0] as $match) {
2613 $matched_text = $match[0];
2614 $pos2 = $match[1];
2615
2616 // encode plain text
2617 $encoded .= nl2br(htmlspecialchars(substr($a_str, $pos1, $pos2 - $pos1)));
2618
2619 // encode URI
2620 $encoded .= ilUtil::makeClickable($matched_text, $a_detect_goto_links);
2621
2622
2623 $pos1 = $pos2 + strlen($matched_text);
2624 }
2625 if ($pos1 < strlen($a_str)) {
2626 $encoded .= nl2br(htmlspecialchars(substr($a_str, $pos1)));
2627 }
2628 } else {
2629 $encoded = nl2br(htmlspecialchars($a_str));
2630 }
2631 return $encoded;
2632 }
2633
2634
2635 public static function maskAttributeTag($a_str, $tag, $tag_att)
2636 {
2637 global $DIC;
2638
2639 $ilLog = $DIC["ilLog"];
2640
2641 $ws = "[\s]*";
2642 $att = $ws . "[^>]*" . $ws;
2643
2644 while (preg_match(
2645 '/<(' . $tag . $att . '(' . $tag_att . $ws . '="' . $ws . '(([$@!*()~;,_0-9A-z\/:=%.&#?+\-])*)")' . $att . ')>/i',
2646 $a_str,
2647 $found
2648 )) {
2649 $old_str = $a_str;
2650 $a_str = preg_replace(
2651 "/<" . preg_quote($found[1], "/") . ">/i",
2652 '&lt;' . $tag . ' ' . $tag_att . $tag_att . '="' . $found[3] . '"&gt;',
2653 $a_str
2654 );
2655 if ($old_str == $a_str) {
2656 $ilLog->write("ilUtil::maskA-" . htmlentities($old_str) . " == " .
2657 htmlentities($a_str));
2658 return $a_str;
2659 }
2660 }
2661 $a_str = str_ireplace(
2662 "</$tag>",
2663 "&lt;/$tag&gt;",
2664 $a_str
2665 );
2666 return $a_str;
2667 }
2668
2669 public static function unmaskAttributeTag($a_str, $tag, $tag_att)
2670 {
2671 global $DIC;
2672
2673 $ilLog = $DIC["ilLog"];
2674
2675 while (preg_match(
2676 '/&lt;(' . $tag . ' ' . $tag_att . $tag_att . '="(([$@!*()~;,_0-9A-z\/:=%.&#?+\-])*)")&gt;/i',
2677 $a_str,
2678 $found
2679 )) {
2680 $old_str = $a_str;
2681 $a_str = preg_replace(
2682 "/&lt;" . preg_quote($found[1], "/") . "&gt;/i",
2683 '<' . $tag . ' ' . $tag_att . '="' . ilUtil::secureLink($found[2]) . '">',
2684 $a_str
2685 );
2686 if ($old_str == $a_str) {
2687 $ilLog->write("ilUtil::unmaskA-" . htmlentities($old_str) . " == " .
2688 htmlentities($a_str));
2689 return $a_str;
2690 }
2691 }
2692 $a_str = str_replace('&lt;/' . $tag . '&gt;', '</' . $tag . '>', $a_str);
2693 return $a_str;
2694 }
2695
2696 public static function maskTag($a_str, $t, $fix_param = "")
2697 {
2698 $a_str = str_replace(
2699 array("<$t>", "<" . strtoupper($t) . ">"),
2700 "&lt;" . $t . "&gt;",
2701 $a_str
2702 );
2703 $a_str = str_replace(
2704 array("</$t>", "</" . strtoupper($t) . ">"),
2705 "&lt;/" . $t . "&gt;",
2706 $a_str
2707 );
2708
2709 if (is_array($fix_param)) {
2710 foreach ($fix_param as $p) {
2711 $k = $p["param"];
2712 $v = $p["value"];
2713 $a_str = str_replace(
2714 "<$t $k=\"$v\">",
2715 "&lt;" . "$t $k=\"$v\"" . "&gt;",
2716 $a_str
2717 );
2718 }
2719 }
2720
2721 return $a_str;
2722 }
2723
2724 public static function unmaskTag($a_str, $t, $fix_param = "")
2725 {
2726 $a_str = str_replace("&lt;" . $t . "&gt;", "<" . $t . ">", $a_str);
2727 $a_str = str_replace("&lt;/" . $t . "&gt;", "</" . $t . ">", $a_str);
2728
2729 if (is_array($fix_param)) {
2730 foreach ($fix_param as $p) {
2731 $k = $p["param"];
2732 $v = $p["value"];
2733 $a_str = str_replace(
2734 "&lt;$t $k=\"$v\"&gt;",
2735 "<" . "$t $k=\"$v\"" . ">",
2736 $a_str
2737 );
2738 }
2739 }
2740 return $a_str;
2741 }
2742
2743 public static function secureLink($a_str)
2744 {
2745 $a_str = str_ireplace("javascript", "jvscrpt", $a_str);
2746 $a_str = str_ireplace(array("%00", "%0a", "%0d", "%1a", "&#00;", "&#x00;",
2747 "&#0;", "&#x0;", "&#x0a;", "&#x0d;", "&#10;", "&#13;"), "-", $a_str);
2748 return $a_str;
2749 }
2750
2764 public static function stripScriptHTML($a_str, $a_allow = "", $a_rm_js = true)
2765 {
2766 //$a_str = strip_tags($a_str, $a_allow);
2767
2768 $negativestr = "a,abbr,acronym,address,applet,area,base,basefont," .
2769 "big,blockquote,body,br,button,caption,center,cite,code,col," .
2770 "colgroup,dd,del,dfn,dir,div,dl,dt,em,fieldset,font,form,frame," .
2771 "frameset,h1,h2,h3,h4,h5,h6,head,hr,html,i,iframe,img,input,ins,isindex,kbd," .
2772 "label,legend,li,link,map,menu,meta,noframes,noscript,object,ol," .
2773 "optgroup,option,p,param,q,s,samp,script,select,small,span," .
2774 "strike,strong,style,sub,sup,table,tbody,td,textarea,tfoot,th,thead," .
2775 "title,tr,tt,u,ul,var";
2776 $a_allow = strtolower($a_allow);
2777 $negatives = explode(",", $negativestr);
2778 $outer_old_str = "";
2779 while ($outer_old_str != $a_str) {
2780 $outer_old_str = $a_str;
2781 foreach ($negatives as $item) {
2782 $pos = strpos($a_allow, "<$item>");
2783
2784 // remove complete tag, if not allowed
2785 if ($pos === false) {
2786 $old_str = "";
2787 while ($old_str != $a_str) {
2788 $old_str = $a_str;
2789 $a_str = preg_replace("/<\/?\s*$item(\/?)\s*>/i", "", $a_str);
2790 $a_str = preg_replace("/<\/?\s*$item(\/?)\s+([^>]*)>/i", "", $a_str);
2791 }
2792 }
2793 }
2794 }
2795
2796 if ($a_rm_js) {
2797 // remove all attributes if an "on..." attribute is given
2798 $a_str = preg_replace("/<\s*\w*(\/?)(\s+[^>]*)?(\s+on[^>]*)>/i", "", $a_str);
2799
2800 // remove all attributes if a "javascript" is within tag
2801 $a_str = preg_replace("/<\s*\w*(\/?)\s+[^>]*javascript[^>]*>/i", "", $a_str);
2802
2803 // remove all attributes if an "expression" is within tag
2804 // (IE allows something like <b style='width:expression(alert(1))'>test</b>)
2805 $a_str = preg_replace("/<\s*\w*(\/?)\s+[^>]*expression[^>]*>/i", "", $a_str);
2806 }
2807
2808 return $a_str;
2809 }
2810
2822 public static function prepareFormOutput($a_str, $a_strip = false)
2823 {
2824 if ($a_strip) {
2825 $a_str = ilUtil::stripSlashes($a_str);
2826 }
2827 $a_str = htmlspecialchars($a_str);
2828 // Added replacement of curly brackets to prevent
2829 // problems with PEAR templates, because {xyz} will
2830 // be removed as unused template variable
2831 $a_str = str_replace("{", "&#123;", $a_str);
2832 $a_str = str_replace("}", "&#125;", $a_str);
2833 // needed for LaTeX conversion \\ in LaTeX is a line break
2834 // but without this replacement, php changes \\ to \
2835 $a_str = str_replace("\\", "&#92;", $a_str);
2836 return $a_str;
2837 }
2838
2845 public static function secureUrl($url)
2846 {
2847 // check if url is valid (absolute or relative)
2848 if (filter_var($url, FILTER_VALIDATE_URL) === false &&
2849 filter_var("http://" . $url, FILTER_VALIDATE_URL) === false &&
2850 filter_var("http:" . $url, FILTER_VALIDATE_URL) === false &&
2851 filter_var("http://de.de" . $url, FILTER_VALIDATE_URL) === false &&
2852 filter_var("http://de.de/" . $url, FILTER_VALIDATE_URL) === false) {
2853 return "";
2854 }
2855 if (trim(strtolower(parse_url($url, PHP_URL_SCHEME))) == "javascript") {
2856 return "";
2857 }
2858 $url = htmlspecialchars($url, ENT_QUOTES);
2859 return $url;
2860 }
2861
2862
2863
2873 public static function prepareDBString($a_str)
2874 {
2875 return addslashes($a_str);
2876 }
2877
2878
2888 public static function extractParameterString($a_parstr)
2889 {
2890 // parse parameters in array
2891 $par = array();
2892 $ok = true;
2893 while (($spos = strpos($a_parstr, "=")) && $ok) {
2894 // extract parameter
2895 $cpar = substr($a_parstr, 0, $spos);
2896 $a_parstr = substr($a_parstr, $spos, strlen($a_parstr) - $spos);
2897 while (substr($cpar, 0, 1) == "," || substr($cpar, 0, 1) == " " || substr($cpar, 0, 1) == chr(13) || substr($cpar, 0, 1) == chr(10)) {
2898 $cpar = substr($cpar, 1, strlen($cpar) - 1);
2899 }
2900 while (substr($cpar, strlen($cpar) - 1, 1) == " " || substr($cpar, strlen($cpar) - 1, 1) == chr(13) || substr($cpar, strlen($cpar) - 1, 1) == chr(10)) {
2901 $cpar = substr($cpar, 0, strlen($cpar) - 1);
2902 }
2903
2904 // parameter name should only
2905 $cpar_old = "";
2906 while ($cpar != $cpar_old) {
2907 $cpar_old = $cpar;
2908 $cpar = preg_replace("/[^a-zA-Z0-9_]/i", "", $cpar);
2909 }
2910
2911 // extract value
2912 if ($cpar != "") {
2913 if ($spos = strpos($a_parstr, "\"")) {
2914 $a_parstr = substr($a_parstr, $spos + 1, strlen($a_parstr) - $spos);
2915 $spos = strpos($a_parstr, "\"");
2916 if (is_int($spos)) {
2917 $cval = substr($a_parstr, 0, $spos);
2918 $par[$cpar] = $cval;
2919 $a_parstr = substr($a_parstr, $spos + 1, strlen($a_parstr) - $spos - 1);
2920 } else {
2921 $ok = false;
2922 }
2923 } else {
2924 $ok = false;
2925 }
2926 }
2927 }
2928
2929 if ($ok) {
2930 return $par;
2931 } else {
2932 return false;
2933 }
2934 }
2935
2936 public static function assembleParameterString($a_par_arr)
2937 {
2938 if (is_array($a_par_arr)) {
2939 $target_arr = array();
2940 foreach ($a_par_arr as $par => $val) {
2941 $target_arr[] = "$par=\"$val\"";
2942 }
2943 $target_str = implode(", ", $target_arr);
2944 }
2945
2946 return $target_str;
2947 }
2948
2955 public static function dumpString($a_str)
2956 {
2957 $ret = $a_str . ": ";
2958 for ($i = 0; $i < strlen($a_str); $i++) {
2959 $ret .= ord(substr($a_str, $i, 1)) . " ";
2960 }
2961 return $ret;
2962 }
2963
2964
2971 public static function yn2tf($a_yn)
2972 {
2973 if (strtolower($a_yn) == "y") {
2974 return true;
2975 } else {
2976 return false;
2977 }
2978 }
2979
2986 public static function tf2yn($a_tf)
2987 {
2988 if ($a_tf) {
2989 return "y";
2990 } else {
2991 return "n";
2992 }
2993 }
2994
3005 public static function sort_func($a, $b)
3006 {
3007 global $array_sortby,$array_sortorder;
3008
3009 if (!isset($array_sortby)) {
3010 // occured in: setup -> new client -> install languages -> sorting of languages
3011 $array_sortby = 0;
3012 }
3013
3014 // this comparison should give optimal results if
3015 // locale is provided and mb string functions are supported
3016 if ($array_sortorder == "asc") {
3017 return ilStr::strCmp($a[$array_sortby], $b[$array_sortby]);
3018 }
3019
3020 if ($array_sortorder == "desc") {
3021 return !ilStr::strCmp($a[$array_sortby], $b[$array_sortby]);
3022 return strcoll(ilStr::strToUpper($b[$array_sortby]), ilStr::strToUpper($a[$array_sortby]));
3023 }
3024 }
3025
3036 public static function sort_func_numeric($a, $b)
3037 {
3038 global $array_sortby,$array_sortorder;
3039
3040 if ($array_sortorder == "asc") {
3041 return $a["$array_sortby"] > $b["$array_sortby"];
3042 }
3043
3044 if ($array_sortorder == "desc") {
3045 return $a["$array_sortby"] < $b["$array_sortby"];
3046 }
3047 }
3060 public static function sortArray(
3061 $array,
3062 $a_array_sortby,
3063 $a_array_sortorder = 0,
3064 $a_numeric = false,
3065 $a_keep_keys = false
3066 ) {
3067 include_once("./Services/Utilities/classes/class.ilStr.php");
3068
3069 // BEGIN WebDAV: Provide a 'stable' sort algorithm
3070 if (!$a_keep_keys) {
3071 return self::stableSortArray($array, $a_array_sortby, $a_array_sortorder, $a_numeric, $a_keep_keys);
3072 }
3073 // END WebDAV Provide a 'stable' sort algorithm
3074
3075 global $array_sortby,$array_sortorder;
3076 $array_sortby = $a_array_sortby;
3077
3078 if ($a_array_sortorder == "desc") {
3079 $array_sortorder = "desc";
3080 } else {
3081 $array_sortorder = "asc";
3082 }
3083 if ($a_numeric) {
3084 if ($a_keep_keys) {
3085 uasort($array, array("ilUtil", "sort_func_numeric"));
3086 } else {
3087 usort($array, array("ilUtil", "sort_func_numeric"));
3088 }
3089 } else {
3090 if ($a_keep_keys) {
3091 uasort($array, array("ilUtil", "sort_func"));
3092 } else {
3093 usort($array, array("ilUtil", "sort_func"));
3094 }
3095 }
3096 //usort($array,"ilUtil::sort_func");
3097
3098 return $array;
3099 }
3100 // BEGIN WebDAV: Provide a 'stable' sort algorithm
3115 public static function stableSortArray($array, $a_array_sortby, $a_array_sortorder = 0, $a_numeric = false)
3116 {
3117 global $array_sortby,$array_sortorder;
3118
3119 $array_sortby = $a_array_sortby;
3120
3121 if ($a_array_sortorder == "desc") {
3122 $array_sortorder = "desc";
3123 } else {
3124 $array_sortorder = "asc";
3125 }
3126
3127 // Create a copy of the array values for sorting
3128 $sort_array = array_values($array);
3129
3130 if ($a_numeric) {
3131 ilUtil::mergesort($sort_array, array("ilUtil", "sort_func_numeric"));
3132 } else {
3133 ilUtil::mergesort($sort_array, array("ilUtil", "sort_func"));
3134 }
3135
3136 return $sort_array;
3137 }
3138 public static function mergesort(&$array, $cmp_function = 'strcmp')
3139 {
3140 // Arrays of size < 2 require no action.
3141 if (count($array) < 2) {
3142 return;
3143 }
3144
3145 // Split the array in half
3146 $halfway = count($array) / 2;
3147 $array1 = array_slice($array, 0, $halfway);
3148 $array2 = array_slice($array, $halfway);
3149
3150 // Recurse to sort the two halves
3151 ilUtil::mergesort($array1, $cmp_function);
3152 ilUtil::mergesort($array2, $cmp_function);
3153
3154 // If all of $array1 is <= all of $array2, just append them.
3155 if (call_user_func($cmp_function, end($array1), $array2[0]) < 1) {
3156 $array = array_merge($array1, $array2);
3157 return;
3158 }
3159
3160 // Merge the two sorted arrays into a single sorted array
3161 $array = array();
3162 $ptr1 = $ptr2 = 0;
3163 while ($ptr1 < count($array1) && $ptr2 < count($array2)) {
3164 if (call_user_func($cmp_function, $array1[$ptr1], $array2[$ptr2]) < 1) {
3165 $array[] = $array1[$ptr1++];
3166 } else {
3167 $array[] = $array2[$ptr2++];
3168 }
3169 }
3170
3171 // Merge the remainder
3172 while ($ptr1 < count($array1)) {
3173 $array[] = $array1[$ptr1++];
3174 }
3175 while ($ptr2 < count($array2)) {
3176 $array[] = $array2[$ptr2++];
3177 }
3178
3179 return;
3180 }
3181 // END WebDAV: Provide a 'stable' sort algorithm
3182
3194 public static function unique_multi_array($array, $sub_key)
3195 {
3196 $target = array();
3197 $existing_sub_key_values = array();
3198
3199 foreach ($array as $key => $sub_array) {
3200 if (!in_array($sub_array[$sub_key], $existing_sub_key_values)) {
3201 $existing_sub_key_values[] = $sub_array[$sub_key];
3202 $target[$key] = $sub_array;
3203 }
3204 }
3205
3206 return $target;
3207 }
3208
3209
3219 public static function getGDSupportedImageType($a_desired_type)
3220 {
3221 $a_desired_type = strtolower($a_desired_type);
3222 // get supported Image Types
3223 $im_types = ImageTypes();
3224
3225 switch ($a_desired_type) {
3226 case "jpg":
3227 case "jpeg":
3228 if ($im_types & IMG_JPG) {
3229 return "jpg";
3230 }
3231 if ($im_types & IMG_GIF) {
3232 return "gif";
3233 }
3234 if ($im_types & IMG_PNG) {
3235 return "png";
3236 }
3237 break;
3238
3239 case "gif":
3240 if ($im_types & IMG_GIF) {
3241 return "gif";
3242 }
3243 if ($im_types & IMG_JPG) {
3244 return "jpg";
3245 }
3246 if ($im_types & IMG_PNG) {
3247 return "png";
3248 }
3249 break;
3250
3251 case "png":
3252 if ($im_types & IMG_PNG) {
3253 return "png";
3254 }
3255 if ($im_types & IMG_JPG) {
3256 return "jpg";
3257 }
3258 if ($im_types & IMG_GIF) {
3259 return "gif";
3260 }
3261 break;
3262
3263 case "svg":
3264 if ($im_types & IMG_PNG) {
3265 return "png";
3266 }
3267 if ($im_types & IMG_JPG) {
3268 return "jpg";
3269 }
3270 if ($im_types & IMG_GIF) {
3271 return "gif";
3272 }
3273 break;
3274 }
3275
3276 return "";
3277 }
3278
3288 public static function deducibleSize($a_mime)
3289 {
3290 if (($a_mime == "image/gif") || ($a_mime == "image/jpeg") ||
3291 ($a_mime == "image/png") || ($a_mime == "application/x-shockwave-flash") ||
3292 ($a_mime == "image/tiff") || ($a_mime == "image/x-ms-bmp") ||
3293 ($a_mime == "image/psd") || ($a_mime == "image/iff")) {
3294 return true;
3295 } else {
3296 return false;
3297 }
3298 }
3299
3300
3306 public static function redirect($a_script)
3307 {
3308 global $DIC;
3309
3310 if (!isset($DIC['ilCtrl']) || !$DIC['ilCtrl'] instanceof ilCtrl) {
3311 $ctrl = new ilCtrl();
3312 } else {
3313 $ctrl = $DIC->ctrl();
3314 }
3315 $ctrl->redirectToURL($a_script);
3316 }
3317
3326 public static function insertInstIntoID($a_value)
3327 {
3328 if (substr($a_value, 0, 4) == "il__") {
3329 $a_value = "il_" . IL_INST_ID . "_" . substr($a_value, 4, strlen($a_value) - 4);
3330 }
3331
3332 return $a_value;
3333 }
3334
3345 public static function groupNameExists($a_group_name, $a_id = 0)
3346 {
3347 global $DIC;
3348
3349 $ilDB = $DIC->database();
3350
3351 $ilErr = null;
3352 if (isset($DIC["ilErr"])) {
3353 $ilErr = $DIC["ilErr"];
3354 }
3355
3356 if (empty($a_group_name)) {
3357 $message = __METHOD__ . ": No groupname given!";
3358 $ilErr->raiseError($message, $ilErr->WARNING);
3359 }
3360
3361 $clause = ($a_id) ? " AND obj_id != " . $ilDB->quote($a_id) . " " : "";
3362
3363 $q = "SELECT obj_id FROM object_data " .
3364 "WHERE title = " . $ilDB->quote($a_group_name, "text") . " " .
3365 "AND type = " . $ilDB->quote("grp", "text") .
3366 $clause;
3367
3368 $r = $ilDB->query($q);
3369
3370 if ($r->numRows()) {
3371 return true;
3372 } else {
3373 return false;
3374 }
3375 }
3376
3383 public static function getMemString()
3384 {
3385 $my_pid = getmypid();
3386 return ("MEMORY USAGE (% KB PID ): " . `ps -eo%mem,rss,pid | grep $my_pid`);
3387 }
3388
3395 public static function isWindows()
3396 {
3397 if (strtolower(substr(php_uname(), 0, 3)) == "win") {
3398 return true;
3399 }
3400 return false;
3401 }
3402
3403
3404 public static function escapeShellArg($a_arg)
3405 {
3406 setlocale(LC_CTYPE, "UTF8", "en_US.UTF-8"); // fix for PHP escapeshellcmd bug. See: http://bugs.php.net/bug.php?id=45132
3407 // see also ilias bug 5630
3408 return escapeshellarg($a_arg);
3409 }
3410
3420 public static function escapeShellCmd($a_arg)
3421 {
3422 if (ini_get('safe_mode') == 1) {
3423 return $a_arg;
3424 }
3425 setlocale(LC_CTYPE, "UTF8", "en_US.UTF-8"); // fix for PHP escapeshellcmd bug. See: http://bugs.php.net/bug.php?id=45132
3426 return escapeshellcmd($a_arg);
3427 }
3428
3438 public static function execQuoted($cmd, $args = null)
3439 {
3440 global $DIC;
3441
3442 if (ilUtil::isWindows() && strpos($cmd, " ") !== false && substr($cmd, 0, 1) !== '"') {
3443 // cmd won't work without quotes
3444 $cmd = '"' . $cmd . '"';
3445 if ($args) {
3446 // args are also quoted, workaround is to quote the whole command AGAIN
3447 // was fixed in php 5.2 (see php bug #25361)
3448 if (version_compare(phpversion(), "5.2", "<") && strpos($args, '"') !== false) {
3449 $cmd = '"' . $cmd . " " . $args . '"';
3450 }
3451 // args are not quoted or php is fixed, just append
3452 else {
3453 $cmd .= " " . $args;
3454 }
3455 }
3456 }
3457 // nothing todo, just append args
3458 elseif ($args) {
3459 $cmd .= " " . $args;
3460 }
3461 exec($cmd, $arr);
3462
3463 $DIC->logger()->root()->debug("ilUtil::execQuoted: " . $cmd . ".");
3464
3465 return $arr;
3466 }
3467
3490 public static function excelTime($year = "", $month = "", $day = "", $hour = "", $minute = "", $second = "")
3491 {
3492 $starting_time = mktime(0, 0, 0, 1, 2, 1970);
3493 if (strcmp("$year$month$day$hour$minute$second", "") == 0) {
3494 $target_time = time();
3495 } else {
3496 if ($year < 1970) {
3497 return 0;
3498 }
3499 }
3500 $target_time = mktime($hour, $minute, $second, $month, $day, $year);
3501 $difference = $target_time - $starting_time;
3502 $days = (($difference - ($difference % 86400)) / 86400);
3503 $difference = $difference - ($days * 86400) + 3600;
3504
3505 // #15343 - using a global locale leads to , instead of . for (implicit) floats
3506 return str_replace(",", ".", ($days + 25570 + ($difference / 86400)));
3507 }
3508
3515 public static function renameExecutables($a_dir)
3516 {
3517 $def_arr = explode(",", SUFFIX_REPL_DEFAULT);
3518 foreach ($def_arr as $def) {
3519 ilUtil::rRenameSuffix($a_dir, trim($def), "sec");
3520 }
3521
3522 $def_arr = explode(",", SUFFIX_REPL_ADDITIONAL);
3523 foreach ($def_arr as $def) {
3524 ilUtil::rRenameSuffix($a_dir, trim($def), "sec");
3525 }
3526 }
3527
3532 public static function getSafeFilename($a_initial_filename)
3533 {
3534 $file_peaces = explode('.', $a_initial_filename);
3535
3536 $file_extension = array_pop($file_peaces);
3537
3538 if (SUFFIX_REPL_ADDITIONAL) {
3539 $string_extensions = SUFFIX_REPL_DEFAULT . "," . SUFFIX_REPL_ADDITIONAL;
3540 } else {
3541 $string_extensions = SUFFIX_REPL_DEFAULT;
3542 }
3543
3544 $sufixes = explode(",", $string_extensions);
3545
3546 if (in_array($file_extension, $sufixes)) {
3547 $file_extension = "sec";
3548 }
3549
3550 array_push($file_peaces, $file_extension);
3551
3552 $safe_filename = "";
3553 foreach ($file_peaces as $piece) {
3554 $safe_filename .= "$piece";
3555 if ($piece != end($file_peaces)) {
3556 $safe_filename .= ".";
3557 }
3558 }
3559
3560 return $safe_filename;
3561 }
3562
3575 public static function rRenameSuffix($a_dir, $a_old_suffix, $a_new_suffix)
3576 {
3577 if ($a_dir == "/" || $a_dir == "" || is_int(strpos($a_dir, ".."))
3578 || trim($a_old_suffix) == "") {
3579 return false;
3580 }
3581
3582 // check if argument is directory
3583 if (!@is_dir($a_dir)) {
3584 return false;
3585 }
3586
3587 // read a_dir
3588 $dir = opendir($a_dir);
3589
3590 while ($file = readdir($dir)) {
3591 if ($file != "." and
3592 $file != "..") {
3593 // triple dot is not allowed in filenames
3594 if ($file === '...') {
3595 unlink($a_dir . "/" . $file);
3596 continue;
3597 }
3598
3599 // directories
3600 if (@is_dir($a_dir . "/" . $file)) {
3601 ilUtil::rRenameSuffix($a_dir . "/" . $file, $a_old_suffix, $a_new_suffix);
3602 }
3603
3604 // files
3605 if (@is_file($a_dir . "/" . $file)) {
3606 // first check for files with trailing dot
3607 if (strrpos($file, '.') == (strlen($file) - 1)) {
3608 try {
3609 rename($a_dir . '/' . $file, substr($a_dir . '/' . $file, 0, -1));
3610 } catch (Throwable $t) {
3611 // to avoid exploits we do delete this file and continue renaming
3612 unlink($a_dir . '/' . $file);
3613 continue;
3614 }
3615
3616 $file = substr($file, 0, -1);
3617 }
3618
3619 $path_info = pathinfo($a_dir . "/" . $file);
3620
3621 if (strtolower($path_info["extension"]) ==
3622 strtolower($a_old_suffix)) {
3623 $pos = strrpos($a_dir . "/" . $file, ".");
3624 $new_name = substr($a_dir . "/" . $file, 0, $pos) . "." . $a_new_suffix;
3625 rename($a_dir . "/" . $file, $new_name);
3626 }
3627 }
3628 }
3629 }
3630 return true;
3631 }
3632
3633 public static function isAPICall()
3634 {
3635 return strpos($_SERVER["SCRIPT_FILENAME"], "api") !== false ||
3636 strpos($_SERVER["SCRIPT_FILENAME"], "dummy") !== false;
3637 }
3638
3639 public static function KT_replaceParam($qstring, $paramName, $paramValue)
3640 {
3641 if (preg_match("/&" . $paramName . "=/", $qstring)) {
3642 return preg_replace("/&" . $paramName . "=[^&]+/", "&" . $paramName . "=" . urlencode($paramValue), $qstring);
3643 } else {
3644 return $qstring . "&" . $paramName . "=" . urlencode($paramValue);
3645 }
3646 }
3647
3648 public static function replaceUrlParameterString($url, $parametersArray)
3649 {
3650 foreach ($parametersArray as $paramName => $paramValue) {
3651 $url = ilUtil::KT_replaceParam($url, $paramName, $paramValue);
3652 }
3653 return $url;
3654 }
3655
3662 public static function generatePasswords($a_number)
3663 {
3664 $ret = array();
3665 srand((double) microtime() * 1000000);
3666
3667 include_once('./Services/PrivacySecurity/classes/class.ilSecuritySettings.php');
3669
3670 for ($i = 1; $i <= $a_number; $i++) {
3671 $min = ($security->getPasswordMinLength() > 0)
3672 ? $security->getPasswordMinLength()
3673 : 6;
3674 $max = ($security->getPasswordMaxLength() > 0)
3675 ? $security->getPasswordMaxLength()
3676 : 10;
3677 if ($min > $max) {
3678 $max = $max + 1;
3679 }
3680 $random = new \ilRandom();
3681 $length = $random->int($min, $max);
3682 $next = $random->int(1, 2);
3683 $vowels = "aeiou";
3684 $vowels_uc = strtoupper($vowels);
3685 $consonants = "bcdfghjklmnpqrstvwxyz";
3686 $consonants_uc = strtoupper($consonants);
3687 $numbers = "1234567890";
3688 $special = "_.+?#-*@!$%~";
3689 $pw = "";
3690
3691 if ($security->getPasswordNumberOfUppercaseChars() > 0) {
3692 for ($j = 0; $j < $security->getPasswordNumberOfUppercaseChars(); $j++) {
3693 switch ($next) {
3694 case 1:
3695 $pw.= $consonants_uc[$random->int(0, strlen($consonants_uc) - 1)];
3696 $next = 2;
3697 break;
3698
3699 case 2:
3700 $pw.= $vowels_uc[$random->int(0, strlen($vowels_uc) - 1)];
3701 $next = 1;
3702 break;
3703 }
3704 }
3705 }
3706
3707 if ($security->isPasswordCharsAndNumbersEnabled()) {
3708 $pw.= $numbers[$random->int(0, strlen($numbers) - 1)];
3709 }
3710
3711 if ($security->isPasswordSpecialCharsEnabled()) {
3712 $pw.= $special[$random->int(0, strlen($special) - 1)];
3713 }
3714
3715 $num_lcase_chars = max($security->getPasswordNumberOfLowercaseChars(), $length - strlen($pw));
3716 for ($j = 0; $j < $num_lcase_chars; $j++) {
3717 switch ($next) {
3718 case 1:
3719 $pw.= $consonants[$random->int(0, strlen($consonants) - 1)];
3720 $next = 2;
3721 break;
3722
3723 case 2:
3724 $pw.= $vowels[$random->int(0, strlen($vowels) - 1)];
3725 $next = 1;
3726 break;
3727 }
3728 }
3729
3730 $pw = str_shuffle($pw);
3731
3732 $ret[] = $pw;
3733 }
3734 return $ret;
3735 }
3736
3737 public static function removeTrailingPathSeparators($path)
3738 {
3739 $path = preg_replace("/[\/\\\]+$/", "", $path);
3740 return $path;
3741 }
3742
3753 public static function array_php2js($data)
3754 {
3755 if (empty($data)) {
3756 $data = array();
3757 }
3758
3759 foreach ($data as $k => $datum) {
3760 if (is_null($datum)) {
3761 $data[$k] = 'null';
3762 }
3763 if (is_string($datum)) {
3764 $data[$k] = "'" . $datum . "'";
3765 }
3766 if (is_array($datum)) {
3767 $data[$k] = array_php2js($datum);
3768 }
3769 }
3770
3771 return "[" . implode(', ', $data) . "]";
3772 }
3773
3780 public static function virusHandling($a_file, $a_orig_name = "", $a_clean = true)
3781 {
3782 global $DIC;
3783
3784 $lng = $DIC->language();
3785
3786 if (IL_VIRUS_SCANNER != "None") {
3787 require_once("./Services/VirusScanner/classes/class.ilVirusScannerFactory.php");
3789 if (($vs_txt = $vs->scanFile($a_file, $a_orig_name)) != "") {
3790 if ($a_clean && (IL_VIRUS_CLEAN_COMMAND != "")) {
3791 $clean_txt = $vs->cleanFile($a_file, $a_orig_name);
3792 if ($vs->fileCleaned()) {
3793 $vs_txt .= "<br />" . $lng->txt("cleaned_file") .
3794 "<br />" . $clean_txt;
3795 $vs_txt .= "<br />" . $lng->txt("repeat_scan");
3796 if (($vs2_txt = $vs->scanFile($a_file, $a_orig_name)) != "") {
3797 return array(false, nl2br($vs_txt) . "<br />" . $lng->txt("repeat_scan_failed") .
3798 "<br />" . nl2br($vs2_txt));
3799 } else {
3800 return array(true, nl2br($vs_txt) . "<br />" . $lng->txt("repeat_scan_succeded"));
3801 }
3802 } else {
3803 return array(false, nl2br($vs_txt) . "<br />" . $lng->txt("cleaning_failed"));
3804 }
3805 } else {
3806 return array(false, nl2br($vs_txt));
3807 }
3808 }
3809 }
3810
3811 return array(true,"");
3812 }
3813
3814
3834 public static function moveUploadedFile($a_file, $a_name, $a_target, $a_raise_errors = true, $a_mode = "move_uploaded")
3835 {
3836 global $DIC;
3837 $target_filename = basename($a_target);
3838
3839 include_once("./Services/Utilities/classes/class.ilFileUtils.php");
3840 $target_filename = ilFileUtils::getValidFilename($target_filename);
3841
3842 // Make sure the target is in a valid subfolder. (e.g. no uploads to ilias/setup/....)
3843 list($target_filesystem, $target_dir) = self::sanitateTargetPath($a_target);
3844
3845 $upload = $DIC->upload();
3846
3847 // If the upload has not yet been processed make sure he gets processed now.
3848 if (!$upload->hasBeenProcessed()) {
3849 $upload->process();
3850 }
3851
3852 try {
3853 if (!$upload->hasUploads()) {
3854 throw new ilException($DIC->language()->txt("upload_error_file_not_found"));
3855 }
3856 $upload_result = $upload->getResults()[$a_file];
3857 if ($upload_result instanceof UploadResult) {
3858 $processing_status = $upload_result->getStatus();
3859 if ($processing_status->getCode() === ProcessingStatus::REJECTED) {
3860 throw new ilException($processing_status->getMessage());
3861 }
3862 } else {
3863 return false;
3864 }
3865 } catch (ilException $e) {
3866 if (!$a_raise_errors) {
3867 ilUtil::sendFailure($e->getMessage(), true);
3868 } else {
3869 throw $e;
3870 }
3871
3872 return false;
3873 }
3874
3875 $upload->moveOneFileTo($upload_result, $target_dir, $target_filesystem, $target_filename, true);
3876
3877 return true;
3878 }
3879
3880
3887 public static function date_mysql2time($mysql_date_time)
3888 {
3889 list($datum, $uhrzeit) = explode(" ", $mysql_date_time);
3890 list($jahr, $monat, $tag) = explode("-", $datum);
3891 list($std, $min, $sec) = explode(":", $uhrzeit);
3892 return mktime((int) $std, (int) $min, (int) $sec, (int) $monat, (int) $tag, (int) $jahr);
3893 }
3894
3901 public static function now()
3902 {
3903 return date("Y-m-d H:i:s");
3904 }
3905
3921 public static function &processCSVRow(&$row, $quoteAll = false, $separator = ";", $outUTF8 = false, $compatibleWithMSExcel = true)
3922 {
3923 $resultarray = array();
3924 foreach ($row as $rowindex => $entry) {
3925 $surround = false;
3926 if ($quoteAll) {
3927 $surround = true;
3928 }
3929 if (strpos($entry, "\"") !== false) {
3930 $entry = str_replace("\"", "\"\"", $entry);
3931 $surround = true;
3932 }
3933 if (strpos($entry, $separator) !== false) {
3934 $surround = true;
3935 }
3936 if ($compatibleWithMSExcel) {
3937 // replace all CR LF with LF (for Excel for Windows compatibility
3938 $entry = str_replace(chr(13) . chr(10), chr(10), $entry);
3939 }
3940 if ($surround) {
3941 if ($outUTF8) {
3942 $resultarray[$rowindex] = "\"" . $entry . "\"";
3943 } else {
3944 $resultarray[$rowindex] = utf8_decode("\"" . $entry . "\"");
3945 }
3946 } else {
3947 if ($outUTF8) {
3948 $resultarray[$rowindex] = $entry;
3949 } else {
3950 $resultarray[$rowindex] = utf8_decode($entry);
3951 }
3952 }
3953 }
3954 return $resultarray;
3955 }
3956
3957 // validates a domain name (example: www.ilias.de)
3958 public static function isDN($a_str)
3959 {
3960 return(preg_match("/^[a-z]+([a-z0-9-]*[a-z0-9]+)?(\.([a-z]+([a-z0-9-]*[a-z0-9]+)?)+)*$/", $a_str));
3961 }
3962
3963 // validates an IP address (example: 192.168.1.1)
3964 public static function isIPv4($a_str)
3965 {
3966 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])\." .
3967 "(\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));
3968 }
3969
3970
3999 public static function _getObjectsByOperations($a_obj_type, $a_operation, $a_usr_id = 0, $limit = 0)
4000 {
4001 global $DIC;
4002
4003 $ilDB = $DIC->database();
4004 $rbacreview = $DIC->rbac()->review();
4005 $ilAccess = $DIC->access();
4006 $ilUser = $DIC->user();
4007 $ilSetting = $DIC->settings();
4008 $tree = $DIC->repositoryTree();
4009
4010 if (!is_array($a_obj_type)) {
4011 $where = "WHERE type = " . $ilDB->quote($a_obj_type, "text") . " ";
4012 } else {
4013 $where = "WHERE " . $ilDB->in("type", $a_obj_type, false, "text") . " ";
4014 }
4015
4016 // limit number of results default is search result limit
4017 if (!$limit) {
4018 $limit = $ilSetting->get('search_max_hits', 100);
4019 }
4020 if ($limit == -1) {
4021 $limit = 10000;
4022 }
4023
4024 // default to logged in usr
4025 $a_usr_id = $a_usr_id ? $a_usr_id : $ilUser->getId();
4026 $a_roles = $rbacreview->assignedRoles($a_usr_id);
4027
4028 // Since no rbac_pa entries are available for the system role. This function returns !all! ref_ids in the case the user
4029 // is assigned to the system role
4030 if ($rbacreview->isAssigned($a_usr_id, SYSTEM_ROLE_ID)) {
4031 $query = "SELECT ref_id FROM object_reference obr LEFT JOIN object_data obd ON obr.obj_id = obd.obj_id " .
4032 "LEFT JOIN tree ON obr.ref_id = tree.child " .
4033 $where .
4034 "AND tree = 1";
4035
4036 $res = $ilDB->query($query);
4037 $counter = 0;
4038 while ($row = $ilDB->fetchObject($res)) {
4039 // Filter recovery folder
4040 if ($tree->isGrandChild(RECOVERY_FOLDER_ID, $row->ref_id)) {
4041 continue;
4042 }
4043
4044 if ($counter++ >= $limit) {
4045 break;
4046 }
4047
4048 $ref_ids[] = $row->ref_id;
4049 }
4050 return $ref_ids ? $ref_ids : array();
4051 } // End Administrators
4052
4053 // Check ownership if it is not asked for edit_permission or a create permission
4054 if ($a_operation == 'edit_permissions' or strpos($a_operation, 'create') !== false) {
4055 $check_owner = ") ";
4056 } else {
4057 $check_owner = "OR owner = " . $ilDB->quote($a_usr_id, "integer") . ") ";
4058 }
4059
4060 $ops_ids = ilRbacReview::_getOperationIdsByName(array($a_operation));
4061 $ops_id = $ops_ids[0];
4062
4063 $and = "AND ((" . $ilDB->in("rol_id", $a_roles, false, "integer") . " ";
4064
4065 $query = "SELECT DISTINCT(obr.ref_id),obr.obj_id,type FROM object_reference obr " .
4066 "JOIN object_data obd ON obd.obj_id = obr.obj_id " .
4067 "LEFT JOIN rbac_pa ON obr.ref_id = rbac_pa.ref_id " .
4068 $where .
4069 $and .
4070 "AND (" . $ilDB->like("ops_id", "text", "%i:" . $ops_id . "%") . " " .
4071 "OR " . $ilDB->like("ops_id", "text", "%:\"" . $ops_id . "\";%") . ")) " .
4072 $check_owner;
4073
4074 $res = $ilDB->query($query);
4075 $counter = 0;
4076 while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) {
4077 if ($counter >= $limit) {
4078 break;
4079 }
4080
4081 // Filter objects in recovery folder
4082 if ($tree->isGrandChild(RECOVERY_FOLDER_ID, $row->ref_id)) {
4083 continue;
4084 }
4085
4086 // Check deleted, hierarchical access ...
4087 if ($ilAccess->checkAccessOfUser($a_usr_id, $a_operation, '', $row->ref_id, $row->type, $row->obj_id)) {
4088 $counter++;
4089 $ref_ids[] = $row->ref_id;
4090 }
4091 }
4092 return $ref_ids ? $ref_ids : array();
4093 }
4094
4095
4101 protected static function sanitateTargetPath($a_target)
4102 {
4103 switch (true) {
4104 case strpos($a_target, ILIAS_WEB_DIR . '/' . CLIENT_ID) === 0:
4105 case strpos($a_target, './' . ILIAS_WEB_DIR . '/' . CLIENT_ID) === 0:
4106 case strpos($a_target, CLIENT_WEB_DIR) === 0:
4107 $targetFilesystem = \ILIAS\FileUpload\Location::WEB;
4108 break;
4109 case strpos($a_target, CLIENT_DATA_DIR . "/temp") === 0:
4110 $targetFilesystem = \ILIAS\FileUpload\Location::TEMPORARY;
4111 break;
4112 case strpos($a_target, CLIENT_DATA_DIR) === 0:
4113 $targetFilesystem = \ILIAS\FileUpload\Location::STORAGE;
4114 break;
4115 case strpos($a_target, ILIAS_ABSOLUTE_PATH . '/Customizing') === 0:
4116 $targetFilesystem = \ILIAS\FileUpload\Location::CUSTOMIZING;
4117 break;
4118 default:
4119 throw new InvalidArgumentException("Can not move files to \"$a_target\" because path can not be mapped to web, storage or customizing location.");
4120 }
4121
4122 $absTargetDir = dirname($a_target);
4123 $targetDir = LegacyPathHelper::createRelativePath($absTargetDir);
4124
4125 return array( $targetFilesystem, $targetDir );
4126 }
4127
4128
4133 public function includeMathjax($a_tpl = null)
4134 {
4135 include_once './Services/MathJax/classes/class.ilMathJax.php';
4136 ilMathJax::getInstance()->includeMathJax($a_tpl);
4137 }
4138
4143 public static function insertLatexImages($a_text, $a_start = '[tex]', $a_end = '[/tex]')
4144 {
4145 include_once './Services/MathJax/classes/class.ilMathJax.php';
4146 return ilMathJax::getInstance()->insertLatexImages($a_text, $a_start, $a_end);
4147 }
4148
4153 public static function buildLatexImages($a_text, $a_dir)
4154 {
4155 include_once './Services/MathJax/classes/class.ilMathJax.php';
4156 return ilMathJax::getInstance()->insertLatexImages($a_text, '[tex]', '[/tex]', $a_dir . '/teximg', './teximg');
4157 }
4158
4167 public static function prepareTextareaOutput($txt_output, $prepare_for_latex_output = false, $omitNl2BrWhenTextArea = false)
4168 {
4169 $result = $txt_output;
4170 $is_html = self::isHTML($result);
4171
4172 // removed: did not work with magic_quotes_gpc = On
4173 if (!$is_html) {
4174 if (!$omitNl2BrWhenTextArea) {
4175 // if the string does not contain HTML code, replace the newlines with HTML line breaks
4176 $result = preg_replace("/[\n]/", "<br />", $result);
4177 }
4178 } else {
4179 // patch for problems with the <pre> tags in tinyMCE
4180 if (preg_match_all("/(<pre>.*?<\/pre>)/ims", $result, $matches)) {
4181 foreach ($matches[0] as $found) {
4182 $replacement = "";
4183 if (strpos("\n", $found) === false) {
4184 $replacement = "\n";
4185 }
4186 $removed = preg_replace("/<br\s*?\/>/ims", $replacement, $found);
4187 $result = str_replace($found, $removed, $result);
4188 }
4189 }
4190 }
4191
4192 // since server side mathjax rendering does include svg-xml structures that indeed have linebreaks,
4193 // do latex conversion AFTER replacing linebreaks with <br>. <svg> tag MUST NOT contain any <br> tags.
4194 if ($prepare_for_latex_output) {
4195 include_once './Services/MathJax/classes/class.ilMathJax.php';
4196 $result = ilMathJax::getInstance()->insertLatexImages($result, "<span class\=\"latex\">", "<\/span>");
4197 $result = ilMathJax::getInstance()->insertLatexImages($result, "\[tex\]", "\[\/tex\]");
4198 }
4199
4200 if ($prepare_for_latex_output) {
4201 // replace special characters to prevent problems with the ILIAS template system
4202 // eg. if someone uses {1} as an answer, nothing will be shown without the replacement
4203 $result = str_replace("{", "&#123;", $result);
4204 $result = str_replace("}", "&#125;", $result);
4205 $result = str_replace("\\", "&#92;", $result);
4206 }
4207
4208 return $result;
4209 }
4210
4219 public static function isHTML($a_text)
4220 {
4221 if (strlen(strip_tags($a_text)) < strlen($a_text)) {
4222 return true;
4223 }
4224
4225 return false;
4226 }
4227
4237 public static function period2String(ilDateTime $a_from, $a_to = null)
4238 {
4239 global $DIC;
4240
4241 $lng = $DIC->language();
4242
4243 if (!$a_to) {
4244 $a_to = new ilDateTime(time(), IL_CAL_UNIX);
4245 }
4246
4247 $from = new DateTime($a_from->get(IL_CAL_DATETIME));
4248 $to = new DateTime($a_to->get(IL_CAL_DATETIME));
4249 $diff = $to->diff($from);
4250
4251 $periods = array();
4252 $periods["years"] = $diff->format("%y");
4253 $periods["months"] = $diff->format("%m");
4254 $periods["days"] = $diff->format("%d");
4255 $periods["hours"] = $diff->format("%h");
4256 $periods["minutes"] = $diff->format("%i");
4257 $periods["seconds"] = $diff->format("%s");
4258
4259 if (!array_sum($periods)) {
4260 return;
4261 }
4262
4263 foreach ($periods as $key => $value) {
4264 if ($value) {
4265 $segment_name = ($value > 1)
4266 ? $key
4267 : substr($key, 0, -1);
4268 $array[] = $value . ' ' . $lng->txt($segment_name);
4269 }
4270 }
4271
4272 $len = sizeof($array);
4273 if ($len > 3) {
4274 $array = array_slice($array, 0, (3 - $len));
4275 }
4276
4277 return implode(', ', $array);
4278 }
4279
4280 public static function getFileSizeInfo()
4281 {
4282 $max_filesize = self::formatBytes(
4283 self::getUploadSizeLimitBytes()
4284 );
4285
4286 global $DIC;
4287
4288 $lng = $DIC->language();
4289 /*
4290 // get the value for the maximal uploadable filesize from the php.ini (if available)
4291 $umf=get_cfg_var("upload_max_filesize");
4292 // get the value for the maximal post data from the php.ini (if available)
4293 $pms=get_cfg_var("post_max_size");
4294
4295 // use the smaller one as limit
4296 $max_filesize=min($umf, $pms);
4297 if (!$max_filesize) $max_filesize=max($umf, $pms);
4298 */
4299 return $lng->txt("file_notice") . " $max_filesize.";
4300 }
4301
4302 public static function formatBytes($size, $decimals = 0)
4303 {
4304 $unit = array('', 'K', 'M', 'G', 'T', 'P');
4305
4306 for ($i = 0, $maxUnits = count($unit); $size >= 1024 && $i <= $maxUnits; $i++) {
4307 $size /= 1024;
4308 }
4309
4310 return round($size, $decimals) . $unit[$i];
4311 }
4312
4313 public static function getUploadSizeLimitBytes()
4314 {
4315 $uploadSizeLimitBytes = min(
4316 self::convertPhpIniSizeValueToBytes(ini_get('post_max_size')),
4317 self::convertPhpIniSizeValueToBytes(ini_get('upload_max_filesize'))
4318 );
4319
4320 return $uploadSizeLimitBytes;
4321 }
4322
4323 public static function convertPhpIniSizeValueToBytes($phpIniSizeValue)
4324 {
4325 if (is_numeric($phpIniSizeValue)) {
4326 return $phpIniSizeValue;
4327 }
4328
4329 $suffix = substr($phpIniSizeValue, -1);
4330 $value = substr($phpIniSizeValue, 0, -1);
4331
4332 switch (strtoupper($suffix)) {
4333 case 'P':
4334 $value *= 1024;
4335 // no break
4336 case 'T':
4337 $value *= 1024;
4338 // no break
4339 case 'G':
4340 $value *= 1024;
4341 // no break
4342 case 'M':
4343 $value *= 1024;
4344 // no break
4345 case 'K':
4346 $value *= 1024;
4347 break;
4348 }
4349
4350 return $value;
4351 }
4352
4361 public static function __extractRefId($role_title)
4362 {
4363 $test_str = explode('_', $role_title);
4364
4365 if ($test_str[0] == 'il') {
4366 $test2 = (int) $test_str[3];
4367 return is_numeric($test2) ? (int) $test2 : false;
4368 }
4369 return false;
4370 }
4371
4382 public static function __extractId($ilias_id, $inst_id)
4383 {
4384 $test_str = explode('_', $ilias_id);
4385
4386 if ($test_str[0] == 'il' && $test_str[1] == $inst_id && count($test_str) == 4) {
4387 $test2 = (int) $test_str[3];
4388 return is_numeric($test2) ? (int) $test2 : false;
4389 }
4390 return false;
4391 }
4392
4407 public static function _sortIds($a_ids, $a_table, $a_field, $a_id_name)
4408 {
4409 global $DIC;
4410
4411 $ilDB = $DIC->database();
4412
4413 if (!$a_ids) {
4414 return array();
4415 }
4416
4417 // use database to sort user array
4418 $where = "WHERE " . $a_id_name . " IN (";
4419 $where .= implode(",", ilUtil::quoteArray($a_ids));
4420 $where .= ") ";
4421
4422 $query = "SELECT " . $a_id_name . " FROM " . $a_table . " " .
4423 $where .
4424 "ORDER BY " . $a_field;
4425
4426 $res = $ilDB->query($query);
4427 while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) {
4428 $ids[] = $row->$a_id_name;
4429 }
4430 return $ids ? $ids : array();
4431 }
4432
4442 public static function getMySQLTimestamp($a_ts)
4443 {
4444 global $DIC;
4445
4446 $ilDB = $DIC->database();
4447
4448 return $a_ts;
4449 }
4450
4457 public static function quoteArray($a_array)
4458 {
4459 global $DIC;
4460
4461 $ilDB = $DIC->database();
4462
4463
4464 if (!is_array($a_array) or !count($a_array)) {
4465 return array("''");
4466 }
4467
4468 foreach ($a_array as $k => $item) {
4469 $a_array[$k] = $ilDB->quote($item);
4470 }
4471
4472 return $a_array;
4473 }
4474
4481 public static function getSystemMessageHTML($a_txt, $a_type = "info")
4482 {
4483 global $DIC;
4484
4485 $lng = $DIC->language();
4486 $mtpl = new ilTemplate("tpl.message.html", true, true, "Services/Utilities");
4487 $mtpl->setCurrentBlock($a_type . "_message");
4488 $mtpl->setVariable("TEXT", $a_txt);
4489 $mtpl->setVariable("MESSAGE_HEADING", $lng->txt($a_type . "_message"));
4490 $mtpl->parseCurrentBlock();
4491
4492 return $mtpl->get();
4493 }
4494
4503 public static function sendInfo($a_info = "", $a_keep = false)
4504 {
4505 global $DIC;
4506
4507 $tpl = $DIC["tpl"];
4508 $tpl->setOnScreenMessage("info", $a_info, $a_keep);
4509 }
4510
4519 public static function sendFailure($a_info = "", $a_keep = false)
4520 {
4521 global $DIC;
4522
4523 if (isset($DIC["tpl"])) {
4524 $tpl = $DIC["tpl"];
4525 $tpl->setOnScreenMessage("failure", $a_info, $a_keep);
4526 }
4527 }
4528
4535 public static function sendQuestion($a_info = "", $a_keep = false)
4536 {
4537 global $DIC;
4538
4539 $tpl = $DIC["tpl"];
4540 $tpl->setOnScreenMessage("question", $a_info, $a_keep);
4541 }
4542
4551 public static function sendSuccess($a_info = "", $a_keep = false)
4552 {
4553 global $DIC;
4554
4556 $tpl = $DIC["tpl"];
4557 $tpl->setOnScreenMessage("success", $a_info, $a_keep);
4558 }
4559
4560 public static function infoPanel($a_keep = true)
4561 {
4562 global $DIC;
4563
4564 $tpl = $DIC["tpl"];
4565 $lng = $DIC->language();
4566 $ilUser = $DIC->user();
4567
4568 if (!empty($_SESSION["infopanel"]) and is_array($_SESSION["infopanel"])) {
4569 $tpl->addBlockFile(
4570 "INFOPANEL",
4571 "infopanel",
4572 "tpl.infopanel.html",
4573 "Services/Utilities"
4574 );
4575 $tpl->setCurrentBlock("infopanel");
4576
4577 if (!empty($_SESSION["infopanel"]["text"])) {
4578 $link = "<a href=\"" . $_SESSION["infopanel"]["link"] . "\" target=\"" .
4579 ilFrameTargetInfo::_getFrame("MainContent") .
4580 "\">";
4581 $link .= $lng->txt($_SESSION["infopanel"]["text"]);
4582 $link .= "</a>";
4583 }
4584
4585 // deactivated
4586 if (!empty($_SESSION["infopanel"]["img"])) {
4587 $link .= "<td><a href=\"" . $_SESSION["infopanel"]["link"] . "\" target=\"" .
4588 ilFrameTargetInfo::_getFrame("MainContent") .
4589 "\">";
4590 $link .= "<img src=\"" . "./templates/" . $ilUser->prefs["skin"] . "/images/" .
4591 $_SESSION["infopanel"]["img"] . "\" border=\"0\" vspace=\"0\"/>";
4592 $link .= "</a></td>";
4593 }
4594
4595 $tpl->setVariable("INFO_ICONS", $link);
4596 $tpl->parseCurrentBlock();
4597 }
4598
4599 //if (!$a_keep)
4600 //{
4601 ilSession::clear("infopanel");
4602 //}
4603 }
4604
4605
4614 public static function dirsize($directory)
4615 {
4616 $size = 0;
4617 if (!is_dir($directory)) {
4618 // BEGIN DiskQuota Suppress PHP warning when attempting to determine
4619 // dirsize of non-existing directory
4620 $size = @filesize($directory);
4621 // END DiskQuota Suppress PHP warning.
4622 return ($size === false) ? -1 : $size;
4623 }
4624 if ($DIR = opendir($directory)) {
4625 while (($dirfile = readdir($DIR)) !== false) {
4626 if (is_link($directory . DIRECTORY_SEPARATOR . $dirfile) || $dirfile == '.' || $dirfile == '..') {
4627 continue;
4628 }
4629 if (is_file($directory . DIRECTORY_SEPARATOR . $dirfile)) {
4630 $size += filesize($directory . DIRECTORY_SEPARATOR . $dirfile);
4631 } elseif (is_dir($directory . DIRECTORY_SEPARATOR . $dirfile)) {
4632 // BEGIN DiskQuota: dirsize is not a global function anymore
4633 $dirSize = ilUtil::dirsize($directory . DIRECTORY_SEPARATOR . $dirfile);
4634 // END DiskQuota: dirsize is not a global function anymore
4635 if ($dirSize >= 0) {
4636 $size += $dirSize;
4637 } else {
4638 return -1;
4639 }
4640 }
4641 }
4642 closedir($DIR);
4643 }
4644 return $size;
4645 }
4646
4647 public static function randomhash()
4648 {
4649 $random = new \ilRandom();
4650 return md5($random->int(1, 9999999) + str_replace(" ", "", (string) microtime()));
4651 }
4652
4653 public static function setCookie($a_cookie_name, $a_cookie_value = '', $a_also_set_super_global = true, $a_set_cookie_invalid = false)
4654 {
4655 /*
4656 if(!(bool)$a_set_cookie_invalid) $expire = IL_COOKIE_EXPIRE;
4657 else $expire = time() - (365*24*60*60);
4658 */
4659 // Temporary fix for feed.php
4660 if (!(bool) $a_set_cookie_invalid) {
4661 $expire = 0;
4662 } else {
4663 $expire = time() - (365 * 24 * 60 * 60);
4664 }
4665 /* We MUST NOT set the global constant here, because this affects the session_set_cookie_params() call as well
4666 if(!defined('IL_COOKIE_SECURE'))
4667 {
4668 define('IL_COOKIE_SECURE', false);
4669 }
4670 */
4671 $secure = false;
4672 if (defined('IL_COOKIE_SECURE')) {
4673 $secure = IL_COOKIE_SECURE;
4674 }
4675
4676 setcookie(
4677 $a_cookie_name,
4678 $a_cookie_value,
4679 $expire,
4681 IL_COOKIE_DOMAIN,
4682 $secure,
4683 IL_COOKIE_HTTPONLY
4684 );
4685
4686 if ((bool) $a_also_set_super_global) {
4687 $_COOKIE[$a_cookie_name] = $a_cookie_value;
4688 }
4689 }
4690
4691 public static function _sanitizeFilemame($a_filename)
4692 {
4693 return strip_tags(self::stripSlashes($a_filename));
4694 }
4695
4696 public static function _getHttpPath()
4697 {
4698 global $DIC;
4699
4700 $ilIliasIniFile = $DIC["ilIliasIniFile"];
4701
4702 if ($_SERVER['SHELL'] || php_sapi_name() == 'cli' ||
4703 // fallback for windows systems, useful in crons
4704 (class_exists("ilContext") && !ilContext::usesHTTP())) {
4705 return $ilIliasIniFile->readVariable('server', 'http_path');
4706 } else {
4707 return ILIAS_HTTP_PATH;
4708 }
4709 }
4710
4716 public static function printBacktrace($a_limit = 0)
4717 {
4718 $bt = debug_backtrace();
4719 $cnt = 0;
4720 foreach ($bt as $t) {
4721 if ($cnt != 0 && ($a_limit == 0 || $cnt <= $a_limit)) {
4722 echo "<br>" . $t["file"] . ", " . $t["function"] . " [" . $t["line"] . "]";
4723 }
4724 $cnt++;
4725 }
4726 echo "<br>";
4727 }
4728
4743 public static function parseImportId($a_import_id)
4744 {
4745 $exploded = explode('_', $a_import_id);
4746
4747 $parsed['orig'] = $a_import_id;
4748 if ($exploded[0] == 'il') {
4749 $parsed['prefix'] = $exploded[0];
4750 }
4751 if (is_numeric($exploded[1])) {
4752 $parsed['inst_id'] = (int) $exploded[1];
4753 }
4754 $parsed['type'] = $exploded[2];
4755
4756 if (is_numeric($exploded[3])) {
4757 $parsed['id'] = (int) $exploded[3];
4758 }
4759 return $parsed;
4760 }
4761
4768 public static function unserializeSession($data)
4769 {
4770 $vars = preg_split(
4771 '/([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff^|]*)\|/',
4772 $data,
4773 -1,
4774 PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE
4775 );
4776
4777 $result = array();
4778
4779 for ($i = 0; $vars[$i]; $i++) {
4780 $result[$vars[$i++]] = unserialize($vars[$i]);
4781 }
4782
4783 return $result;
4784 }
4785
4786
4799 public function rangeDownload($file)
4800 {
4801 $fp = @fopen($file, 'rb');
4802
4803 $size = filesize($file); // File size
4804 $length = $size; // Content length
4805 $start = 0; // Start byte
4806 $end = $size - 1; // End byte
4807 // Now that we've gotten so far without errors we send the accept range header
4808 /* At the moment we only support single ranges.
4809 * Multiple ranges requires some more work to ensure it works correctly
4810 * and comply with the spesifications: http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.2
4811 *
4812 * Multirange support annouces itself with:
4813 * header('Accept-Ranges: bytes');
4814 *
4815 * Multirange content must be sent with multipart/byteranges mediatype,
4816 * (mediatype = mimetype)
4817 * as well as a boundry header to indicate the various chunks of data.
4818 */
4819 header("Accept-Ranges: 0-$length");
4820 // header('Accept-Ranges: bytes');
4821 // multipart/byteranges
4822 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.2
4823 if (isset($_SERVER['HTTP_RANGE'])) {
4824 $c_start = $start;
4825 $c_end = $end;
4826 // Extract the range string
4827 list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
4828 // Make sure the client hasn't sent us a multibyte range
4829 if (strpos($range, ',') !== false) {
4830
4831 // (?) Shoud this be issued here, or should the first
4832 // range be used? Or should the header be ignored and
4833 // we output the whole content?
4834 header('HTTP/1.1 416 Requested Range Not Satisfiable');
4835 header("Content-Range: bytes $start-$end/$size");
4836 // (?) Echo some info to the client?
4837 exit;
4838 }
4839 // If the range starts with an '-' we start from the beginning
4840 // If not, we forward the file pointer
4841 // And make sure to get the end byte if spesified
4842 if ($range == '-') {
4843
4844 // The n-number of the last bytes is requested
4845 $c_start = $size - substr($range, 1);
4846 } else {
4847 $range = explode('-', $range);
4848 $c_start = $range[0];
4849 $c_end = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size;
4850 }
4851 /* Check the range and make sure it's treated according to the specs.
4852 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
4853 */
4854 // End bytes can not be larger than $end.
4855 $c_end = ($c_end > $end) ? $end : $c_end;
4856 // Validate the requested range and return an error if it's not correct.
4857 if ($c_start > $c_end || $c_start > $size - 1 || $c_end >= $size) {
4858 header('HTTP/1.1 416 Requested Range Not Satisfiable');
4859 header("Content-Range: bytes $start-$end/$size");
4860 // (?) Echo some info to the client?
4861 exit;
4862 }
4863 $start = $c_start;
4864 $end = $c_end;
4865 $length = $end - $start + 1; // Calculate new content length
4866 fseek($fp, $start);
4867 header('HTTP/1.1 206 Partial Content');
4868 }
4869 // Notify the client the byte range we'll be outputting
4870 header("Content-Range: bytes $start-$end/$size");
4871 header("Content-Length: $length");
4872
4873 // Start buffered download
4874 $buffer = 1024 * 8;
4875 while (!feof($fp) && ($p = ftell($fp)) <= $end) {
4876 if ($p + $buffer > $end) {
4877
4878 // In case we're only outputtin a chunk, make sure we don't
4879 // read past the length
4880 $buffer = $end - $p + 1;
4881 }
4882 set_time_limit(0); // Reset time limit for big files
4883 echo fread($fp, $buffer);
4884 flush(); // Free up memory. Otherwise large files will trigger PHP's memory limit.
4885 }
4886
4887 fclose($fp);
4888 }
4889
4890
4891 //
4892 // used to be in ilFormat
4893 //
4894
4907 protected static function _getSizeMagnitude()
4908 {
4909 return 1024;
4910 }
4911
4925 protected static function fmtFloat($a_float, $a_decimals = 0, $a_dec_point = null, $a_thousands_sep = null, $a_suppress_dot_zero = false)
4926 {
4927 global $DIC;
4928
4929 $lng = $DIC->language();
4930
4931 if ($a_dec_point == null) {
4932 {
4933 $a_dec_point = ".";
4934 }
4935 }
4936 if ($a_dec_point == '-lang_sep_decimal-') {
4937 $a_dec_point = ".";
4938 }
4939
4940 if ($a_thousands_sep == null) {
4941 $a_thousands_sep = $lng->txt('lang_sep_thousand');
4942 }
4943 if ($a_thousands_sep == '-lang_sep_thousand-') {
4944 $a_thousands_sep = ",";
4945 }
4946
4947 $txt = number_format($a_float, $a_decimals, $a_dec_point, $a_thousands_sep);
4948
4949 // remove trailing ".0"
4950 if (($a_suppress_dot_zero == 0 || $a_decimals == 0)
4951 && substr($txt, -2) == $a_dec_point . '0'
4952 ) {
4953 $txt = substr($txt, 0, strlen($txt) - 2);
4954 }
4955 if ($a_float == 0 and $txt == "") {
4956 $txt = "0";
4957 }
4958
4959 return $txt;
4960 }
4961
4978 public static function formatSize($size, $a_mode = 'short', $a_lng = null)
4979 {
4980 global $DIC;
4981
4982 $lng = $DIC->language();
4983 if ($a_lng == null) {
4984 $a_lng = $lng;
4985 }
4986
4987 $mag = self::_getSizeMagnitude();
4988
4989 if ($size >= $mag * $mag * $mag) {
4990 $scaled_size = $size / $mag / $mag / $mag;
4991 $scaled_unit = 'lang_size_gb';
4992 } else {
4993 if ($size >= $mag * $mag) {
4994 $scaled_size = $size / $mag / $mag;
4995 $scaled_unit = 'lang_size_mb';
4996 } else {
4997 if ($size >= $mag) {
4998 $scaled_size = $size / $mag;
4999 $scaled_unit = 'lang_size_kb';
5000 } else {
5001 $scaled_size = $size;
5002 $scaled_unit = 'lang_size_bytes';
5003 }
5004 }
5005 }
5006
5007 $result = self::fmtFloat($scaled_size, ($scaled_unit
5008 == 'lang_size_bytes') ? 0 : 1, $a_lng->txt('lang_sep_decimal'), $a_lng->txt('lang_sep_thousand'), true)
5009 . ' ' . $a_lng->txt($scaled_unit);
5010 if ($a_mode == 'long' && $size > $mag) {
5011 $result .= ' (' . self::fmtFloat($size, 0, $a_lng->txt('lang_sep_decimal'), $a_lng->txt('lang_sep_thousand')) . ' '
5012 . $a_lng->txt('lang_size_bytes') . ')';
5013 }
5014
5015 return $result;
5016 }
5017
5018
5019 //
5020 // used for disk quotas
5021 //
5022
5023 public static function MB2Bytes($a_value)
5024 {
5025 return ((int) $a_value) * pow(self::_getSizeMagnitude(), 2);
5026 }
5027
5028 public static function Bytes2MB($a_value)
5029 {
5030 return ((int) $a_value) / (pow(self::_getSizeMagnitude(), 2));
5031 }
5032
5040 public static function dbSupportsDisctinctUmlauts()
5041 {
5042 global $DIC;
5043
5044 if (!isset(self::$db_supports_distinct_umlauts)) {
5045 $ilDB = $DIC->database();
5046 $set = $ilDB->query("SELECT (" . $ilDB->quote("A", "text") . " = " . $ilDB->quote("Ä", "text") . ") t FROM DUAL ");
5047 $rec = $ilDB->fetchAssoc($set);
5048 self::$db_supports_distinct_umlauts = !(bool) $rec["t"];
5049 }
5050
5052 }
5053
5059 public static function dumpVar($mixed = null)
5060 {
5061 echo '<pre>';
5062 var_dump($mixed);
5063 echo '</pre>';
5064 }
5065} // END class.ilUtil
$parser
Definition: BPMN2Parser.php:23
$result
$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.
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
Base class for ILIAS Exception handling.
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 _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
Util class various functions, usage as namespace.
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 rRenameSuffix($a_dir, $a_old_suffix, $a_new_suffix)
Renames all files with certain suffix and gives them a new suffix.
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 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 unzip($a_file, $overwrite=false, $a_flat=false)
unzip file
static htmlencodePlainString($a_str, $a_make_links_clickable, $a_detect_goto_links=false)
Encodes a plain text string into HTML for display in a browser.
static array_php2js($data)
convert php arrays to javascript arrays
includeMathjax($a_tpl=null)
Include Mathjax.
static unique_multi_array($array, $sub_key)
Make a multi-dimensional array to have only DISTINCT values for a certain "column".
static makeDateSelect($prefix, $year="", $month="", $day="", $startyear="", $a_long_month=true, $a_further_options=array(), $emptyoption=false)
Creates a combination of HTML selects for date inputs.
static generatePasswords($a_number)
Generate a number of passwords.
static getSelectName($selected, $values)
???
static randomhash()
static stripSlashes($a_str, $a_strip_html=true, $a_allow="")
strip slashes if magic qoutes is enabled
static date_mysql2time($mysql_date_time)
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')
$login
Definition: cron.php:13
$txt
Definition: error.php:13
$target_arr
Definition: goto.php:47
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
$base
Definition: index.php:4
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.
Class ChatMainBarProvider \MainMenu\Provider.
$a
thx to https://mlocati.github.io/php-cs-fixer-configurator for the examples
$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
$ilIliasIniFile
if(isset($_FILES['img_file']['size']) && $_FILES['img_file']['size'] > 0) $tpl
$errors
$ilUser
Definition: imgupload.php:18
const ILIAS_MODULE
Definition: server.php:14
$a_type
Definition: workflow.php:92
$message
Definition: xapiexit.php:14
$DIC
Definition: xapitoken.php:46
$_COOKIE[session_name()]
Definition: xapitoken.php:39