ILIAS  release_5-3 Revision v5.3.23-19-g915713cf615
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");
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
185  : ilStyleDefinition::getCurrentStyle() . ".css";
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
204  $skin = ilStyleDefinition::getSkins()[ilStyleDefinition::getCurrentSkin()];
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  $str = "<select name=\"" . $varname . "\"" . $multiple . " $class size=\"" . $size . "\" $attributes $disabled>\n";
366 
367  foreach ((array) $options as $key => $val) {
368  $style = "";
369  if (is_array($val)) {
370  $style = $val["style"];
371  $val = $val["text"]; // mus be last line, since we overwrite
372  }
373 
374  $sty = ($style != "")
375  ? ' style="' . $style . '" '
376  : "";
377 
378  if ($direct_text) {
379  $str .= " <option $sty value=\"" . $key . "\"";
380  } else {
381  $str .= " <option $sty value=\"" . $val . "\"";
382  }
383  if (is_array($selected)) {
384  if (in_array($key, $selected)) {
385  $str .= " selected=\"selected\"";
386  }
387  } elseif ($selected == $key) {
388  $str .= " selected=\"selected\"";
389  }
390 
391  if ($direct_text) {
392  $str .= ">" . $val . "</option>\n";
393  } else {
394  $str .= ">" . $lng->txt($val) . "</option>\n";
395  }
396  }
397 
398  $str .= "</select>\n";
399 
400  return $str;
401  }
402 
412  public static function getSelectName($selected, $values)
413  {
414  return($values[$selected]);
415  }
416 
428  public static function formCheckbox($checked, $varname, $value, $disabled = false)
429  {
430  $str = "<input type=\"checkbox\" name=\"" . $varname . "\"";
431 
432  if ($checked == 1) {
433  $str .= " checked=\"checked\"";
434  }
435 
436  if ($disabled) {
437  $str .= " disabled=\"disabled\"";
438  }
439 
440  $array_var = false;
441 
442  if (substr($varname, -2) == "[]") {
443  $array_var = true;
444  }
445 
446  // if varname ends with [], use varname[-2] + _ + value as id tag (e.g. "user_id[]" => "user_id_15")
447  if ($array_var) {
448  $varname_id = substr($varname, 0, -2) . "_" . $value;
449  } else {
450  $varname_id = $varname;
451  }
452 
453  // dirty removal of other "[]" in string
454  $varname_id = str_replace("[", "_", $varname_id);
455  $varname_id = str_replace("]", "", $varname_id);
456 
457  $str .= " value=\"" . $value . "\" id=\"" . $varname_id . "\" />\n";
458 
459  return $str;
460  }
461 
473  public static function formDisabledRadioButton($checked, $varname, $value, $disabled)
474  {
475  if ($disabled) {
476  $str = "<input disabled type=\"radio\" name=\"" . $varname . "\"";
477  } else {
478  $str = "<input type=\"radio\" name=\"" . $varname . "\"";
479  }
480  if ($checked == 1) {
481  $str .= " checked=\"checked\"";
482  }
483 
484  $str .= " value=\"" . $value . "\"";
485  $str .= " id=\"" . $value . "\" />\n";
486 
487  return $str;
488  }
489 
490 
501  public static function formRadioButton($checked, $varname, $value, $onclick=null, $disabled = false)
502  {
503  $str = '<input ';
504 
505  if ($onclick) {
506  $str .= ('onclick="' . $onclick . '"');
507  }
508 
509  $str .= (" type=\"radio\" name=\"" . $varname . "\"");
510  if ($checked == 1) {
511  $str .= " checked=\"checked\"";
512  }
513 
514  if ($disabled) {
515  $str .= " disabled=\"disabled\"";
516  }
517 
518  $str .= " value=\"" . $value . "\"";
519 
520  $str .= " id=\"" . $value . "\" />\n";
521 
522  return $str;
523  }
524 
525 
535  public static function formInput($varname, $value, $disabled = false)
536  {
537  $str = "<input type=\"input\" name=\"" . $varname . "\"";
538  if ($disabled) {
539  $str .= " disabled";
540  }
541 
542  $str .= " value=\"" . $value . "\"";
543 
544  $str .= " id=\"" . $value . "\" />\n";
545 
546  return $str;
547  }
548 
549 
556  public static function checkInput($vars)
557  {
558  // TO DO:
559  // Diese Funktion soll Formfeldeingaben berprfen (empty und required)
560  }
561 
568  public static function setPathStr($a_path)
569  {
570  if ("" != $a_path && "/" != substr($a_path, -1)) {
571  $a_path .= "/";
572  //$a_path = substr($a_path,1);
573  }
574 
575  //return getcwd().$a_path;
576  return $a_path;
577  }
578 
591  public static function switchColor($a_num, $a_css1, $a_css2)
592  {
593  if (!($a_num % 2)) {
594  return $a_css1;
595  } else {
596  return $a_css2;
597  }
598  }
599 
608  public static function checkFormEmpty($emptyFields)
609  {
610  $feedback = "";
611 
612  foreach ($emptyFields as $key => $val) {
613  if ($val == "") {
614  if ($feedback != "") {
615  $feedback .= ", ";
616  }
617  $feedback .= $key;
618  }
619  }
620 
621  return $feedback;
622  }
623 
648  public static function Linkbar($AScript, $AHits, $ALimit, $AOffset, $AParams = array(), $ALayout = array(), $prefix = '')
649  {
650  $LinkBar = "";
651 
652  $layout_link = "";
653  $layout_prev = "&lt;&lt;";
654  $layout_next = "&gt;&gt;";
655 
656  // layout options
657  if ((is_array($ALayout) && (count($ALayout) > 0))) {
658  if ($ALayout["link"]) {
659  $layout_link = " class=\"" . $ALayout["link"] . "\"";
660  }
661 
662  if ($ALayout["prev"]) {
663  $layout_prev = $ALayout["prev"];
664  }
665 
666  if ($ALayout["next"]) {
667  $layout_next = $ALayout["next"];
668  }
669  }
670 
671  // show links, if hits greater limit
672  // or offset > 0 (can be > 0 due to former setting)
673  if ($AHits > $ALimit || $AOffset > 0) {
674  if (!empty($AParams)) {
675  foreach ($AParams as $key => $value) {
676  $params.= $key . "=" . $value . "&";
677  }
678  }
679  // if ($params) $params = substr($params,0,-1);
680  if (strpos($AScript, '&')) {
681  $link = $AScript . "&" . $params . $prefix . "offset=";
682  } else {
683  $link = $AScript . "?" . $params . $prefix . "offset=";
684  }
685 
686  // ?bergehe "zurck"-link, wenn offset 0 ist.
687  if ($AOffset >= 1) {
688  $prevoffset = $AOffset - $ALimit;
689  if ($prevoffset < 0) {
690  $prevoffset = 0;
691  }
692  $LinkBar .= "<a" . $layout_link . " href=\"" . $link . $prevoffset . "\">" . $layout_prev . "&nbsp;</a>";
693  }
694 
695  // Ben?tigte Seitenzahl kalkulieren
696  $pages=intval($AHits/$ALimit);
697 
698  // Wenn ein Rest bleibt, addiere eine Seite
699  if (($AHits % $ALimit)) {
700  $pages++;
701  }
702 
703  // Bei Offset = 0 keine Seitenzahlen anzeigen : DEAKTIVIERT
704  // if ($AOffset != 0) {
705 
706  // ansonsten zeige Links zu den anderen Seiten an
707  for ($i = 1 ;$i <= $pages ; $i++) {
708  $newoffset=$ALimit*($i-1);
709 
710  if ($newoffset == $AOffset) {
711  $LinkBar .= "[" . $i . "] ";
712  } else {
713  $LinkBar .= '<a ' . $layout_link . ' href="' .
714  $link . $newoffset . '">[' . $i . ']</a> ';
715  }
716  }
717  // }
718 
719  // Checken, ob letze Seite erreicht ist
720  // Wenn nicht, gebe einen "Weiter"-Link aus
721  if (!(($AOffset/$ALimit)==($pages-1)) && ($pages!=1)) {
722  $newoffset=$AOffset+$ALimit;
723  $LinkBar .= "<a" . $layout_link . " href=\"" . $link . $newoffset . "\">&nbsp;" . $layout_next . "</a>";
724  }
725 
726  return $LinkBar;
727  } else {
728  return false;
729  }
730  }
731 
743  public static function makeClickable($a_text, $detectGotoLinks = false)
744  {
745  // New code, uses MediaWiki Sanitizer
746  $ret = $a_text;
747 
748  // www-URL ohne ://-Angabe
749  $ret = preg_replace(
750  "/(^|[\s]+)(www\.)([A-Za-z0-9#&=?.\/\-]+)/i",
751  "$1http://$2$3",
752  $ret
753  );
754 
755  // ftp-URL ohne ://-Angabe
756  $ret = preg_replace(
757  "/(^|[\s]+)(ftp\.)([A-Za-z0-9#&=?.\/\-]+)/i",
758  "$1ftp://$2$3",
759  $ret
760  );
761 
762  // E-Mail (this does not work as expected, users must add mailto: manually)
763  //$ret = preg_replace("/(([a-z0-9_]|\-|\.)+@([^[\s]*)([A-Za-z0-9\-]))/i",
764  // "mailto:$1", $ret);
765 
766  // mask existing image tags
767  $ret = str_replace('src="http://', '"***masked_im_start***', $ret);
768 
769  include_once("./Services/Utilities/classes/class.ilMWParserAdapter.php");
770  $parser = new ilMWParserAdapter();
771  $ret = $parser->replaceFreeExternalLinks($ret);
772 
773  // unmask existing image tags
774  $ret = str_replace('"***masked_im_start***', 'src="http://', $ret);
775 
776  // Should be Safe
777 
778  if ($detectGotoLinks) {
779  // replace target blank with self and text with object title.
780  $regExp = "<a[^>]*href=\"(" . str_replace("/", "\/", ILIAS_HTTP_PATH) . "\/goto.php\?target=\w+_(\d+)[^\"]*)\"[^>]*>[^<]*<\/a>";
781  // echo htmlentities($regExp);
782  $ret = preg_replace_callback(
783  "/" . $regExp . "/i",
784  array("ilUtil", "replaceLinkProperties"),
785  $ret
786  );
787 
788  // Static links
789  $regExp = "<a[^>]*href=\"(" . str_replace("/", "\/", ILIAS_HTTP_PATH) . "\/goto_.*[a-z0-9]+_([0-9]+)\.html)\"[^>]*>[^<]*<\/a>";
790  // echo htmlentities($regExp);
791  $ret = preg_replace_callback(
792  "/" . $regExp . "/i",
793  array("ilUtil", "replaceLinkProperties"),
794  $ret
795  );
796  }
797 
798  return($ret);
799  }
800 
814  public static function replaceLinkProperties($matches)
815  {
816  $link = $matches[0];
817  $ref_id = $matches[2];
818 
819  if ($ref_id > 0) {
820  $obj_id = ilObject::_lookupObjId($ref_id);
821  if ($obj_id > 0) {
822  $title = ilObject::_lookupTitle($obj_id);
823  $link = "<a href=" . $matches[1] . " target=\"_self\">" . $title . "</a>";
824  }
825  }
826  return $link;
827  }
828 
847  public static function makeDateSelect($prefix, $year = "", $month = "", $day = "", $startyear = "", $a_long_month = true, $a_further_options = array(), $emptyoption = false)
848  {
849  global $DIC;
850 
851  $lng = $DIC->language();
852 
853  $disabled = '';
854  if (isset($a_further_options['disabled']) and $a_further_options['disabled']) {
855  $disabled = 'disabled="disabled" ';
856  }
857 
858  $now = getdate();
859  if (!$emptyoption) {
860  if (!strlen($year)) {
861  $year = $now["year"];
862  }
863  if (!strlen($month)) {
864  $month = $now["mon"];
865  }
866  if (!strlen($day)) {
867  $day = $now["mday"];
868  }
869  }
870 
871  $year = (int) $year;
872  $month = (int) $month;
873  $day = (int) $day;
874 
875  // build day select
876 
877  $sel_day .= '<select class="form-control" ';
878  if (isset($a_further_options['select_attributes'])) {
879  foreach ($a_further_options['select_attributes'] as $name => $value) {
880  $sel_day .= ($name . '="' . $value . '" ');
881  }
882  }
883 
884  $sel_day .= $disabled . "name=\"" . $prefix . "[d]\" id=\"" . $prefix . "_d\">\n";
885 
886  if ($emptyoption) {
887  $sel_day .= "<option value=\"0\">--</option>\n";
888  }
889  for ($i = 1; $i <= 31; $i++) {
890  $sel_day .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
891  }
892  $sel_day .= "</select>\n";
893  $sel_day = preg_replace("/(value\=\"$day\")/", "$1 selected=\"selected\"", $sel_day);
894 
895  // build month select
896  $sel_month = '<select class="form-control" ';
897  if (isset($a_further_options['select_attributes'])) {
898  foreach ($a_further_options['select_attributes'] as $name => $value) {
899  $sel_month .= ($name . '="' . $value . '" ');
900  }
901  }
902  $sel_month .= $disabled . "name=\"" . $prefix . "[m]\" id=\"" . $prefix . "_m\">\n";
903 
904  if ($emptyoption) {
905  $sel_month .= "<option value=\"0\">--</option>\n";
906  }
907  for ($i = 1; $i <= 12; $i++) {
908  if ($a_long_month) {
909  $sel_month .= "<option value=\"$i\">" . $lng->txt("month_" . sprintf("%02d", $i) . "_long") . "</option>\n";
910  } else {
911  $sel_month .= "<option value=\"$i\">" . $i . "</option>\n";
912  }
913  }
914  $sel_month .= "</select>\n";
915  $sel_month = preg_replace("/(value\=\"$month\")/", "$1 selected=\"selected\"", $sel_month);
916 
917  // build year select
918  $sel_year = '<select class="form-control" ';
919  if (isset($a_further_options['select_attributes'])) {
920  foreach ($a_further_options['select_attributes'] as $name => $value) {
921  $sel_year .= ($name . '="' . $value . '" ');
922  }
923  }
924  $sel_year .= $disabled . "name=\"" . $prefix . "[y]\" id=\"" . $prefix . "_y\">\n";
925  if ((strlen($startyear) == 0) || ($startyear > $year)) {
926  if (!$emptyoption || $year != 0) {
927  $startyear = $year - 5;
928  }
929  }
930 
931  if (($year + 5) < (date('Y', time()) + 5)) {
932  $end_year = date('Y', time()) + 5;
933  } else {
934  $end_year = $year + 5;
935  }
936 
937  if ($emptyoption) {
938  $sel_year .= "<option value=\"0\">----</option>\n";
939  }
940  for ($i = $startyear; $i <= $end_year; $i++) {
941  $sel_year .= "<option value=\"$i\">" . sprintf("%04d", $i) . "</option>\n";
942  }
943  $sel_year .= "</select>\n";
944  $sel_year = preg_replace("/(value\=\"$year\")/", "$1 selected=\"selected\"", $sel_year);
945 
946  //$dateformat = $lng->text["lang_dateformat"];
947  $dateformat = "d-m-Y";
948  $dateformat = strtolower(preg_replace("/\W/", "", $dateformat));
949  $dateformat = strtolower(preg_replace("/(\w)/", "%%$1", $dateformat));
950  $dateformat = preg_replace("/%%d/", $sel_day, $dateformat);
951  $dateformat = preg_replace("/%%m/", $sel_month, $dateformat);
952  $dateformat = preg_replace("/%%y/", $sel_year, $dateformat);
953  return $dateformat;
954  }
955 
974  public static function makeTimeSelect($prefix, $short = true, $hour = "", $minute = "", $second = "", $a_use_default = true, $a_further_options = array())
975  {
976  global $DIC;
977 
978  $lng = $DIC->language();
979  $ilUser = $DIC->user();
980 
981  $minute_steps = 1;
982  $disabled = '';
983  if (count($a_further_options)) {
984  if (isset($a_further_options['minute_steps'])) {
985  $minute_steps = $a_further_options['minute_steps'];
986  }
987  if (isset($a_further_options['disabled']) and $a_further_options['disabled']) {
988  $disabled = 'disabled="disabled" ';
989  }
990  }
991 
992  if ($a_use_default and !strlen("$hour$minute$second")) {
993  $now = localtime();
994  $hour = $now[2];
995  $minute = $now[1];
996  $second = $now[0];
997  } else {
998  $hour = (int) $hour;
999  $minute = (int) $minute;
1000  $second = (int) $second;
1001  }
1002  // build hour select
1003  $sel_hour = '<select ';
1004  if (isset($a_further_options['select_attributes'])) {
1005  foreach ($a_further_options['select_attributes'] as $name => $value) {
1006  $sel_hour .= $name . '=' . $value . ' ';
1007  }
1008  }
1009  $sel_hour .= " " . $disabled . "name=\"" . $prefix . "[h]\" id=\"" . $prefix . "_h\" class=\"form-control\">\n";
1010 
1011  $format = $ilUser->getTimeFormat();
1012  for ($i = 0; $i <= 23; $i++) {
1014  $sel_hour .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
1015  } else {
1016  $sel_hour .= "<option value=\"$i\">" . date("ga", mktime($i, 0, 0)) . "</option>\n";
1017  }
1018  }
1019  $sel_hour .= "</select>\n";
1020  $sel_hour = preg_replace("/(value\=\"$hour\")/", "$1 selected=\"selected\"", $sel_hour);
1021 
1022  // build minutes select
1023  $sel_minute .= "<select " . $disabled . "name=\"" . $prefix . "[m]\" id=\"" . $prefix . "_m\" class=\"form-control\">\n";
1024 
1025  for ($i = 0; $i <= 59; $i = $i + $minute_steps) {
1026  $sel_minute .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
1027  }
1028  $sel_minute .= "</select>\n";
1029  $sel_minute = preg_replace("/(value\=\"$minute\")/", "$1 selected=\"selected\"", $sel_minute);
1030 
1031  if (!$short) {
1032  // build seconds select
1033  $sel_second .= "<select " . $disabled . "name=\"" . $prefix . "[s]\" id=\"" . $prefix . "_s\" class=\"form-control\">\n";
1034 
1035  for ($i = 0; $i <= 59; $i++) {
1036  $sel_second .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
1037  }
1038  $sel_second .= "</select>\n";
1039  $sel_second = preg_replace("/(value\=\"$second\")/", "$1 selected=\"selected\"", $sel_second);
1040  }
1041  $timeformat = $lng->text["lang_timeformat"];
1042  if (strlen($timeformat) == 0) {
1043  $timeformat = "H:i:s";
1044  }
1045  $timeformat = strtolower(preg_replace("/\W/", "", $timeformat));
1046  $timeformat = preg_replace("/(\w)/", "%%$1", $timeformat);
1047  $timeformat = preg_replace("/%%h/", $sel_hour, $timeformat);
1048  $timeformat = preg_replace("/%%i/", $sel_minute, $timeformat);
1049  if ($short) {
1050  $timeformat = preg_replace("/%%s/", "", $timeformat);
1051  } else {
1052  $timeformat = preg_replace("/%%s/", $sel_second, $timeformat);
1053  }
1054  return $timeformat;
1055  }
1056 
1070  public static function is_email($a_email, ilMailRfc822AddressParserFactory $mailAddressParserFactory = null)
1071  {
1072  global $DIC;
1073 
1074  $ilErr = $DIC["ilErr"];
1075 
1076  if ($mailAddressParserFactory === null) {
1077  $mailAddressParserFactory = new ilMailRfc822AddressParserFactory();
1078  }
1079  // additional check for ilias object is needed,
1080  // otherwise setup will fail with this if branch
1081  if (is_object($ilErr)) { // seems to work in Setup now
1082  try {
1083  $parser = $mailAddressParserFactory->getParser($a_email);
1084  $addresses = $parser->parse();
1085  return count($addresses) == 1 && $addresses[0]->getHost() != ilMail::ILIAS_HOST;
1086  } catch (ilException $e) {
1087  return false;
1088  }
1089  } else {
1090  $tlds = strtolower(
1091  "AC|AD|AE|AERO|AF|AG|AI|AL|AM|AN|AO|AQ|AR|ARPA|AS|ASIA|AT|AU|AW|AX|AZ|BA|BB|BD|BE|BF|BG|BH|BI|BIZ|BJ|BM|BN|BO|BR|BS|BT|BV|BW|BY|" .
1092  "BZ|CA|CAT|CC|CD|CF|CG|CH|CI|CK|CL|CM|CN|CO|COM|COOP|CR|CU|CV|CX|CY|CZ|DE|DJ|DK|DM|DO|DZ|EC|EDU|EE|EG|" .
1093  "ER|ES|ET|EU|FI|FJ|FK|FM|FO|FR|GA|GB|GD|GE|GF|GG|GH|GI|GL|GM|GN|GOV|GP|GQ|GR|GS|GT|GU|GW|GY|HK|HM|HN|HR|HT|" .
1094  "HU|ID|IE|IL|IM|IN|INFO|INT|IO|IQ|IR|IS|IT|JE|JM|JO|JOBS|JP|KE|KG|KH|KI|KM|KN|KP|KR|KW|KY|KZ|LA|LB|LC|" .
1095  "LI|LK|LR|LS|LT|LU|LV|LY|MA|MC|MD|ME|MG|MH|MIL|MK|ML|MM|MN|MO|MOBI|MP|MQ|MR|MS|MT|MU|MUSEUM|MV|MW|MX|" .
1096  "MY|MZ|NA|NAME|NC|NE|NET|NF|NG|NI|NL|NO|NP|NR|NU|NZ|OM|ORG|PA|PE|PF|PG|PH|PK|PL|PM|PN|PR|PRO|PS|" .
1097  "PT|PW|PY|QA|RE|RO|RS|RU|RW|SA|SB|SC|SD|SE|SG|SH|SI|SJ|SK|SL|SM|SN|SO|SR|ST|SU|SV|SY|SZ|TC|TD|TEL|" .
1098  "TF|TG|TH|TJ|TK|TL|TM|TN|TO|TP|TR|TRAVEL|TT|TV|TW|TZ|UA|UG|UK|US|UY|UZ|VA|VC|VE|VG|VI|VN|VU|" .
1099  "WF|WS|XN|YE|YT|YU|ZA|ZM|ZW"
1100  );
1101 
1102  return(preg_match("/^[-_.[:alnum:]]+@((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(" . $tlds . ")|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i", $a_email));
1103  }
1104  }
1105 
1114  public static function isPassword($a_passwd, &$customError = null)
1115  {
1116  global $DIC;
1117 
1118  $lng = $DIC->language();
1119 
1120  include_once('./Services/PrivacySecurity/classes/class.ilSecuritySettings.php');
1121  $security = ilSecuritySettings::_getInstance();
1122 
1123  // check if password is empty
1124  if (empty($a_passwd)) {
1125  $customError = $lng->txt('password_empty');
1126  return false;
1127  }
1128 
1129  $isPassword = true;
1130  $errors = array();
1131 
1132  // check if password to short
1133  if ($security->getPasswordMinLength() > 0 && strlen($a_passwd) < $security->getPasswordMinLength()) {
1134  $errors[] = sprintf($lng->txt('password_to_short'), $security->getPasswordMinLength());
1135  $isPassword = false;
1136  }
1137 
1138  // check if password not to long
1139  // 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).
1140  if ($security->getPasswordMaxLength() > 0 && strlen($a_passwd) > $security->getPasswordMaxLength()) {
1141  $errors[] = sprintf($lng->txt('password_to_long'), $security->getPasswordMaxLength());
1142  $isPassword = false;
1143  }
1144 
1145  // if password must contains Chars and Numbers
1146  if ($security->isPasswordCharsAndNumbersEnabled()) {
1147  $hasCharsAndNumbers = true;
1148 
1149  // check password for existing chars
1150  if (!preg_match('/[A-Za-z]+/', $a_passwd)) {
1151  $hasCharsAndNumbers = false;
1152  }
1153 
1154  // check password for existing numbers
1155  if (!preg_match('/[0-9]+/', $a_passwd)) {
1156  $hasCharsAndNumbers = false;
1157  }
1158 
1159  if (!$hasCharsAndNumbers) {
1160  $errors[] = $lng->txt('password_must_chars_and_numbers');
1161  $isPassword = false;
1162  }
1163  }
1164 
1165  require_once 'Services/Utilities/classes/class.ilStr.php';
1166  if ($security->getPasswordNumberOfUppercaseChars() > 0) {
1167  if (ilStr::strLen($a_passwd) - ilStr::strLen(preg_replace('/[A-Z]/', '', $a_passwd)) < $security->getPasswordNumberOfUppercaseChars()) {
1168  $errors[] = sprintf($lng->txt('password_must_contain_ucase_chars'), $security->getPasswordNumberOfUppercaseChars());
1169  $isPassword = false;
1170  }
1171  }
1172 
1173  if ($security->getPasswordNumberOfLowercaseChars() > 0) {
1174  if (ilStr::strLen($a_passwd) - ilStr::strLen(preg_replace('/[a-z]/', '', $a_passwd)) < $security->getPasswordNumberOfLowercaseChars()) {
1175  $errors[] = sprintf($lng->txt('password_must_contain_lcase_chars'), $security->getPasswordNumberOfLowercaseChars());
1176  $isPassword = false;
1177  }
1178  }
1179 
1180  // if password must contains Special-Chars
1181  if ($security->isPasswordSpecialCharsEnabled()) {
1182  // check password for existing special-chars
1183  if (!preg_match(self::getPasswordValidChars(true, true), $a_passwd)) {
1184  $errors[] = $lng->txt('password_must_special_chars');
1185  $isPassword = false;
1186  }
1187  }
1188 
1189  // ensure password matches the positive list of chars/special-chars
1190  if (!preg_match(self::getPasswordValidChars(), $a_passwd)) {
1191  $errors[] = $lng->txt('password_contains_invalid_chars');
1192  $isPassword = false;
1193  }
1194 
1195  // build custom error message
1196  if (count($errors) == 1) {
1197  $customError = $errors[0];
1198  } elseif (count($errors) > 1) {
1199  $customError = $lng->txt('password_multiple_errors');
1200  $customError .= '<br />' . implode('<br />', $errors);
1201  }
1202 
1203  return $isPassword;
1204  }
1205 
1212  public static function isPasswordValidForUserContext($clear_text_password, $user, &$error_language_variable = null)
1213  {
1214  include_once 'Services/PrivacySecurity/classes/class.ilSecuritySettings.php';
1215  $security = ilSecuritySettings::_getInstance();
1216 
1217  $login = null;
1218 
1219  if (is_string($user)) {
1220  $login = $user;
1221  } elseif (is_array($user)) {
1222  // Try to get loginname and user_id from array
1223  $login = $user['login'];
1224  $userId = $user['id'];
1225  } elseif ($user instanceof ilObjUser) {
1226  $login = $user->getLogin();
1227  $userId = $user->getId();
1228  }
1229 
1230  // 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.
1231 
1232  if ($login && (int) $security->getPasswordMustNotContainLoginnameStatus() &&
1233  strpos(strtolower($clear_text_password), strtolower($login)) !== false
1234  ) {
1235  $error_language_variable = 'password_contains_parts_of_login_err';
1236  return false;
1237  }
1238 
1239  return true;
1240  }
1241 
1249  public static function getPasswordValidChars($a_as_regex = true, $a_only_special_chars = false)
1250  {
1251  if ($a_as_regex) {
1252  if ($a_only_special_chars) {
1253  return '/[_\.\+\?\#\-\*\@!\$\%\~\/\:\;]+/';
1254  } else {
1255  return '/^[A-Za-z0-9_\.\+\?\#\-\*\@!\$\%\~\/\:\;]+$/';
1256  }
1257  } else {
1258  return 'A-Z a-z 0-9 _.+?#-*@!$%~/:;';
1259  }
1260  }
1261 
1269  public static function getPasswordRequirementsInfo()
1270  {
1271  global $DIC;
1272 
1273  $lng = $DIC->language();
1274 
1275  include_once('./Services/PrivacySecurity/classes/class.ilSecuritySettings.php');
1276  $security = ilSecuritySettings::_getInstance();
1277 
1278  $infos = array(sprintf($lng->txt('password_allow_chars'), self::getPasswordValidChars(false)));
1279 
1280  // check if password to short
1281  if ($security->getPasswordMinLength() > 0) {
1282  $infos[] = sprintf($lng->txt('password_to_short'), $security->getPasswordMinLength());
1283  }
1284 
1285  // check if password not to long
1286  if ($security->getPasswordMaxLength() > 0) {
1287  $infos[] = sprintf($lng->txt('password_to_long'), $security->getPasswordMaxLength());
1288  }
1289 
1290  // if password must contains Chars and Numbers
1291  if ($security->isPasswordCharsAndNumbersEnabled()) {
1292  $infos[] = $lng->txt('password_must_chars_and_numbers');
1293  }
1294 
1295  // if password must contains Special-Chars
1296  if ($security->isPasswordSpecialCharsEnabled()) {
1297  $infos[] = $lng->txt('password_must_special_chars');
1298  }
1299 
1300  if ($security->getPasswordNumberOfUppercaseChars() > 0) {
1301  $infos[] = sprintf($lng->txt('password_must_contain_ucase_chars'), $security->getPasswordNumberOfUppercaseChars());
1302  }
1303 
1304  if ($security->getPasswordNumberOfLowercaseChars() > 0) {
1305  $infos[] = sprintf($lng->txt('password_must_contain_lcase_chars'), $security->getPasswordNumberOfLowercaseChars());
1306  }
1307 
1308  return implode('<br />', $infos);
1309  }
1310 
1311  /*
1312  * validates a login
1313  * @access public
1314  * @param string login
1315  * @return boolean true if valid
1316  */
1317  public static function isLogin($a_login)
1318  {
1319  if (empty($a_login)) {
1320  return false;
1321  }
1322 
1323  if (strlen($a_login) < 3) {
1324  return false;
1325  }
1326 
1327  // FIXME - If ILIAS is configured to use RFC 822
1328  // compliant mail addresses we should not
1329  // allow the @ character.
1330  if (!preg_match("/^[A-Za-z0-9_\.\+\*\@!\$\%\~\-]+$/", $a_login)) {
1331  return false;
1332  }
1333 
1334  return true;
1335  }
1336 
1350  public static function shortenText(
1351  $a_str,
1352  $a_len,
1353  $a_dots = false,
1354  $a_next_blank = false,
1355  $a_keep_extension = false
1356  ) {
1357  include_once("./Services/Utilities/classes/class.ilStr.php");
1358  if (ilStr::strLen($a_str) > $a_len) {
1359  if ($a_next_blank) {
1360  $len = ilStr::strPos($a_str, " ", $a_len);
1361  } else {
1362  $len = $a_len;
1363  }
1364  // BEGIN WebDAV
1365  // - Shorten names in the middle, before the filename extension
1366  // Workaround for Windows WebDAV Client:
1367  // Use the unicode ellipsis symbol for shortening instead of
1368  // three full stop characters.
1369  if ($a_keep_extension) {
1370  $p = strrpos($a_str, '.'); // this messes up normal shortening, see bug #6190
1371  }
1372  if ($p === false || $p == 0 || strlen($a_str) - $p > $a_len) {
1373  $a_str = ilStr::subStr($a_str, 0, $len);
1374  if ($a_dots) {
1375  $a_str .= "\xe2\x80\xa6"; // UTF-8 encoding for Unicode ellipsis character.
1376  }
1377  } else {
1378  if ($a_dots) {
1379  $a_str = ilStr::subStr($a_str, 0, $len - (strlen($a_str) - $p + 1)) . "\xe2\x80\xa6" . substr($a_str, $p);
1380  } else {
1381  $a_str = ilStr::subStr($a_str, 0, $len - (strlen($a_str) - $p + 1)) . substr($a_str, $p);
1382  }
1383  }
1384  }
1385 
1386  return $a_str;
1387  }
1388 
1389 
1402  public static function shortenWords($a_str, $a_len = 30, $a_dots = true)
1403  {
1404  include_once("./Services/Utilities/classes/class.ilStr.php");
1405  $str_arr = explode(" ", $a_str);
1406 
1407  for ($i = 0; $i < count($str_arr); $i++) {
1408  if (ilStr::strLen($str_arr[$i]) > $a_len) {
1409  $str_arr[$i] = ilStr::subStr($str_arr[$i], 0, $a_len);
1410  if ($a_dots) {
1411  $str_arr[$i].= "...";
1412  }
1413  }
1414  }
1415 
1416  return implode($str_arr, " ");
1417  }
1418 
1428  public static function attribsToArray($a_str)
1429  {
1430  $attribs = array();
1431  while (is_int(strpos($a_str, "="))) {
1432  $eq_pos = strpos($a_str, "=");
1433  $qu1_pos = strpos($a_str, "\"");
1434  $qu2_pos = strpos(substr($a_str, $qu1_pos + 1), "\"") + $qu1_pos + 1;
1435  if (is_int($eq_pos) && is_int($qu1_pos) && is_int($qu2_pos)) {
1436  $var = trim(substr($a_str, 0, $eq_pos));
1437  $val = trim(substr($a_str, $qu1_pos + 1, ($qu2_pos - $qu1_pos) - 1));
1438  $attribs[$var] = $val;
1439  $a_str = substr($a_str, $qu2_pos + 1);
1440  } else {
1441  $a_str = "";
1442  }
1443  }
1444  return $attribs;
1445  }
1446 
1447 
1465  public static function rCopy($a_sdir, $a_tdir, $preserveTimeAttributes = false)
1466  {
1467  $sourceFS = LegacyPathHelper::deriveFilesystemFrom($a_sdir);
1468  $targetFS = LegacyPathHelper::deriveFilesystemFrom($a_tdir);
1469 
1470  $sourceDir = LegacyPathHelper::createRelativePath($a_sdir);
1471  $targetDir = LegacyPathHelper::createRelativePath($a_tdir);
1472 
1473  // check if arguments are directories
1474  if (!$sourceFS->hasDir($sourceDir)) {
1475  return false;
1476  }
1477 
1478  $sourceList = $sourceFS->listContents($sourceDir, true);
1479 
1480  foreach ($sourceList as $item) {
1481  if ($item->isDir()) {
1482  continue;
1483  }
1484  try {
1485  $itemPath = $targetDir . '/' . substr($item->getPath(), strlen($sourceDir));
1486  $stream = $sourceFS->readStream($item->getPath());
1487  $targetFS->writeStream($itemPath, $stream);
1488  } catch (\ILIAS\Filesystem\Exception\FileAlreadyExistsException $e) {
1489  // Do nothing with that type of exception
1490  }
1491  }
1492 
1493  return true;
1494  }
1495 
1496 
1512  public static function getWebspaceDir($mode = "filesystem")
1513  {
1514  if ($mode == "filesystem") {
1515  return "./" . ILIAS_WEB_DIR . "/" . CLIENT_ID;
1516  } else {
1517  if (defined("ILIAS_MODULE")) {
1518  return "../" . ILIAS_WEB_DIR . "/" . CLIENT_ID;
1519  } else {
1520  return "./" . ILIAS_WEB_DIR . "/" . CLIENT_ID;
1521  }
1522  }
1523  }
1524 
1535  public static function getDataDir()
1536  {
1537  return CLIENT_DATA_DIR;
1538  }
1539 
1549  public static function getUsersOnline($a_user_id = 0)
1550  {
1551  include_once("./Services/User/classes/class.ilObjUser.php");
1552  return ilObjUser::_getUsersOnline($a_user_id);
1553  }
1554 
1565  public static function getAssociatedUsersOnline($a_user_id)
1566  {
1567  include_once("./Services/User/classes/class.ilObjUser.php");
1568  return ilObjUser::_getAssociatedUsersOnline($a_user_id);
1569  }
1570 
1578  public static function ilTempnam($a_temp_path = null)
1579  {
1580  if ($a_temp_path === null) {
1581  $temp_path = ilUtil::getDataDir() . "/temp";
1582  } else {
1583  $temp_path = $a_temp_path;
1584  }
1585 
1586  if (!is_dir($temp_path)) {
1587  ilUtil::createDirectory($temp_path);
1588  }
1589  $temp_name = tempnam($temp_path, "tmp");
1590  // --->
1591  // added the following line because tempnam creates a backslash on some
1592  // Windows systems which leads to problems, because the "...\tmp..." can be
1593  // interpreted as "...{TAB-CHARACTER}...". The normal slash works fine
1594  // even under windows (Helmut Schottmüller, 2005-08-31)
1595  $temp_name = str_replace("\\", "/", $temp_name);
1596  // --->
1597  unlink($temp_name);
1598  return $temp_name;
1599  }
1600 
1601 
1614  public static function createDirectory($a_dir, $a_mod = 0755)
1615  {
1616  ilUtil::makeDir($a_dir);
1617  //@mkdir($a_dir);
1618  //@chmod($a_dir, $a_mod);
1619  }
1620 
1621 
1630  public static function unzip($a_file, $overwrite = false, $a_flat = false)
1631  {
1632  global $DIC;
1633 
1634  $log = $DIC->logger()->root();
1635 
1636  if (!is_file($a_file)) {
1637  return;
1638  }
1639 
1640  // if flat, move file to temp directory first
1641  if ($a_flat) {
1642  $tmpdir = ilUtil::ilTempnam();
1643  ilUtil::makeDir($tmpdir);
1644  copy($a_file, $tmpdir . DIRECTORY_SEPARATOR . basename($a_file));
1645  $orig_file = $a_file;
1646  $a_file = $tmpdir . DIRECTORY_SEPARATOR . basename($a_file);
1647  $origpathinfo = pathinfo($orig_file);
1648  }
1649 
1650  $pathinfo = pathinfo($a_file);
1651  $dir = $pathinfo["dirname"];
1652  $file = $pathinfo["basename"];
1653 
1654  // unzip
1655  $cdir = getcwd();
1656  chdir($dir);
1657  $unzip = PATH_TO_UNZIP;
1658 
1659  // the following workaround has been removed due to bug
1660  // http://www.ilias.de/mantis/view.php?id=7578
1661  // since the workaround is quite old, it may not be necessary
1662  // anymore, alex 9 Oct 2012
1663  /*
1664  // workaround for unzip problem (unzip of subdirectories fails, so
1665  // we create the subdirectories ourselves first)
1666  // get list
1667  $unzipcmd = "-Z -1 ".ilUtil::escapeShellArg($file);
1668  $arr = ilUtil::execQuoted($unzip, $unzipcmd);
1669  $zdirs = array();
1670 
1671  foreach($arr as $line)
1672  {
1673  if(is_int(strpos($line, "/")))
1674  {
1675  $zdir = substr($line, 0, strrpos($line, "/"));
1676  $nr = substr_count($zdir, "/");
1677  //echo $zdir." ".$nr."<br>";
1678  while ($zdir != "")
1679  {
1680  $nr = substr_count($zdir, "/");
1681  $zdirs[$zdir] = $nr; // collect directories
1682  //echo $dir." ".$nr."<br>";
1683  $zdir = substr($zdir, 0, strrpos($zdir, "/"));
1684  }
1685  }
1686  }
1687 
1688  asort($zdirs);
1689 
1690  foreach($zdirs as $zdir => $nr) // create directories
1691  {
1692  ilUtil::createDirectory($zdir);
1693  }
1694  */
1695 
1696  // real unzip
1697  if (!$overwrite) {
1698  $unzipcmd = ilUtil::escapeShellArg($file);
1699  } else {
1700  $unzipcmd = "-o " . ilUtil::escapeShellArg($file);
1701  }
1702  ilUtil::execQuoted($unzip, $unzipcmd);
1703 
1704  chdir($cdir);
1705 
1706  // remove all sym links
1707  clearstatcache(); // prevent is_link from using cache
1708  $dir_realpath = realpath($dir);
1709  foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)) as $name => $f) {
1710  if (is_link($name)) {
1711  $target = readlink($name);
1712  if (substr($target, 0, strlen($dir_realpath)) != $dir_realpath) {
1713  unlink($name);
1714  $log->info("Removed symlink " . $name);
1715  }
1716  }
1717  }
1718 
1719  // if flat, get all files and move them to original directory
1720  if ($a_flat) {
1721  include_once("./Services/Utilities/classes/class.ilFileUtils.php");
1722  $filearray = array();
1723  ilFileUtils::recursive_dirscan($tmpdir, $filearray);
1724  if (is_array($filearray["file"])) {
1725  foreach ($filearray["file"] as $k => $f) {
1726  if (substr($f, 0, 1) != "." && $f != basename($orig_file)) {
1727  copy($filearray["path"][$k] . $f, $origpathinfo["dirname"] . DIRECTORY_SEPARATOR . $f);
1728  }
1729  }
1730  }
1731  ilUtil::delDir($tmpdir);
1732  }
1733  }
1734 
1741  public static function zip($a_dir, $a_file, $compress_content = false)
1742  {
1743  $cdir = getcwd();
1744 
1745  if ($compress_content) {
1746  $a_dir .="/*";
1747  $pathinfo = pathinfo($a_dir);
1748  chdir($pathinfo["dirname"]);
1749  }
1750 
1751  $pathinfo = pathinfo($a_file);
1752  $dir = $pathinfo["dirname"];
1753  $file = $pathinfo["basename"];
1754 
1755  if (!$compress_content) {
1756  chdir($dir);
1757  }
1758 
1759  $zip = PATH_TO_ZIP;
1760 
1761  if (!$zip) {
1762  chdir($cdir);
1763  return false;
1764  }
1765 
1766  if (is_array($a_dir)) {
1767  $source = "";
1768  foreach ($a_dir as $dir) {
1769  $name = basename($dir);
1771  }
1772  } else {
1773  $name = basename($a_dir);
1774  if (trim($name) != "*") {
1776  } else {
1777  $source = $name;
1778  }
1779  }
1780 
1781  $zipcmd = "-r " . ilUtil::escapeShellArg($a_file) . " " . $source;
1782  ilUtil::execQuoted($zip, $zipcmd);
1783  chdir($cdir);
1784  return true;
1785  }
1786 
1787  public static function CreateIsoFromFolder($a_dir, $a_file)
1788  {
1789  $cdir = getcwd();
1790 
1791  $pathinfo = pathinfo($a_dir);
1792  chdir($pathinfo["dirname"]);
1793 
1794  $pathinfo = pathinfo($a_file);
1795  $dir = $pathinfo["dirname"];
1796  $file = $pathinfo["basename"];
1797  $zipcmd = "-r " . ilUtil::escapeShellArg($a_file) . " " . $source;
1798 
1799  $mkisofs = PATH_TO_MKISOFS;
1800  if (!$mkisofs) {
1801  chdir($cdir);
1802  return false;
1803  }
1804 
1805  $name = basename($a_dir);
1807 
1808  $zipcmd = "-r -J -o " . $a_file . " " . $source;
1809  ilUtil::execQuoted($mkisofs, $zipcmd);
1810  chdir($cdir);
1811  return true;
1812  }
1813 
1822  public static function getConvertCmd()
1823  {
1824  return PATH_TO_CONVERT;
1825  }
1826 
1834  public static function execConvert($args)
1835  {
1836  ilUtil::execQuoted(PATH_TO_CONVERT, $args);
1837  }
1838 
1845  public static function isConvertVersionAtLeast($a_version)
1846  {
1847  $current_version = ilUtil::execQuoted(PATH_TO_CONVERT, "--version");
1848  $current_version = self::processConvertVersion($current_version[0]);
1849  $version = self::processConvertVersion($a_version);
1850  if ($current_version >= $version) {
1851  return true;
1852  }
1853  return false;
1854  }
1855 
1862  protected static function processConvertVersion($a_version)
1863  {
1864  if (preg_match("/([0-9]+)\.([0-9]+)\.([0-9]+)([\.|\-]([0-9]+))?/", $a_version, $match)) {
1865  $version = str_pad($match[1], 2, 0, STR_PAD_LEFT) .
1866  str_pad($match[2], 2, 0, STR_PAD_LEFT) .
1867  str_pad($match[3], 2, 0, STR_PAD_LEFT) .
1868  str_pad($match[5], 2, 0, STR_PAD_LEFT);
1869  return (int) $version;
1870  }
1871  }
1872 
1882  public static function convertImage(
1883  $a_from,
1884  $a_to,
1885  $a_target_format = "",
1886  $a_geometry = "",
1887  $a_background_color = ""
1888  ) {
1889  $format_str = ($a_target_format != "")
1890  ? strtoupper($a_target_format) . ":"
1891  : "";
1892  $geometry = "";
1893  if ($a_geometry != "") {
1894  if (is_int(strpos($a_geometry, "x"))) {
1895  $geometry = " -geometry " . $a_geometry . " ";
1896  } else {
1897  $geometry = " -geometry " . $a_geometry . "x" . $a_geometry . " ";
1898  }
1899  }
1900 
1901  $bg_color = ($a_background_color != "")
1902  ? " -background color " . $a_background_color . " "
1903  : "";
1904  $convert_cmd = ilUtil::escapeShellArg($a_from) . " " . $bg_color . $geometry . ilUtil::escapeShellArg($format_str . $a_to);
1905 
1906  ilUtil::execConvert($convert_cmd);
1907  }
1908 
1919  public static function resizeImage($a_from, $a_to, $a_width, $a_height, $a_constrain_prop = false)
1920  {
1921  if ($a_constrain_prop) {
1922  $size = " -geometry " . $a_width . "x" . $a_height . " ";
1923  } else {
1924  $size = " -resize " . $a_width . "x" . $a_height . "! ";
1925  }
1926  $convert_cmd = ilUtil::escapeShellArg($a_from) . " " . $size . ilUtil::escapeShellArg($a_to);
1927 
1928  ilUtil::execConvert($convert_cmd);
1929  }
1930 
1937  public static function img($a_src, $a_alt = "", $a_width = "", $a_height = "", $a_border = 0, $a_id = "", $a_class = "")
1938  {
1939  $img = '<img src="' . $a_src . '"';
1940  if ($a_alt != "") {
1941  $img.= ' alt="' . htmlspecialchars($a_alt) . '" title="' . htmlspecialchars($a_alt) . '"';
1942  }
1943  if ($a_width != "") {
1944  $img.= ' width="' . htmlspecialchars($a_width) . '"';
1945  }
1946  if ($a_height != "") {
1947  $img.= ' height="' . htmlspecialchars($a_height) . '"';
1948  }
1949  if ($a_class != "") {
1950  $img.= ' class="' . $a_class . '"';
1951  }
1952  if ($a_id != "") {
1953  $img.= ' id="' . $a_id . '"';
1954  }
1955  $img.= ' border="' . (int) $a_border . '"/>';
1956 
1957  return $img;
1958  }
1959 
1966  public static function deliverData($a_data, $a_filename, $mime = "application/octet-stream", $charset = "")
1967  {
1968  $disposition = "attachment"; // "inline" to view file in browser or "attachment" to download to hard disk
1969  // $mime = "application/octet-stream"; // or whatever the mime type is
1970 
1971  include_once './Services/Http/classes/class.ilHTTPS.php';
1972 
1973  //if($_SERVER['HTTPS'])
1974  if (ilHTTPS::getInstance()->isDetected()) {
1975 
1976  // Added different handling for IE and HTTPS => send pragma after content informations
1980  #header("Pragma: ");
1981  #header("Cache-Control: ");
1982  #header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
1983  #header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
1984  #header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1
1985  #header("Cache-Control: post-check=0, pre-check=0", false);
1986  } elseif ($disposition == "attachment") {
1987  header("Cache-control: private");
1988  } else {
1989  header("Cache-Control: no-cache, must-revalidate");
1990  header("Pragma: no-cache");
1991  }
1992 
1994 
1995  if (strlen($charset)) {
1996  $charset = "; charset=$charset";
1997  }
1998  header("Content-Type: $mime$charset");
1999  header("Content-Disposition:$disposition; filename=\"" . $ascii_filename . "\"");
2000  header("Content-Description: " . $ascii_filename);
2001  header("Content-Length: " . (string) (strlen($a_data)));
2002 
2003  //if($_SERVER['HTTPS'])
2004  if (ilHTTPS::getInstance()->isDetected()) {
2005  header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
2006  header('Pragma: public');
2007  }
2008 
2009  header("Connection: close");
2010  echo $a_data;
2011  exit;
2012  }
2013 
2014  // BEGIN WebDAV: Show file in browser or provide it as attachment
2022  public static function deliverFile(
2023  $a_file,
2024  $a_filename,
2025  $a_mime = '',
2026  $isInline = false,
2027  $removeAfterDelivery = false,
2028  $a_exit_after = true
2029  ) {
2030  global $DIC;
2031  // should we fail silently?
2032  if (!file_exists($a_file)) {
2033  return false;
2034  }
2035  $delivery = new ilFileDelivery($a_file);
2036 
2037  if ($isInline) {
2038  $delivery->setDisposition(ilFileDelivery::DISP_INLINE);
2039  } else {
2040  $delivery->setDisposition(ilFileDelivery::DISP_ATTACHMENT);
2041  }
2042 
2043  if (strlen($a_mime)) {
2044  $delivery->setMimeType($a_mime);
2045  }
2046 
2047  $delivery->setDownloadFileName($a_filename);
2048  $delivery->setConvertFileNameToAsci((bool) !$DIC['ilClientIniFile']->readVariable('file_access', 'disable_ascii'));
2049  $delivery->setDeleteFile($removeAfterDelivery);
2050  $delivery->deliver();
2051  }
2052 
2053 
2063  public static function readFile($a_file)
2064  {
2065  $chunksize = 1*(1024*1024); // how many bytes per chunk
2066  $buffer = '';
2067  $handle = fopen($a_file, 'rb');
2068  if ($handle === false) {
2069  return false;
2070  }
2071  while (!feof($handle)) {
2072  $buffer = fread($handle, $chunksize);
2073  print $buffer;
2074  }
2075  return fclose($handle);
2076  }
2077 
2085  public static function getASCIIFilename($a_filename)
2086  {
2087  // The filename must be converted to ASCII, as of RFC 2183,
2088  // section 2.3.
2089 
2101 
2104 
2105  // #15914 - try to fix german umlauts
2106  $umlauts = array("Ä"=>"Ae", "Ö"=>"Oe", "Ãœ"=>"Ue",
2107  "ä"=>"ae", "ö"=>"oe", "ü"=>"ue", "ß"=>"ss");
2108  foreach ($umlauts as $src => $tgt) {
2109  $a_filename = str_replace($src, $tgt, $a_filename);
2110  }
2111 
2112  $ascii_filename = htmlentities($a_filename, ENT_NOQUOTES, 'UTF-8');
2113  $ascii_filename = preg_replace('/\&(.)[^;]*;/', '\\1', $ascii_filename);
2114  $ascii_filename = preg_replace('/[\x7f-\xff]/', '_', $ascii_filename);
2115 
2116  // OS do not allow the following characters in filenames: \/:*?"<>|
2117  $ascii_filename = preg_replace('/[:\x5c\/\*\?\"<>\|]/', '_', $ascii_filename);
2118  return $ascii_filename;
2119  }
2120 
2127  public static function htmlentitiesOutsideHTMLTags($htmlText)
2128  {
2129  $matches = array();
2130  $sep = '###HTMLTAG###';
2131 
2132  preg_match_all("@<[^>]*>@", $htmlText, $matches);
2133  $tmp = preg_replace("@(<[^>]*>)@", $sep, $htmlText);
2134  $tmp = explode($sep, $tmp);
2135 
2136  for ($i=0; $i<count($tmp); $i++) {
2137  $tmp[$i] = htmlentities($tmp[$i], ENT_COMPAT, "UTF-8");
2138  }
2139 
2140  $tmp = join($sep, $tmp);
2141 
2142  for ($i=0; $i<count($matches[0]); $i++) {
2143  $tmp = preg_replace("@$sep@", $matches[0][$i], $tmp, 1);
2144  }
2145 
2146  return $tmp;
2147  }
2148 
2155  public static function getJavaPath()
2156  {
2157  return PATH_TO_JAVA;
2158  //global $ilias;
2159 
2160  //return $ilias->getSetting("java_path");
2161  }
2162 
2170  public static function appendUrlParameterString($a_url, $a_par, $xml_style = false)
2171  {
2172  $amp = $xml_style
2173  ? "&amp;"
2174  : "&";
2175 
2176  $url = (is_int(strpos($a_url, "?")))
2177  ? $a_url . $amp . $a_par
2178  : $a_url . "?" . $a_par;
2179 
2180  return $url;
2181  }
2182 
2201  public static function makeDir($a_dir)
2202  {
2203  $a_dir = trim($a_dir);
2204 
2205  // remove trailing slash (bugfix for php 4.2.x)
2206  if (substr($a_dir, -1) == "/") {
2207  $a_dir = substr($a_dir, 0, -1);
2208  }
2209 
2210  // check if a_dir comes with a path
2211  if (!($path = substr($a_dir, 0, strrpos($a_dir, "/") - strlen($a_dir)))) {
2212  $path = ".";
2213  }
2214 
2215  // create directory with file permissions of parent directory
2216  umask(0000);
2217  return @mkdir($a_dir, fileperms($path));
2218  }
2219 
2220 
2240  public static function makeDirParents($a_dir)
2241  {
2242  $dirs = array($a_dir);
2243  $a_dir = dirname($a_dir);
2244  $last_dirname = '';
2245 
2246  while ($last_dirname != $a_dir) {
2247  array_unshift($dirs, $a_dir);
2248  $last_dirname = $a_dir;
2249  $a_dir = dirname($a_dir);
2250  }
2251 
2252  // find the first existing dir
2253  $reverse_paths = array_reverse($dirs, true);
2254  $found_index = -1;
2255  foreach ($reverse_paths as $key => $value) {
2256  if ($found_index == -1) {
2257  if (is_dir($value)) {
2258  $found_index = $key;
2259  }
2260  }
2261  }
2262 
2263  umask(0000);
2264  foreach ($dirs as $dirindex => $dir) {
2265  // starting with the longest existing path
2266  if ($dirindex >= $found_index) {
2267  if (!file_exists($dir)) {
2268  if (strcmp(substr($dir, strlen($dir)-1, 1), "/") == 0) {
2269  // on some systems there is an error when there is a slash
2270  // at the end of a directory in mkdir, see Mantis #2554
2271  $dir = substr($dir, 0, strlen($dir)-1);
2272  }
2273  if (!mkdir($dir, $umask)) {
2274  error_log("Can't make directory: $dir");
2275  return false;
2276  }
2277  } elseif (!is_dir($dir)) {
2278  error_log("$dir is not a directory");
2279  return false;
2280  } else {
2281  // get umask of the last existing parent directory
2282  $umask = fileperms($dir);
2283  }
2284  }
2285  }
2286  return true;
2287  }
2288 
2289 
2305  public static function delDir($a_dir, $a_clean_only = false)
2306  {
2307  if (!is_dir($a_dir) || is_int(strpos($a_dir, ".."))) {
2308  return;
2309  }
2310 
2311  $current_dir = opendir($a_dir);
2312 
2313  $files = array();
2314 
2315  // this extra loop has been necessary because of a strange bug
2316  // at least on MacOS X. A looped readdir() didn't work
2317  // correctly with larger directories
2318  // when an unlink happened inside the loop. Getting all files
2319  // into the memory first solved the problem.
2320  while ($entryname = readdir($current_dir)) {
2321  $files[] = $entryname;
2322  }
2323 
2324  foreach ($files as $file) {
2325  if (is_dir($a_dir . "/" . $file) and ($file != "." and $file!="..")) {
2326  ilUtil::delDir($a_dir . "/" . $file);
2327  } elseif ($file != "." and $file != "..") {
2328  unlink($a_dir . "/" . $file);
2329  }
2330  }
2331 
2332  closedir($current_dir);
2333  if (!$a_clean_only) {
2334  @rmdir($a_dir);
2335  }
2336  }
2337 
2338 
2354  public static function getDir($a_dir, $a_rec = false, $a_sub_dir = "")
2355  {
2356  $current_dir = opendir($a_dir . $a_sub_dir);
2357 
2358  $dirs = array();
2359  $files = array();
2360  $subitems = array();
2361  while ($entry = readdir($current_dir)) {
2362  if (is_dir($a_dir . "/" . $entry)) {
2363  $dirs[$entry] = array("type" => "dir", "entry" => $entry,
2364  "subdir" => $a_sub_dir);
2365  if ($a_rec && $entry != "." && $entry != "..") {
2366  $si = ilUtil::getDir($a_dir, true, $a_sub_dir . "/" . $entry);
2367  $subitems = array_merge($subitems, $si);
2368  }
2369  } else {
2370  if ($entry != "." && $entry != "..") {
2371  $size = filesize($a_dir . $a_sub_dir . "/" . $entry);
2372  $files[$entry] = array("type" => "file", "entry" => $entry,
2373  "size" => $size, "subdir" => $a_sub_dir);
2374  }
2375  }
2376  }
2377  ksort($dirs);
2378  ksort($files);
2379 
2380  return array_merge($dirs, $files, $subitems);
2381  }
2382 
2389  public static function stripSlashesArray($a_arr, $a_strip_html = true, $a_allow = "")
2390  {
2391  if (is_array($a_arr)) {
2392  foreach ($a_arr as $k => $v) {
2393  $a_arr[$k] = ilUtil::stripSlashes($v, $a_strip_html, $a_allow);
2394  }
2395  }
2396 
2397  return $a_arr;
2398  }
2399 
2404  public static function getClientIdByString($clientId)
2405  {
2406  $df = new \ILIAS\Data\Factory;
2407 
2408  return $df->clientId($clientId);
2409  }
2410 
2417  public static function stripSlashesRecursive($a_data, $a_strip_html = true, $a_allow = "")
2418  {
2419  if (is_array($a_data)) {
2420  foreach ($a_data as $k => $v) {
2421  if (is_array($v)) {
2422  $a_data[$k] = ilUtil::stripSlashesRecursive($v, $a_strip_html, $a_allow);
2423  } else {
2424  $a_data[$k] = ilUtil::stripSlashes($v, $a_strip_html, $a_allow);
2425  }
2426  }
2427  } else {
2428  $a_data = ilUtil::stripSlashes($a_data, $a_strip_html, $a_allow);
2429  }
2430 
2431  return $a_data;
2432  }
2433 
2441  public static function stripSlashes($a_str, $a_strip_html = true, $a_allow = "")
2442  {
2443  if (ini_get("magic_quotes_gpc")) {
2444  $a_str = stripslashes($a_str);
2445  }
2446  //echo "<br><br>-".$a_strip_html."-".htmlentities($a_str);
2447  //echo "<br>-".htmlentities(ilUtil::secureString($a_str, $a_strip_html, $a_allow));
2448  return ilUtil::secureString($a_str, $a_strip_html, $a_allow);
2449  }
2450 
2458  public static function stripOnlySlashes($a_str)
2459  {
2460  if (ini_get("magic_quotes_gpc")) {
2461  $a_str = stripslashes($a_str);
2462  }
2463 
2464  return $a_str;
2465  }
2466 
2473  public static function secureString($a_str, $a_strip_html = true, $a_allow = "")
2474  {
2475  // check whether all allowed tags can be made secure
2476  $only_secure = true;
2477  $allow_tags = explode(">", $a_allow);
2478  $sec_tags = ilUtil::getSecureTags();
2479  $allow_array = array();
2480  foreach ($allow_tags as $allow) {
2481  if ($allow != "") {
2482  $allow = str_replace("<", "", $allow);
2483 
2484  if (!in_array($allow, $sec_tags)) {
2485  $only_secure = false;
2486  }
2487  $allow_array[] = $allow;
2488  }
2489  }
2490 
2491  // default behaviour: allow only secure tags 1:1
2492  if (($only_secure || $a_allow == "") && $a_strip_html) {
2493  if ($a_allow == "") {
2494  $allow_array = array("b", "i", "strong", "em", "code", "cite",
2495  "gap", "sub", "sup", "pre", "strike", "bdo");
2496  }
2497 
2498  // this currently removes parts of strings like "a <= b"
2499  // because "a <= b" is treated like "<spam onclick='hurt()'>ss</spam>"
2500  $a_str = ilUtil::maskSecureTags($a_str, $allow_array);
2501  $a_str = strip_tags($a_str); // strip all other tags
2502  $a_str = ilUtil::unmaskSecureTags($a_str, $allow_array);
2503 
2504  // a possible solution could be something like:
2505  // $a_str = str_replace("<", "&lt;", $a_str);
2506  // $a_str = str_replace(">", "&gt;", $a_str);
2507  // $a_str = ilUtil::unmaskSecureTags($a_str, $allow_array);
2508  //
2509  // output would be ok then, but input fields would show
2510  // "a &lt;= b" for input "a <= b" if data is brought back to a form
2511  } else {
2512  // only for scripts, that need to allow more/other tags and parameters
2513  if ($a_strip_html) {
2514  $a_str = ilUtil::stripScriptHTML($a_str, $a_allow);
2515  }
2516  }
2517 
2518  return $a_str;
2519  }
2520 
2521  public static function getSecureTags()
2522  {
2523  return array("strong", "em", "u", "strike", "ol", "li", "ul", "p", "div",
2524  "i", "b", "code", "sup", "sub", "pre", "gap", "a", "img", "bdo");
2525  }
2526 
2527  public static function maskSecureTags($a_str, $allow_array)
2528  {
2529  foreach ($allow_array as $t) {
2530  switch ($t) {
2531  case "a":
2532  $a_str = ilUtil::maskAttributeTag($a_str, "a", "href");
2533  break;
2534 
2535  case "img":
2536  $a_str = ilUtil::maskAttributeTag($a_str, "img", "src");
2537  break;
2538 
2539  case "p":
2540  case "div":
2541  $a_str = ilUtil::maskTag($a_str, $t, array(
2542  array("param" => "align", "value" => "left"),
2543  array("param" => "align", "value" => "center"),
2544  array("param" => "align", "value" => "justify"),
2545  array("param" => "align", "value" => "right")
2546  ));
2547  break;
2548 
2549  default:
2550  $a_str = ilUtil::maskTag($a_str, $t);
2551  break;
2552  }
2553  }
2554 
2555  return $a_str;
2556  }
2557 
2558  public static function unmaskSecureTags($a_str, $allow_array)
2559  {
2560  foreach ($allow_array as $t) {
2561  switch ($t) {
2562  case "a":
2563  $a_str = ilUtil::unmaskAttributeTag($a_str, "a", "href");
2564  break;
2565 
2566  case "img":
2567  $a_str = ilUtil::unmaskAttributeTag($a_str, "img", "src");
2568  break;
2569 
2570  case "p":
2571  case "div":
2572  $a_str = ilUtil::unmaskTag($a_str, $t, array(
2573  array("param" => "align", "value" => "left"),
2574  array("param" => "align", "value" => "center"),
2575  array("param" => "align", "value" => "justify"),
2576  array("param" => "align", "value" => "right")
2577  ));
2578  break;
2579 
2580  default:
2581  $a_str = ilUtil::unmaskTag($a_str, $t);
2582  break;
2583  }
2584  }
2585 
2586  return $a_str;
2587  }
2588 
2596  public static function securePlainString($a_str)
2597  {
2598  if (ini_get("magic_quotes_gpc")) {
2599  return stripslashes($a_str);
2600  } else {
2601  return $a_str;
2602  }
2603  }
2620  public static function htmlencodePlainString($a_str, $a_make_links_clickable, $a_detect_goto_links = false)
2621  {
2622  $encoded = "";
2623 
2624  if ($a_make_links_clickable) {
2625  // Find text sequences in the plain text string which match
2626  // the URI syntax rules, and pass them to ilUtil::makeClickable.
2627  // Encode all other text sequences in the plain text string using
2628  // htmlspecialchars and nl2br.
2629  // The following expressions matches URI's as specified in RFC 2396.
2630  //
2631  // The expression matches URI's, which start with some well known
2632  // schemes, like "http:", or with "www.". This must be followed
2633  // by at least one of the following RFC 2396 expressions:
2634  // - alphanum: [a-zA-Z0-9]
2635  // - reserved: [;\/?:|&=+$,]
2636  // - mark: [\\-_.!~*\'()]
2637  // - escaped: %[0-9a-fA-F]{2}
2638  // - fragment delimiter: #
2639  // - uric_no_slash: [;?:@&=+$,]
2640  $matches = array();
2641  $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);
2642  $pos1 = 0;
2643  $encoded = "";
2644 
2645  foreach ($matches[0] as $match) {
2646  $matched_text = $match[0];
2647  $pos2 = $match[1];
2648 
2649  // encode plain text
2650  $encoded .= nl2br(htmlspecialchars(substr($a_str, $pos1, $pos2 - $pos1)));
2651 
2652  // encode URI
2653  $encoded .= ilUtil::makeClickable($matched_text, $a_detect_goto_links);
2654 
2655 
2656  $pos1 = $pos2 + strlen($matched_text);
2657  }
2658  if ($pos1 < strlen($a_str)) {
2659  $encoded .= nl2br(htmlspecialchars(substr($a_str, $pos1)));
2660  }
2661  } else {
2662  $encoded = nl2br(htmlspecialchars($a_str));
2663  }
2664  return $encoded;
2665  }
2666 
2667 
2668  public static function maskAttributeTag($a_str, $tag, $tag_att)
2669  {
2670  global $DIC;
2671 
2672  $ilLog = $DIC["ilLog"];
2673 
2674  $ws = "[\s]*";
2675  $att = $ws . "[^>]*" . $ws;
2676 
2677  while (preg_match(
2678  '/<(' . $tag . $att . '(' . $tag_att . $ws . '="' . $ws . '(([$@!*()~;,_0-9A-z\/:=%.&#?+\-])*)")' . $att . ')>/i',
2679  $a_str,
2680  $found
2681  )) {
2682  $old_str = $a_str;
2683  $a_str = preg_replace(
2684  "/<" . preg_quote($found[1], "/") . ">/i",
2685  '&lt;' . $tag . ' ' . $tag_att . $tag_att . '="' . $found[3] . '"&gt;',
2686  $a_str
2687  );
2688  if ($old_str == $a_str) {
2689  $ilLog->write("ilUtil::maskA-" . htmlentities($old_str) . " == " .
2690  htmlentities($a_str));
2691  return $a_str;
2692  }
2693  }
2694  $a_str = str_ireplace(
2695  "</$tag>",
2696  "&lt;/$tag&gt;",
2697  $a_str
2698  );
2699  return $a_str;
2700  }
2701 
2702  public static function unmaskAttributeTag($a_str, $tag, $tag_att)
2703  {
2704  global $DIC;
2705 
2706  $ilLog = $DIC["ilLog"];
2707 
2708  while (preg_match(
2709  '/&lt;(' . $tag . ' ' . $tag_att . $tag_att . '="(([$@!*()~;,_0-9A-z\/:=%.&#?+\-])*)")&gt;/i',
2710  $a_str,
2711  $found
2712  )) {
2713  $old_str = $a_str;
2714  $a_str = preg_replace(
2715  "/&lt;" . preg_quote($found[1], "/") . "&gt;/i",
2716  '<' . $tag . ' ' . $tag_att . '="' . ilUtil::secureLink($found[2]) . '">',
2717  $a_str
2718  );
2719  if ($old_str == $a_str) {
2720  $ilLog->write("ilUtil::unmaskA-" . htmlentities($old_str) . " == " .
2721  htmlentities($a_str));
2722  return $a_str;
2723  }
2724  }
2725  $a_str = str_replace('&lt;/' . $tag . '&gt;', '</' . $tag . '>', $a_str);
2726  return $a_str;
2727  }
2728 
2729  public static function maskTag($a_str, $t, $fix_param = "")
2730  {
2731  $a_str = str_replace(
2732  array("<$t>", "<" . strtoupper($t) . ">"),
2733  "&lt;" . $t . "&gt;",
2734  $a_str
2735  );
2736  $a_str = str_replace(
2737  array("</$t>", "</" . strtoupper($t) . ">"),
2738  "&lt;/" . $t . "&gt;",
2739  $a_str
2740  );
2741 
2742  if (is_array($fix_param)) {
2743  foreach ($fix_param as $p) {
2744  $k = $p["param"];
2745  $v = $p["value"];
2746  $a_str = str_replace(
2747  "<$t $k=\"$v\">",
2748  "&lt;" . "$t $k=\"$v\"" . "&gt;",
2749  $a_str
2750  );
2751  }
2752  }
2753 
2754  return $a_str;
2755  }
2756 
2757  public static function unmaskTag($a_str, $t, $fix_param = "")
2758  {
2759  $a_str = str_replace("&lt;" . $t . "&gt;", "<" . $t . ">", $a_str);
2760  $a_str = str_replace("&lt;/" . $t . "&gt;", "</" . $t . ">", $a_str);
2761 
2762  if (is_array($fix_param)) {
2763  foreach ($fix_param as $p) {
2764  $k = $p["param"];
2765  $v = $p["value"];
2766  $a_str = str_replace(
2767  "&lt;$t $k=\"$v\"&gt;",
2768  "<" . "$t $k=\"$v\"" . ">",
2769  $a_str
2770  );
2771  }
2772  }
2773  return $a_str;
2774  }
2775 
2776  public static function secureLink($a_str)
2777  {
2778  $a_str = str_ireplace("javascript", "jvscrpt", $a_str);
2779  $a_str = str_ireplace(array("%00", "%0a", "%0d", "%1a", "&#00;", "&#x00;",
2780  "&#0;", "&#x0;", "&#x0a;", "&#x0d;", "&#10;", "&#13;"), "-", $a_str);
2781  return $a_str;
2782  }
2783 
2797  public static function stripScriptHTML($a_str, $a_allow = "", $a_rm_js = true)
2798  {
2799  //$a_str = strip_tags($a_str, $a_allow);
2800 
2801  $negativestr = "a,abbr,acronym,address,applet,area,base,basefont," .
2802  "big,blockquote,body,br,button,caption,center,cite,code,col," .
2803  "colgroup,dd,del,dfn,dir,div,dl,dt,em,fieldset,font,form,frame," .
2804  "frameset,h1,h2,h3,h4,h5,h6,head,hr,html,i,iframe,img,input,ins,isindex,kbd," .
2805  "label,legend,li,link,map,menu,meta,noframes,noscript,object,ol," .
2806  "optgroup,option,p,param,q,s,samp,script,select,small,span," .
2807  "strike,strong,style,sub,sup,table,tbody,td,textarea,tfoot,th,thead," .
2808  "title,tr,tt,u,ul,var";
2809  $a_allow = strtolower($a_allow);
2810  $negatives = explode(",", $negativestr);
2811  $outer_old_str = "";
2812  while ($outer_old_str != $a_str) {
2813  $outer_old_str = $a_str;
2814  foreach ($negatives as $item) {
2815  $pos = strpos($a_allow, "<$item>");
2816 
2817  // remove complete tag, if not allowed
2818  if ($pos === false) {
2819  $old_str = "";
2820  while ($old_str != $a_str) {
2821  $old_str = $a_str;
2822  $a_str = preg_replace("/<\/?\s*$item(\/?)\s*>/i", "", $a_str);
2823  $a_str = preg_replace("/<\/?\s*$item(\/?)\s+([^>]*)>/i", "", $a_str);
2824  }
2825  }
2826  }
2827  }
2828 
2829  if ($a_rm_js) {
2830  // remove all attributes if an "on..." attribute is given
2831  $a_str = preg_replace("/<\s*\w*(\/?)(\s+[^>]*)?(\s+on[^>]*)>/i", "", $a_str);
2832 
2833  // remove all attributes if a "javascript" is within tag
2834  $a_str = preg_replace("/<\s*\w*(\/?)\s+[^>]*javascript[^>]*>/i", "", $a_str);
2835 
2836  // remove all attributes if an "expression" is within tag
2837  // (IE allows something like <b style='width:expression(alert(1))'>test</b>)
2838  $a_str = preg_replace("/<\s*\w*(\/?)\s+[^>]*expression[^>]*>/i", "", $a_str);
2839  }
2840 
2841  return $a_str;
2842  }
2843 
2855  public static function prepareFormOutput($a_str, $a_strip = false)
2856  {
2857  if ($a_strip) {
2858  $a_str = ilUtil::stripSlashes($a_str);
2859  }
2860  $a_str = htmlspecialchars($a_str);
2861  // Added replacement of curly brackets to prevent
2862  // problems with PEAR templates, because {xyz} will
2863  // be removed as unused template variable
2864  $a_str = str_replace("{", "&#123;", $a_str);
2865  $a_str = str_replace("}", "&#125;", $a_str);
2866  // needed for LaTeX conversion \\ in LaTeX is a line break
2867  // but without this replacement, php changes \\ to \
2868  $a_str = str_replace("\\", "&#92;", $a_str);
2869  return $a_str;
2870  }
2871 
2878  public static function secureUrl($url)
2879  {
2880  // check if url is valid (absolute or relative)
2881  if (filter_var($url, FILTER_VALIDATE_URL) === false &&
2882  filter_var("http://" . $url, FILTER_VALIDATE_URL) === false &&
2883  filter_var("http:" . $url, FILTER_VALIDATE_URL) === false &&
2884  filter_var("http://de.de" . $url, FILTER_VALIDATE_URL) === false &&
2885  filter_var("http://de.de/" . $url, FILTER_VALIDATE_URL) === false) {
2886  return "";
2887  }
2888  if (trim(strtolower(parse_url($url, PHP_URL_SCHEME))) == "javascript") {
2889  return "";
2890  }
2891  $url = htmlspecialchars($url, ENT_QUOTES);
2892  return $url;
2893  }
2894 
2895 
2896 
2906  public static function prepareDBString($a_str)
2907  {
2908  return addslashes($a_str);
2909  }
2910 
2911 
2920  public static function removeItemFromDesktops($a_id)
2921  {
2922  return ilObjUser::_removeItemFromDesktops($a_id);
2923  }
2924 
2925 
2935  public static function extractParameterString($a_parstr)
2936  {
2937  // parse parameters in array
2938  $par = array();
2939  $ok=true;
2940  while (($spos=strpos($a_parstr, "=")) && $ok) {
2941  // extract parameter
2942  $cpar = substr($a_parstr, 0, $spos);
2943  $a_parstr = substr($a_parstr, $spos, strlen($a_parstr)-$spos);
2944  while (substr($cpar, 0, 1)=="," ||substr($cpar, 0, 1)==" " || substr($cpar, 0, 1)==chr(13) || substr($cpar, 0, 1)==chr(10)) {
2945  $cpar = substr($cpar, 1, strlen($cpar)-1);
2946  }
2947  while (substr($cpar, strlen($cpar)-1, 1)==" " || substr($cpar, strlen($cpar)-1, 1)==chr(13) || substr($cpar, strlen($cpar)-1, 1)==chr(10)) {
2948  $cpar = substr($cpar, 0, strlen($cpar)-1);
2949  }
2950 
2951  // parameter name should only
2952  $cpar_old = "";
2953  while ($cpar != $cpar_old) {
2954  $cpar_old = $cpar;
2955  $cpar = preg_replace("/[^a-zA-Z0-9_]/i", "", $cpar);
2956  }
2957 
2958  // extract value
2959  if ($cpar != "") {
2960  if ($spos=strpos($a_parstr, "\"")) {
2961  $a_parstr = substr($a_parstr, $spos+1, strlen($a_parstr)-$spos);
2962  $spos=strpos($a_parstr, "\"");
2963  if (is_int($spos)) {
2964  $cval = substr($a_parstr, 0, $spos);
2965  $par[$cpar]=$cval;
2966  $a_parstr = substr($a_parstr, $spos+1, strlen($a_parstr)-$spos-1);
2967  } else {
2968  $ok=false;
2969  }
2970  } else {
2971  $ok=false;
2972  }
2973  }
2974  }
2975 
2976  if ($ok) {
2977  return $par;
2978  } else {
2979  return false;
2980  }
2981  }
2982 
2983  public static function assembleParameterString($a_par_arr)
2984  {
2985  if (is_array($a_par_arr)) {
2986  $target_arr = array();
2987  foreach ($a_par_arr as $par => $val) {
2988  $target_arr[] = "$par=\"$val\"";
2989  }
2990  $target_str = implode(", ", $target_arr);
2991  }
2992 
2993  return $target_str;
2994  }
2995 
3002  public static function dumpString($a_str)
3003  {
3004  $ret = $a_str . ": ";
3005  for ($i=0; $i<strlen($a_str); $i++) {
3006  $ret.= ord(substr($a_str, $i, 1)) . " ";
3007  }
3008  return $ret;
3009  }
3010 
3011 
3018  public static function yn2tf($a_yn)
3019  {
3020  if (strtolower($a_yn) == "y") {
3021  return true;
3022  } else {
3023  return false;
3024  }
3025  }
3026 
3033  public static function tf2yn($a_tf)
3034  {
3035  if ($a_tf) {
3036  return "y";
3037  } else {
3038  return "n";
3039  }
3040  }
3041 
3052  public static function sort_func($a, $b)
3053  {
3054  global $array_sortby,$array_sortorder;
3055 
3056  if (!isset($array_sortby)) {
3057  // occured in: setup -> new client -> install languages -> sorting of languages
3058  $array_sortby = 0;
3059  }
3060 
3061  // this comparison should give optimal results if
3062  // locale is provided and mb string functions are supported
3063  if ($array_sortorder == "asc") {
3064  return ilStr::strCmp($a[$array_sortby], $b[$array_sortby]);
3065  }
3066 
3067  if ($array_sortorder == "desc") {
3068  return !ilStr::strCmp($a[$array_sortby], $b[$array_sortby]);
3069  return strcoll(ilStr::strToUpper($b[$array_sortby]), ilStr::strToUpper($a[$array_sortby]));
3070  }
3071  }
3072 
3083  public static function sort_func_numeric($a, $b)
3084  {
3085  global $array_sortby,$array_sortorder;
3086 
3087  if ($array_sortorder == "asc") {
3088  return $a["$array_sortby"] > $b["$array_sortby"];
3089  }
3090 
3091  if ($array_sortorder == "desc") {
3092  return $a["$array_sortby"] < $b["$array_sortby"];
3093  }
3094  }
3107  public static function sortArray(
3108  $array,
3109  $a_array_sortby,
3110  $a_array_sortorder = 0,
3111  $a_numeric = false,
3112  $a_keep_keys = false
3113  ) {
3114  include_once("./Services/Utilities/classes/class.ilStr.php");
3115 
3116  // BEGIN WebDAV: Provide a 'stable' sort algorithm
3117  if (!$a_keep_keys) {
3118  return self::stableSortArray($array, $a_array_sortby, $a_array_sortorder, $a_numeric, $a_keep_keys);
3119  }
3120  // END WebDAV Provide a 'stable' sort algorithm
3121 
3122  global $array_sortby,$array_sortorder;
3123  $array_sortby = $a_array_sortby;
3124 
3125  if ($a_array_sortorder == "desc") {
3126  $array_sortorder = "desc";
3127  } else {
3128  $array_sortorder = "asc";
3129  }
3130  if ($a_numeric) {
3131  if ($a_keep_keys) {
3132  uasort($array, array("ilUtil", "sort_func_numeric"));
3133  } else {
3134  usort($array, array("ilUtil", "sort_func_numeric"));
3135  }
3136  } else {
3137  if ($a_keep_keys) {
3138  uasort($array, array("ilUtil", "sort_func"));
3139  } else {
3140  usort($array, array("ilUtil", "sort_func"));
3141  }
3142  }
3143  //usort($array,"ilUtil::sort_func");
3144 
3145  return $array;
3146  }
3147  // BEGIN WebDAV: Provide a 'stable' sort algorithm
3162  public static function stableSortArray($array, $a_array_sortby, $a_array_sortorder = 0, $a_numeric = false)
3163  {
3164  global $array_sortby,$array_sortorder;
3165 
3166  $array_sortby = $a_array_sortby;
3167 
3168  if ($a_array_sortorder == "desc") {
3169  $array_sortorder = "desc";
3170  } else {
3171  $array_sortorder = "asc";
3172  }
3173 
3174  // Create a copy of the array values for sorting
3175  $sort_array = array_values($array);
3176 
3177  if ($a_numeric) {
3178  ilUtil::mergesort($sort_array, array("ilUtil", "sort_func_numeric"));
3179  } else {
3180  ilUtil::mergesort($sort_array, array("ilUtil", "sort_func"));
3181  }
3182 
3183  return $sort_array;
3184  }
3185  public static function mergesort(&$array, $cmp_function = 'strcmp')
3186  {
3187  // Arrays of size < 2 require no action.
3188  if (count($array) < 2) {
3189  return;
3190  }
3191 
3192  // Split the array in half
3193  $halfway = count($array) / 2;
3194  $array1 = array_slice($array, 0, $halfway);
3195  $array2 = array_slice($array, $halfway);
3196 
3197  // Recurse to sort the two halves
3198  ilUtil::mergesort($array1, $cmp_function);
3199  ilUtil::mergesort($array2, $cmp_function);
3200 
3201  // If all of $array1 is <= all of $array2, just append them.
3202  if (call_user_func($cmp_function, end($array1), $array2[0]) < 1) {
3203  $array = array_merge($array1, $array2);
3204  return;
3205  }
3206 
3207  // Merge the two sorted arrays into a single sorted array
3208  $array = array();
3209  $ptr1 = $ptr2 = 0;
3210  while ($ptr1 < count($array1) && $ptr2 < count($array2)) {
3211  if (call_user_func($cmp_function, $array1[$ptr1], $array2[$ptr2]) < 1) {
3212  $array[] = $array1[$ptr1++];
3213  } else {
3214  $array[] = $array2[$ptr2++];
3215  }
3216  }
3217 
3218  // Merge the remainder
3219  while ($ptr1 < count($array1)) {
3220  $array[] = $array1[$ptr1++];
3221  }
3222  while ($ptr2 < count($array2)) {
3223  $array[] = $array2[$ptr2++];
3224  }
3225 
3226  return;
3227  }
3228  // END WebDAV: Provide a 'stable' sort algorithm
3229 
3241  public static function unique_multi_array($array, $sub_key)
3242  {
3243  $target = array();
3244  $existing_sub_key_values = array();
3245 
3246  foreach ($array as $key=>$sub_array) {
3247  if (!in_array($sub_array[$sub_key], $existing_sub_key_values)) {
3248  $existing_sub_key_values[] = $sub_array[$sub_key];
3249  $target[$key] = $sub_array;
3250  }
3251  }
3252 
3253  return $target;
3254  }
3255 
3256 
3266  public static function getGDSupportedImageType($a_desired_type)
3267  {
3268  $a_desired_type = strtolower($a_desired_type);
3269  // get supported Image Types
3270  $im_types = ImageTypes();
3271 
3272  switch ($a_desired_type) {
3273  case "jpg":
3274  case "jpeg":
3275  if ($im_types & IMG_JPG) {
3276  return "jpg";
3277  }
3278  if ($im_types & IMG_GIF) {
3279  return "gif";
3280  }
3281  if ($im_types & IMG_PNG) {
3282  return "png";
3283  }
3284  break;
3285 
3286  case "gif":
3287  if ($im_types & IMG_GIF) {
3288  return "gif";
3289  }
3290  if ($im_types & IMG_JPG) {
3291  return "jpg";
3292  }
3293  if ($im_types & IMG_PNG) {
3294  return "png";
3295  }
3296  break;
3297 
3298  case "png":
3299  if ($im_types & IMG_PNG) {
3300  return "png";
3301  }
3302  if ($im_types & IMG_JPG) {
3303  return "jpg";
3304  }
3305  if ($im_types & IMG_GIF) {
3306  return "gif";
3307  }
3308  break;
3309 
3310  case "svg":
3311  if ($im_types & IMG_PNG) {
3312  return "png";
3313  }
3314  if ($im_types & IMG_JPG) {
3315  return "jpg";
3316  }
3317  if ($im_types & IMG_GIF) {
3318  return "gif";
3319  }
3320  break;
3321  }
3322 
3323  return "";
3324  }
3325 
3335  public static function deducibleSize($a_mime)
3336  {
3337  if (($a_mime == "image/gif") || ($a_mime == "image/jpeg") ||
3338  ($a_mime == "image/png") || ($a_mime == "application/x-shockwave-flash") ||
3339  ($a_mime == "image/tiff") || ($a_mime == "image/x-ms-bmp") ||
3340  ($a_mime == "image/psd") || ($a_mime == "image/iff")) {
3341  return true;
3342  } else {
3343  return false;
3344  }
3345  }
3346 
3347 
3353  public static function redirect($a_script)
3354  {
3355  global $DIC;
3356 
3357  if (!isset($DIC['ilCtrl']) || !$DIC['ilCtrl'] instanceof ilCtrl) {
3358  $ctrl = new ilCtrl();
3359  } else {
3360  $ctrl = $DIC->ctrl();
3361  }
3362  $ctrl->redirectToURL($a_script);
3363  }
3364 
3373  public static function insertInstIntoID($a_value)
3374  {
3375  if (substr($a_value, 0, 4) == "il__") {
3376  $a_value = "il_" . IL_INST_ID . "_" . substr($a_value, 4, strlen($a_value) - 4);
3377  }
3378 
3379  return $a_value;
3380  }
3381 
3392  public static function groupNameExists($a_group_name, $a_id = 0)
3393  {
3394  global $DIC;
3395 
3396  $ilDB = $DIC->database();
3397 
3398  $ilErr = null;
3399  if (isset($DIC["ilErr"])) {
3400  $ilErr = $DIC["ilErr"];
3401  }
3402 
3403  if (empty($a_group_name)) {
3404  $message = __METHOD__ . ": No groupname given!";
3405  $ilErr->raiseError($message, $ilErr->WARNING);
3406  }
3407 
3408  $clause = ($a_id) ? " AND obj_id != " . $ilDB->quote($a_id) . " " : "";
3409 
3410  $q = "SELECT obj_id FROM object_data " .
3411  "WHERE title = " . $ilDB->quote($a_group_name, "text") . " " .
3412  "AND type = " . $ilDB->quote("grp", "text") .
3413  $clause;
3414 
3415  $r = $ilDB->query($q);
3416 
3417  if ($r->numRows()) {
3418  return true;
3419  } else {
3420  return false;
3421  }
3422  }
3423 
3430  public static function getMemString()
3431  {
3432  $my_pid = getmypid();
3433  return ("MEMORY USAGE (% KB PID ): " . `ps -eo%mem,rss,pid | grep $my_pid`);
3434  }
3435 
3442  public static function isWindows()
3443  {
3444  if (strtolower(substr(php_uname(), 0, 3)) == "win") {
3445  return true;
3446  }
3447  return false;
3448  }
3449 
3450 
3451  public static function escapeShellArg($a_arg)
3452  {
3453  setlocale(LC_CTYPE, "UTF8", "en_US.UTF-8"); // fix for PHP escapeshellcmd bug. See: http://bugs.php.net/bug.php?id=45132
3454  // see also ilias bug 5630
3455  return escapeshellarg($a_arg);
3456  }
3457 
3467  public static function escapeShellCmd($a_arg)
3468  {
3469  if (ini_get('safe_mode') == 1) {
3470  return $a_arg;
3471  }
3472  setlocale(LC_CTYPE, "UTF8", "en_US.UTF-8"); // fix for PHP escapeshellcmd bug. See: http://bugs.php.net/bug.php?id=45132
3473  return escapeshellcmd($a_arg);
3474  }
3475 
3485  public static function execQuoted($cmd, $args = null)
3486  {
3487  global $DIC;
3488 
3489  if (ilUtil::isWindows() && strpos($cmd, " ") !== false && substr($cmd, 0, 1) !== '"') {
3490  // cmd won't work without quotes
3491  $cmd = '"' . $cmd . '"';
3492  if ($args) {
3493  // args are also quoted, workaround is to quote the whole command AGAIN
3494  // was fixed in php 5.2 (see php bug #25361)
3495  if (version_compare(phpversion(), "5.2", "<") && strpos($args, '"') !== false) {
3496  $cmd = '"' . $cmd . " " . $args . '"';
3497  }
3498  // args are not quoted or php is fixed, just append
3499  else {
3500  $cmd .= " " . $args;
3501  }
3502  }
3503  }
3504  // nothing todo, just append args
3505  elseif ($args) {
3506  $cmd .= " " . $args;
3507  }
3508 
3509  exec($cmd, $arr);
3510 
3511  $DIC->logger()->root()->debug("ilUtil::execQuoted: " . $cmd . ".");
3512 
3513  return $arr;
3514  }
3515 
3538  public static function excelTime($year = "", $month = "", $day = "", $hour = "", $minute = "", $second = "")
3539  {
3540  $starting_time = mktime(0, 0, 0, 1, 2, 1970);
3541  if (strcmp("$year$month$day$hour$minute$second", "") == 0) {
3542  $target_time = time();
3543  } else {
3544  if ($year < 1970) {
3545  return 0;
3546  }
3547  }
3548  $target_time = mktime($hour, $minute, $second, $month, $day, $year);
3549  $difference = $target_time - $starting_time;
3550  $days = (($difference - ($difference % 86400)) / 86400);
3551  $difference = $difference - ($days * 86400) + 3600;
3552 
3553  // #15343 - using a global locale leads to , instead of . for (implicit) floats
3554  return str_replace(",", ".", ($days + 25570 + ($difference / 86400)));
3555  }
3556 
3563  public static function renameExecutables($a_dir)
3564  {
3565  $def_arr = explode(",", SUFFIX_REPL_DEFAULT);
3566  foreach ($def_arr as $def) {
3567  ilUtil::rRenameSuffix($a_dir, trim($def), "sec");
3568  }
3569 
3570  $def_arr = explode(",", SUFFIX_REPL_ADDITIONAL);
3571  foreach ($def_arr as $def) {
3572  ilUtil::rRenameSuffix($a_dir, trim($def), "sec");
3573  }
3574  }
3575 
3580  public static function getSafeFilename($a_initial_filename)
3581  {
3582  $file_peaces = explode('.', $a_initial_filename);
3583 
3584  $file_extension = array_pop($file_peaces);
3585 
3586  if (SUFFIX_REPL_ADDITIONAL) {
3587  $string_extensions = SUFFIX_REPL_DEFAULT . "," . SUFFIX_REPL_ADDITIONAL;
3588  } else {
3589  $string_extensions = SUFFIX_REPL_DEFAULT;
3590  }
3591 
3592  $sufixes = explode(",", $string_extensions);
3593 
3594  if (in_array($file_extension, $sufixes)) {
3595  $file_extension = "sec";
3596  }
3597 
3598  array_push($file_peaces, $file_extension);
3599 
3600  $safe_filename = "";
3601  foreach ($file_peaces as $piece) {
3602  $safe_filename .= "$piece";
3603  if ($piece != end($file_peaces)) {
3604  $safe_filename .= ".";
3605  }
3606  }
3607 
3608  return $safe_filename;
3609  }
3610 
3623  public static function rRenameSuffix($a_dir, $a_old_suffix, $a_new_suffix)
3624  {
3625  if ($a_dir == "/" || $a_dir == "" || is_int(strpos($a_dir, ".."))
3626  || trim($a_old_suffix) == "") {
3627  return false;
3628  }
3629 
3630  // check if argument is directory
3631  if (!@is_dir($a_dir)) {
3632  return false;
3633  }
3634 
3635  // read a_dir
3636  $dir = opendir($a_dir);
3637 
3638  while ($file = readdir($dir)) {
3639  if ($file != "." and
3640  $file != "..") {
3641  // directories
3642  if (@is_dir($a_dir . "/" . $file)) {
3643  ilUtil::rRenameSuffix($a_dir . "/" . $file, $a_old_suffix, $a_new_suffix);
3644  }
3645 
3646  // files
3647  if (@is_file($a_dir . "/" . $file)) {
3648  // first check for files with trailing dot
3649  if (strrpos($file, '.') == (strlen($file) - 1)) {
3650  rename($a_dir . '/' . $file, substr($a_dir . '/' . $file, 0, -1));
3651  $file = substr($file, 0, -1);
3652  }
3653 
3654  $path_info = pathinfo($a_dir . "/" . $file);
3655 
3656  if (strtolower($path_info["extension"]) ==
3657  strtolower($a_old_suffix)) {
3658  $pos = strrpos($a_dir . "/" . $file, ".");
3659  $new_name = substr($a_dir . "/" . $file, 0, $pos) . "." . $a_new_suffix;
3660  rename($a_dir . "/" . $file, $new_name);
3661  }
3662  }
3663  }
3664  }
3665  return true;
3666  }
3667 
3668  public static function isAPICall()
3669  {
3670  return strpos($_SERVER["SCRIPT_FILENAME"], "api") !== false ||
3671  strpos($_SERVER["SCRIPT_FILENAME"], "dummy") !== false;
3672  }
3673 
3674  public static function KT_replaceParam($qstring, $paramName, $paramValue)
3675  {
3676  if (preg_match("/&" . $paramName . "=/", $qstring)) {
3677  return preg_replace("/&" . $paramName . "=[^&]+/", "&" . $paramName . "=" . urlencode($paramValue), $qstring);
3678  } else {
3679  return $qstring . "&" . $paramName . "=" . urlencode($paramValue);
3680  }
3681  }
3682 
3683  public static function replaceUrlParameterString($url, $parametersArray)
3684  {
3685  foreach ($parametersArray as $paramName => $paramValue) {
3686  $url = ilUtil::KT_replaceParam($url, $paramName, $paramValue);
3687  }
3688  return $url;
3689  }
3690 
3697  public static function generatePasswords($a_number)
3698  {
3699  $ret = array();
3700  srand((double) microtime()*1000000);
3701 
3702  include_once('./Services/PrivacySecurity/classes/class.ilSecuritySettings.php');
3703  $security = ilSecuritySettings::_getInstance();
3704 
3705  for ($i=1; $i<=$a_number; $i++) {
3706  $min = ($security->getPasswordMinLength() > 0)
3707  ? $security->getPasswordMinLength()
3708  : 6;
3709  $max = ($security->getPasswordMaxLength() > 0)
3710  ? $security->getPasswordMaxLength()
3711  : 10;
3712  if ($min > $max) {
3713  $max = $max + 1;
3714  }
3715  $random = new \ilRandom();
3716  $length = $random->int($min, $max);
3717  $next = $random->int(1, 2);
3718  $vowels = "aeiou";
3719  $vowels_uc = strtoupper($vowels);
3720  $consonants = "bcdfghjklmnpqrstvwxyz";
3721  $consonants_uc = strtoupper($consonants);
3722  $numbers = "1234567890";
3723  $special = "_.+?#-*@!$%~";
3724  $pw = "";
3725 
3726  if ($security->getPasswordNumberOfUppercaseChars() > 0) {
3727  for ($j = 0; $j < $security->getPasswordNumberOfUppercaseChars(); $j++) {
3728  switch ($next) {
3729  case 1:
3730  $pw.= $consonants_uc[$random->int(0, strlen($consonants_uc) - 1)];
3731  $next = 2;
3732  break;
3733 
3734  case 2:
3735  $pw.= $vowels_uc[$random->int(0, strlen($vowels_uc) - 1)];
3736  $next = 1;
3737  break;
3738  }
3739  }
3740  }
3741 
3742  if ($security->isPasswordCharsAndNumbersEnabled()) {
3743  $pw.= $numbers[$random->int(0, strlen($numbers) - 1)];
3744  }
3745 
3746  if ($security->isPasswordSpecialCharsEnabled()) {
3747  $pw.= $special[$random->int(0, strlen($special) - 1)];
3748  }
3749 
3750  $num_lcase_chars = max($security->getPasswordNumberOfLowercaseChars(), $length - strlen($pw));
3751  for ($j = 0; $j < $num_lcase_chars; $j++) {
3752  switch ($next) {
3753  case 1:
3754  $pw.= $consonants[$random->int(0, strlen($consonants) - 1)];
3755  $next = 2;
3756  break;
3757 
3758  case 2:
3759  $pw.= $vowels[$random->int(0, strlen($vowels) - 1)];
3760  $next = 1;
3761  break;
3762  }
3763  }
3764 
3765  $pw = str_shuffle($pw);
3766 
3767  $ret[] = $pw;
3768  }
3769  return $ret;
3770  }
3771 
3772  public static function removeTrailingPathSeparators($path)
3773  {
3774  $path = preg_replace("/[\/\\\]+$/", "", $path);
3775  return $path;
3776  }
3777 
3788  public static function array_php2js($data)
3789  {
3790  if (empty($data)) {
3791  $data = array();
3792  }
3793 
3794  foreach ($data as $k=>$datum) {
3795  if (is_null($datum)) {
3796  $data[$k] = 'null';
3797  }
3798  if (is_string($datum)) {
3799  $data[$k] = "'" . $datum . "'";
3800  }
3801  if (is_array($datum)) {
3802  $data[$k] = array_php2js($datum);
3803  }
3804  }
3805 
3806  return "[" . implode(', ', $data) . "]";
3807  }
3808 
3815  public static function virusHandling($a_file, $a_orig_name = "", $a_clean = true)
3816  {
3817  global $DIC;
3818 
3819  $lng = $DIC->language();
3820 
3821  if (IL_VIRUS_SCANNER != "None") {
3822  require_once("./Services/VirusScanner/classes/class.ilVirusScannerFactory.php");
3824  if (($vs_txt = $vs->scanFile($a_file, $a_orig_name)) != "") {
3825  if ($a_clean && (IL_VIRUS_CLEAN_COMMAND != "")) {
3826  $clean_txt = $vs->cleanFile($a_file, $a_orig_name);
3827  if ($vs->fileCleaned()) {
3828  $vs_txt.= "<br />" . $lng->txt("cleaned_file") .
3829  "<br />" . $clean_txt;
3830  $vs_txt.= "<br />" . $lng->txt("repeat_scan");
3831  if (($vs2_txt = $vs->scanFile($a_file, $a_orig_name)) != "") {
3832  return array(false, nl2br($vs_txt) . "<br />" . $lng->txt("repeat_scan_failed") .
3833  "<br />" . nl2br($vs2_txt));
3834  } else {
3835  return array(true, nl2br($vs_txt) . "<br />" . $lng->txt("repeat_scan_succeded"));
3836  }
3837  } else {
3838  return array(false, nl2br($vs_txt) . "<br />" . $lng->txt("cleaning_failed"));
3839  }
3840  } else {
3841  return array(false, nl2br($vs_txt));
3842  }
3843  }
3844  }
3845 
3846  return array(true,"");
3847  }
3848 
3849 
3869  public static function moveUploadedFile($a_file, $a_name, $a_target, $a_raise_errors = true, $a_mode = "move_uploaded")
3870  {
3871  global $DIC;
3872  $targetFilename = basename($a_target);
3873 
3874  include_once("./Services/Utilities/classes/class.ilFileUtils.php");
3875  $targetFilename = ilFileUtils::getValidFilename($targetFilename);
3876 
3877  // Make sure the target is in a valid subfolder. (e.g. no uploads to ilias/setup/....)
3878  list($targetFilesystem, $targetDir) = self::sanitateTargetPath($a_target);
3879 
3880  $upload = $DIC->upload();
3881 
3882  // If the upload has not yet been processed make sure he gets processed now.
3883  if (!$upload->hasBeenProcessed()) {
3884  $upload->process();
3885  }
3886 
3887  try {
3888  if (!$upload->hasUploads()) {
3889  throw new ilException($DIC->language()->txt("upload_error_file_not_found"));
3890  }
3894  $UploadResult = $upload->getResults()[$a_file];
3895  $ProcessingStatus = $UploadResult->getStatus();
3896  if ($ProcessingStatus->getCode() === ProcessingStatus::REJECTED) {
3897  throw new ilException($ProcessingStatus->getMessage());
3898  }
3899  } catch (ilException $e) {
3900  if ($a_raise_errors) {
3901  throw $e;
3902  } else {
3903  ilUtil::sendFailure($e->getMessage(), true);
3904  }
3905 
3906  return false;
3907  }
3908 
3909  $upload->moveOneFileTo($UploadResult, $targetDir, $targetFilesystem, $targetFilename, true);
3910 
3911  return true;
3912  }
3913 
3914 
3921  public static function date_mysql2time($mysql_date_time)
3922  {
3923  list($datum, $uhrzeit) = explode(" ", $mysql_date_time);
3924  list($jahr, $monat, $tag) = explode("-", $datum);
3925  list($std, $min, $sec) = explode(":", $uhrzeit);
3926  return mktime((int) $std, (int) $min, (int) $sec, (int) $monat, (int) $tag, (int) $jahr);
3927  }
3928 
3935  public static function now()
3936  {
3937  return date("Y-m-d H:i:s");
3938  }
3939 
3955  public static function &processCSVRow(&$row, $quoteAll = false, $separator = ";", $outUTF8 = false, $compatibleWithMSExcel = true)
3956  {
3957  $resultarray = array();
3958  foreach ($row as $rowindex => $entry) {
3959  $surround = false;
3960  if ($quoteAll) {
3961  $surround = true;
3962  }
3963  if (strpos($entry, "\"") !== false) {
3964  $entry = str_replace("\"", "\"\"", $entry);
3965  $surround = true;
3966  }
3967  if (strpos($entry, $separator) !== false) {
3968  $surround = true;
3969  }
3970  if ($compatibleWithMSExcel) {
3971  // replace all CR LF with LF (for Excel for Windows compatibility
3972  $entry = str_replace(chr(13) . chr(10), chr(10), $entry);
3973  }
3974  if ($surround) {
3975  if ($outUTF8) {
3976  $resultarray[$rowindex] = "\"" . $entry . "\"";
3977  } else {
3978  $resultarray[$rowindex] = utf8_decode("\"" . $entry . "\"");
3979  }
3980  } else {
3981  if ($outUTF8) {
3982  $resultarray[$rowindex] = $entry;
3983  } else {
3984  $resultarray[$rowindex] = utf8_decode($entry);
3985  }
3986  }
3987  }
3988  return $resultarray;
3989  }
3990 
3991  // validates a domain name (example: www.ilias.de)
3992  public static function isDN($a_str)
3993  {
3994  return(preg_match("/^[a-z]+([a-z0-9-]*[a-z0-9]+)?(\.([a-z]+([a-z0-9-]*[a-z0-9]+)?)+)*$/", $a_str));
3995  }
3996 
3997  // validates an IP address (example: 192.168.1.1)
3998  public static function isIPv4($a_str)
3999  {
4000  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])\." .
4001  "(\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));
4002  }
4003 
4004 
4033  public static function _getObjectsByOperations($a_obj_type, $a_operation, $a_usr_id = 0, $limit = 0)
4034  {
4035  global $DIC;
4036 
4037  $ilDB = $DIC->database();
4038  $rbacreview = $DIC->rbac()->review();
4039  $ilAccess = $DIC->access();
4040  $ilUser = $DIC->user();
4041  $ilSetting = $DIC->settings();
4042  $tree = $DIC->repositoryTree();
4043 
4044  if (!is_array($a_obj_type)) {
4045  $where = "WHERE type = " . $ilDB->quote($a_obj_type, "text") . " ";
4046  } else {
4047  $where = "WHERE " . $ilDB->in("type", $a_obj_type, false, "text") . " ";
4048  }
4049 
4050  // limit number of results default is search result limit
4051  if (!$limit) {
4052  $limit = $ilSetting->get('search_max_hits', 100);
4053  }
4054  if ($limit == -1) {
4055  $limit = 10000;
4056  }
4057 
4058  // default to logged in usr
4059  $a_usr_id = $a_usr_id ? $a_usr_id : $ilUser->getId();
4060  $a_roles = $rbacreview->assignedRoles($a_usr_id);
4061 
4062  // Since no rbac_pa entries are available for the system role. This function returns !all! ref_ids in the case the user
4063  // is assigned to the system role
4064  if ($rbacreview->isAssigned($a_usr_id, SYSTEM_ROLE_ID)) {
4065  $query = "SELECT ref_id FROM object_reference obr LEFT JOIN object_data obd ON obr.obj_id = obd.obj_id " .
4066  "LEFT JOIN tree ON obr.ref_id = tree.child " .
4067  $where .
4068  "AND tree = 1";
4069 
4070  $res = $ilDB->query($query);
4071  $counter = 0;
4072  while ($row = $ilDB->fetchObject($res)) {
4073  // Filter recovery folder
4074  if ($tree->isGrandChild(RECOVERY_FOLDER_ID, $row->ref_id)) {
4075  continue;
4076  }
4077 
4078  if ($counter++ >= $limit) {
4079  break;
4080  }
4081 
4082  $ref_ids[] = $row->ref_id;
4083  }
4084  return $ref_ids ? $ref_ids : array();
4085  } // End Administrators
4086 
4087  // Check ownership if it is not asked for edit_permission or a create permission
4088  if ($a_operation == 'edit_permissions' or strpos($a_operation, 'create') !== false) {
4089  $check_owner = ") ";
4090  } else {
4091  $check_owner = "OR owner = " . $ilDB->quote($a_usr_id, "integer") . ") ";
4092  }
4093 
4094  $ops_ids = ilRbacReview::_getOperationIdsByName(array($a_operation));
4095  $ops_id = $ops_ids[0];
4096 
4097  $and = "AND ((" . $ilDB->in("rol_id", $a_roles, false, "integer") . " ";
4098 
4099  $query = "SELECT DISTINCT(obr.ref_id),obr.obj_id,type FROM object_reference obr " .
4100  "JOIN object_data obd ON obd.obj_id = obr.obj_id " .
4101  "LEFT JOIN rbac_pa ON obr.ref_id = rbac_pa.ref_id " .
4102  $where .
4103  $and .
4104  "AND (" . $ilDB->like("ops_id", "text", "%i:" . $ops_id . "%") . " " .
4105  "OR " . $ilDB->like("ops_id", "text", "%:\"" . $ops_id . "\";%") . ")) " .
4106  $check_owner;
4107 
4108  $res = $ilDB->query($query);
4109  $counter = 0;
4110  while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) {
4111  if ($counter >= $limit) {
4112  break;
4113  }
4114 
4115  // Filter objects in recovery folder
4116  if ($tree->isGrandChild(RECOVERY_FOLDER_ID, $row->ref_id)) {
4117  continue;
4118  }
4119 
4120  // Check deleted, hierarchical access ...
4121  if ($ilAccess->checkAccessOfUser($a_usr_id, $a_operation, '', $row->ref_id, $row->type, $row->obj_id)) {
4122  $counter++;
4123  $ref_ids[] = $row->ref_id;
4124  }
4125  }
4126  return $ref_ids ? $ref_ids : array();
4127  }
4128 
4129 
4135  protected static function sanitateTargetPath($a_target)
4136  {
4137  switch (true) {
4138  case strpos($a_target, ILIAS_WEB_DIR . '/' . CLIENT_ID) === 0:
4139  case strpos($a_target, './' . ILIAS_WEB_DIR . '/' . CLIENT_ID) === 0:
4140  case strpos($a_target, CLIENT_WEB_DIR) === 0:
4141  $targetFilesystem = \ILIAS\FileUpload\Location::WEB;
4142  break;
4143  case strpos($a_target, CLIENT_DATA_DIR . "/temp") === 0:
4144  $targetFilesystem = \ILIAS\FileUpload\Location::TEMPORARY;
4145  break;
4146  case strpos($a_target, CLIENT_DATA_DIR) === 0:
4147  $targetFilesystem = \ILIAS\FileUpload\Location::STORAGE;
4148  break;
4149  case strpos($a_target, ILIAS_ABSOLUTE_PATH . '/Customizing') === 0:
4150  $targetFilesystem = \ILIAS\FileUpload\Location::CUSTOMIZING;
4151  break;
4152  default:
4153  throw new InvalidArgumentException("Can not move files to \"$a_target\" because path can not be mapped to web, storage or customizing location.");
4154  }
4155 
4156  $absTargetDir = dirname($a_target);
4157  $targetDir = LegacyPathHelper::createRelativePath($absTargetDir);
4158 
4159  return array( $targetFilesystem, $targetDir );
4160  }
4161 
4162 
4167  public function includeMathjax($a_tpl = null)
4168  {
4169  include_once './Services/MathJax/classes/class.ilMathJax.php';
4170  ilMathJax::getInstance()->includeMathJax($a_tpl);
4171  }
4172 
4177  public static function insertLatexImages($a_text, $a_start = '[tex]', $a_end = '[/tex]')
4178  {
4179  include_once './Services/MathJax/classes/class.ilMathJax.php';
4180  return ilMathJax::getInstance()->insertLatexImages($a_text, $a_start, $a_end);
4181  }
4182 
4187  public static function buildLatexImages($a_text, $a_dir)
4188  {
4189  include_once './Services/MathJax/classes/class.ilMathJax.php';
4190  return ilMathJax::getInstance()->insertLatexImages($a_text, '[tex]', '[/tex]', $a_dir . '/teximg', './teximg');
4191  }
4192 
4201  public static function prepareTextareaOutput($txt_output, $prepare_for_latex_output = false, $omitNl2BrWhenTextArea = false)
4202  {
4203  $result = $txt_output;
4204  $is_html = self::isHTML($result);
4205 
4206  if ($prepare_for_latex_output) {
4207  include_once './Services/MathJax/classes/class.ilMathJax.php';
4208  $result = ilMathJax::getInstance()->insertLatexImages($result, "<span class\=\"latex\">", "<\/span>");
4209  $result = ilMathJax::getInstance()->insertLatexImages($result, "\[tex\]", "\[\/tex\]");
4210  }
4211 
4212  // removed: did not work with magic_quotes_gpc = On
4213  if (!$is_html) {
4214  if (!$omitNl2BrWhenTextArea) {
4215  // if the string does not contain HTML code, replace the newlines with HTML line breaks
4216  $result = preg_replace("/[\n]/", "<br />", $result);
4217  }
4218  } else {
4219  // patch for problems with the <pre> tags in tinyMCE
4220  if (preg_match_all("/(<pre>.*?<\/pre>)/ims", $result, $matches)) {
4221  foreach ($matches[0] as $found) {
4222  $replacement = "";
4223  if (strpos("\n", $found) === false) {
4224  $replacement = "\n";
4225  }
4226  $removed = preg_replace("/<br\s*?\/>/ims", $replacement, $found);
4227  $result = str_replace($found, $removed, $result);
4228  }
4229  }
4230  }
4231  if ($prepare_for_latex_output) {
4232  // replace special characters to prevent problems with the ILIAS template system
4233  // eg. if someone uses {1} as an answer, nothing will be shown without the replacement
4234  $result = str_replace("{", "&#123;", $result);
4235  $result = str_replace("}", "&#125;", $result);
4236  $result = str_replace("\\", "&#92;", $result);
4237  }
4238 
4239  return $result;
4240  }
4241 
4250  public static function isHTML($a_text)
4251  {
4252  if (strlen(strip_tags($a_text)) < strlen($a_text)) {
4253  return true;
4254  }
4255 
4256  return false;
4257  }
4258 
4268  public static function period2String(ilDateTime $a_from, $a_to = null)
4269  {
4270  global $DIC;
4271 
4272  $lng = $DIC->language();
4273 
4274  if (!$a_to) {
4275  $a_to = new ilDateTime(time(), IL_CAL_UNIX);
4276  }
4277 
4278  $from = new DateTime($a_from->get(IL_CAL_DATETIME));
4279  $to = new DateTime($a_to->get(IL_CAL_DATETIME));
4280  $diff = $to->diff($from);
4281 
4282  $periods = array();
4283  $periods["years"] = $diff->format("%y");
4284  $periods["months"] = $diff->format("%m");
4285  $periods["days"] = $diff->format("%d");
4286  $periods["hours"] = $diff->format("%h");
4287  $periods["minutes"] = $diff->format("%i");
4288  $periods["seconds"] = $diff->format("%s");
4289 
4290  if (!array_sum($periods)) {
4291  return;
4292  }
4293 
4294  foreach ($periods as $key => $value) {
4295  if ($value) {
4296  $segment_name = ($value > 1)
4297  ? $key
4298  : substr($key, 0, -1);
4299  $array[] = $value . ' ' . $lng->txt($segment_name);
4300  }
4301  }
4302 
4303  $len = sizeof($array);
4304  if ($len > 3) {
4305  $array = array_slice($array, 0, (3-$len));
4306  }
4307 
4308  return implode(', ', $array);
4309  }
4310 
4311  public static function getFileSizeInfo()
4312  {
4313  $max_filesize = self::formatBytes(
4314  self::getUploadSizeLimitBytes()
4315  );
4316 
4317  global $DIC;
4318 
4319  $lng = $DIC->language();
4320  /*
4321  // get the value for the maximal uploadable filesize from the php.ini (if available)
4322  $umf=get_cfg_var("upload_max_filesize");
4323  // get the value for the maximal post data from the php.ini (if available)
4324  $pms=get_cfg_var("post_max_size");
4325 
4326  // use the smaller one as limit
4327  $max_filesize=min($umf, $pms);
4328  if (!$max_filesize) $max_filesize=max($umf, $pms);
4329  */
4330  return $lng->txt("file_notice") . " $max_filesize.";
4331  }
4332 
4333  public static function formatBytes($size, $decimals = 0)
4334  {
4335  $unit = array('', 'K', 'M', 'G', 'T', 'P');
4336 
4337  for ($i = 0, $maxUnits = count($unit); $size >= 1024 && $i <= $maxUnits; $i++) {
4338  $size /= 1024;
4339  }
4340 
4341  return round($size, $decimals) . $unit[$i];
4342  }
4343 
4344  public static function getUploadSizeLimitBytes()
4345  {
4346  $uploadSizeLimitBytes = min(
4347  self::convertPhpIniSizeValueToBytes(ini_get('post_max_size')),
4348  self::convertPhpIniSizeValueToBytes(ini_get('upload_max_filesize'))
4349  );
4350 
4351  return $uploadSizeLimitBytes;
4352  }
4353 
4354  public static function convertPhpIniSizeValueToBytes($phpIniSizeValue)
4355  {
4356  if (is_numeric($phpIniSizeValue)) {
4357  return $phpIniSizeValue;
4358  }
4359 
4360  $suffix = substr($phpIniSizeValue, -1);
4361  $value = substr($phpIniSizeValue, 0, -1);
4362 
4363  switch (strtoupper($suffix)) {
4364  case 'P':
4365  $value *= 1024;
4366  // no break
4367  case 'T':
4368  $value *= 1024;
4369  // no break
4370  case 'G':
4371  $value *= 1024;
4372  // no break
4373  case 'M':
4374  $value *= 1024;
4375  // no break
4376  case 'K':
4377  $value *= 1024;
4378  break;
4379  }
4380 
4381  return $value;
4382  }
4383 
4392  public static function __extractRefId($role_title)
4393  {
4394  $test_str = explode('_', $role_title);
4395 
4396  if ($test_str[0] == 'il') {
4397  $test2 = (int) $test_str[3];
4398  return is_numeric($test2) ? (int) $test2 : false;
4399  }
4400  return false;
4401  }
4402 
4413  public static function __extractId($ilias_id, $inst_id)
4414  {
4415  $test_str = explode('_', $ilias_id);
4416 
4417  if ($test_str[0] == 'il' && $test_str[1] == $inst_id && count($test_str) == 4) {
4418  $test2 = (int) $test_str[3];
4419  return is_numeric($test2) ? (int) $test2 : false;
4420  }
4421  return false;
4422  }
4423 
4438  public static function _sortIds($a_ids, $a_table, $a_field, $a_id_name)
4439  {
4440  global $DIC;
4441 
4442  $ilDB = $DIC->database();
4443 
4444  if (!$a_ids) {
4445  return array();
4446  }
4447 
4448  // use database to sort user array
4449  $where = "WHERE " . $a_id_name . " IN (";
4450  $where .= implode(",", ilUtil::quoteArray($a_ids));
4451  $where .= ") ";
4452 
4453  $query = "SELECT " . $a_id_name . " FROM " . $a_table . " " .
4454  $where .
4455  "ORDER BY " . $a_field;
4456 
4457  $res = $ilDB->query($query);
4458  while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) {
4459  $ids[] = $row->$a_id_name;
4460  }
4461  return $ids ? $ids : array();
4462  }
4463 
4473  public static function getMySQLTimestamp($a_ts)
4474  {
4475  global $DIC;
4476 
4477  $ilDB = $DIC->database();
4478 
4479  return $a_ts;
4480  }
4481 
4488  public static function quoteArray($a_array)
4489  {
4490  global $DIC;
4491 
4492  $ilDB = $DIC->database();
4493 
4494 
4495  if (!is_array($a_array) or !count($a_array)) {
4496  return array("''");
4497  }
4498 
4499  foreach ($a_array as $k => $item) {
4500  $a_array[$k] = $ilDB->quote($item);
4501  }
4502 
4503  return $a_array;
4504  }
4505 
4514  public static function sendInfo($a_info = "", $a_keep = false)
4515  {
4516  global $DIC;
4517 
4518  $tpl = $DIC["tpl"];
4519  $tpl->setMessage("info", $a_info, $a_keep);
4520  }
4521 
4530  public static function sendFailure($a_info = "", $a_keep = false)
4531  {
4532  global $DIC;
4533 
4534  if (isset($DIC["tpl"])) {
4535  $tpl = $DIC["tpl"];
4536  $tpl->setMessage("failure", $a_info, $a_keep);
4537  }
4538  }
4539 
4546  public static function sendQuestion($a_info = "", $a_keep = false)
4547  {
4548  global $DIC;
4549 
4550  $tpl = $DIC["tpl"];
4551  $tpl->setMessage("question", $a_info, $a_keep);
4552  }
4553 
4562  public static function sendSuccess($a_info = "", $a_keep = false)
4563  {
4564  global $DIC;
4565 
4566  $tpl = $DIC["tpl"];
4567  $tpl->setMessage("success", $a_info, $a_keep);
4568  }
4569 
4570  public static function infoPanel($a_keep = true)
4571  {
4572  global $DIC;
4573 
4574  $tpl = $DIC["tpl"];
4575  $lng = $DIC->language();
4576  $ilUser = $DIC->user();
4577 
4578  if (!empty($_SESSION["infopanel"]) and is_array($_SESSION["infopanel"])) {
4579  $tpl->addBlockFile(
4580  "INFOPANEL",
4581  "infopanel",
4582  "tpl.infopanel.html",
4583  "Services/Utilities"
4584  );
4585  $tpl->setCurrentBlock("infopanel");
4586 
4587  if (!empty($_SESSION["infopanel"]["text"])) {
4588  $link = "<a href=\"" . $_SESSION["infopanel"]["link"] . "\" target=\"" .
4589  ilFrameTargetInfo::_getFrame("MainContent") .
4590  "\">";
4591  $link .= $lng->txt($_SESSION["infopanel"]["text"]);
4592  $link .= "</a>";
4593  }
4594 
4595  // deactivated
4596  if (!empty($_SESSION["infopanel"]["img"])) {
4597  $link .= "<td><a href=\"" . $_SESSION["infopanel"]["link"] . "\" target=\"" .
4598  ilFrameTargetInfo::_getFrame("MainContent") .
4599  "\">";
4600  $link .= "<img src=\"" . "./templates/" . $ilUser->prefs["skin"] . "/images/" .
4601  $_SESSION["infopanel"]["img"] . "\" border=\"0\" vspace=\"0\"/>";
4602  $link .= "</a></td>";
4603  }
4604 
4605  $tpl->setVariable("INFO_ICONS", $link);
4606  $tpl->parseCurrentBlock();
4607  }
4608 
4609  //if (!$a_keep)
4610  //{
4611  ilSession::clear("infopanel");
4612  //}
4613  }
4614 
4615 
4624  public static function dirsize($directory)
4625  {
4626  $size = 0;
4627  if (!is_dir($directory)) {
4628  // BEGIN DiskQuota Suppress PHP warning when attempting to determine
4629  // dirsize of non-existing directory
4630  $size = @filesize($directory);
4631  // END DiskQuota Suppress PHP warning.
4632  return ($size === false) ? -1 : $size;
4633  }
4634  if ($DIR = opendir($directory)) {
4635  while (($dirfile = readdir($DIR)) !== false) {
4636  if (is_link($directory . DIRECTORY_SEPARATOR . $dirfile) || $dirfile == '.' || $dirfile == '..') {
4637  continue;
4638  }
4639  if (is_file($directory . DIRECTORY_SEPARATOR . $dirfile)) {
4640  $size += filesize($directory . DIRECTORY_SEPARATOR . $dirfile);
4641  } elseif (is_dir($directory . DIRECTORY_SEPARATOR . $dirfile)) {
4642  // BEGIN DiskQuota: dirsize is not a global function anymore
4643  $dirSize = ilUtil::dirsize($directory . DIRECTORY_SEPARATOR . $dirfile);
4644  // END DiskQuota: dirsize is not a global function anymore
4645  if ($dirSize >= 0) {
4646  $size += $dirSize;
4647  } else {
4648  return -1;
4649  }
4650  }
4651  }
4652  closedir($DIR);
4653  }
4654  return $size;
4655  }
4656 
4657  public static function randomhash()
4658  {
4659  $random = new \ilRandom();
4660  return md5($random->int(1, 9999999) + str_replace(" ", "", (string) microtime()));
4661  }
4662 
4663  public static function setCookie($a_cookie_name, $a_cookie_value = '', $a_also_set_super_global = true, $a_set_cookie_invalid = false)
4664  {
4665  /*
4666  if(!(bool)$a_set_cookie_invalid) $expire = IL_COOKIE_EXPIRE;
4667  else $expire = time() - (365*24*60*60);
4668  */
4669  // Temporary fix for feed.php
4670  if (!(bool) $a_set_cookie_invalid) {
4671  $expire = 0;
4672  } else {
4673  $expire = time() - (365*24*60*60);
4674  }
4675  /* We MUST NOT set the global constant here, because this affects the session_set_cookie_params() call as well
4676  if(!defined('IL_COOKIE_SECURE'))
4677  {
4678  define('IL_COOKIE_SECURE', false);
4679  }
4680  */
4681  $secure = false;
4682  if (defined('IL_COOKIE_SECURE')) {
4683  $secure = IL_COOKIE_SECURE;
4684  }
4685 
4686  setcookie(
4687  $a_cookie_name,
4688  $a_cookie_value,
4689  $expire,
4691  IL_COOKIE_DOMAIN,
4692  $secure,
4693  IL_COOKIE_HTTPONLY
4694  );
4695 
4696  if ((bool) $a_also_set_super_global) {
4697  $_COOKIE[$a_cookie_name] = $a_cookie_value;
4698  }
4699  }
4700 
4701  public static function _sanitizeFilemame($a_filename)
4702  {
4703  return strip_tags(self::stripSlashes($a_filename));
4704  }
4705 
4706  public static function _getHttpPath()
4707  {
4708  global $DIC;
4709 
4710  $ilIliasIniFile = $DIC["ilIliasIniFile"];
4711 
4712  if ($_SERVER['SHELL'] || php_sapi_name() == 'cli' ||
4713  // fallback for windows systems, useful in crons
4714  (class_exists("ilContext") && !ilContext::usesHTTP())) {
4715  return $ilIliasIniFile->readVariable('server', 'http_path');
4716  } else {
4717  return ILIAS_HTTP_PATH;
4718  }
4719  }
4720 
4726  public static function printBacktrace($a_limit = 0)
4727  {
4728  $bt = debug_backtrace();
4729  $cnt = 0;
4730  foreach ($bt as $t) {
4731  if ($cnt != 0 && ($a_limit == 0 || $cnt <= $a_limit)) {
4732  echo "<br>" . $t["file"] . ", " . $t["function"] . " [" . $t["line"] . "]";
4733  }
4734  $cnt++;
4735  }
4736  echo "<br>";
4737  }
4738 
4753  public static function parseImportId($a_import_id)
4754  {
4755  $exploded = explode('_', $a_import_id);
4756 
4757  $parsed['orig'] = $a_import_id;
4758  if ($exploded[0] == 'il') {
4759  $parsed['prefix'] = $exploded[0];
4760  }
4761  if (is_numeric($exploded[1])) {
4762  $parsed['inst_id'] = (int) $exploded[1];
4763  }
4764  $parsed['type'] = $exploded[2];
4765 
4766  if (is_numeric($exploded[3])) {
4767  $parsed['id'] = (int) $exploded[3];
4768  }
4769  return $parsed;
4770  }
4771 
4778  public static function unserializeSession($data)
4779  {
4780  $vars = preg_split(
4781  '/([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff^|]*)\|/',
4782  $data,
4783  -1,
4784  PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE
4785  );
4786 
4787  $result = array();
4788 
4789  for ($i = 0; $vars[$i]; $i++) {
4790  $result[$vars[$i++]] = unserialize($vars[$i]);
4791  }
4792 
4793  return $result;
4794  }
4795 
4796 
4809  public function rangeDownload($file)
4810  {
4811  $fp = @fopen($file, 'rb');
4812 
4813  $size = filesize($file); // File size
4814  $length = $size; // Content length
4815  $start = 0; // Start byte
4816  $end = $size - 1; // End byte
4817  // Now that we've gotten so far without errors we send the accept range header
4818  /* At the moment we only support single ranges.
4819  * Multiple ranges requires some more work to ensure it works correctly
4820  * and comply with the spesifications: http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.2
4821  *
4822  * Multirange support annouces itself with:
4823  * header('Accept-Ranges: bytes');
4824  *
4825  * Multirange content must be sent with multipart/byteranges mediatype,
4826  * (mediatype = mimetype)
4827  * as well as a boundry header to indicate the various chunks of data.
4828  */
4829  header("Accept-Ranges: 0-$length");
4830  // header('Accept-Ranges: bytes');
4831  // multipart/byteranges
4832  // http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.2
4833  if (isset($_SERVER['HTTP_RANGE'])) {
4834  $c_start = $start;
4835  $c_end = $end;
4836  // Extract the range string
4837  list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
4838  // Make sure the client hasn't sent us a multibyte range
4839  if (strpos($range, ',') !== false) {
4840 
4841  // (?) Shoud this be issued here, or should the first
4842  // range be used? Or should the header be ignored and
4843  // we output the whole content?
4844  header('HTTP/1.1 416 Requested Range Not Satisfiable');
4845  header("Content-Range: bytes $start-$end/$size");
4846  // (?) Echo some info to the client?
4847  exit;
4848  }
4849  // If the range starts with an '-' we start from the beginning
4850  // If not, we forward the file pointer
4851  // And make sure to get the end byte if spesified
4852  if ($range == '-') {
4853 
4854  // The n-number of the last bytes is requested
4855  $c_start = $size - substr($range, 1);
4856  } else {
4857  $range = explode('-', $range);
4858  $c_start = $range[0];
4859  $c_end = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size;
4860  }
4861  /* Check the range and make sure it's treated according to the specs.
4862  * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
4863  */
4864  // End bytes can not be larger than $end.
4865  $c_end = ($c_end > $end) ? $end : $c_end;
4866  // Validate the requested range and return an error if it's not correct.
4867  if ($c_start > $c_end || $c_start > $size - 1 || $c_end >= $size) {
4868  header('HTTP/1.1 416 Requested Range Not Satisfiable');
4869  header("Content-Range: bytes $start-$end/$size");
4870  // (?) Echo some info to the client?
4871  exit;
4872  }
4873  $start = $c_start;
4874  $end = $c_end;
4875  $length = $end - $start + 1; // Calculate new content length
4876  fseek($fp, $start);
4877  header('HTTP/1.1 206 Partial Content');
4878  }
4879  // Notify the client the byte range we'll be outputting
4880  header("Content-Range: bytes $start-$end/$size");
4881  header("Content-Length: $length");
4882 
4883  // Start buffered download
4884  $buffer = 1024 * 8;
4885  while (!feof($fp) && ($p = ftell($fp)) <= $end) {
4886  if ($p + $buffer > $end) {
4887 
4888  // In case we're only outputtin a chunk, make sure we don't
4889  // read past the length
4890  $buffer = $end - $p + 1;
4891  }
4892  set_time_limit(0); // Reset time limit for big files
4893  echo fread($fp, $buffer);
4894  flush(); // Free up memory. Otherwise large files will trigger PHP's memory limit.
4895  }
4896 
4897  fclose($fp);
4898  }
4899 
4900 
4901  //
4902  // used to be in ilFormat
4903  //
4904 
4917  protected static function _getSizeMagnitude()
4918  {
4919  return 1024;
4920  }
4921 
4935  protected static function fmtFloat($a_float, $a_decimals=0, $a_dec_point = null, $a_thousands_sep = null, $a_suppress_dot_zero=false)
4936  {
4937  global $DIC;
4938 
4939  $lng = $DIC->language();
4940 
4941  if ($a_dec_point == null) {
4942  {
4943  $a_dec_point = ".";
4944  }
4945  }
4946  if ($a_dec_point == '-lang_sep_decimal-') {
4947  $a_dec_point = ".";
4948  }
4949 
4950  if ($a_thousands_sep == null) {
4951  $a_thousands_sep = $lng->txt('lang_sep_thousand');
4952  }
4953  if ($a_thousands_sep == '-lang_sep_thousand-') {
4954  $a_thousands_sep = ",";
4955  }
4956 
4957  $txt = number_format($a_float, $a_decimals, $a_dec_point, $a_thousands_sep);
4958 
4959  // remove trailing ".0"
4960  if (($a_suppress_dot_zero == 0 || $a_decimals == 0)
4961  && substr($txt, -2) == $a_dec_point . '0'
4962  ) {
4963  $txt = substr($txt, 0, strlen($txt) - 2);
4964  }
4965  if ($a_float == 0 and $txt == "") {
4966  $txt = "0";
4967  }
4968 
4969  return $txt;
4970  }
4971 
4988  public static function formatSize($size, $a_mode = 'short', $a_lng = null)
4989  {
4990  global $DIC;
4991 
4992  $lng = $DIC->language();
4993  if ($a_lng == null) {
4994  $a_lng = $lng;
4995  }
4996 
4997  $mag = self::_getSizeMagnitude();
4998 
4999  if ($size >= $mag * $mag * $mag) {
5000  $scaled_size = $size / $mag / $mag / $mag;
5001  $scaled_unit = 'lang_size_gb';
5002  } else {
5003  if ($size >= $mag * $mag) {
5004  $scaled_size = $size / $mag / $mag;
5005  $scaled_unit = 'lang_size_mb';
5006  } else {
5007  if ($size >= $mag) {
5008  $scaled_size = $size / $mag;
5009  $scaled_unit = 'lang_size_kb';
5010  } else {
5011  $scaled_size = $size;
5012  $scaled_unit = 'lang_size_bytes';
5013  }
5014  }
5015  }
5016 
5017  $result = self::fmtFloat($scaled_size, ($scaled_unit
5018  == 'lang_size_bytes') ? 0 : 1, $a_lng->txt('lang_sep_decimal'), $a_lng->txt('lang_sep_thousand'), true)
5019  . ' ' . $a_lng->txt($scaled_unit);
5020  if ($a_mode == 'long' && $size > $mag) {
5021  $result .= ' (' . self::fmtFloat($size, 0, $a_lng->txt('lang_sep_decimal'), $a_lng->txt('lang_sep_thousand')) . ' '
5022  . $a_lng->txt('lang_size_bytes') . ')';
5023  }
5024 
5025  return $result;
5026  }
5027 
5028 
5029  //
5030  // used for disk quotas
5031  //
5032 
5033  public static function MB2Bytes($a_value)
5034  {
5035  return ((int) $a_value) * pow(self::_getSizeMagnitude(), 2);
5036  }
5037 
5038  public static function Bytes2MB($a_value)
5039  {
5040  return ((int) $a_value) / (pow(self::_getSizeMagnitude(), 2));
5041  }
5042 
5050  public static function dbSupportsDisctinctUmlauts()
5051  {
5052  global $DIC;
5053 
5054  if (!isset(self::$db_supports_distinct_umlauts)) {
5055  $ilDB = $DIC->database();
5056  $set = $ilDB->query("SELECT (" . $ilDB->quote("A", "text") . " = " . $ilDB->quote("Ä", "text") . ") t FROM DUAL ");
5057  $rec = $ilDB->fetchAssoc($set);
5058  self::$db_supports_distinct_umlauts = !(bool) $rec["t"];
5059  }
5060 
5061  return self::$db_supports_distinct_umlauts;
5062  }
5063 
5069  public static function dumpVar($mixed = null)
5070  {
5071  echo '<pre>';
5072  var_dump($mixed);
5073  echo '</pre>';
5074  }
5075 } // END class.ilUtil
static maskTag($a_str, $t, $fix_param="")
$files
Definition: add-vimline.php:18
static sendSuccess($a_info="", $a_keep=false)
Send Success Message to Screen.
$params
Definition: disable.php:11
static isConvertVersionAtLeast($a_version)
Compare convert version numbers.
static _getIcon( $a_obj_id="", $a_size="big", $a_type="", $a_offline=false)
Get icon for repository item.
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
global $ilErr
Definition: raiseError.php:16
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.
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" ...
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; ...
$end
Definition: saml1-acs.php:18
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...
$attributes
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.
static getClientIdByString($clientId)
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()
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
$base
Definition: index.php:4
static & processCSVRow(&$row, $quoteAll=false, $separator=";", $outUTF8=false, $compatibleWithMSExcel=true)
Convertes an array for CSV usage.
static sendInfo($a_info="", $a_keep=false)
Send Info Message to Screen.
$counter
$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.
if($format !==null) $name
Definition: metadata.php:146
static getAssociatedUsersOnline($a_user_id)
reads all active sessions from db and returns users that are online and who have a local role in a gr...
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 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.
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)
static KT_replaceParam($qstring, $paramName, $paramValue)
static _lookupObjId($a_id)
static makeClickable($a_text, $detectGotoLinks=false)
makeClickable In Texten enthaltene URLs und Mail-Adressen klickbar machen
date( 'd-M-Y', $objPHPExcel->getProperties() ->getCreated())
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:36
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
Add a drawing to the header
Definition: 04printing.php:69
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
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
static _getAssociatedUsersOnline($a_user_id, $a_no_anonymous=false)
reads all active sessions from db and returns users that are online and who have a local role in a gr...
$ascii_filename
Definition: metadata.php:317
Create styles array
The data for the language used.
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.
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
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)
Create a temporary file in an ILIAS writable 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.
static secureLink($a_str)
$parser
Definition: BPMN2Parser.php:23
$errors
Definition: index.php:6
static img($a_src, $a_alt="", $a_width="", $a_height="", $a_border=0, $a_id="", $a_class="")
Build img tag.
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.
global $lng
Definition: privfeed.php:17
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
$ilIliasIniFile
$url
static recursive_dirscan($dir, &$arr)
Recursively scans a given directory and writes path and filename into referenced array.
Add data(end) time
Method that wraps PHPs time in order to allow simulations with the workflow.
if(!file_exists("$old.txt")) if($old===$new) if(file_exists("$new.txt")) $file
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 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
defined( 'APPLICATION_ENV')||define( 'APPLICATION_ENV'
Definition: bootstrap.php:27
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.
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
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.
if(!isset($_REQUEST['ReturnTo'])) if(!isset($_REQUEST['AuthId'])) $options
Definition: as_login.php:20
static dumpString($a_str)
dumps ord values of every character of string $a_str
static sanitateTargetPath($a_target)
static readFile($a_file)
there are some known problems with the original readfile method, which sometimes truncates delivered ...