ILIAS  release_5-2 Revision v5.2.25-18-g3f80b828510
class.ilUtil.php
Go to the documentation of this file.
1<?php
2/* Copyright (c) 1998-2010 ILIAS open source, Extended GPL, see docs/LICENSE */
3
17class ilUtil
18{
29 public static function getImageTagByType($a_type, $a_path, $a_big = false)
30 {
31 global $lng;
32
33 $size = ($a_big)
34 ? "big"
35 : "small";
36
37 include_once("./Services/Object/classes/class.ilObject.php");
39
40 return "<img src=\"".$filename."\" alt=\"".$lng->txt("obj_".$a_type)."\" title=\"".$lng->txt("obj_".$a_type)."\" border=\"0\" vspace=\"0\"/>";
41 }
42
55 public static function getTypeIconPath($a_type,$a_obj_id,$a_size = 'small')
56 {
57 include_once("./Services/Object/classes/class.ilObject.php");
58 return ilObject::_getIcon($a_obj_id, $a_size, $a_type);
59 }
60
71 public static function getImagePath($img, $module_path = "", $mode = "output", $offline = false)
72 {
73 global $ilias, $styleDefinition, $ilCtrl, $ilUser;
74
75 if (is_int(strpos($_SERVER["PHP_SELF"], "setup.php")))
76 {
77 $module_path = "..";
78 }
79 if ($module_path != "")
80 {
81 $module_path = "/".$module_path;
82 }
83
84 // default image
85 $default_img = ".".$module_path."/templates/default/images/".$img;
86
87 // use ilStyleDefinition instead of account to get the current skin and style
88 require_once("./Services/Style/System/classes/class.ilStyleDefinition.php");
89 $current_skin = ilStyleDefinition::getCurrentSkin();
90 $current_style = ilStyleDefinition::getCurrentStyle();
91
92 if (is_object($styleDefinition))
93 {
94 $image_dir = $styleDefinition->getImageDirectory($current_style);
95 }
96 if ($current_skin == "default")
97 {
98 $user_img = ".".$module_path."/templates/default/".$image_dir."/".$img;
99 $skin_img = ".".$module_path."/templates/default/images/".$img;
100 }
101 else if (is_object($styleDefinition) && $current_skin != "default")
102 {
103 $user_img = "./Customizing/global/skin/".
104 $current_skin.$module_path."/".$image_dir."/".$img;
105 $skin_img = "./Customizing/global/skin/".
106 $current_skin.$module_path."/images/".$img;
107 }
108
109 // temp svg patch
110 /*
111 $pi = pathinfo($img);
112 if ($pi["dirname"] != "") {
113 $pi["dirname"] = $pi["dirname"]."/";
114 }
115 $svg_img = ".".$module_path."/templates/default/images/".$pi["dirname"].$pi["filename"].".svg";
116 if (file_exists($svg_img))
117 {
118 return $svg_img;
119 }*/
120
121
122 if ($offline)
123 {
124 return "./images/".$img;
125 }
126 else if (@file_exists($user_img) && $image_dir != "")
127 {
128 return $user_img; // found image for skin and style
129 }
130 else if (file_exists($skin_img))
131 {
132 return $skin_img; // found image in skin/images
133 }
134
135 return $default_img; // take image in default
136 }
137
148 public static function getHtmlPath($relative_path)
149 {
150 if (substr($relative_path, 0, 2) == './')
151 {
152 $relative_path = (substr($relative_path, 1));
153 }
154 if (substr($relative_path, 0, 1) != '/')
155 {
156 $relative_path = '/' . $relative_path;
157 }
158 $htmlpath = ILIAS_HTTP_PATH . $relative_path;
159 return $htmlpath;
160 }
161
174 public static function getStyleSheetLocation($mode = "output", $a_css_name = "", $a_css_location = "")
175 {
176 global $ilias;
177
178 // add version as parameter to force reload for new releases
179 // use ilStyleDefinition instead of account to get the current style
180 require_once("./Services/Style/System/classes/class.ilStyleDefinition.php");
181 $stylesheet_name = (strlen($a_css_name))
182 ? $a_css_name
183 : ilStyleDefinition::getCurrentStyle().".css";
184 if (strlen($a_css_location) && (strcmp(substr($a_css_location, -1), "/") != 0))
185 {
186 $a_css_location = $a_css_location . "/";
187 }
188
189 $filename = "";
190 // use ilStyleDefinition instead of account to get the current skin
191 require_once("./Services/Style/System/classes/class.ilStyleDefinition.php");
192 if (ilStyleDefinition::getCurrentSkin() != "default")
193 {
194 $filename = "./Customizing/global/skin/".ilStyleDefinition::getCurrentSkin()."/".$a_css_location.$stylesheet_name;
195 }
196 if (strlen($filename) == 0 || !file_exists($filename))
197 {
198 $filename = "./" . $a_css_location . "templates/default/".$stylesheet_name;
199 }
200 $vers = "";
201 if ($mode != "filesystem")
202 {
203 $vers = str_replace(" ", "-", $ilias->getSetting("ilias_version"));
204 $vers = "?vers=".str_replace(".", "-", $vers);
205 // use version from template xml to force reload on changes
206 $skin = ilStyleDefinition::getSkins()[ilStyleDefinition::getCurrentSkin()];
207 $vers .= ($skin->getVersion() != '' ? str_replace(".", "-", '-' . $skin->getVersion()) : '');
208 }
209 return $filename . $vers;
210 }
211
222 public static function getJSLocation($a_js_name, $a_js_location = "", $add_version = FALSE)
223 {
224 global $ilias;
225
226 // add version as parameter to force reload for new releases
227 $js_name = $a_js_name;
228 if (strlen($a_js_location) && (strcmp(substr($a_js_location, -1), "/") != 0)) $a_js_location = $a_js_location . "/";
229
230 $filename = "";
231 // use ilStyleDefinition instead of account to get the current skin
232 require_once("./Services/Style/System/classes/class.ilStyleDefinition.php");
233 if (ilStyleDefinition::getCurrentSkin() != "default")
234 {
235 $filename = "./Customizing/global/skin/".ilStyleDefinition::getCurrentSkin()."/".$a_js_location.$js_name;
236 }
237 if (strlen($filename) == 0 || !file_exists($filename))
238 {
239 $filename = "./" . $a_js_location . "templates/default/".$js_name;
240 }
241 $vers = "";
242 if ($add_version)
243 {
244 $vers = str_replace(" ", "-", $ilias->getSetting("ilias_version"));
245 $vers = "?vers=".str_replace(".", "-", $vers);
246 }
247 return $filename . $vers;
248 }
249
257 public static function getP3PLocation()
258 {
259 global $ilias;
260
261 if (defined("ILIAS_MODULE"))
262 {
263 $base = '';
264 for($i = 0;$i < count(explode('/',ILIAS_MODULE));$i++)
265 {
266 $base .= "../Services/Privacy/";
267 }
268 }
269 else
270 {
271 $base = "./Services/Privacy/";
272 }
273
274 if (is_file($base."w3c/p3p.xml"))
275 {
276 return ILIAS_HTTP_PATH."w3c/p3p.xml";
277 }
278 else
279 {
280 return ILIAS_HTTP_PATH."/w3c/p3p_template.xml";
281 }
282 }
283
291 public static function getNewContentStyleSheetLocation($mode = "output")
292 {
293 global $ilias;
294
295 // add version as parameter to force reload for new releases
296 if ($mode != "filesystem")
297 {
298 $vers = str_replace(" ", "-", $ilias->getSetting("ilias_version"));
299 $vers = "?vers=".str_replace(".", "-", $vers);
300 }
301
302 // use ilStyleDefinition instead of account to get the current skin and style
303 require_once("./Services/Style/System/classes/class.ilStyleDefinition.php");
304 if (ilStyleDefinition::getCurrentSkin() == "default")
305 {
306 $in_style = "./templates/".ilStyleDefinition::getCurrentSkin()."/"
307 .ilStyleDefinition::getCurrentStyle()."_cont.css";
308 }
309 else
310 {
311 $in_style = "./Customizing/global/skin/".ilStyleDefinition::getCurrentSkin()."/"
312 .ilStyleDefinition::getCurrentStyle()."_cont.css";
313 }
314
315 if (is_file("./".$in_style))
316 {
317 return $in_style.$vers;
318 }
319 else
320 {
321 return "templates/default/delos_cont.css".$vers;
322 }
323 }
324
343 public static function formSelect($selected,$varname,$options,$multiple = false,$direct_text = false, $size = "0",
344 $style_class = "", $attribs = "",$disabled = false)
345 {
346 global $lng;
347
348 if ($multiple == true)
349 {
350 $multiple = " multiple=\"multiple\"";
351 }
352 else
353 {
354 $multiple = "";
355 $size = 0;
356 }
357
358 $class = " class=\" form-control ".$style_class."\"";
359
360 // use form-inline!
361 // this is workaround the whole function should be set deprecated
362 // $attributes = " style='display:inline-block;' ";
363
364 if (is_array($attribs))
365 {
366 foreach ($attribs as $key => $val)
367 {
368 $attributes .= " ".$key."=\"".$val."\"";
369 }
370 }
371 if($disabled)
372 {
373 $disabled = ' disabled=\"disabled\"';
374 }
375
376 $str = "<select name=\"".$varname ."\"".$multiple." $class size=\"".$size."\" $attributes $disabled>\n";
377
378 foreach ((array) $options as $key => $val)
379 {
380 $style = "";
381 if (is_array($val))
382 {
383 $style = $val["style"];
384 $val = $val["text"]; // mus be last line, since we overwrite
385 }
386
387 $sty = ($style != "")
388 ? ' style="'.$style.'" '
389 : "";
390
391 if ($direct_text)
392 {
393 $str .= " <option $sty value=\"".$key."\"";
394 }
395 else
396 {
397 $str .= " <option $sty value=\"".$val."\"";
398 }
399 if (is_array($selected) )
400 {
401 if (in_array($key,$selected))
402 {
403 $str .= " selected=\"selected\"";
404 }
405 }
406 else if ($selected == $key)
407 {
408 $str .= " selected=\"selected\"";
409 }
410
411 if ($direct_text)
412 {
413 $str .= ">".$val."</option>\n";
414 }
415 else
416 {
417 $str .= ">".$lng->txt($val)."</option>\n";
418 }
419 }
420
421 $str .= "</select>\n";
422
423 return $str;
424 }
425
435 public static function getSelectName ($selected,$values)
436 {
437 return($values[$selected]);
438 }
439
451 public static function formCheckbox ($checked,$varname,$value,$disabled = false)
452 {
453 $str = "<input type=\"checkbox\" name=\"".$varname."\"";
454
455 if ($checked == 1)
456 {
457 $str .= " checked=\"checked\"";
458 }
459
460 if ($disabled)
461 {
462 $str .= " disabled=\"disabled\"";
463 }
464
465 $array_var = false;
466
467 if (substr($varname,-2) == "[]")
468 {
469 $array_var = true;
470 }
471
472 // if varname ends with [], use varname[-2] + _ + value as id tag (e.g. "user_id[]" => "user_id_15")
473 if ($array_var)
474 {
475 $varname_id = substr($varname,0,-2)."_".$value;
476 }
477 else
478 {
479 $varname_id = $varname;
480 }
481
482 // dirty removal of other "[]" in string
483 $varname_id = str_replace("[","_",$varname_id);
484 $varname_id = str_replace("]","",$varname_id);
485
486 $str .= " value=\"".$value."\" id=\"".$varname_id."\" />\n";
487
488 return $str;
489 }
490
502 public static function formDisabledRadioButton($checked,$varname,$value,$disabled)
503 {
504 if ($disabled) {
505 $str = "<input disabled type=\"radio\" name=\"".$varname."\"";
506 }
507 else {
508 $str = "<input type=\"radio\" name=\"".$varname."\"";
509 }
510 if ($checked == 1)
511 {
512 $str .= " checked=\"checked\"";
513 }
514
515 $str .= " value=\"".$value."\"";
516 $str .= " id=\"".$value."\" />\n";
517
518 return $str;
519
520 }
521
522
533 public static function formRadioButton($checked,$varname,$value,$onclick=null, $disabled = false)
534 {
535 $str = '<input ';
536
537 if($onclick)
538 {
539 $str .= ('onclick="'.$onclick.'"');
540 }
541
542 $str .= (" type=\"radio\" name=\"".$varname."\"");
543 if ($checked == 1)
544 {
545 $str .= " checked=\"checked\"";
546 }
547
548 if ($disabled)
549 {
550 $str .= " disabled=\"disabled\"";
551 }
552
553 $str .= " value=\"".$value."\"";
554
555 $str .= " id=\"".$value."\" />\n";
556
557 return $str;
558 }
559
560
570 public static function formInput($varname,$value,$disabled = false)
571 {
572
573 $str = "<input type=\"input\" name=\"".$varname."\"";
574 if ($disabled)
575 {
576 $str .= " disabled";
577 }
578
579 $str .= " value=\"".$value."\"";
580
581 $str .= " id=\"".$value."\" />\n";
582
583 return $str;
584 }
585
586
593 public static function checkInput ($vars)
594 {
595 // TO DO:
596 // Diese Funktion soll Formfeldeingaben berprfen (empty und required)
597 }
598
605 public static function setPathStr ($a_path)
606 {
607 if ("" != $a_path && "/" != substr($a_path, -1))
608 {
609 $a_path .= "/";
610 //$a_path = substr($a_path,1);
611 }
612
613 //return getcwd().$a_path;
614 return $a_path;
615 }
616
629 public static function switchColor ($a_num,$a_css1,$a_css2)
630 {
631 if (!($a_num % 2))
632 {
633 return $a_css1;
634 }
635 else
636 {
637 return $a_css2;
638 }
639 }
640
649 public static function checkFormEmpty ($emptyFields)
650 {
651
652 $feedback = "";
653
654 foreach ($emptyFields as $key => $val)
655 {
656 if ($val == "") {
657 if ($feedback != "") $feedback .= ", ";
658 $feedback .= $key;
659 }
660 }
661
662 return $feedback;
663 }
664
689 public static function Linkbar ($AScript,$AHits,$ALimit,$AOffset,$AParams = array(),$ALayout = array(), $prefix = '')
690 {
691 $LinkBar = "";
692
693 $layout_link = "";
694 $layout_prev = "&lt;&lt;";
695 $layout_next = "&gt;&gt;";
696
697 // layout options
698 if (count($ALayout > 0))
699 {
700 if ($ALayout["link"])
701 {
702 $layout_link = " class=\"".$ALayout["link"]."\"";
703 }
704
705 if ($ALayout["prev"])
706 {
707 $layout_prev = $ALayout["prev"];
708 }
709
710 if ($ALayout["next"])
711 {
712 $layout_next = $ALayout["next"];
713 }
714 }
715
716 // show links, if hits greater limit
717 // or offset > 0 (can be > 0 due to former setting)
718 if ($AHits > $ALimit || $AOffset > 0)
719 {
720 if (!empty($AParams))
721 {
722 foreach ($AParams as $key => $value)
723 {
724 $params.= $key."=".$value."&";
725 }
726 }
727 // if ($params) $params = substr($params,0,-1);
728 if(strpos($AScript,'&'))
729 {
730 $link = $AScript."&".$params.$prefix."offset=";
731 }
732 else
733 {
734 $link = $AScript."?".$params.$prefix."offset=";
735 }
736
737 // ?bergehe "zurck"-link, wenn offset 0 ist.
738 if ($AOffset >= 1)
739 {
740 $prevoffset = $AOffset - $ALimit;
741 if ($prevoffset < 0) $prevoffset = 0;
742 $LinkBar .= "<a".$layout_link." href=\"".$link.$prevoffset."\">".$layout_prev."&nbsp;</a>";
743 }
744
745 // Ben?tigte Seitenzahl kalkulieren
746 $pages=intval($AHits/$ALimit);
747
748 // Wenn ein Rest bleibt, addiere eine Seite
749 if (($AHits % $ALimit))
750 $pages++;
751
752 // Bei Offset = 0 keine Seitenzahlen anzeigen : DEAKTIVIERT
753 // if ($AOffset != 0) {
754
755 // ansonsten zeige Links zu den anderen Seiten an
756 for ($i = 1 ;$i <= $pages ; $i++)
757 {
758 $newoffset=$ALimit*($i-1);
759
760 if ($newoffset == $AOffset)
761 {
762 $LinkBar .= "[".$i."] ";
763 }
764 else
765 {
766 $LinkBar .= '<a '.$layout_link.' href="'.
767 $link.$newoffset.'">['.$i.']</a> ';
768 }
769 }
770 // }
771
772 // Checken, ob letze Seite erreicht ist
773 // Wenn nicht, gebe einen "Weiter"-Link aus
774 if (! ( ($AOffset/$ALimit)==($pages-1) ) && ($pages!=1) )
775 {
776 $newoffset=$AOffset+$ALimit;
777 $LinkBar .= "<a".$layout_link." href=\"".$link.$newoffset."\">&nbsp;".$layout_next."</a>";
778 }
779
780 return $LinkBar;
781 }
782 else
783 {
784 return false;
785 }
786 }
787
799 public static function makeClickable($a_text, $detectGotoLinks = false)
800 {
801 // New code, uses MediaWiki Sanitizer
802 $ret = $a_text;
803
804 // www-URL ohne ://-Angabe
805 $ret = preg_replace("/(^|[\s]+)(www\.)([A-Za-z0-9#&=?.\/\-]+)/i",
806 "$1http://$2$3", $ret);
807
808 // ftp-URL ohne ://-Angabe
809 $ret = preg_replace("/(^|[\s]+)(ftp\.)([A-Za-z0-9#&=?.\/\-]+)/i",
810 "$1ftp://$2$3", $ret);
811
812 // E-Mail (this does not work as expected, users must add mailto: manually)
813 //$ret = preg_replace("/(([a-z0-9_]|\-|\.)+@([^[\s]*)([A-Za-z0-9\-]))/i",
814 // "mailto:$1", $ret);
815
816 // mask existing image tags
817 $ret = str_replace('src="http://', '"***masked_im_start***', $ret);
818
819 include_once("./Services/Utilities/classes/class.ilMWParserAdapter.php");
821 $ret = $parser->replaceFreeExternalLinks($ret);
822
823 // unmask existing image tags
824 $ret = str_replace('"***masked_im_start***', 'src="http://', $ret);
825
826 // Should be Safe
827
828 if ($detectGotoLinks)
829 // replace target blank with self and text with object title.
830 {
831 $regExp = "<a[^>]*href=\"(".str_replace("/","\/",ILIAS_HTTP_PATH)."\/goto.php\?target=\w+_(\d+)[^\"]*)\"[^>]*>[^<]*<\/a>";
832// echo htmlentities($regExp);
833 $ret = preg_replace_callback(
834 "/".$regExp."/i",
835 array("ilUtil", "replaceLinkProperties"),
836 $ret);
837
838 // Static links
839 $regExp = "<a[^>]*href=\"(".str_replace("/","\/",ILIAS_HTTP_PATH)."\/goto_.*[a-z0-9]+_([0-9]+)\.html)\"[^>]*>[^<]*<\/a>";
840// echo htmlentities($regExp);
841 $ret = preg_replace_callback(
842 "/".$regExp."/i",
843 array("ilUtil", "replaceLinkProperties"),
844 $ret);
845 }
846
847 return($ret);
848 }
849
863 public static function replaceLinkProperties ($matches)
864 {
865 $link = $matches[0];
866 $ref_id = $matches[2];
867
868 if ($ref_id > 0)
869 {
871 if ($obj_id > 0)
872 {
874 $link = "<a href=".$matches[1]." target=\"_self\">".$title."</a>";
875 }
876 }
877 return $link;
878 }
879
898 public static function makeDateSelect($prefix, $year = "", $month = "", $day = "", $startyear = "",$a_long_month = true,$a_further_options = array(), $emptyoption = false)
899 {
900 global $lng;
901
902 $disabled = '';
903 if(isset($a_further_options['disabled']) and $a_further_options['disabled'])
904 {
905 $disabled = 'disabled="disabled" ';
906 }
907
908 $now = getdate();
909 if (!$emptyoption)
910 {
911 if (!strlen($year)) $year = $now["year"];
912 if (!strlen($month)) $month = $now["mon"];
913 if (!strlen($day)) $day = $now["mday"];
914 }
915
916 $year = (int) $year;
917 $month = (int) $month;
918 $day = (int) $day;
919
920 // build day select
921
922 $sel_day .= '<select class="form-control" ';
923 if(isset($a_further_options['select_attributes']))
924 {
925 foreach($a_further_options['select_attributes'] as $name => $value)
926 {
927 $sel_day .= ($name.'="'.$value.'" ');
928 }
929 }
930
931 $sel_day .= $disabled."name=\"".$prefix."[d]\" id=\"".$prefix."_d\">\n";
932
933 if ($emptyoption) $sel_day .= "<option value=\"0\">--</option>\n";
934 for ($i = 1; $i <= 31; $i++)
935 {
936 $sel_day .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
937 }
938 $sel_day .= "</select>\n";
939 $sel_day = preg_replace("/(value\=\"$day\")/", "$1 selected=\"selected\"", $sel_day);
940
941 // build month select
942 $sel_month = '<select class="form-control" ';
943 if(isset($a_further_options['select_attributes']))
944 {
945 foreach($a_further_options['select_attributes'] as $name => $value)
946 {
947 $sel_month .= ($name.'="'.$value.'" ');
948 }
949 }
950 $sel_month .= $disabled."name=\"".$prefix."[m]\" id=\"".$prefix."_m\">\n";
951
952 if ($emptyoption) $sel_month .= "<option value=\"0\">--</option>\n";
953 for ($i = 1; $i <= 12; $i++)
954 {
955 if($a_long_month)
956 {
957 $sel_month .= "<option value=\"$i\">" . $lng->txt("month_" . sprintf("%02d", $i) . "_long") . "</option>\n";
958 }
959 else
960 {
961 $sel_month .= "<option value=\"$i\">" . $i . "</option>\n";
962 }
963 }
964 $sel_month .= "</select>\n";
965 $sel_month = preg_replace("/(value\=\"$month\")/", "$1 selected=\"selected\"", $sel_month);
966
967 // build year select
968 $sel_year = '<select class="form-control" ';
969 if(isset($a_further_options['select_attributes']))
970 {
971 foreach($a_further_options['select_attributes'] as $name => $value)
972 {
973 $sel_year .= ($name.'="'.$value.'" ');
974 }
975 }
976 $sel_year .= $disabled."name=\"".$prefix."[y]\" id=\"".$prefix."_y\">\n";
977 if ((strlen($startyear) == 0) || ($startyear > $year))
978 {
979 if (!$emptyoption || $year != 0) $startyear = $year - 5;
980 }
981
982 if(($year + 5) < (date('Y',time()) + 5))
983 {
984 $end_year = date('Y',time()) + 5;
985 }
986 else
987 {
988 $end_year = $year + 5;
989 }
990
991 if ($emptyoption) $sel_year .= "<option value=\"0\">----</option>\n";
992 for ($i = $startyear; $i <= $end_year; $i++)
993 {
994 $sel_year .= "<option value=\"$i\">" . sprintf("%04d", $i) . "</option>\n";
995 }
996 $sel_year .= "</select>\n";
997 $sel_year = preg_replace("/(value\=\"$year\")/", "$1 selected=\"selected\"", $sel_year);
998
999 //$dateformat = $lng->text["lang_dateformat"];
1000 $dateformat = "d-m-Y";
1001 $dateformat = strtolower(preg_replace("/\W/", "", $dateformat));
1002 $dateformat = strtolower(preg_replace("/(\w)/", "%%$1", $dateformat));
1003 $dateformat = preg_replace("/%%d/", $sel_day, $dateformat);
1004 $dateformat = preg_replace("/%%m/", $sel_month, $dateformat);
1005 $dateformat = preg_replace("/%%y/", $sel_year, $dateformat);
1006 return $dateformat;
1007 }
1008
1027 public static function makeTimeSelect($prefix, $short = true, $hour = "", $minute = "", $second = "",$a_use_default = true,$a_further_options = array())
1028 {
1029 global $lng, $ilUser;
1030
1031 $minute_steps = 1;
1032 $disabled = '';
1033 if(count($a_further_options))
1034 {
1035 if(isset($a_further_options['minute_steps']))
1036 {
1037 $minute_steps = $a_further_options['minute_steps'];
1038 }
1039 if(isset($a_further_options['disabled']) and $a_further_options['disabled'])
1040 {
1041 $disabled = 'disabled="disabled" ';
1042 }
1043 }
1044
1045 if ($a_use_default and !strlen("$hour$minute$second")) {
1046 $now = localtime();
1047 $hour = $now[2];
1048 $minute = $now[1];
1049 $second = $now[0];
1050 } else {
1051 $hour = (int)$hour;
1052 $minute = (int)$minute;
1053 $second = (int)$second;
1054 }
1055 // build hour select
1056 $sel_hour = '<select ';
1057 if(isset($a_further_options['select_attributes']))
1058 {
1059 foreach($a_further_options['select_attributes'] as $name => $value)
1060 {
1061 $sel_hour .= $name.'='.$value.' ';
1062 }
1063 }
1064 $sel_hour .= " ".$disabled."name=\"".$prefix."[h]\" id=\"".$prefix."_h\" class=\"form-control\">\n";
1065
1066 $format = $ilUser->getTimeFormat();
1067 for ($i = 0; $i <= 23; $i++)
1068 {
1070 {
1071 $sel_hour .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
1072 }
1073 else
1074 {
1075 $sel_hour .= "<option value=\"$i\">" . date("ga", mktime($i, 0, 0)) . "</option>\n";
1076 }
1077 }
1078 $sel_hour .= "</select>\n";
1079 $sel_hour = preg_replace("/(value\=\"$hour\")/", "$1 selected=\"selected\"", $sel_hour);
1080
1081 // build minutes select
1082 $sel_minute .= "<select ".$disabled."name=\"".$prefix."[m]\" id=\"".$prefix."_m\" class=\"form-control\">\n";
1083
1084 for ($i = 0; $i <= 59; $i = $i + $minute_steps)
1085 {
1086 $sel_minute .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
1087 }
1088 $sel_minute .= "</select>\n";
1089 $sel_minute = preg_replace("/(value\=\"$minute\")/", "$1 selected=\"selected\"", $sel_minute);
1090
1091 if (!$short) {
1092 // build seconds select
1093 $sel_second .= "<select ".$disabled."name=\"".$prefix."[s]\" id=\"".$prefix."_s\" class=\"form-control\">\n";
1094
1095 for ($i = 0; $i <= 59; $i++)
1096 {
1097 $sel_second .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
1098 }
1099 $sel_second .= "</select>\n";
1100 $sel_second = preg_replace("/(value\=\"$second\")/", "$1 selected=\"selected\"", $sel_second);
1101 }
1102 $timeformat = $lng->text["lang_timeformat"];
1103 if (strlen($timeformat) == 0) $timeformat = "H:i:s";
1104 $timeformat = strtolower(preg_replace("/\W/", "", $timeformat));
1105 $timeformat = preg_replace("/(\w)/", "%%$1", $timeformat);
1106 $timeformat = preg_replace("/%%h/", $sel_hour, $timeformat);
1107 $timeformat = preg_replace("/%%i/", $sel_minute, $timeformat);
1108 if ($short) {
1109 $timeformat = preg_replace("/%%s/", "", $timeformat);
1110 } else {
1111 $timeformat = preg_replace("/%%s/", $sel_second, $timeformat);
1112 }
1113 return $timeformat;
1114 }
1115
1129 public static function is_email($a_email)
1130 {
1131 global $ilErr;
1132
1133 // additional check for ilias object is needed,
1134 // otherwise setup will fail with this if branch
1135 if(is_object($ilErr)) // seems to work in Setup now
1136 {
1137 try
1138 {
1139 require_once 'Services/Mail/classes/Address/Parser/class.ilMailRfc822AddressParserFactory.php';
1141 $addresses = $parser->parse();
1142 return count($addresses) == 1 && $addresses[0]->getHost() != ilMail::ILIAS_HOST;
1143 }
1144 catch(ilException $e)
1145 {
1146 return false;
1147 }
1148 }
1149 else
1150 {
1151 $tlds = strtolower(
1152 "AC|AD|AE|AERO|AF|AG|AI|AL|AM|AN|AO|AQ|AR|ARPA|AS|ASIA|AT|AU|AW|AX|AZ|BA|BB|BD|BE|BF|BG|BH|BI|BIZ|BJ|BM|BN|BO|BR|BS|BT|BV|BW|BY|".
1153 "BZ|CA|CAT|CC|CD|CF|CG|CH|CI|CK|CL|CM|CN|CO|COM|COOP|CR|CU|CV|CX|CY|CZ|DE|DJ|DK|DM|DO|DZ|EC|EDU|EE|EG|".
1154 "ER|ES|ET|EU|FI|FJ|FK|FM|FO|FR|GA|GB|GD|GE|GF|GG|GH|GI|GL|GM|GN|GOV|GP|GQ|GR|GS|GT|GU|GW|GY|HK|HM|HN|HR|HT|".
1155 "HU|ID|IE|IL|IM|IN|INFO|INT|IO|IQ|IR|IS|IT|JE|JM|JO|JOBS|JP|KE|KG|KH|KI|KM|KN|KP|KR|KW|KY|KZ|LA|LB|LC|".
1156 "LI|LK|LR|LS|LT|LU|LV|LY|MA|MC|MD|ME|MG|MH|MIL|MK|ML|MM|MN|MO|MOBI|MP|MQ|MR|MS|MT|MU|MUSEUM|MV|MW|MX|".
1157 "MY|MZ|NA|NAME|NC|NE|NET|NF|NG|NI|NL|NO|NP|NR|NU|NZ|OM|ORG|PA|PE|PF|PG|PH|PK|PL|PM|PN|PR|PRO|PS|".
1158 "PT|PW|PY|QA|RE|RO|RS|RU|RW|SA|SB|SC|SD|SE|SG|SH|SI|SJ|SK|SL|SM|SN|SO|SR|ST|SU|SV|SY|SZ|TC|TD|TEL|".
1159 "TF|TG|TH|TJ|TK|TL|TM|TN|TO|TP|TR|TRAVEL|TT|TV|TW|TZ|UA|UG|UK|US|UY|UZ|VA|VC|VE|VG|VI|VN|VU|".
1160 "WF|WS|XN|YE|YT|YU|ZA|ZM|ZW");
1161
1162 return(preg_match("/^[-_.[:alnum:]]+@((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(".$tlds.")|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$a_email));
1163 }
1164 }
1165
1174 public static function isPassword($a_passwd, &$customError = null)
1175 {
1176 global $lng;
1177
1178 include_once('./Services/PrivacySecurity/classes/class.ilSecuritySettings.php');
1180
1181 // check if password is empty
1182 if( empty($a_passwd) )
1183 {
1184 $customError = $lng->txt('password_empty');
1185 return false;
1186 }
1187
1188 $isPassword = true;
1189 $errors = array();
1190
1191 // check if password to short
1192 if( $security->getPasswordMinLength() > 0 && strlen($a_passwd) < $security->getPasswordMinLength() )
1193 {
1194 $errors[] = sprintf( $lng->txt('password_to_short'), $security->getPasswordMinLength() );
1195 $isPassword = false;
1196 }
1197
1198 // check if password not to long
1199 // 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).
1200 if( $security->getPasswordMaxLength() > 0 && strlen($a_passwd) > $security->getPasswordMaxLength() )
1201 {
1202 $errors[] = sprintf( $lng->txt('password_to_long'), $security->getPasswordMaxLength() );
1203 $isPassword = false;
1204 }
1205
1206 // if password must contains Chars and Numbers
1207 if( $security->isPasswordCharsAndNumbersEnabled() )
1208 {
1209 $hasCharsAndNumbers = true;
1210
1211 // check password for existing chars
1212 if( !preg_match('/[A-Za-z]+/',$a_passwd) )
1213 {
1214 $hasCharsAndNumbers = false;
1215 }
1216
1217 // check password for existing numbers
1218 if( !preg_match('/[0-9]+/',$a_passwd) )
1219 {
1220 $hasCharsAndNumbers = false;
1221 }
1222
1223 if( !$hasCharsAndNumbers )
1224 {
1225 $errors[] = $lng->txt('password_must_chars_and_numbers');
1226 $isPassword = false;
1227 }
1228 }
1229
1230 require_once 'Services/Utilities/classes/class.ilStr.php';
1231 if($security->getPasswordNumberOfUppercaseChars() > 0)
1232 {
1233 if(ilStr::strLen($a_passwd) - ilStr::strLen(preg_replace('/[A-Z]/', '', $a_passwd)) < $security->getPasswordNumberOfUppercaseChars())
1234 {
1235 $errors[] = sprintf($lng->txt('password_must_contain_ucase_chars'), $security->getPasswordNumberOfUppercaseChars());
1236 $isPassword = false;
1237 }
1238 }
1239
1240 if($security->getPasswordNumberOfLowercaseChars() > 0)
1241 {
1242 if(ilStr::strLen($a_passwd) - ilStr::strLen(preg_replace('/[a-z]/', '', $a_passwd)) < $security->getPasswordNumberOfLowercaseChars())
1243 {
1244 $errors[] = sprintf($lng->txt('password_must_contain_lcase_chars'), $security->getPasswordNumberOfLowercaseChars());
1245 $isPassword = false;
1246 }
1247 }
1248
1249 // if password must contains Special-Chars
1250 if( $security->isPasswordSpecialCharsEnabled() )
1251 {
1252 // check password for existing special-chars
1253 if( !preg_match( self::getPasswordValidChars(true, true) , $a_passwd) )
1254 {
1255 $errors[] = $lng->txt('password_must_special_chars');
1256 $isPassword = false;
1257 }
1258 }
1259
1260 // ensure password matches the positive list of chars/special-chars
1261 if( !preg_match( self::getPasswordValidChars() , $a_passwd) )
1262 {
1263 $errors[] = $lng->txt('password_contains_invalid_chars');
1264 $isPassword = false;
1265 }
1266
1267 // build custom error message
1268 if( count($errors) == 1 )
1269 {
1270 $customError = $errors[0];
1271 }
1272 elseif( count($errors) > 1 )
1273 {
1274 $customError = $lng->txt('password_multiple_errors');
1275 $customError .= '<br />'.implode('<br />', $errors);
1276 }
1277
1278 return $isPassword;
1279 }
1280
1287 public static function isPasswordValidForUserContext($clear_text_password, $user, &$error_language_variable = null)
1288 {
1289 include_once 'Services/PrivacySecurity/classes/class.ilSecuritySettings.php';
1291
1292 $login = null;
1293
1294 if(is_string($user))
1295 {
1296 $login = $user;
1297 }
1298 else if(is_array($user))
1299 {
1300 // Try to get loginname and user_id from array
1301 $login = $user['login'];
1302 $userId = $user['id'];
1303 }
1304 else if($user instanceof ilObjUser)
1305 {
1306 $login = $user->getLogin();
1307 $userId = $user->getId();
1308 }
1309
1310 // 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.
1311
1312 if($login && (int)$security->getPasswordMustNotContainLoginnameStatus() &&
1313 strpos(strtolower($clear_text_password), strtolower($login)) !== false
1314 )
1315 {
1316 $error_language_variable = 'password_contains_parts_of_login_err';
1317 return false;
1318 }
1319
1320 return true;
1321 }
1322
1330 public static function getPasswordValidChars($a_as_regex = true, $a_only_special_chars = false)
1331 {
1332 if( $a_as_regex )
1333 {
1334 if( $a_only_special_chars )
1335 {
1336 return '/[_\.\+\?\#\-\*\@!\$\%\~\/\:\;]+/';
1337 }
1338 else
1339 {
1340 return '/^[A-Za-z0-9_\.\+\?\#\-\*\@!\$\%\~\/\:\;]+$/';
1341 }
1342 }
1343 else
1344 {
1345 return 'A-Z a-z 0-9 _.+?#-*@!$%~/:;';
1346 }
1347 }
1348
1356 public static function getPasswordRequirementsInfo()
1357 {
1358 global $lng;
1359
1360 include_once('./Services/PrivacySecurity/classes/class.ilSecuritySettings.php');
1362
1363 $infos = array(sprintf($lng->txt('password_allow_chars'), self::getPasswordValidChars(false)));
1364
1365 // check if password to short
1366 if( $security->getPasswordMinLength() > 0 )
1367 {
1368 $infos[] = sprintf( $lng->txt('password_to_short'), $security->getPasswordMinLength() );
1369 }
1370
1371 // check if password not to long
1372 if( $security->getPasswordMaxLength() > 0 )
1373 {
1374 $infos[] = sprintf( $lng->txt('password_to_long'), $security->getPasswordMaxLength() );
1375 }
1376
1377 // if password must contains Chars and Numbers
1378 if( $security->isPasswordCharsAndNumbersEnabled() )
1379 {
1380 $infos[] = $lng->txt('password_must_chars_and_numbers');
1381 }
1382
1383 // if password must contains Special-Chars
1384 if( $security->isPasswordSpecialCharsEnabled() )
1385 {
1386 $infos[] = $lng->txt('password_must_special_chars');
1387 }
1388
1389 if($security->getPasswordNumberOfUppercaseChars() > 0)
1390 {
1391 $infos[] = sprintf($lng->txt('password_must_contain_ucase_chars'), $security->getPasswordNumberOfUppercaseChars());
1392 }
1393
1394 if($security->getPasswordNumberOfLowercaseChars() > 0)
1395 {
1396 $infos[] = sprintf($lng->txt('password_must_contain_lcase_chars'), $security->getPasswordNumberOfLowercaseChars());
1397 }
1398
1399 return implode('<br />', $infos);
1400 }
1401
1402 /*
1403 * validates a login
1404 * @access public
1405 * @param string login
1406 * @return boolean true if valid
1407 */
1408 static function isLogin($a_login)
1409 {
1410 if (empty($a_login))
1411 {
1412 return false;
1413 }
1414
1415 if (strlen($a_login) < 3)
1416 {
1417 return false;
1418 }
1419
1420 // FIXME - If ILIAS is configured to use RFC 822
1421 // compliant mail addresses we should not
1422 // allow the @ character.
1423 if (!preg_match("/^[A-Za-z0-9_\.\+\*\@!\$\%\~\-]+$/", $a_login))
1424 {
1425 return false;
1426 }
1427
1428 return true;
1429 }
1430
1444 public static function shortenText ($a_str, $a_len, $a_dots = false, $a_next_blank = false,
1445 $a_keep_extension = false)
1446 {
1447 include_once("./Services/Utilities/classes/class.ilStr.php");
1448 if (ilStr::strLen($a_str) > $a_len)
1449 {
1450 if ($a_next_blank)
1451 {
1452 $len = ilStr::strPos($a_str, " ", $a_len);
1453 }
1454 else
1455 {
1456 $len = $a_len;
1457 }
1458 // BEGIN WebDAV
1459 // - Shorten names in the middle, before the filename extension
1460 // Workaround for Windows WebDAV Client:
1461 // Use the unicode ellipsis symbol for shortening instead of
1462 // three full stop characters.
1463 if ($a_keep_extension)
1464 {
1465 $p = strrpos($a_str, '.'); // this messes up normal shortening, see bug #6190
1466 }
1467 if ($p === false || $p == 0 || strlen($a_str) - $p > $a_len)
1468 {
1469 $a_str = ilStr::subStr($a_str,0,$len);
1470 if ($a_dots)
1471 {
1472 $a_str .= "\xe2\x80\xa6"; // UTF-8 encoding for Unicode ellipsis character.
1473 }
1474 }
1475 else
1476 {
1477 if ($a_dots)
1478 {
1479 $a_str = ilStr::subStr($a_str,0,$len - (strlen($a_str) - $p + 1))."\xe2\x80\xa6".substr($a_str, $p);
1480 }
1481 else
1482 {
1483 $a_str = ilStr::subStr($a_str,0,$len - (strlen($a_str) - $p + 1)).substr($a_str, $p);
1484 }
1485 }
1486 }
1487
1488 return $a_str;
1489 }
1490
1501 public static function shortenWords($a_str, $a_len = 30, $a_dots = true)
1502 {
1503 include_once("./Services/Utilities/classes/class.ilStr.php");
1504 $str_arr = explode(" ", $a_str);
1505
1506 for ($i = 0; $i < count($str_arr); $i++)
1507 {
1508 if (ilStr::strLen($str_arr[$i]) > $a_len)
1509 {
1510 $str_arr[$i] = ilStr::subStr($str_arr[$i], 0, $a_len);
1511 if ($a_dots)
1512 {
1513 $str_arr[$i].= "...";
1514 }
1515 }
1516 }
1517
1518 return implode($str_arr, " ");
1519 }
1520
1530 public static function attribsToArray($a_str)
1531 {
1532 $attribs = array();
1533 while (is_int(strpos($a_str, "=")))
1534 {
1535 $eq_pos = strpos($a_str, "=");
1536 $qu1_pos = strpos($a_str, "\"");
1537 $qu2_pos = strpos(substr($a_str, $qu1_pos + 1), "\"") + $qu1_pos + 1;
1538 if (is_int($eq_pos) && is_int($qu1_pos) && is_int($qu2_pos))
1539 {
1540 $var = trim(substr($a_str, 0, $eq_pos));
1541 $val = trim(substr($a_str, $qu1_pos + 1, ($qu2_pos - $qu1_pos) - 1));
1542 $attribs[$var] = $val;
1543 $a_str = substr($a_str, $qu2_pos + 1);
1544 }
1545 else
1546 {
1547 $a_str = "";
1548 }
1549 }
1550 return $attribs;
1551 }
1552
1564 public static function rCopy ($a_sdir, $a_tdir, $preserveTimeAttributes = false)
1565 {
1566 // check if arguments are directories
1567 if (!@is_dir($a_sdir) or
1568 !@is_dir($a_tdir))
1569 {
1570 return FALSE;
1571 }
1572
1573 // read a_sdir, copy files and copy directories recursively
1574 $dir = opendir($a_sdir);
1575
1576 while($file = readdir($dir))
1577 {
1578 if ($file != "." and
1579 $file != "..")
1580 {
1581 // directories
1582 if (@is_dir($a_sdir."/".$file))
1583 {
1584 if (!@is_dir($a_tdir."/".$file))
1585 {
1586 if (!ilUtil::makeDir($a_tdir."/".$file))
1587 return FALSE;
1588
1589 //chmod($a_tdir."/".$file, 0775);
1590 }
1591
1592 if (!ilUtil::rCopy($a_sdir."/".$file,$a_tdir."/".$file))
1593 {
1594 return FALSE;
1595 }
1596 }
1597
1598 // files
1599 if (@is_file($a_sdir."/".$file))
1600 {
1601 if (!copy($a_sdir."/".$file,$a_tdir."/".$file))
1602 {
1603 return FALSE;
1604 }
1605 if ($preserveTimeAttributes)
1606 touch($a_tdir."/".$file, filectime($a_sdir."/".$file));
1607 }
1608 }
1609 }
1610 return TRUE;
1611 }
1612
1621 public static function getWebspaceDir($mode = "filesystem")
1622 {
1623 global $ilias;
1624
1625 if ($mode == "filesystem")
1626 {
1627 return "./".ILIAS_WEB_DIR."/".$ilias->client_id;
1628 }
1629 else
1630 {
1631 if (defined("ILIAS_MODULE"))
1632 {
1633 return "../".ILIAS_WEB_DIR."/".$ilias->client_id;
1634 }
1635 else
1636 {
1637 return "./".ILIAS_WEB_DIR."/".$ilias->client_id;
1638 }
1639 }
1640
1641 //return $ilias->ini->readVariable("server","webspace_dir");
1642 }
1643
1650 public static function getDataDir()
1651 {
1652 return CLIENT_DATA_DIR;
1653 //global $ilias;
1654
1655 //return $ilias->ini->readVariable("server", "data_dir");
1656 }
1657
1667 public static function getUsersOnline($a_user_id = 0)
1668 {
1669 include_once("./Services/User/classes/class.ilObjUser.php");
1670 return ilObjUser::_getUsersOnline($a_user_id);
1671 }
1672
1683 public static function getAssociatedUsersOnline($a_user_id)
1684 {
1685 include_once("./Services/User/classes/class.ilObjUser.php");
1686 return ilObjUser::_getAssociatedUsersOnline($a_user_id);
1687 }
1688
1696 public static function ilTempnam($a_temp_path = null)
1697 {
1698 if($a_temp_path === null )
1699 {
1700 $temp_path = ilUtil::getDataDir() . "/temp";
1701 }
1702 else
1703 {
1704 $temp_path = $a_temp_path;
1705 }
1706
1707 if (!is_dir($temp_path))
1708 {
1709 ilUtil::createDirectory($temp_path);
1710 }
1711 $temp_name = tempnam($temp_path, "tmp");
1712 // --->
1713 // added the following line because tempnam creates a backslash on some
1714 // Windows systems which leads to problems, because the "...\tmp..." can be
1715 // interpreted as "...{TAB-CHARACTER}...". The normal slash works fine
1716 // even under windows (Helmut Schottmüller, 2005-08-31)
1717 $temp_name = str_replace("\\", "/", $temp_name);
1718 // --->
1719 unlink($temp_name);
1720 return $temp_name;
1721 }
1722
1731 public static function createDirectory($a_dir, $a_mod = 0755)
1732 {
1733 ilUtil::makeDir($a_dir);
1734 //@mkdir($a_dir);
1735 //@chmod($a_dir, $a_mod);
1736 }
1737
1738
1747 public static function unzip($a_file, $overwrite = false, $a_flat = false)
1748 {
1749 global $DIC;
1750
1751 $log = $DIC->logger()->root();
1752
1753 if (!is_file($a_file))
1754 {
1755 return;
1756 }
1757
1758 // if flat, move file to temp directory first
1759 if ($a_flat)
1760 {
1761 $tmpdir = ilUtil::ilTempnam();
1762 ilUtil::makeDir($tmpdir);
1763 copy($a_file, $tmpdir.DIRECTORY_SEPARATOR.basename($a_file));
1764 $orig_file = $a_file;
1765 $a_file = $tmpdir.DIRECTORY_SEPARATOR.basename($a_file);
1766 $origpathinfo = pathinfo($orig_file);
1767 }
1768
1769 $pathinfo = pathinfo($a_file);
1770 $dir = $pathinfo["dirname"];
1771 $file = $pathinfo["basename"];
1772
1773 // unzip
1774 $cdir = getcwd();
1775 chdir($dir);
1776 $unzip = PATH_TO_UNZIP;
1777
1778 // the following workaround has been removed due to bug
1779 // http://www.ilias.de/mantis/view.php?id=7578
1780 // since the workaround is quite old, it may not be necessary
1781 // anymore, alex 9 Oct 2012
1782/*
1783 // workaround for unzip problem (unzip of subdirectories fails, so
1784 // we create the subdirectories ourselves first)
1785 // get list
1786 $unzipcmd = "-Z -1 ".ilUtil::escapeShellArg($file);
1787 $arr = ilUtil::execQuoted($unzip, $unzipcmd);
1788 $zdirs = array();
1789
1790 foreach($arr as $line)
1791 {
1792 if(is_int(strpos($line, "/")))
1793 {
1794 $zdir = substr($line, 0, strrpos($line, "/"));
1795 $nr = substr_count($zdir, "/");
1796 //echo $zdir." ".$nr."<br>";
1797 while ($zdir != "")
1798 {
1799 $nr = substr_count($zdir, "/");
1800 $zdirs[$zdir] = $nr; // collect directories
1801 //echo $dir." ".$nr."<br>";
1802 $zdir = substr($zdir, 0, strrpos($zdir, "/"));
1803 }
1804 }
1805 }
1806
1807 asort($zdirs);
1808
1809 foreach($zdirs as $zdir => $nr) // create directories
1810 {
1811 ilUtil::createDirectory($zdir);
1812 }
1813*/
1814
1815 // real unzip
1816 if (!$overwrite)
1817 {
1818 $unzipcmd = ilUtil::escapeShellArg($file);
1819 }
1820 else
1821 {
1822 $unzipcmd = "-o ".ilUtil::escapeShellArg($file);
1823 }
1824 ilUtil::execQuoted($unzip, $unzipcmd);
1825
1826 chdir($cdir);
1827
1828 // remove all sym links
1829 clearstatcache(); // prevent is_link from using cache
1830 $dir_realpath = realpath($dir);
1831 foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)) as $name => $f)
1832 {
1833 if (is_link($name))
1834 {
1835 $target = readlink($name);
1836 if (substr($target, 0, strlen($dir_realpath)) != $dir_realpath)
1837 {
1838 unlink($name);
1839 $log->info("Removed symlink " . $name);
1840 }
1841 }
1842 }
1843
1844 // if flat, get all files and move them to original directory
1845 if ($a_flat)
1846 {
1847 include_once("./Services/Utilities/classes/class.ilFileUtils.php");
1848 $filearray = array();
1849 ilFileUtils::recursive_dirscan($tmpdir, $filearray);
1850 if (is_array($filearray["file"]))
1851 {
1852 foreach ($filearray["file"] as $k => $f)
1853 {
1854 if (substr($f, 0, 1) != "." && $f != basename($orig_file))
1855 {
1856 copy($filearray["path"][$k].$f, $origpathinfo["dirname"].DIRECTORY_SEPARATOR.$f);
1857 }
1858 }
1859 }
1860 ilUtil::delDir($tmpdir);
1861 }
1862 }
1863
1870 public static function zip($a_dir, $a_file, $compress_content = false)
1871 {
1872 $cdir = getcwd();
1873
1874 if($compress_content)
1875 {
1876 $a_dir .="/*";
1877 $pathinfo = pathinfo($a_dir);
1878 chdir($pathinfo["dirname"]);
1879 }
1880
1881 $pathinfo = pathinfo($a_file);
1882 $dir = $pathinfo["dirname"];
1883 $file = $pathinfo["basename"];
1884
1885 if(!$compress_content)
1886 {
1887 chdir($dir);
1888 }
1889
1890 $zip = PATH_TO_ZIP;
1891
1892 if(!$zip)
1893 {
1894 chdir($cdir);
1895 return false;
1896 }
1897
1898 if (is_array($a_dir))
1899 {
1900 $source = "";
1901 foreach($a_dir as $dir)
1902 {
1903 $name = basename($dir);
1904 $source.= " ".ilUtil::escapeShellArg($name);
1905 }
1906 }
1907 else
1908 {
1909 $name = basename($a_dir);
1910 if (trim($name) != "*")
1911 {
1912 $source = ilUtil::escapeShellArg($name);
1913 }
1914 else
1915 {
1916 $source = $name;
1917 }
1918 }
1919
1920 $zipcmd = "-r ".ilUtil::escapeShellArg($a_file)." ".$source;
1921 ilUtil::execQuoted($zip, $zipcmd);
1922 chdir($cdir);
1923 return true;
1924 }
1925
1926 public static function CreateIsoFromFolder($a_dir, $a_file)
1927 {
1928 $cdir = getcwd();
1929
1930 $pathinfo = pathinfo($a_dir);
1931 chdir($pathinfo["dirname"]);
1932
1933 $pathinfo = pathinfo($a_file);
1934 $dir = $pathinfo["dirname"];
1935 $file = $pathinfo["basename"]; $zipcmd = "-r ".ilUtil::escapeShellArg($a_file)." ".$source;
1936
1937 $mkisofs = PATH_TO_MKISOFS;
1938 if(!$mkisofs)
1939 {
1940 chdir($cdir);
1941 return false;
1942 }
1943
1944 $name = basename($a_dir);
1945 $source = ilUtil::escapeShellArg($name);
1946
1947 $zipcmd = "-r -J -o ".$a_file." ".$source;
1948 ilUtil::execQuoted($mkisofs, $zipcmd);
1949 chdir($cdir);
1950 return true;
1951 }
1952
1961 public static function getConvertCmd()
1962 {
1963 return PATH_TO_CONVERT;
1964 }
1965
1973 public static function execConvert($args)
1974 {
1975 ilUtil::execQuoted(PATH_TO_CONVERT, $args);
1976 }
1977
1984 public static function isConvertVersionAtLeast($a_version)
1985 {
1986 $current_version = ilUtil::execQuoted(PATH_TO_CONVERT, "--version");
1987 $current_version = self::processConvertVersion($current_version[0]);
1989 if($current_version >= $version)
1990 {
1991 return true;
1992 }
1993 return false;
1994 }
1995
2002 protected static function processConvertVersion($a_version)
2003 {
2004 if(preg_match("/([0-9]+)\.([0-9]+)\.([0-9]+)([\.|\-]([0-9]+))?/", $a_version, $match))
2005 {
2006 $version = str_pad($match[1], 2, 0, STR_PAD_LEFT).
2007 str_pad($match[2], 2, 0, STR_PAD_LEFT).
2008 str_pad($match[3], 2, 0, STR_PAD_LEFT).
2009 str_pad($match[5], 2, 0, STR_PAD_LEFT);
2010 return (int)$version;
2011 }
2012 }
2013
2023 public static function convertImage($a_from, $a_to, $a_target_format = "", $a_geometry = "",
2024 $a_background_color = "")
2025 {
2026 $format_str = ($a_target_format != "")
2027 ? strtoupper($a_target_format).":"
2028 : "";
2029 $geometry = "";
2030 if ($a_geometry != "")
2031 {
2032 if (is_int(strpos($a_geometry, "x")))
2033 {
2034 $geometry = " -geometry ".$a_geometry." ";
2035 }
2036 else
2037 {
2038 $geometry = " -geometry ".$a_geometry."x".$a_geometry." ";
2039 }
2040 }
2041
2042 $bg_color = ($a_background_color != "")
2043 ? " -background color ".$a_background_color." "
2044 : "";
2045 $convert_cmd = ilUtil::escapeShellArg($a_from)." ".$bg_color.$geometry.ilUtil::escapeShellArg($format_str.$a_to);
2046
2047 ilUtil::execConvert($convert_cmd);
2048 }
2049
2060 public static function resizeImage($a_from, $a_to, $a_width, $a_height, $a_constrain_prop = false)
2061 {
2062 if ($a_constrain_prop)
2063 {
2064 $size = " -geometry ".$a_width."x".$a_height." ";
2065 }
2066 else
2067 {
2068 $size = " -resize ".$a_width."x".$a_height."! ";
2069 }
2070 $convert_cmd = ilUtil::escapeShellArg($a_from)." ".$size.ilUtil::escapeShellArg($a_to);
2071
2072 ilUtil::execConvert($convert_cmd);
2073 }
2074
2081 public static function img($a_src, $a_alt = "", $a_width = "", $a_height = "", $a_border = 0, $a_id = "", $a_class = "")
2082 {
2083 $img = '<img src="'.$a_src.'"';
2084 if ($a_alt != "")
2085 {
2086 $img.= ' alt="'.htmlspecialchars($a_alt).'" title="'.htmlspecialchars($a_alt).'"';
2087 }
2088 if ($a_width != "")
2089 {
2090 $img.= ' width="'.htmlspecialchars($a_width).'"';
2091 }
2092 if ($a_height != "")
2093 {
2094 $img.= ' height="'.htmlspecialchars($a_height).'"';
2095 }
2096 if ($a_class != "")
2097 {
2098 $img.= ' class="'.$a_class.'"';
2099 }
2100 if ($a_id != "")
2101 {
2102 $img.= ' id="'.$a_id.'"';
2103 }
2104 $img.= ' border="'.(int) $a_border.'"/>';
2105
2106 return $img;
2107 }
2108
2115 public static function deliverData($a_data, $a_filename, $mime = "application/octet-stream", $charset = "")
2116 {
2117 $disposition = "attachment"; // "inline" to view file in browser or "attachment" to download to hard disk
2118 // $mime = "application/octet-stream"; // or whatever the mime type is
2119
2120 include_once './Services/Http/classes/class.ilHTTPS.php';
2121
2122 //if($_SERVER['HTTPS'])
2123 if( ilHTTPS::getInstance()->isDetected() )
2124 {
2125
2126 // Added different handling for IE and HTTPS => send pragma after content informations
2130 #header("Pragma: ");
2131 #header("Cache-Control: ");
2132 #header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
2133 #header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
2134 #header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1
2135 #header("Cache-Control: post-check=0, pre-check=0", false);
2136 }
2137 else if ($disposition == "attachment")
2138 {
2139 header("Cache-control: private");
2140 }
2141 else
2142 {
2143 header("Cache-Control: no-cache, must-revalidate");
2144 header("Pragma: no-cache");
2145 }
2146
2147 $ascii_filename = ilUtil::getASCIIFilename($a_filename);
2148
2149 if (strlen($charset))
2150 {
2151 $charset = "; charset=$charset";
2152 }
2153 header("Content-Type: $mime$charset");
2154 header("Content-Disposition:$disposition; filename=\"".$ascii_filename."\"");
2155 header("Content-Description: ".$ascii_filename);
2156 header("Content-Length: ".(string)(strlen($a_data)));
2157
2158 //if($_SERVER['HTTPS'])
2159 if( ilHTTPS::getInstance()->isDetected() )
2160 {
2161 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
2162 header('Pragma: public');
2163 }
2164
2165 header("Connection: close");
2166 echo $a_data;
2167 exit;
2168 }
2169
2170 // BEGIN WebDAV: Show file in browser or provide it as attachment
2178 public static function deliverFile($a_file, $a_filename,$a_mime = '', $isInline = false, $removeAfterDelivery = false,
2179 $a_exit_after = true)
2180 {
2181 // should we fail silently?
2182 if(!file_exists($a_file))
2183 {
2184 return false;
2185 }
2186
2187 if ($isInline) {
2188 $disposition = "inline"; // "inline" to view file in browser
2189 } else {
2190 $disposition = "attachment"; // "attachment" to download to hard disk
2191 //$a_mime = "application/octet-stream"; // override mime type to ensure that no browser tries to show the file anyway.
2192 }
2193 // END WebDAV: Show file in browser or provide it as attachment
2194
2195 if(strlen($a_mime))
2196 {
2197 $mime = $a_mime;
2198 }
2199 else
2200 {
2201 $mime = "application/octet-stream"; // or whatever the mime type is
2202 }
2203 // BEGIN WebDAV: Removed broken HTTPS code.
2204 // END WebDAV: Removed broken HTTPS code.
2205 if ($disposition == "attachment")
2206 {
2207 header("Cache-control: private");
2208 }
2209 else
2210 {
2211 header("Cache-Control: no-cache, must-revalidate");
2212 header("Pragma: no-cache");
2213 }
2214
2215 $ascii_filename = ilUtil::getASCIIFilename($a_filename);
2216
2217 header("Content-Type: $mime");
2218 header("Content-Disposition:$disposition; filename=\"".$ascii_filename."\"");
2219 header("Content-Description: ".$ascii_filename);
2220
2221 // #7271: if notice gets thrown download will fail in IE
2222 $filesize = @filesize($a_file);
2223 if ($filesize)
2224 {
2225 header("Content-Length: ".(string)$filesize);
2226 }
2227
2228 include_once './Services/Http/classes/class.ilHTTPS.php';
2229 #if($_SERVER['HTTPS'])
2230 if(ilHTTPS::getInstance()->isDetected())
2231 {
2232 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
2233 header('Pragma: public');
2234 }
2235
2236 header("Connection: close");
2237 ilUtil::readFile( $a_file );
2238 if ($removeAfterDelivery)
2239 {
2240 unlink ($a_file);
2241 }
2242 if ($a_exit_after)
2243 {
2244 exit;
2245 }
2246 }
2247
2248
2258 public static function readFile($a_file)
2259 {
2260 $chunksize = 1*(1024*1024); // how many bytes per chunk
2261 $buffer = '';
2262 $handle = fopen($a_file, 'rb');
2263 if ($handle === false)
2264 {
2265 return false;
2266 }
2267 while (!feof($handle))
2268 {
2269 $buffer = fread($handle, $chunksize);
2270 print $buffer;
2271 }
2272 return fclose($handle);
2273 }
2274
2282 public static function getASCIIFilename($a_filename)
2283 {
2284 // The filename must be converted to ASCII, as of RFC 2183,
2285 // section 2.3.
2286
2298
2301
2302 // #15914 - try to fix german umlauts
2303 $umlauts = array("Ä"=>"Ae", "Ö"=>"Oe", "Ü"=>"Ue",
2304 "ä"=>"ae", "ö"=>"oe", "ü"=>"ue", "ß"=>"ss");
2305 foreach($umlauts as $src => $tgt)
2306 {
2307 $a_filename = str_replace($src, $tgt, $a_filename);
2308 }
2309
2310 $ascii_filename = htmlentities($a_filename, ENT_NOQUOTES, 'UTF-8');
2311 $ascii_filename = preg_replace('/\&(.)[^;]*;/', '\\1', $ascii_filename);
2312 $ascii_filename = preg_replace('/[\x7f-\xff]/', '_', $ascii_filename);
2313
2314 // OS do not allow the following characters in filenames: \/:*?"<>|
2315 $ascii_filename = preg_replace('/[:\x5c\/\*\?\"<>\|]/', '_', $ascii_filename);
2316 return $ascii_filename;
2317 }
2318
2325 public static function htmlentitiesOutsideHTMLTags($htmlText)
2326 {
2327 $matches = Array();
2328 $sep = '###HTMLTAG###';
2329
2330 preg_match_all("@<[^>]*>@", $htmlText, $matches);
2331 $tmp = preg_replace("@(<[^>]*>)@", $sep, $htmlText);
2332 $tmp = explode($sep, $tmp);
2333
2334 for ($i=0; $i<count($tmp); $i++)
2335 $tmp[$i] = htmlentities($tmp[$i], ENT_COMPAT, "UTF-8");
2336
2337 $tmp = join($sep, $tmp);
2338
2339 for ($i=0; $i<count($matches[0]); $i++)
2340 $tmp = preg_replace("@$sep@", $matches[0][$i], $tmp, 1);
2341
2342 return $tmp;
2343 }
2344
2351 public static function getJavaPath()
2352 {
2353 return PATH_TO_JAVA;
2354 //global $ilias;
2355
2356 //return $ilias->getSetting("java_path");
2357 }
2358
2366 public static function appendUrlParameterString($a_url, $a_par, $xml_style = false)
2367 {
2368 $amp = $xml_style
2369 ? "&amp;"
2370 : "&";
2371
2372 $url = (is_int(strpos($a_url, "?")))
2373 ? $a_url.$amp.$a_par
2374 : $a_url."?".$a_par;
2375
2376 return $url;
2377 }
2378
2394 public static function makeDir($a_dir)
2395 {
2396 $a_dir = trim($a_dir);
2397
2398 // remove trailing slash (bugfix for php 4.2.x)
2399 if (substr($a_dir,-1) == "/")
2400 {
2401 $a_dir = substr($a_dir,0,-1);
2402 }
2403
2404 // check if a_dir comes with a path
2405 if (!($path = substr($a_dir,0, strrpos($a_dir,"/") - strlen($a_dir))))
2406 {
2407 $path = ".";
2408 }
2409
2410 // create directory with file permissions of parent directory
2411 umask(0000);
2412 return @mkdir($a_dir,fileperms($path));
2413 }
2414
2415
2430 public static function makeDirParents($a_dir)
2431 {
2432 $dirs = array($a_dir);
2433 $a_dir = dirname($a_dir);
2434 $last_dirname = '';
2435
2436 while($last_dirname != $a_dir)
2437 {
2438 array_unshift($dirs, $a_dir);
2439 $last_dirname = $a_dir;
2440 $a_dir = dirname($a_dir);
2441 }
2442
2443 // find the first existing dir
2444 $reverse_paths = array_reverse($dirs, TRUE);
2445 $found_index = -1;
2446 foreach ($reverse_paths as $key => $value)
2447 {
2448 if ($found_index == -1)
2449 {
2450 if (is_dir($value))
2451 {
2452 $found_index = $key;
2453 }
2454 }
2455 }
2456
2457 umask(0000);
2458 foreach ($dirs as $dirindex => $dir)
2459 {
2460 // starting with the longest existing path
2461 if ($dirindex >= $found_index)
2462 {
2463 if (! file_exists($dir))
2464 {
2465 if (strcmp(substr($dir,strlen($dir)-1,1),"/") == 0)
2466 {
2467 // on some systems there is an error when there is a slash
2468 // at the end of a directory in mkdir, see Mantis #2554
2469 $dir = substr($dir,0,strlen($dir)-1);
2470 }
2471 if (! mkdir($dir, $umask))
2472 {
2473 error_log("Can't make directory: $dir");
2474 return false;
2475 }
2476 }
2477 elseif (! is_dir($dir))
2478 {
2479 error_log("$dir is not a directory");
2480 return false;
2481 }
2482 else
2483 {
2484 // get umask of the last existing parent directory
2485 $umask = fileperms($dir);
2486 }
2487 }
2488 }
2489 return true;
2490 }
2491
2501 public static function delDir($a_dir, $a_clean_only = false)
2502 {
2503 if (!is_dir($a_dir) || is_int(strpos($a_dir, "..")))
2504 {
2505 return;
2506 }
2507
2508 $current_dir = opendir($a_dir);
2509
2510 $files = array();
2511
2512 // this extra loop has been necessary because of a strange bug
2513 // at least on MacOS X. A looped readdir() didn't work
2514 // correctly with larger directories
2515 // when an unlink happened inside the loop. Getting all files
2516 // into the memory first solved the problem.
2517 while($entryname = readdir($current_dir))
2518 {
2519 $files[] = $entryname;
2520 }
2521
2522 foreach($files as $file)
2523 {
2524 if(is_dir($a_dir."/".$file) and ($file != "." and $file!=".."))
2525 {
2526 ilUtil::delDir(${a_dir}."/".${file});
2527 }
2528 elseif ($file != "." and $file != "..")
2529 {
2530 unlink(${a_dir}."/".${file});
2531 }
2532 }
2533
2534 closedir($current_dir);
2535 if (!$a_clean_only)
2536 {
2537 @rmdir(${a_dir});
2538 }
2539 }
2540
2541
2548 public static function getDir($a_dir, $a_rec = false, $a_sub_dir = "")
2549 {
2550 $current_dir = opendir($a_dir.$a_sub_dir);
2551
2552 $dirs = array();
2553 $files = array();
2554 $subitems = array();
2555 while($entry = readdir($current_dir))
2556 {
2557 if(is_dir($a_dir."/".$entry))
2558 {
2559 $dirs[$entry] = array("type" => "dir", "entry" => $entry,
2560 "subdir" => $a_sub_dir);
2561 if ($a_rec && $entry != "." && $entry != "..")
2562 {
2563 $si = ilUtil::getDir($a_dir, true, $a_sub_dir."/".$entry);
2564 $subitems = array_merge($subitems, $si);
2565 }
2566 }
2567 else
2568 {
2569 if ($entry != "." && $entry != "..")
2570 {
2571 $size = filesize($a_dir.$a_sub_dir."/".$entry);
2572 $files[$entry] = array("type" => "file", "entry" => $entry,
2573 "size" => $size, "subdir" => $a_sub_dir);
2574 }
2575 }
2576 }
2577 ksort($dirs);
2578 ksort($files);
2579
2580 return array_merge($dirs, $files, $subitems);
2581 }
2582
2589 public static function stripSlashesArray($a_arr, $a_strip_html = true, $a_allow = "")
2590 {
2591 if (is_array($a_arr))
2592 {
2593 foreach ($a_arr as $k => $v)
2594 {
2595 $a_arr[$k] = ilUtil::stripSlashes($v, $a_strip_html, $a_allow);
2596 }
2597 }
2598
2599 return $a_arr;
2600 }
2601
2608 public static function stripSlashesRecursive($a_data, $a_strip_html = true, $a_allow = "")
2609 {
2610 if (is_array($a_data))
2611 {
2612 foreach ($a_data as $k => $v)
2613 {
2614 if (is_array($v))
2615 {
2616 $a_data[$k] = ilUtil::stripSlashesRecursive($v, $a_strip_html, $a_allow);
2617 }
2618 else
2619 {
2620 $a_data[$k] = ilUtil::stripSlashes($v, $a_strip_html, $a_allow);
2621 }
2622 }
2623 }
2624 else
2625 {
2626 $a_data = ilUtil::stripSlashes($a_data, $a_strip_html, $a_allow);
2627 }
2628
2629 return $a_data;
2630 }
2631
2639 public static function stripSlashes($a_str, $a_strip_html = true, $a_allow = "")
2640 {
2641 if (ini_get("magic_quotes_gpc"))
2642 {
2643 $a_str = stripslashes($a_str);
2644 }
2645//echo "<br><br>-".$a_strip_html."-".htmlentities($a_str);
2646//echo "<br>-".htmlentities(ilUtil::secureString($a_str, $a_strip_html, $a_allow));
2647 return ilUtil::secureString($a_str, $a_strip_html, $a_allow);
2648 }
2649
2657 public static function stripOnlySlashes($a_str)
2658 {
2659 if (ini_get("magic_quotes_gpc"))
2660 {
2661 $a_str = stripslashes($a_str);
2662 }
2663
2664 return $a_str;
2665 }
2666
2673 public static function secureString($a_str, $a_strip_html = true, $a_allow = "")
2674 {
2675 // check whether all allowed tags can be made secure
2676 $only_secure = true;
2677 $allow_tags = explode(">", $a_allow);
2678 $sec_tags = ilUtil::getSecureTags();
2679 $allow_array = array();
2680 foreach($allow_tags as $allow)
2681 {
2682 if ($allow != "")
2683 {
2684 $allow = str_replace("<", "", $allow);
2685
2686 if (!in_array($allow, $sec_tags))
2687 {
2688 $only_secure = false;
2689 }
2690 $allow_array[] = $allow;
2691 }
2692 }
2693
2694 // default behaviour: allow only secure tags 1:1
2695 if (($only_secure || $a_allow == "") && $a_strip_html)
2696 {
2697 if ($a_allow == "")
2698 {
2699 $allow_array = array ("b", "i", "strong", "em", "code", "cite",
2700 "gap", "sub", "sup", "pre", "strike", "bdo");
2701 }
2702
2703 // this currently removes parts of strings like "a <= b"
2704 // because "a <= b" is treated like "<spam onclick='hurt()'>ss</spam>"
2705 $a_str = ilUtil::maskSecureTags($a_str, $allow_array);
2706 $a_str = strip_tags($a_str); // strip all other tags
2707 $a_str = ilUtil::unmaskSecureTags($a_str, $allow_array);
2708
2709 // a possible solution could be something like:
2710 // $a_str = str_replace("<", "&lt;", $a_str);
2711 // $a_str = str_replace(">", "&gt;", $a_str);
2712 // $a_str = ilUtil::unmaskSecureTags($a_str, $allow_array);
2713 //
2714 // output would be ok then, but input fields would show
2715 // "a &lt;= b" for input "a <= b" if data is brought back to a form
2716 }
2717 else
2718 {
2719 // only for scripts, that need to allow more/other tags and parameters
2720 if ($a_strip_html)
2721 {
2722 $a_str = ilUtil::stripScriptHTML($a_str, $a_allow);
2723 }
2724 }
2725
2726 return $a_str;
2727 }
2728
2729 public static function getSecureTags()
2730 {
2731 return array("strong", "em", "u", "strike", "ol", "li", "ul", "p", "div",
2732 "i", "b", "code", "sup", "sub", "pre", "gap", "a", "img", "bdo");
2733 }
2734
2735 public static function maskSecureTags($a_str, $allow_array)
2736 {
2737 foreach ($allow_array as $t)
2738 {
2739 switch($t)
2740 {
2741 case "a":
2742 $a_str = ilUtil::maskAttributeTag($a_str, "a", "href");
2743 break;
2744
2745 case "img":
2746 $a_str = ilUtil::maskAttributeTag($a_str, "img", "src");
2747 break;
2748
2749 case "p":
2750 case "div":
2751 $a_str = ilUtil::maskTag($a_str, $t, array(
2752 array("param" => "align", "value" => "left"),
2753 array("param" => "align", "value" => "center"),
2754 array("param" => "align", "value" => "justify"),
2755 array("param" => "align", "value" => "right")
2756 ));
2757 break;
2758
2759 default:
2760 $a_str = ilUtil::maskTag($a_str, $t);
2761 break;
2762 }
2763 }
2764
2765 return $a_str;
2766 }
2767
2768 public static function unmaskSecureTags($a_str, $allow_array)
2769 {
2770 foreach ($allow_array as $t)
2771 {
2772 switch($t)
2773 {
2774 case "a":
2775 $a_str = ilUtil::unmaskAttributeTag($a_str, "a", "href");
2776 break;
2777
2778 case "img":
2779 $a_str = ilUtil::unmaskAttributeTag($a_str, "img", "src");
2780 break;
2781
2782 case "p":
2783 case "div":
2784 $a_str = ilUtil::unmaskTag($a_str, $t, array(
2785 array("param" => "align", "value" => "left"),
2786 array("param" => "align", "value" => "center"),
2787 array("param" => "align", "value" => "justify"),
2788 array("param" => "align", "value" => "right")
2789 ));
2790 break;
2791
2792 default:
2793 $a_str = ilUtil::unmaskTag($a_str, $t);
2794 break;
2795 }
2796 }
2797
2798 return $a_str;
2799 }
2800
2808 public static function securePlainString($a_str)
2809 {
2810 if (ini_get("magic_quotes_gpc"))
2811 {
2812 return stripslashes($a_str);
2813 }
2814 else
2815 {
2816 return $a_str;
2817 }
2818 }
2835 public static function htmlencodePlainString($a_str, $a_make_links_clickable, $a_detect_goto_links = false)
2836 {
2837 $encoded = "";
2838
2839 if ($a_make_links_clickable)
2840 {
2841 // Find text sequences in the plain text string which match
2842 // the URI syntax rules, and pass them to ilUtil::makeClickable.
2843 // Encode all other text sequences in the plain text string using
2844 // htmlspecialchars and nl2br.
2845 // The following expressions matches URI's as specified in RFC 2396.
2846 //
2847 // The expression matches URI's, which start with some well known
2848 // schemes, like "http:", or with "www.". This must be followed
2849 // by at least one of the following RFC 2396 expressions:
2850 // - alphanum: [a-zA-Z0-9]
2851 // - reserved: [;\/?:|&=+$,]
2852 // - mark: [\\-_.!~*\'()]
2853 // - escaped: %[0-9a-fA-F]{2}
2854 // - fragment delimiter: #
2855 // - uric_no_slash: [;?:@&=+$,]
2856 $matches = array();
2857 $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);
2858 $pos1 = 0;
2859 $encoded = "";
2860 foreach ($matches as $match)
2861 {
2862 }
2863 foreach ($matches[0] as $match)
2864 {
2865 $matched_text = $match[0];
2866 $pos2 = $match[1];
2867 if ($matched_offset != previous_offset)
2868 {
2869 // encode plain text
2870 $encoded .= nl2br(htmlspecialchars(substr($a_str, $pos1, $pos2 - $pos1)));
2871 }
2872 // encode URI
2873 $encoded .= ilUtil::makeClickable($matched_text, $a_detect_goto_links);
2874
2875
2876 $pos1 = $pos2 + strlen($matched_text);
2877 }
2878 if ($pos1 < strlen($a_str))
2879 {
2880 $encoded .= nl2br(htmlspecialchars(substr($a_str, $pos1)));
2881 }
2882 }
2883 else
2884 {
2885 $encoded = nl2br(htmlspecialchars($a_str));
2886 }
2887 return $encoded;
2888 }
2889
2890
2891 public static function maskAttributeTag($a_str, $tag, $tag_att)
2892 {
2893 global $ilLog;
2894
2895 $ws = "[\s]*";
2896 $att = $ws."[^>]*".$ws;
2897
2898 while (preg_match('/<('.$tag.$att.'('.$tag_att.$ws.'="'.$ws.'(([$@!*()~;,_0-9A-z\/:=%.&#?+\-])*)")'.$att.')>/i',
2899 $a_str, $found))
2900 {
2901 $old_str = $a_str;
2902 $a_str = preg_replace("/<".preg_quote($found[1], "/").">/i",
2903 '&lt;'.$tag.' '.$tag_att.$tag_att.'="'.$found[3].'"&gt;', $a_str);
2904 if ($old_str == $a_str)
2905 {
2906 $ilLog->write("ilUtil::maskA-".htmlentities($old_str)." == ".
2907 htmlentities($a_str));
2908 return $a_str;
2909 }
2910 }
2911 $a_str = str_ireplace("</$tag>",
2912 "&lt;/$tag&gt;", $a_str);
2913 return $a_str;
2914 }
2915
2916 public static function unmaskAttributeTag($a_str, $tag, $tag_att)
2917 {
2918 global $ilLog;
2919
2920 while (preg_match('/&lt;('.$tag.' '.$tag_att.$tag_att.'="(([$@!*()~;,_0-9A-z\/:=%.&#?+\-])*)")&gt;/i',
2921 $a_str, $found))
2922 {
2923 $old_str = $a_str;
2924 $a_str = preg_replace("/&lt;".preg_quote($found[1], "/")."&gt;/i",
2925 '<'.$tag.' '.$tag_att.'="'.ilUtil::secureLink($found[2]).'">', $a_str);
2926 if ($old_str == $a_str)
2927 {
2928 $ilLog->write("ilUtil::unmaskA-".htmlentities($old_str)." == ".
2929 htmlentities($a_str));
2930 return $a_str;
2931 }
2932 }
2933 $a_str = str_replace('&lt;/'.$tag.'&gt;', '</'.$tag.'>', $a_str);
2934 return $a_str;
2935 }
2936
2937 public static function maskTag($a_str, $t, $fix_param = "")
2938 {
2939 $a_str = str_replace(array("<$t>", "<".strtoupper($t).">"),
2940 "&lt;".$t."&gt;", $a_str);
2941 $a_str = str_replace(array("</$t>", "</".strtoupper($t).">"),
2942 "&lt;/".$t."&gt;", $a_str);
2943
2944 if (is_array($fix_param))
2945 {
2946 foreach ($fix_param as $p)
2947 {
2948 $k = $p["param"];
2949 $v = $p["value"];
2950 $a_str = str_replace("<$t $k=\"$v\">",
2951 "&lt;"."$t $k=\"$v\""."&gt;", $a_str);
2952 }
2953 }
2954
2955 return $a_str;
2956 }
2957
2958 public static function unmaskTag($a_str, $t, $fix_param = "")
2959 {
2960 $a_str = str_replace("&lt;".$t."&gt;", "<".$t.">", $a_str);
2961 $a_str = str_replace("&lt;/".$t."&gt;", "</".$t.">", $a_str);
2962
2963 if (is_array($fix_param))
2964 {
2965 foreach ($fix_param as $p)
2966 {
2967 $k = $p["param"];
2968 $v = $p["value"];
2969 $a_str = str_replace("&lt;$t $k=\"$v\"&gt;",
2970 "<"."$t $k=\"$v\"".">", $a_str);
2971 }
2972 }
2973 return $a_str;
2974 }
2975
2976 public static function secureLink($a_str)
2977 {
2978 $a_str = str_ireplace("javascript", "jvscrpt", $a_str);
2979 $a_str = str_ireplace(array("%00", "%0a", "%0d", "%1a", "&#00;", "&#x00;",
2980 "&#0;", "&#x0;", "&#x0a;", "&#x0d;", "&#10;", "&#13;"), "-", $a_str);
2981 return $a_str;
2982 }
2983
2997 public static function stripScriptHTML($a_str, $a_allow = "", $a_rm_js = true)
2998 {
2999 //$a_str = strip_tags($a_str, $a_allow);
3000
3001 $negativestr = "a,abbr,acronym,address,applet,area,base,basefont,".
3002 "big,blockquote,body,br,button,caption,center,cite,code,col,".
3003 "colgroup,dd,del,dfn,dir,div,dl,dt,em,fieldset,font,form,frame,".
3004 "frameset,h1,h2,h3,h4,h5,h6,head,hr,html,i,iframe,img,input,ins,isindex,kbd,".
3005 "label,legend,li,link,map,menu,meta,noframes,noscript,object,ol,".
3006 "optgroup,option,p,param,q,s,samp,script,select,small,span,".
3007 "strike,strong,style,sub,sup,table,tbody,td,textarea,tfoot,th,thead,".
3008 "title,tr,tt,u,ul,var";
3009 $a_allow = strtolower ($a_allow);
3010 $negatives = explode(",",$negativestr);
3011 $outer_old_str = "";
3012 while($outer_old_str != $a_str)
3013 {
3014 $outer_old_str = $a_str;
3015 foreach ($negatives as $item)
3016 {
3017 $pos = strpos($a_allow, "<$item>");
3018
3019 // remove complete tag, if not allowed
3020 if ($pos === false)
3021 {
3022 $old_str = "";
3023 while($old_str != $a_str)
3024 {
3025 $old_str = $a_str;
3026 $a_str = preg_replace("/<\/?\s*$item(\/?)\s*>/i", "", $a_str);
3027 $a_str = preg_replace("/<\/?\s*$item(\/?)\s+([^>]*)>/i", "", $a_str);
3028 }
3029 }
3030 }
3031 }
3032
3033 if ($a_rm_js)
3034 {
3035 // remove all attributes if an "on..." attribute is given
3036 $a_str = preg_replace("/<\s*\w*(\/?)(\s+[^>]*)?(\s+on[^>]*)>/i", "", $a_str);
3037
3038 // remove all attributes if a "javascript" is within tag
3039 $a_str = preg_replace("/<\s*\w*(\/?)\s+[^>]*javascript[^>]*>/i", "", $a_str);
3040
3041 // remove all attributes if an "expression" is within tag
3042 // (IE allows something like <b style='width:expression(alert(1))'>test</b>)
3043 $a_str = preg_replace("/<\s*\w*(\/?)\s+[^>]*expression[^>]*>/i", "", $a_str);
3044 }
3045
3046 return $a_str;
3047 }
3048
3060 public static function prepareFormOutput($a_str, $a_strip = false)
3061 {
3062 if($a_strip)
3063 {
3064 $a_str = ilUtil::stripSlashes($a_str);
3065 }
3066 $a_str = htmlspecialchars($a_str);
3067 // Added replacement of curly brackets to prevent
3068 // problems with PEAR templates, because {xyz} will
3069 // be removed as unused template variable
3070 $a_str = str_replace("{", "&#123;", $a_str);
3071 $a_str = str_replace("}", "&#125;", $a_str);
3072 // needed for LaTeX conversion \\ in LaTeX is a line break
3073 // but without this replacement, php changes \\ to \
3074 $a_str = str_replace("\\", "&#92;", $a_str);
3075 return $a_str;
3076 }
3077
3084 static function secureUrl($url)
3085 {
3086 // check if url is valid (absolute or relative)
3087 if (filter_var($url, FILTER_VALIDATE_URL) === false &&
3088 filter_var("http://".$url, FILTER_VALIDATE_URL) === false &&
3089 filter_var("http:".$url, FILTER_VALIDATE_URL) === false &&
3090 filter_var("http://de.de".$url, FILTER_VALIDATE_URL) === false &&
3091 filter_var("http://de.de/".$url, FILTER_VALIDATE_URL) === false)
3092 {
3093 return "";
3094 }
3095 if (trim(strtolower(parse_url($url, PHP_URL_SCHEME))) == "javascript")
3096 {
3097 return "";
3098 }
3099 $url = htmlspecialchars($url, ENT_QUOTES);
3100 return $url;
3101 }
3102
3103
3104
3114 public static function prepareDBString($a_str)
3115 {
3116 return addslashes($a_str);
3117 }
3118
3119
3128 public static function removeItemFromDesktops($a_id)
3129 {
3131 }
3132
3133
3143 public static function extractParameterString($a_parstr)
3144 {
3145 // parse parameters in array
3146 $par = array();
3147 $ok=true;
3148 while(($spos=strpos($a_parstr,"=")) && $ok)
3149 {
3150 // extract parameter
3151 $cpar = substr($a_parstr,0,$spos);
3152 $a_parstr = substr($a_parstr,$spos,strlen($a_parstr)-$spos);
3153 while(substr($cpar,0,1)=="," ||substr($cpar,0,1)==" " || substr($cpar,0,1)==chr(13) || substr($cpar,0,1)==chr(10))
3154 $cpar = substr($cpar,1,strlen($cpar)-1);
3155 while(substr($cpar,strlen($cpar)-1,1)==" " || substr($cpar,strlen($cpar)-1,1)==chr(13) || substr($cpar,strlen($cpar)-1,1)==chr(10))
3156 $cpar = substr($cpar,0,strlen($cpar)-1);
3157
3158 // parameter name should only
3159 $cpar_old = "";
3160 while($cpar != $cpar_old)
3161 {
3162 $cpar_old = $cpar;
3163 $cpar = preg_replace("/[^a-zA-Z0-9_]/i", "", $cpar);
3164 }
3165
3166 // extract value
3167 if ($cpar != "")
3168 {
3169 if($spos=strpos($a_parstr,"\""))
3170 {
3171 $a_parstr = substr($a_parstr,$spos+1,strlen($a_parstr)-$spos);
3172 $spos=strpos($a_parstr,"\"");
3173 if(is_int($spos))
3174 {
3175 $cval = substr($a_parstr,0,$spos);
3176 $par[$cpar]=$cval;
3177 $a_parstr = substr($a_parstr,$spos+1,strlen($a_parstr)-$spos-1);
3178 }
3179 else
3180 $ok=false;
3181 }
3182 else
3183 $ok=false;
3184 }
3185 }
3186
3187 if($ok) return $par; else return false;
3188 }
3189
3190 public static function assembleParameterString($a_par_arr)
3191 {
3192 if (is_array($a_par_arr))
3193 {
3194 $target_arr = array();
3195 foreach ($a_par_arr as $par => $val)
3196 {
3197 $target_arr[] = "$par=\"$val\"";
3198 }
3199 $target_str = implode(", ", $target_arr);
3200 }
3201
3202 return $target_str;
3203 }
3204
3211 public static function dumpString($a_str)
3212 {
3213 $ret = $a_str.": ";
3214 for($i=0; $i<strlen($a_str); $i++)
3215 {
3216 $ret.= ord(substr($a_str,$i,1))." ";
3217 }
3218 return $ret;
3219 }
3220
3221
3228 public static function yn2tf($a_yn)
3229 {
3230 if(strtolower($a_yn) == "y")
3231 {
3232 return true;
3233 }
3234 else
3235 {
3236 return false;
3237 }
3238 }
3239
3246 public static function tf2yn($a_tf)
3247 {
3248 if($a_tf)
3249 {
3250 return "y";
3251 }
3252 else
3253 {
3254 return "n";
3255 }
3256 }
3257
3268 public static function sort_func ($a, $b)
3269 {
3270 global $array_sortby,$array_sortorder;
3271
3272 if(!isset($array_sortby))
3273 {
3274 // occured in: setup -> new client -> install languages -> sorting of languages
3275 $array_sortby = 0;
3276 }
3277
3278 // this comparison should give optimal results if
3279 // locale is provided and mb string functions are supported
3280 if ($array_sortorder == "asc")
3281 {
3282 return ilStr::strCmp($a[$array_sortby], $b[$array_sortby]);
3283 }
3284
3285 if ($array_sortorder == "desc")
3286 {
3287 return !ilStr::strCmp($a[$array_sortby], $b[$array_sortby]);
3288 return strcoll(ilStr::strToUpper($b[$array_sortby]), ilStr::strToUpper($a[$array_sortby]));
3289 }
3290 }
3291
3302 public static function sort_func_numeric ($a, $b)
3303 {
3304 global $array_sortby,$array_sortorder;
3305
3306 if ($array_sortorder == "asc")
3307 {
3308 return $a["$array_sortby"] > $b["$array_sortby"];
3309 }
3310
3311 if ($array_sortorder == "desc")
3312 {
3313 return $a["$array_sortby"] < $b["$array_sortby"];
3314 }
3315 }
3328 public static function sortArray($array,$a_array_sortby,$a_array_sortorder = 0,$a_numeric = false,
3329 $a_keep_keys = false)
3330 {
3331 include_once("./Services/Utilities/classes/class.ilStr.php");
3332
3333 // BEGIN WebDAV: Provide a 'stable' sort algorithm
3334 if (! $a_keep_keys) {
3335 return self::stableSortArray($array,$a_array_sortby,$a_array_sortorder,$a_numeric,$a_keep_keys);
3336 }
3337 // END WebDAV Provide a 'stable' sort algorithm
3338
3339 global $array_sortby,$array_sortorder;
3340
3341 $array_sortby = $a_array_sortby;
3342
3343 if ($a_array_sortorder == "desc")
3344 {
3345 $array_sortorder = "desc";
3346 }
3347 else
3348 {
3349 $array_sortorder = "asc";
3350 }
3351 if($a_numeric)
3352 {
3353 if ($a_keep_keys)
3354 {
3355 uasort($array, array("ilUtil", "sort_func_numeric"));
3356 }
3357 else
3358 {
3359 usort($array, array("ilUtil", "sort_func_numeric"));
3360 }
3361 }
3362 else
3363 {
3364 if ($a_keep_keys)
3365 {
3366 uasort($array, array("ilUtil", "sort_func"));
3367 }
3368 else
3369 {
3370 usort($array, array("ilUtil", "sort_func"));
3371 }
3372 }
3373 //usort($array,"ilUtil::sort_func");
3374
3375 return $array;
3376 }
3377 // BEGIN WebDAV: Provide a 'stable' sort algorithm
3392 public static function stableSortArray($array,$a_array_sortby,$a_array_sortorder = 0,$a_numeric = false)
3393 {
3394 global $array_sortby,$array_sortorder;
3395
3396 $array_sortby = $a_array_sortby;
3397
3398 if ($a_array_sortorder == "desc")
3399 {
3400 $array_sortorder = "desc";
3401 }
3402 else
3403 {
3404 $array_sortorder = "asc";
3405 }
3406
3407 // Create a copy of the array values for sorting
3408 $sort_array = array_values($array);
3409
3410 if($a_numeric)
3411 {
3412 ilUtil::mergesort($sort_array, array("ilUtil", "sort_func_numeric"));
3413 }
3414 else
3415 {
3416 ilUtil::mergesort($sort_array, array("ilUtil", "sort_func"));
3417 }
3418
3419 return $sort_array;
3420 }
3421 public static function mergesort(&$array, $cmp_function = 'strcmp') {
3422 // Arrays of size < 2 require no action.
3423 if (count($array) < 2) return;
3424
3425 // Split the array in half
3426 $halfway = count($array) / 2;
3427 $array1 = array_slice($array, 0, $halfway);
3428 $array2 = array_slice($array, $halfway);
3429
3430 // Recurse to sort the two halves
3431 ilUtil::mergesort($array1, $cmp_function);
3432 ilUtil::mergesort($array2, $cmp_function);
3433
3434 // If all of $array1 is <= all of $array2, just append them.
3435 if (call_user_func($cmp_function, end($array1), $array2[0]) < 1) {
3436 $array = array_merge($array1, $array2);
3437 return;
3438 }
3439
3440 // Merge the two sorted arrays into a single sorted array
3441 $array = array();
3442 $ptr1 = $ptr2 = 0;
3443 while ($ptr1 < count($array1) && $ptr2 < count($array2)) {
3444 if (call_user_func($cmp_function, $array1[$ptr1], $array2[$ptr2]) < 1) {
3445 $array[] = $array1[$ptr1++];
3446 }
3447 else {
3448 $array[] = $array2[$ptr2++];
3449 }
3450 }
3451
3452 // Merge the remainder
3453 while ($ptr1 < count($array1)) $array[] = $array1[$ptr1++];
3454 while ($ptr2 < count($array2)) $array[] = $array2[$ptr2++];
3455
3456 return;
3457 }
3458 // END WebDAV: Provide a 'stable' sort algorithm
3459
3471 public static function unique_multi_array($array, $sub_key)
3472 {
3473 $target = array();
3474 $existing_sub_key_values = array();
3475
3476 foreach ($array as $key=>$sub_array)
3477 {
3478 if (!in_array($sub_array[$sub_key], $existing_sub_key_values))
3479 {
3480 $existing_sub_key_values[] = $sub_array[$sub_key];
3481 $target[$key] = $sub_array;
3482 }
3483 }
3484
3485 return $target;
3486 }
3487
3488
3498 public static function getGDSupportedImageType($a_desired_type)
3499 {
3500 $a_desired_type = strtolower($a_desired_type);
3501 // get supported Image Types
3502 $im_types = ImageTypes();
3503
3504 switch($a_desired_type)
3505 {
3506 case "jpg":
3507 case "jpeg":
3508 if ($im_types & IMG_JPG) return "jpg";
3509 if ($im_types & IMG_GIF) return "gif";
3510 if ($im_types & IMG_PNG) return "png";
3511 break;
3512
3513 case "gif":
3514 if ($im_types & IMG_GIF) return "gif";
3515 if ($im_types & IMG_JPG) return "jpg";
3516 if ($im_types & IMG_PNG) return "png";
3517 break;
3518
3519 case "png":
3520 if ($im_types & IMG_PNG) return "png";
3521 if ($im_types & IMG_JPG) return "jpg";
3522 if ($im_types & IMG_GIF) return "gif";
3523 break;
3524
3525 case "svg":
3526 if ($im_types & IMG_PNG) return "png";
3527 if ($im_types & IMG_JPG) return "jpg";
3528 if ($im_types & IMG_GIF) return "gif";
3529 break;
3530 }
3531
3532 return "";
3533 }
3534
3544 public static function deducibleSize($a_mime)
3545 {
3546 if (($a_mime == "image/gif") || ($a_mime == "image/jpeg") ||
3547 ($a_mime == "image/png") || ($a_mime == "application/x-shockwave-flash") ||
3548 ($a_mime == "image/tiff") || ($a_mime == "image/x-ms-bmp") ||
3549 ($a_mime == "image/psd") || ($a_mime == "image/iff"))
3550 {
3551 return true;
3552 }
3553 else
3554 {
3555 return false;
3556 }
3557 }
3558
3559
3567 public static function redirect($a_script)
3568 {
3569 global $log, $PHP_SELF;
3570
3571//echo "<br>".$a_script;
3572 if (!is_int(strpos($a_script, "://")))
3573 {
3574 if (substr($a_script, 0, 1) != "/" && defined("ILIAS_HTTP_PATH"))
3575 {
3576 if (is_int(strpos($_SERVER["PHP_SELF"], "/setup/")))
3577 {
3578 $a_script = "setup/".$a_script;
3579 }
3580 $a_script = ILIAS_HTTP_PATH."/".$a_script;
3581 }
3582 }
3583//echo "<br>".$a_script; exit;
3584
3585 // include the user interface hook
3586 global $ilPluginAdmin;
3587 if (is_object($ilPluginAdmin))
3588 {
3589 $pl_names = $ilPluginAdmin->getActivePluginsForSlot(IL_COMP_SERVICE, "UIComponent", "uihk");
3590 foreach ($pl_names as $pl)
3591 {
3592 $ui_plugin = ilPluginAdmin::getPluginObject(IL_COMP_SERVICE, "UIComponent", "uihk", $pl);
3593 $gui_class = $ui_plugin->getUIClassInstance();
3594 $resp = $gui_class->getHTML("Services/Utilities", "redirect", array("html" => $a_script));
3595 if ($resp["mode"] != ilUIHookPluginGUI::KEEP)
3596 {
3597 $a_script = $gui_class->modifyHTML($a_script, $resp);
3598 }
3599 }
3600 }
3601
3602 // Manually trigger to write and close the session. This has the advantage that if an exception is thrown
3603 // during the writing of the session (ILIAS writes the session into the database by default) we get an exception
3604 // if the session_write_close() is triggered by exit() then the exception will be dismissed but the session
3605 // is never written, which is a nightmare to develop with.
3606 session_write_close();
3607
3608 header("Location: ".$a_script);
3609 exit();
3610 }
3611
3620 public static function insertInstIntoID($a_value)
3621 {
3622 if (substr($a_value, 0, 4) == "il__")
3623 {
3624 $a_value = "il_".IL_INST_ID."_".substr($a_value, 4, strlen($a_value) - 4);
3625 }
3626
3627 return $a_value;
3628 }
3629
3640 public static function groupNameExists($a_group_name,$a_id = 0)
3641 {
3642 global $ilDB,$ilErr;
3643
3644 if (empty($a_group_name))
3645 {
3646 $message = __METHOD__.": No groupname given!";
3647 $ilErr->raiseError($message,$ilErr->WARNING);
3648 }
3649
3650 $clause = ($a_id) ? " AND obj_id != ".$ilDB->quote($a_id)." " : "";
3651
3652 $q = "SELECT obj_id FROM object_data ".
3653 "WHERE title = ".$ilDB->quote($a_group_name, "text")." ".
3654 "AND type = ".$ilDB->quote("grp", "text").
3655 $clause;
3656
3657 $r = $ilDB->query($q);
3658
3659 if ($r->numRows())
3660 {
3661 return true;
3662 }
3663 else
3664 {
3665 return false;
3666 }
3667 }
3668
3675 public static function getMemString()
3676 {
3677 $my_pid = getmypid();
3678 return ("MEMORY USAGE (% KB PID ): ".`ps -eo%mem,rss,pid | grep $my_pid`);
3679 }
3680
3687 public static function isWindows()
3688 {
3689 if (strtolower(substr(php_uname(), 0, 3)) == "win")
3690 {
3691 return true;
3692 }
3693 return false;
3694 }
3695
3696
3697 public static function escapeShellArg($a_arg)
3698 {
3699 setlocale(LC_CTYPE, "UTF8", "en_US.UTF-8"); // fix for PHP escapeshellcmd bug. See: http://bugs.php.net/bug.php?id=45132
3700 // see also ilias bug 5630
3701 return escapeshellarg($a_arg);
3702 }
3703
3713 public static function escapeShellCmd($a_arg)
3714 {
3715 if(ini_get('safe_mode') == 1)
3716 {
3717 return $a_arg;
3718 }
3719 setlocale(LC_CTYPE, "UTF8", "en_US.UTF-8"); // fix for PHP escapeshellcmd bug. See: http://bugs.php.net/bug.php?id=45132
3720 return escapeshellcmd($a_arg);
3721 }
3722
3732 public static function execQuoted($cmd, $args = NULL)
3733 {
3734 global $ilLog;
3735
3736 if(ilUtil::isWindows() && strpos($cmd, " ") !== false && substr($cmd, 0, 1) !== '"')
3737 {
3738 // cmd won't work without quotes
3739 $cmd = '"'.$cmd.'"';
3740 if($args)
3741 {
3742 // args are also quoted, workaround is to quote the whole command AGAIN
3743 // was fixed in php 5.2 (see php bug #25361)
3744 if (version_compare(phpversion(), "5.2", "<") && strpos($args, '"') !== false)
3745 {
3746 $cmd = '"'.$cmd." ".$args.'"';
3747 }
3748 // args are not quoted or php is fixed, just append
3749 else
3750 {
3751 $cmd .= " ".$args;
3752 }
3753 }
3754 }
3755 // nothing todo, just append args
3756 else if($args)
3757 {
3758 $cmd .= " ".$args;
3759 }
3760//ilUtil::printBacktrace(5);
3761//echo "<br>".$cmd; exit;
3762 exec($cmd, $arr);
3763// $ilLog->write("ilUtil::execQuoted: ".$cmd.".");
3764 return $arr;
3765 }
3766
3789 public static function excelTime($year = "", $month = "", $day = "", $hour = "", $minute = "", $second = "")
3790 {
3791 $starting_time = mktime(0, 0, 0, 1, 2, 1970);
3792 if (strcmp("$year$month$day$hour$minute$second", "") == 0)
3793 {
3794 $target_time = time();
3795 }
3796 else
3797 {
3798 if ($year < 1970)
3799 {
3800 return 0;
3801 }
3802 }
3803 $target_time = mktime($hour, $minute, $second, $month, $day, $year);
3804 $difference = $target_time - $starting_time;
3805 $days = (($difference - ($difference % 86400)) / 86400);
3806 $difference = $difference - ($days * 86400) + 3600;
3807
3808 // #15343 - using a global locale leads to , instead of . for (implicit) floats
3809 return str_replace(",", ".", ($days + 25570 + ($difference / 86400)));
3810 }
3811
3818 public static function renameExecutables($a_dir)
3819 {
3820 $def_arr = explode(",", SUFFIX_REPL_DEFAULT);
3821 foreach ($def_arr as $def)
3822 {
3823 ilUtil::rRenameSuffix($a_dir, trim($def), "sec");
3824 }
3825
3826 $def_arr = explode(",", SUFFIX_REPL_ADDITIONAL);
3827 foreach ($def_arr as $def)
3828 {
3829 ilUtil::rRenameSuffix($a_dir, trim($def), "sec");
3830 }
3831 }
3832
3845 public static function rRenameSuffix ($a_dir, $a_old_suffix, $a_new_suffix)
3846 {
3847 if ($a_dir == "/" || $a_dir == "" || is_int(strpos($a_dir, ".."))
3848 || trim($a_old_suffix) == "")
3849 {
3850 return false;
3851 }
3852
3853 // check if argument is directory
3854 if (!@is_dir($a_dir))
3855 {
3856 return false;
3857 }
3858
3859 // read a_dir
3860 $dir = opendir($a_dir);
3861
3862 while($file = readdir($dir))
3863 {
3864 if ($file != "." and
3865 $file != "..")
3866 {
3867 // directories
3868 if (@is_dir($a_dir."/".$file))
3869 {
3870 ilUtil::rRenameSuffix($a_dir."/".$file, $a_old_suffix, $a_new_suffix);
3871 }
3872
3873 // files
3874 if (@is_file($a_dir."/".$file))
3875 {
3876 // first check for files with trailing dot
3877 if(strrpos($file,'.') == (strlen($file) - 1))
3878 {
3879 rename($a_dir.'/'.$file,substr($a_dir.'/'.$file,0,-1));
3880 $file = substr($file,0,-1);
3881 }
3882
3883 $path_info = pathinfo($a_dir."/".$file);
3884
3885 if (strtolower($path_info["extension"]) ==
3886 strtolower($a_old_suffix))
3887 {
3888 $pos = strrpos($a_dir."/".$file, ".");
3889 $new_name = substr($a_dir."/".$file, 0, $pos).".".$a_new_suffix;
3890 rename($a_dir."/".$file, $new_name);
3891 }
3892 }
3893 }
3894 }
3895 return true;
3896 }
3897
3898 public static function isAPICall () {
3899 return strpos($_SERVER["SCRIPT_FILENAME"],"api") !== false ||
3900 strpos($_SERVER["SCRIPT_FILENAME"],"dummy") !== false;
3901 }
3902
3903 public static function KT_replaceParam($qstring, $paramName, $paramValue) {
3904 if (preg_match("/&" . $paramName . "=/", $qstring)) {
3905 return preg_replace("/&" . $paramName . "=[^&]+/", "&" . $paramName . "=" . urlencode($paramValue), $qstring);
3906 } else {
3907 return $qstring . "&" . $paramName . "=" . urlencode($paramValue);
3908 }
3909 }
3910
3911 public static function replaceUrlParameterString ($url, $parametersArray) {
3912
3913 foreach ($parametersArray as $paramName => $paramValue ) {
3914 $url = ilUtil::KT_replaceParam($url, $paramName, $paramValue);
3915 }
3916 return $url;
3917 }
3918
3925 public static function generatePasswords ($a_number)
3926 {
3927 $ret = array();
3928 srand((double) microtime()*1000000);
3929
3930 include_once('./Services/PrivacySecurity/classes/class.ilSecuritySettings.php');
3932
3933 for ($i=1; $i<=$a_number; $i++)
3934 {
3935 $min = ($security->getPasswordMinLength() > 0)
3936 ? $security->getPasswordMinLength()
3937 : 6;
3938 $max = ($security->getPasswordMaxLength() > 0)
3939 ? $security->getPasswordMaxLength()
3940 : 10;
3941 if ($min > $max)
3942 {
3943 $max = $max + 1;
3944 }
3945 $length = rand($min,$max);
3946 $next = rand(1,2);
3947 $vowels = "aeiou";
3948 $vowels_uc = strtoupper($vowels);
3949 $consonants = "bcdfghjklmnpqrstvwxyz";
3950 $consonants_uc = strtoupper($consonants);
3951 $numbers = "1234567890";
3952 $special = "_.+?#-*@!$%~";
3953 $pw = "";
3954
3955 if($security->getPasswordNumberOfUppercaseChars() > 0)
3956 {
3957 for($j = 0; $j < $security->getPasswordNumberOfUppercaseChars(); $j++)
3958 {
3959 switch ($next)
3960 {
3961 case 1:
3962 $pw.= $consonants_uc[rand(0, strlen($consonants_uc) - 1)];
3963 $next = 2;
3964 break;
3965
3966 case 2:
3967 $pw.= $vowels_uc[rand(0, strlen($vowels_uc) - 1)];
3968 $next = 1;
3969 break;
3970 }
3971 }
3972 }
3973
3974 if($security->isPasswordCharsAndNumbersEnabled())
3975 {
3976 $pw.= $numbers[rand(0, strlen($numbers) - 1)];
3977 }
3978
3979 if($security->isPasswordSpecialCharsEnabled())
3980 {
3981 $pw.= $special[rand(0, strlen($special) - 1)];
3982 }
3983
3984 $num_lcase_chars = max($security->getPasswordNumberOfLowercaseChars(), $length - strlen($pw));
3985 for($j = 0; $j < $num_lcase_chars; $j++)
3986 {
3987 switch ($next)
3988 {
3989 case 1:
3990 $pw.= $consonants[rand(0, strlen($consonants) - 1)];
3991 $next = 2;
3992 break;
3993
3994 case 2:
3995 $pw.= $vowels[rand(0, strlen($vowels) - 1)];
3996 $next = 1;
3997 break;
3998 }
3999 }
4000
4001 $pw = str_shuffle($pw);
4002
4003 $ret[] = $pw;
4004 }
4005 return $ret;
4006 }
4007
4008 public static function removeTrailingPathSeparators($path)
4009 {
4010 $path = preg_replace("/[\/\\\]+$/", "", $path);
4011 return $path;
4012 }
4013
4024 public static function array_php2js($data)
4025 {
4026 if (empty($data))
4027 {
4028 $data = array();
4029 }
4030
4031 foreach($data as $k=>$datum)
4032 {
4033 if(is_null($datum)) $data[$k] = 'null';
4034 if(is_string($datum)) $data[$k] = "'" . $datum . "'";
4035 if(is_array($datum)) $data[$k] = array_php2js($datum);
4036 }
4037
4038 return "[" . implode(', ', $data) . "]";
4039 }
4040
4047 public static function virusHandling($a_file, $a_orig_name = "", $a_clean = true)
4048 {
4049 global $lng;
4050
4051 if (IL_VIRUS_SCANNER != "None")
4052 {
4053 require_once("./Services/VirusScanner/classes/class.ilVirusScannerFactory.php");
4055 if (($vs_txt = $vs->scanFile($a_file, $a_orig_name)) != "")
4056 {
4057 if ($a_clean && (IL_VIRUS_CLEAN_COMMAND != ""))
4058 {
4059 $clean_txt = $vs->cleanFile($a_file, $a_orig_name);
4060 if ($vs->fileCleaned())
4061 {
4062 $vs_txt.= "<br />".$lng->txt("cleaned_file").
4063 "<br />".$clean_txt;
4064 $vs_txt.= "<br />".$lng->txt("repeat_scan");
4065 if (($vs2_txt = $vs->scanFile($a_file, $a_orig_name)) != "")
4066 {
4067 return array(false, nl2br($vs_txt)."<br />".$lng->txt("repeat_scan_failed").
4068 "<br />".nl2br($vs2_txt));
4069 }
4070 else
4071 {
4072 return array(true, nl2br($vs_txt)."<br />".$lng->txt("repeat_scan_succeded"));
4073 }
4074 }
4075 else
4076 {
4077 return array(false, nl2br($vs_txt)."<br />".$lng->txt("cleaning_failed"));
4078 }
4079 }
4080 else
4081 {
4082 return array(false, nl2br($vs_txt));
4083 }
4084 }
4085 }
4086
4087 return array(true,"");
4088 }
4089
4090
4096 public static function moveUploadedFile($a_file, $a_name, $a_target, $a_raise_errors = true,
4097 $a_mode = "move_uploaded")
4098 {
4099 global $lng, $ilias;
4100
4101 if (!is_file($a_file))
4102 {
4103 if ($a_raise_errors)
4104 {
4105 $ilias->raiseError($lng->txt("upload_error_file_not_found"), $ilias->error_obj->MESSAGE);
4106 }
4107 else
4108 {
4109 ilUtil::sendFailure($lng->txt("upload_error_file_not_found"), true);
4110 }
4111 return false;
4112 }
4113
4114 // virus handling
4115 $vir = ilUtil::virusHandling($a_file, $a_name);
4116 if (!$vir[0])
4117 {
4118 unlink($a_file);
4119 if ($a_raise_errors)
4120 {
4121 $ilias->raiseError($lng->txt("file_is_infected")."<br />".
4122 $vir[1],
4123 $ilias->error_obj->MESSAGE);
4124 }
4125 else
4126 {
4127 ilUtil::sendFailure($lng->txt("file_is_infected")."<br />".
4128 $vir[1], true);
4129 }
4130 return false;
4131 }
4132 else
4133 {
4134 if ($vir[1] != "")
4135 {
4136 ilUtil::sendInfo($vir[1], true);
4137 }
4138 include_once("./Services/Utilities/classes/class.ilFileUtils.php");
4139 $a_target = ilFileUtils::getValidFilename($a_target);
4140 switch ($a_mode)
4141 {
4142 case "rename":
4143 return rename($a_file, $a_target);
4144 break;
4145
4146 case "copy":
4147 return copy($a_file, $a_target);
4148 break;
4149
4150 default:
4151 return move_uploaded_file($a_file, $a_target);
4152 break;
4153 }
4154 }
4155 }
4156
4157
4164 public static function date_mysql2time($mysql_date_time) {
4165 list($datum, $uhrzeit) = explode (" ",$mysql_date_time);
4166 list($jahr, $monat, $tag) = explode("-", $datum);
4167 list($std, $min, $sec) = explode(":", $uhrzeit);
4168 return mktime ((int) $std, (int) $min, (int) $sec, (int) $monat, (int) $tag, (int) $jahr);
4169 }
4170
4177 public static function now()
4178 {
4179 return date("Y-m-d H:i:s");
4180 }
4181
4197 public static function &processCSVRow(&$row, $quoteAll = FALSE, $separator = ";", $outUTF8 = FALSE, $compatibleWithMSExcel = TRUE)
4198 {
4199 $resultarray = array();
4200 foreach ($row as $rowindex => $entry)
4201 {
4202 $surround = FALSE;
4203 if ($quoteAll)
4204 {
4205 $surround = TRUE;
4206 }
4207 if (strpos($entry, "\"") !== FALSE)
4208 {
4209 $entry = str_replace("\"", "\"\"", $entry);
4210 $surround = TRUE;
4211 }
4212 if (strpos($entry, $separator) !== FALSE)
4213 {
4214 $surround = TRUE;
4215 }
4216 if ($compatibleWithMSExcel)
4217 {
4218 // replace all CR LF with LF (for Excel for Windows compatibility
4219 $entry = str_replace(chr(13).chr(10), chr(10), $entry);
4220 }
4221 if ($surround)
4222 {
4223 if ($outUTF8)
4224 {
4225 $resultarray[$rowindex] = "\"" . $entry . "\"";
4226 }
4227 else
4228 {
4229 $resultarray[$rowindex] = utf8_decode("\"" . $entry . "\"");
4230 }
4231 }
4232 else
4233 {
4234 if ($outUTF8)
4235 {
4236 $resultarray[$rowindex] = $entry;
4237 }
4238 else
4239 {
4240 $resultarray[$rowindex] = utf8_decode($entry);
4241 }
4242 }
4243 }
4244 return $resultarray;
4245 }
4246
4247 // validates a domain name (example: www.ilias.de)
4248 public static function isDN($a_str)
4249 {
4250 return(preg_match("/^[a-z]+([a-z0-9-]*[a-z0-9]+)?(\.([a-z]+([a-z0-9-]*[a-z0-9]+)?)+)*$/",$a_str));
4251 }
4252
4253 // validates an IP address (example: 192.168.1.1)
4254 public static function isIPv4($a_str)
4255 {
4256 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])\.".
4257 "(\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));
4258 }
4259
4260
4289 public static function _getObjectsByOperations($a_obj_type,$a_operation,$a_usr_id = 0,$limit = 0)
4290 {
4291 global $ilDB,$rbacreview,$ilAccess,$ilUser,$ilias,$tree;
4292
4293 if(!is_array($a_obj_type))
4294 {
4295 $where = "WHERE type = ".$ilDB->quote($a_obj_type, "text")." ";
4296 }
4297 else
4298 {
4299 $where = "WHERE ".$ilDB->in("type", $a_obj_type, false, "text")." ";
4300 }
4301
4302 // limit number of results default is search result limit
4303 if(!$limit)
4304 {
4305 $limit = $ilias->getSetting('search_max_hits',100);
4306 }
4307 if($limit == -1)
4308 {
4309 $limit = 10000;
4310 }
4311
4312 // default to logged in usr
4313 $a_usr_id = $a_usr_id ? $a_usr_id : $ilUser->getId();
4314 $a_roles = $rbacreview->assignedRoles($a_usr_id);
4315
4316 // Since no rbac_pa entries are available for the system role. This function returns !all! ref_ids in the case the user
4317 // is assigned to the system role
4318 if($rbacreview->isAssigned($a_usr_id,SYSTEM_ROLE_ID))
4319 {
4320 $query = "SELECT ref_id FROM object_reference obr LEFT JOIN object_data obd ON obr.obj_id = obd.obj_id ".
4321 "LEFT JOIN tree ON obr.ref_id = tree.child ".
4322 $where.
4323 "AND tree = 1";
4324
4325 $res = $ilDB->query($query);
4326 $counter = 0;
4327 while($row = $ilDB->fetchObject($res))
4328 {
4329 // Filter recovery folder
4330 if($tree->isGrandChild(RECOVERY_FOLDER_ID, $row->ref_id))
4331 {
4332 continue;
4333 }
4334
4335 if($counter++ >= $limit)
4336 {
4337 break;
4338 }
4339
4340 $ref_ids[] = $row->ref_id;
4341 }
4342 return $ref_ids ? $ref_ids : array();
4343 } // End Administrators
4344
4345 // Check ownership if it is not asked for edit_permission or a create permission
4346 if($a_operation == 'edit_permissions' or strpos($a_operation,'create') !== false)
4347 {
4348 $check_owner = ") ";
4349 }
4350 else
4351 {
4352 $check_owner = "OR owner = ".$ilDB->quote($a_usr_id, "integer").") ";
4353 }
4354
4355 $ops_ids = ilRbacReview::_getOperationIdsByName(array($a_operation));
4356 $ops_id = $ops_ids[0];
4357
4358 $and = "AND ((".$ilDB->in("rol_id", $a_roles, false, "integer")." ";
4359
4360 $query = "SELECT DISTINCT(obr.ref_id),obr.obj_id,type FROM object_reference obr ".
4361 "JOIN object_data obd ON obd.obj_id = obr.obj_id ".
4362 "LEFT JOIN rbac_pa ON obr.ref_id = rbac_pa.ref_id ".
4363 $where.
4364 $and.
4365 "AND (".$ilDB->like("ops_id", "text","%i:".$ops_id."%"). " ".
4366 "OR ".$ilDB->like("ops_id", "text", "%:\"".$ops_id."\";%").")) ".
4367 $check_owner;
4368
4369 $res = $ilDB->query($query);
4370 $counter = 0;
4371 while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT))
4372 {
4373 if($counter >= $limit)
4374 {
4375 break;
4376 }
4377
4378 // Filter objects in recovery folder
4379 if($tree->isGrandChild(RECOVERY_FOLDER_ID, $row->ref_id))
4380 {
4381 continue;
4382 }
4383
4384 // Check deleted, hierarchical access ...
4385 if($ilAccess->checkAccessOfUser($a_usr_id,$a_operation,'',$row->ref_id,$row->type,$row->obj_id))
4386 {
4387 $counter++;
4388 $ref_ids[] = $row->ref_id;
4389 }
4390 }
4391 return $ref_ids ? $ref_ids : array();
4392 }
4393
4398 function includeMathjax($a_tpl = null)
4399 {
4400 include_once './Services/MathJax/classes/class.ilMathJax.php';
4401 ilMathJax::getInstance()->includeMathJax($a_tpl);
4402 }
4403
4408 public static function insertLatexImages($a_text, $a_start = '[tex]', $a_end = '[/tex]')
4409 {
4410 include_once './Services/MathJax/classes/class.ilMathJax.php';
4411 return ilMathJax::getInstance()->insertLatexImages($a_text, $a_start, $a_end);
4412 }
4413
4418 public static function buildLatexImages($a_text, $a_dir)
4419 {
4420 include_once './Services/MathJax/classes/class.ilMathJax.php';
4421 return ilMathJax::getInstance()->insertLatexImages($a_text, '[tex]','[/tex]', $a_dir.'/teximg', './teximg');
4422 }
4423
4432 public static function prepareTextareaOutput($txt_output, $prepare_for_latex_output = FALSE, $omitNl2BrWhenTextArea = false)
4433 {
4434 $result = $txt_output;
4435 $is_html = self::isHTML($result);
4436
4437 if ($prepare_for_latex_output)
4438 {
4439 include_once './Services/MathJax/classes/class.ilMathJax.php';
4440 $result = ilMathJax::getInstance()->insertLatexImages($result, "<span class\=\"latex\">", "<\/span>");
4441 $result = ilMathJax::getInstance()->insertLatexImages($result, "\[tex\]", "\[\/tex\]");
4442 }
4443
4444 // removed: did not work with magic_quotes_gpc = On
4445 if (!$is_html )
4446 {
4447 if(!$omitNl2BrWhenTextArea)
4448 {
4449 // if the string does not contain HTML code, replace the newlines with HTML line breaks
4450 $result = preg_replace("/[\n]/", "<br />", $result);
4451 }
4452 }
4453 else
4454 {
4455 // patch for problems with the <pre> tags in tinyMCE
4456 if (preg_match_all("/(<pre>.*?<\/pre>)/ims", $result, $matches))
4457 {
4458 foreach ($matches[0] as $found)
4459 {
4460 $replacement = "";
4461 if (strpos("\n", $found) === FALSE)
4462 {
4463 $replacement = "\n";
4464 }
4465 $removed = preg_replace("/<br\s*?\/>/ims", $replacement, $found);
4466 $result = str_replace($found, $removed, $result);
4467 }
4468 }
4469 }
4470 if ($prepare_for_latex_output)
4471 {
4472 // replace special characters to prevent problems with the ILIAS template system
4473 // eg. if someone uses {1} as an answer, nothing will be shown without the replacement
4474 $result = str_replace("{", "&#123;", $result);
4475 $result = str_replace("}", "&#125;", $result);
4476 $result = str_replace("\\", "&#92;", $result);
4477 }
4478
4479 return $result;
4480 }
4481
4490 public static function isHTML($a_text)
4491 {
4492 if( strlen(strip_tags($a_text)) < strlen($a_text) )
4493 {
4494 return true;
4495 }
4496
4497 return false;
4498 }
4499
4509 public static function period2String(ilDateTime $a_from, $a_to = null)
4510 {
4511 global $lng;
4512
4513 if (!$a_to)
4514 {
4515 $a_to = new ilDateTime(time(), IL_CAL_UNIX);
4516 }
4517
4518 $from = new DateTime($a_from->get(IL_CAL_DATETIME));
4519 $to = new DateTime($a_to->get(IL_CAL_DATETIME));
4520 $diff = $to->diff($from);
4521
4522 $periods = array();
4523 $periods["years"] = $diff->format("%y");
4524 $periods["months"] = $diff->format("%m");
4525 $periods["days"] = $diff->format("%d");
4526 $periods["hours"] = $diff->format("%h");
4527 $periods["minutes"] = $diff->format("%i");
4528 $periods["seconds"] = $diff->format("%s");
4529
4530 if (!array_sum($periods))
4531 {
4532 return;
4533 }
4534
4535 foreach ($periods as $key => $value)
4536 {
4537 if($value)
4538 {
4539 $segment_name = ($value > 1)
4540 ? $key
4541 : substr($key, 0, -1);
4542 $array[] = $value . ' ' . $lng->txt($segment_name);
4543 }
4544 }
4545
4546 $len = sizeof($array);
4547 if ($len > 3)
4548 {
4549 $array = array_slice($array, 0, (3-$len));
4550 }
4551
4552 return implode(', ', $array);
4553 }
4554
4555 public static function getFileSizeInfo()
4556 {
4557 $max_filesize = self::formatBytes(
4558 self::getUploadSizeLimitBytes()
4559 );
4560
4561 global $lng;
4562 /*
4563 // get the value for the maximal uploadable filesize from the php.ini (if available)
4564 $umf=get_cfg_var("upload_max_filesize");
4565 // get the value for the maximal post data from the php.ini (if available)
4566 $pms=get_cfg_var("post_max_size");
4567
4568 // use the smaller one as limit
4569 $max_filesize=min($umf, $pms);
4570 if (!$max_filesize) $max_filesize=max($umf, $pms);
4571 */
4572 return $lng->txt("file_notice")." $max_filesize.";
4573 }
4574
4575 public static function formatBytes($size, $decimals = 0)
4576 {
4577 $unit = array('', 'K', 'M', 'G', 'T', 'P');
4578
4579 for($i = 0, $maxUnits = count($unit); $size >= 1024 && $i <= $maxUnits; $i++)
4580 {
4581 $size /= 1024;
4582 }
4583
4584 return round($size, $decimals).$unit[$i];
4585 }
4586
4587 public static function getUploadSizeLimitBytes()
4588 {
4589 $uploadSizeLimitBytes = min(
4590 self::convertPhpIniSizeValueToBytes(ini_get('post_max_size')),
4591 self::convertPhpIniSizeValueToBytes(ini_get('upload_max_filesize'))
4592 );
4593
4594 return $uploadSizeLimitBytes;
4595 }
4596
4597 public static function convertPhpIniSizeValueToBytes($phpIniSizeValue)
4598 {
4599 if( is_numeric($phpIniSizeValue) )
4600 {
4601 return $phpIniSizeValue;
4602 }
4603
4604 $suffix = substr($phpIniSizeValue, -1);
4605 $value = substr($phpIniSizeValue, 0, -1);
4606
4607 switch( strtoupper($suffix) )
4608 {
4609 case 'P':
4610 $value *= 1024;
4611 case 'T':
4612 $value *= 1024;
4613 case 'G':
4614 $value *= 1024;
4615 case 'M':
4616 $value *= 1024;
4617 case 'K':
4618 $value *= 1024;
4619 break;
4620 }
4621
4622 return $value;
4623 }
4624
4633 public static function __extractRefId($role_title)
4634 {
4635
4636 $test_str = explode('_',$role_title);
4637
4638 if ($test_str[0] == 'il')
4639 {
4640 $test2 = (int) $test_str[3];
4641 return is_numeric ($test2) ? (int) $test2 : false;
4642 }
4643 return false;
4644 }
4645
4656 public static function __extractId($ilias_id, $inst_id)
4657 {
4658
4659 $test_str = explode('_',$ilias_id);
4660
4661 if ($test_str[0] == 'il' && $test_str[1] == $inst_id && count($test_str) == 4)
4662 {
4663 $test2 = (int) $test_str[3];
4664 return is_numeric ($test2) ? (int) $test2 : false;
4665 }
4666 return false;
4667 }
4668
4683 public static function _sortIds($a_ids,$a_table,$a_field,$a_id_name)
4684 {
4685 global $ilDB;
4686
4687 if(!$a_ids)
4688 {
4689 return array();
4690 }
4691
4692 // use database to sort user array
4693 $where = "WHERE ".$a_id_name." IN (";
4694 $where .= implode(",", ilUtil::quoteArray($a_ids));
4695 $where .= ") ";
4696
4697 $query = "SELECT ".$a_id_name." FROM ".$a_table." ".
4698 $where.
4699 "ORDER BY ".$a_field;
4700
4701 $res = $ilDB->query($query);
4702 while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT))
4703 {
4704 $ids[] = $row->$a_id_name;
4705 }
4706 return $ids ? $ids : array();
4707 }
4708
4718 public static function getMySQLTimestamp($a_ts)
4719 {
4720 global $ilDB;
4721
4722 return $a_ts;
4723 }
4724
4731 public static function quoteArray($a_array)
4732 {
4733 global $ilDB;
4734
4735
4736 if(!is_array($a_array) or !count($a_array))
4737 {
4738 return array("''");
4739 }
4740
4741 foreach($a_array as $k => $item)
4742 {
4743 $a_array[$k] = $ilDB->quote($item);
4744 }
4745
4746 return $a_array;
4747 }
4748
4757 public static function sendInfo($a_info = "",$a_keep = false)
4758 {
4759 global $tpl;
4760 $tpl->setMessage("info", $a_info, $a_keep);
4761 }
4762
4771 public static function sendFailure($a_info = "",$a_keep = false)
4772 {
4773 global $tpl;
4774
4775 if(is_object($tpl))
4776 {
4777 $tpl->setMessage("failure", $a_info, $a_keep);
4778 }
4779 }
4780
4787 public static function sendQuestion($a_info = "",$a_keep = false)
4788 {
4789 global $tpl;
4790 $tpl->setMessage("question", $a_info, $a_keep);
4791 }
4792
4801 public static function sendSuccess($a_info = "",$a_keep = false)
4802 {
4803 global $tpl;
4804 $tpl->setMessage("success", $a_info, $a_keep);
4805 }
4806
4807 public static function infoPanel($a_keep = true)
4808 {
4809 global $tpl,$ilias,$lng;
4810
4811 if (!empty($_SESSION["infopanel"]) and is_array($_SESSION["infopanel"]))
4812 {
4813 $tpl->addBlockFile("INFOPANEL", "infopanel", "tpl.infopanel.html",
4814 "Services/Utilities");
4815 $tpl->setCurrentBlock("infopanel");
4816
4817 if (!empty($_SESSION["infopanel"]["text"]))
4818 {
4819 $link = "<a href=\"".$dir.$_SESSION["infopanel"]["link"]."\" target=\"".
4820 ilFrameTargetInfo::_getFrame("MainContent").
4821 "\">";
4822 $link .= $lng->txt($_SESSION["infopanel"]["text"]);
4823 $link .= "</a>";
4824 }
4825
4826 // deactivated
4827 if (!empty($_SESSION["infopanel"]["img"]))
4828 {
4829 $link .= "<td><a href=\"".$_SESSION["infopanel"]["link"]."\" target=\"".
4830 ilFrameTargetInfo::_getFrame("MainContent").
4831 "\">";
4832 $link .= "<img src=\"".$ilias->tplPath.$ilias->account->prefs["skin"]."/images/".
4833 $_SESSION["infopanel"]["img"]."\" border=\"0\" vspace=\"0\"/>";
4834 $link .= "</a></td>";
4835 }
4836
4837 $tpl->setVariable("INFO_ICONS",$link);
4838 $tpl->parseCurrentBlock();
4839 }
4840
4841 //if (!$a_keep)
4842 //{
4843 ilSession::clear("infopanel");
4844 //}
4845 }
4846
4847
4856 public static function dirsize($directory)
4857 {
4858 $size = 0;
4859 if (!is_dir($directory))
4860 {
4861 // BEGIN DiskQuota Suppress PHP warning when attempting to determine
4862 // dirsize of non-existing directory
4863 $size = @filesize($directory);
4864 // END DiskQuota Suppress PHP warning.
4865 return ($size === false) ? -1 : $size;
4866 }
4867 if ($DIR = opendir($directory))
4868 {
4869 while (($dirfile = readdir($DIR)) !== false)
4870 {
4871 if (is_link($directory . DIRECTORY_SEPARATOR . $dirfile) || $dirfile == '.' || $dirfile == '..')
4872 continue;
4873 if (is_file($directory . DIRECTORY_SEPARATOR . $dirfile))
4874 $size += filesize($directory . DIRECTORY_SEPARATOR . $dirfile);
4875 else if (is_dir($directory . DIRECTORY_SEPARATOR . $dirfile))
4876 {
4877 // BEGIN DiskQuota: dirsize is not a global function anymore
4878 $dirSize = ilUtil::dirsize($directory . DIRECTORY_SEPARATOR . $dirfile);
4879 // END DiskQuota: dirsize is not a global function anymore
4880 if ($dirSize >= 0)
4881 $size += $dirSize;
4882 else return -1;
4883 }
4884 }
4885 closedir($DIR);
4886 }
4887 return $size;
4888 }
4889
4890 public static function randomhash()
4891 {
4892 return md5(rand(1,9999999) + str_replace(" ", "", (string) microtime()));
4893 }
4894
4895 public static function setCookie($a_cookie_name,$a_cookie_value = '', $a_also_set_super_global = true, $a_set_cookie_invalid = false)
4896 {
4897 /*
4898 if(!(bool)$a_set_cookie_invalid) $expire = IL_COOKIE_EXPIRE;
4899 else $expire = time() - (365*24*60*60);
4900 */
4901 // Temporary fix for feed.php
4902 if(!(bool)$a_set_cookie_invalid) $expire = 0;
4903 else $expire = time() - (365*24*60*60);
4904
4905 if(!defined('IL_COOKIE_SECURE'))
4906 {
4907 define('IL_COOKIE_SECURE', false);
4908 }
4909
4910 setcookie( $a_cookie_name, $a_cookie_value, $expire,
4911 IL_COOKIE_PATH, IL_COOKIE_DOMAIN, IL_COOKIE_SECURE, IL_COOKIE_HTTPONLY
4912 );
4913
4914 if((bool)$a_also_set_super_global) $_COOKIE[$a_cookie_name] = $a_cookie_value;
4915 }
4916
4917 public static function _sanitizeFilemame($a_filename)
4918 {
4919 return strip_tags(self::stripSlashes($a_filename));
4920 }
4921
4922 public static function _getHttpPath()
4923 {
4924 global $ilIliasIniFile;
4925
4926 if($_SERVER['SHELL'] || php_sapi_name() == 'cli' ||
4927 // fallback for windows systems, useful in crons
4928 (class_exists("ilContext") && !ilContext::usesHTTP()))
4929 {
4930 return $ilIliasIniFile->readVariable('server', 'http_path');
4931 }
4932 else
4933 {
4934 return ILIAS_HTTP_PATH;
4935 }
4936 }
4937
4943 public static function printBacktrace($a_limit = 0)
4944 {
4945 $bt = debug_backtrace();
4946 $cnt = 0;
4947 foreach ($bt as $t)
4948 {
4949 if ($cnt != 0 && ($a_limit == 0 || $cnt <= $a_limit))
4950 {
4951 echo "<br>".$t["file"].", ".$t["function"]." [".$t["line"]."]";
4952 }
4953 $cnt++;
4954 }
4955 echo "<br>";
4956 }
4957
4972 public static function parseImportId($a_import_id)
4973 {
4974 $exploded = explode('_',$a_import_id);
4975
4976 $parsed['orig'] = $a_import_id;
4977 if($exploded[0] == 'il')
4978 {
4979 $parsed['prefix'] = $exploded[0];
4980 }
4981 if(is_numeric($exploded[1]))
4982 {
4983 $parsed['inst_id'] = (int) $exploded[1];
4984 }
4985 $parsed['type'] = $exploded[2];
4986
4987 if(is_numeric($exploded[3]))
4988 {
4989 $parsed['id'] = (int) $exploded[3];
4990 }
4991 return $parsed;
4992 }
4993
5000 public static function unserializeSession($data)
5001 {
5002 $vars = preg_split(
5003 '/([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff^|]*)\|/',
5004 $data,
5005 -1,
5006 PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE
5007 );
5008
5009 $result = array();
5010
5011 for($i = 0; $vars[$i]; $i++)
5012 {
5013 $result[$vars[$i++]] = unserialize($vars[$i]);
5014 }
5015
5016 return $result;
5017 }
5018
5019
5033
5034 $fp = @fopen($file, 'rb');
5035
5036 $size = filesize($file); // File size
5037 $length = $size; // Content length
5038 $start = 0; // Start byte
5039 $end = $size - 1; // End byte
5040 // Now that we've gotten so far without errors we send the accept range header
5041 /* At the moment we only support single ranges.
5042 * Multiple ranges requires some more work to ensure it works correctly
5043 * and comply with the spesifications: http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.2
5044 *
5045 * Multirange support annouces itself with:
5046 * header('Accept-Ranges: bytes');
5047 *
5048 * Multirange content must be sent with multipart/byteranges mediatype,
5049 * (mediatype = mimetype)
5050 * as well as a boundry header to indicate the various chunks of data.
5051 */
5052 header("Accept-Ranges: 0-$length");
5053 // header('Accept-Ranges: bytes');
5054 // multipart/byteranges
5055 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.2
5056 if (isset($_SERVER['HTTP_RANGE'])) {
5057
5058 $c_start = $start;
5059 $c_end = $end;
5060 // Extract the range string
5061 list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
5062 // Make sure the client hasn't sent us a multibyte range
5063 if (strpos($range, ',') !== false) {
5064
5065 // (?) Shoud this be issued here, or should the first
5066 // range be used? Or should the header be ignored and
5067 // we output the whole content?
5068 header('HTTP/1.1 416 Requested Range Not Satisfiable');
5069 header("Content-Range: bytes $start-$end/$size");
5070 // (?) Echo some info to the client?
5071 exit;
5072 }
5073 // If the range starts with an '-' we start from the beginning
5074 // If not, we forward the file pointer
5075 // And make sure to get the end byte if spesified
5076 if ($range == '-') {
5077
5078 // The n-number of the last bytes is requested
5079 $c_start = $size - substr($range, 1);
5080 }
5081 else {
5082
5083 $range = explode('-', $range);
5084 $c_start = $range[0];
5085 $c_end = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size;
5086 }
5087 /* Check the range and make sure it's treated according to the specs.
5088 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
5089 */
5090 // End bytes can not be larger than $end.
5091 $c_end = ($c_end > $end) ? $end : $c_end;
5092 // Validate the requested range and return an error if it's not correct.
5093 if ($c_start > $c_end || $c_start > $size - 1 || $c_end >= $size) {
5094
5095 header('HTTP/1.1 416 Requested Range Not Satisfiable');
5096 header("Content-Range: bytes $start-$end/$size");
5097 // (?) Echo some info to the client?
5098 exit;
5099 }
5100 $start = $c_start;
5101 $end = $c_end;
5102 $length = $end - $start + 1; // Calculate new content length
5103 fseek($fp, $start);
5104 header('HTTP/1.1 206 Partial Content');
5105 }
5106 // Notify the client the byte range we'll be outputting
5107 header("Content-Range: bytes $start-$end/$size");
5108 header("Content-Length: $length");
5109
5110 // Start buffered download
5111 $buffer = 1024 * 8;
5112 while(!feof($fp) && ($p = ftell($fp)) <= $end) {
5113
5114 if ($p + $buffer > $end) {
5115
5116 // In case we're only outputtin a chunk, make sure we don't
5117 // read past the length
5118 $buffer = $end - $p + 1;
5119 }
5120 set_time_limit(0); // Reset time limit for big files
5121 echo fread($fp, $buffer);
5122 flush(); // Free up memory. Otherwise large files will trigger PHP's memory limit.
5123 }
5124
5125 fclose($fp);
5126 }
5127
5128
5129 //
5130 // used to be in ilFormat
5131 //
5132
5145 protected static function _getSizeMagnitude()
5146 {
5147 return 1024;
5148 }
5149
5163 protected static function fmtFloat($a_float, $a_decimals=0, $a_dec_point = null, $a_thousands_sep = null, $a_suppress_dot_zero=false)
5164 {
5165 global $lng;
5166
5167 if ($a_dec_point == null) {
5168 {
5169 $a_dec_point = ".";
5170 }
5171 }
5172 if ($a_dec_point == '-lang_sep_decimal-') {
5173 $a_dec_point = ".";
5174 }
5175
5176 if ($a_thousands_sep == null) {
5177 $a_thousands_sep = $lng->txt('lang_sep_thousand');
5178 }
5179 if ($a_thousands_sep == '-lang_sep_thousand-') {
5180 $a_thousands_sep = ",";
5181 }
5182
5183 $txt = number_format($a_float, $a_decimals, $a_dec_point, $a_thousands_sep);
5184
5185 // remove trailing ".0"
5186 if (($a_suppress_dot_zero == 0 || $a_decimals == 0)
5187 && substr($txt, - 2) == $a_dec_point . '0'
5188 ) {
5189 $txt = substr($txt, 0, strlen($txt) - 2);
5190 }
5191 if ($a_float == 0 and $txt == "") {
5192 $txt = "0";
5193 }
5194
5195 return $txt;
5196 }
5197
5214 public static function formatSize($size, $a_mode = 'short', $a_lng = null)
5215 {
5216 global $lng;
5217 if ($a_lng == null) {
5218 $a_lng = $lng;
5219 }
5220
5221 $mag = self::_getSizeMagnitude();
5222
5223 if ($size >= $mag * $mag * $mag) {
5224 $scaled_size = $size / $mag / $mag / $mag;
5225 $scaled_unit = 'lang_size_gb';
5226 } else {
5227 if ($size >= $mag * $mag) {
5228 $scaled_size = $size / $mag / $mag;
5229 $scaled_unit = 'lang_size_mb';
5230 } else {
5231 if ($size >= $mag) {
5232 $scaled_size = $size / $mag;
5233 $scaled_unit = 'lang_size_kb';
5234 } else {
5235 $scaled_size = $size;
5236 $scaled_unit = 'lang_size_bytes';
5237 }
5238 }
5239 }
5240
5241 $result = self::fmtFloat($scaled_size, ($scaled_unit
5242 == 'lang_size_bytes') ? 0 : 1, $a_lng->txt('lang_sep_decimal'), $a_lng->txt('lang_sep_thousand'), true)
5243 . ' ' . $a_lng->txt($scaled_unit);
5244 if ($a_mode == 'long' && $size > $mag) {
5245 $result .= ' (' . self::fmtFloat($size, 0, $a_lng->txt('lang_sep_decimal'), $a_lng->txt('lang_sep_thousand')) . ' '
5246 . $a_lng->txt('lang_size_bytes') . ')';
5247 }
5248
5249 return $result;
5250 }
5251
5252
5253 //
5254 // used for disk quotas
5255 //
5256
5257 public static function MB2Bytes($a_value)
5258 {
5259 return $a_value * pow(self::_getSizeMagnitude(), 2);
5260 }
5261
5262 public static function Bytes2MB($a_value)
5263 {
5264 return $a_value / (pow(self::_getSizeMagnitude(), 2));
5265 }
5266
5272 static function dumpVar($mixed = null)
5273 {
5274 echo '<pre>';
5275 var_dump($mixed);
5276 echo '</pre>';
5277 }
5278
5279
5280} // END class.ilUtil
5281
5282
5283?>
sprintf('%.4f', $callTime)
date( 'd-M-Y', $objPHPExcel->getProperties() ->getCreated())
$parser
Definition: BPMN2Parser.php:24
$_COOKIE['ilClientId']
Definition: BPMN2Parser.php:15
$result
$size
Definition: RandomTest.php:79
global $tpl
Definition: ilias.php:8
if(! $in) print
$files
Definition: add-vimline.php:18
$path
Definition: aliased.php:25
PHPExcel root directory.
Definition: PHPExcel.php:30
$_SESSION["AccountId"]
An exception for terminatinating execution or to throw for unit testing.
const IL_COMP_SERVICE
const IL_CAL_UNIX
const IL_CAL_DATETIME
static usesHTTP()
Uses HTTP aka browser.
@classDescription Date and time handling
get($a_format, $a_format_str='', $a_tz='')
get formatted date
Base class for ILIAS Exception handling.
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.
const ILIAS_HOST
static getInstance()
Singleton: get instance.
static _getAssociatedUsersOnline($a_user_id, $a_no_anonymous=false)
static _removeItemFromDesktops($a_id)
removes object from all user's desktops @access public
static _lookupObjId($a_id)
static _lookupTitle($a_id)
lookup object title
static _getIcon($a_obj_id="", $a_size="big", $a_type="", $a_offline=false)
Get icon for repository item.
static getPluginObject($a_ctype, $a_cname, $a_slot_id, $a_pname)
Get Plugin Object.
static _getOperationIdsByName($operations)
get ops_id's by name.
static _getInstance()
Get instance of ilSecuritySettings.
static clear($a_var)
Unset a value.
static strPos($a_haystack, $a_needle, $a_offset=NULL)
Definition: class.ilStr.php:34
static strCmp($a, $b)
Compare two strings.
static strToUpper($a_string)
static strLen($a_string)
Definition: class.ilStr.php:91
static subStr($a_str, $a_start, $a_length=NULL)
Definition: class.ilStr.php:15
Util class various functions, usage as namespace.
static getPasswordValidChars($a_as_regex=true, $a_only_special_chars=false)
All valid chars for password.
static is_email($a_email)
This preg-based function checks whether an e-mail address is formally valid.
static CreateIsoFromFolder($a_dir, $a_file)
static getDataDir()
get data directory (outside webspace)
static moveUploadedFile($a_file, $a_name, $a_target, $a_raise_errors=true, $a_mode="move_uploaded")
move uploaded file
static getJSLocation($a_js_name, $a_js_location="", $add_version=FALSE)
get full javascript file name (path inclusive) of current user
static _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 getMySQLTimestamp($a_ts)
Get MySQL timestamp in 4.1.x or higher format (yyyy-mm-dd hh:mm:ss) This function converts a timestam...
static assembleParameterString($a_par_arr)
static dumpString($a_str)
dumps ord values of every character of string $a_str
static appendUrlParameterString($a_url, $a_par, $xml_style=false)
append URL parameter string ("par1=value1&par2=value2...") to given URL string
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 stripOnlySlashes($a_str)
strip slashes if magic qoutes is enabled
static sendQuestion($a_info="", $a_keep=false)
Send Question to Screen.
static replaceUrlParameterString($url, $parametersArray)
static insertInstIntoID($a_value)
inserts installation id into ILIAS id
static __extractRefId($role_title)
extract ref id from role title, e.g.
static KT_replaceParam($qstring, $paramName, $paramValue)
static shortenText($a_str, $a_len, $a_dots=false, $a_next_blank=false, $a_keep_extension=false)
shorten a string to given length.
static isIPv4($a_str)
static tf2yn($a_tf)
convert true/false to "y"/"n"
static replaceLinkProperties($matches)
replaces target _blank with _self and the link text with the according object title.
static Linkbar($AScript, $AHits, $ALimit, $AOffset, $AParams=array(), $ALayout=array(), $prefix='')
Linkbar Diese Funktion erzeugt einen typischen Navigationsbalken mit "Previous"- und "Next"-Links und...
static parseImportId($a_import_id)
Parse an ilias import id Typically of type il_[IL_INST_ID]_[OBJ_TYPE]_[OBJ_ID] returns array( 'orig' ...
static prepareTextareaOutput($txt_output, $prepare_for_latex_output=FALSE, $omitNl2BrWhenTextArea=false)
Prepares a string for a text area output where latex code may be in it If the text is HTML-free,...
static sortArray($array, $a_array_sortby, $a_array_sortorder=0, $a_numeric=false, $a_keep_keys=false)
sortArray
static getJavaPath()
get full java path (dir + java command)
static escapeShellArg($a_arg)
static setPathStr($a_path)
??? @access public
static getImageTagByType($a_type, $a_path, $a_big=false)
Builds an html image tag TODO: function still in use, but in future use getImagePath and move HTML-Co...
static readFile($a_file)
there are some known problems with the original readfile method, which sometimes truncates delivered ...
static getWebspaceDir($mode="filesystem")
get webspace directory
static unmaskAttributeTag($a_str, $tag, $tag_att)
static sendSuccess($a_info="", $a_keep=false)
Send Success Message to Screen.
rangeDownload($file)
Send a file via range request, see http://mobiforge.com/design-development/content-delivery-mobile-de...
static execConvert($args)
execute convert command
static rCopy($a_sdir, $a_tdir, $preserveTimeAttributes=false)
Copies content of a directory $a_sdir recursively to a directory $a_tdir.
static getStyleSheetLocation($mode="output", $a_css_name="", $a_css_location="")
get full style sheet file name (path inclusive) of current user
static redirect($a_script)
http redirect to other script
static resizeImage($a_from, $a_to, $a_width, $a_height, $a_constrain_prop=false)
resize image
static isPassword($a_passwd, &$customError=null)
validates a password @access public
static sendFailure($a_info="", $a_keep=false)
Send Failure Message to Screen.
static stripSlashesRecursive($a_data, $a_strip_html=true, $a_allow="")
Strip slashes from array and sub-arrays.
static _getHttpPath()
static makeClickable($a_text, $detectGotoLinks=false)
makeClickable In Texten enthaltene URLs und Mail-Adressen klickbar machen
static groupNameExists($a_group_name, $a_id=0)
checks if group name already exists.
static virusHandling($a_file, $a_orig_name="", $a_clean=true)
scan file for viruses and clean files if possible
static buildLatexImages($a_text, $a_dir)
replace [tex]...[/tex] tags with formula image code for offline use
static printBacktrace($a_limit=0)
printBacktrace
static getAssociatedUsersOnline($a_user_id)
static deliverData($a_data, $a_filename, $mime="application/octet-stream", $charset="")
deliver data for download via browser.
static maskSecureTags($a_str, $allow_array)
static unmaskTag($a_str, $t, $fix_param="")
static zip($a_dir, $a_file, $compress_content=false)
static isWindows()
check wether the current client system is a windows system
static dumpVar($mixed=null)
Dump var.
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 execQuoted($cmd, $args=NULL)
exec command and fix spaces on windows
static getDir($a_dir, $a_rec=false, $a_sub_dir="")
get directory
static _getObjectsByOperations($a_obj_type, $a_operation, $a_usr_id=0, $limit=0)
Get all objects of a specific type and check access This function is not recursive,...
static img($a_src, $a_alt="", $a_width="", $a_height="", $a_border=0, $a_id="", $a_class="")
Build img tag.
static now()
Return current timestamp in Y-m-d H:i:s format.
static getConvertCmd()
get convert command
static getP3PLocation()
Get p3p file path.
static escapeShellCmd($a_arg)
escape shell cmd
static maskAttributeTag($a_str, $tag, $tag_att)
static 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 ilTempnam($a_temp_path=null)
Create a temporary file in an ILIAS writable directory.
static getASCIIFilename($a_filename)
convert utf8 to ascii filename
static htmlentitiesOutsideHTMLTags($htmlText)
Encodes HTML entities outside of HTML tags.
static getHtmlPath($relative_path)
get url of path
static convertImage($a_from, $a_to, $a_target_format="", $a_geometry="", $a_background_color="")
convert image
static getPasswordRequirementsInfo()
static stripScriptHTML($a_str, $a_allow="", $a_rm_js=true)
strip only html tags (4.0) from text $allowed contains tags to be allowed, in format tags a and b ar...
static unzip($a_file, $overwrite=false, $a_flat=false)
unzip file
static htmlencodePlainString($a_str, $a_make_links_clickable, $a_detect_goto_links=false)
Encodes a plain text string into HTML for display in a browser.
static array_php2js($data)
convert php arrays to javascript arrays
includeMathjax($a_tpl=null)
Include Mathjax.
static unique_multi_array($array, $sub_key)
Make a multi-dimensional array to have only DISTINCT values for a certain "column".
static makeDateSelect($prefix, $year="", $month="", $day="", $startyear="", $a_long_month=true, $a_further_options=array(), $emptyoption=false)
Creates a combination of HTML selects for date inputs.
static generatePasswords($a_number)
Generate a number of passwords.
static getSelectName($selected, $values)
???
static randomhash()
static stripSlashes($a_str, $a_strip_html=true, $a_allow="")
strip slashes if magic qoutes is enabled
static date_mysql2time($mysql_date_time)
static getFileSizeInfo()
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 stableSortArray($array, $a_array_sortby, $a_array_sortorder=0, $a_numeric=false)
static & processCSVRow(&$row, $quoteAll=FALSE, $separator=";", $outUTF8=FALSE, $compatibleWithMSExcel=TRUE)
Convertes an array for CSV usage.
static removeItemFromDesktops($a_id)
removes object from all user's desktops @access public
static sendInfo($a_info="", $a_keep=false)
Send Info Message to Screen.
static formSelect($selected, $varname, $options, $multiple=false, $direct_text=false, $size="0", $style_class="", $attribs="", $disabled=false)
Builds a select form field with options and shows the selected option first.
static __extractId($ilias_id, $inst_id)
extract ref id from role title, e.g.
static getTypeIconPath($a_type, $a_obj_id, $a_size='small')
Get type icon path path Return image path for icon_xxx.pngs Or (if enabled) path to custom icon Depre...
static getImagePath($img, $module_path="", $mode="output", $offline=false)
get image path (for images located in a template directory)
static deducibleSize($a_mime)
checks if mime type is provided by getimagesize()
static isDN($a_str)
static attribsToArray($a_str)
converts a string of format var1 = "val1" var2 = "val2" ... into an array
static maskTag($a_str, $t, $fix_param="")
static removeTrailingPathSeparators($path)
static infoPanel($a_keep=true)
static deliverFile($a_file, $a_filename, $a_mime='', $isInline=false, $removeAfterDelivery=false, $a_exit_after=true)
deliver file for download via browser.
static 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')
$counter
$txt
Definition: error.php:12
$style
Definition: example_012.php:70
$r
Definition: example_031.php:79
$params
Definition: example_049.php:96
$target_arr
Definition: goto.php:49
global $ilCtrl
Definition: ilias.php:18
$ret
Definition: parser.php:6
defined( 'APPLICATION_ENV')||define( 'APPLICATION_ENV'
Definition: bootstrap.php:27
global $lng
Definition: privfeed.php:17
global $ilErr
Definition: raiseError.php:16
if(!file_exists("$old.txt")) if( $old===$new) if(file_exists("$new.txt")) $file
$cmd
Definition: sahs_server.php:35
$ref_id
Definition: sahs_server.php:39
echo;exit;}function LogoutNotification($SessionID) { global $ilDB; $q="SELECT session_id, data FROM usr_session WHERE expires > (\w+)\|/" PREG_SPLIT_NO_EMPTY PREG_SPLIT_DELIM_CAPTURE
$url
Definition: shib_logout.php:72
const IL_COOKIE_PATH(isset($_GET["client_id"]))
Definition: index.php:26
global $ilDB
$errors
if(!is_array($argv)) $options
if((!isset($_SERVER['DOCUMENT_ROOT'])) OR(empty($_SERVER['DOCUMENT_ROOT']))) $_SERVER['DOCUMENT_ROOT']
$ilIliasIniFile
global $DIC
$ilUser
Definition: imgupload.php:18
const ILIAS_MODULE
Definition: server.php:14
$a_type
Definition: workflow.php:93