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