ILIAS  release_5-0 Revision 5.0.0-1144-gc4397b1f870
All Data Structures Namespaces Files Functions Variables Modules Pages
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 
17 class ilUtil
18 {
29  public static function getImageTagByType($a_type, $a_path, $a_big = false)
30  {
31  global $lng;
32 
33  $size = ($a_big)
34  ? "big"
35  : "small";
36 
37  include_once("./Services/Object/classes/class.ilObject.php");
38  $filename = ilObject::_getIcon("", $size, $a_type);
39 
40  return "<img src=\"".$filename."\" alt=\"".$lng->txt("obj_".$a_type)."\" title=\"".$lng->txt("obj_".$a_type)."\" border=\"0\" vspace=\"0\"/>";
41  }
42 
55  public static function getTypeIconPath($a_type,$a_obj_id,$a_size = 'small')
56  {
57  include_once("./Services/Object/classes/class.ilObject.php");
58  return ilObject::_getIcon($a_obj_id, $a_size, $a_type);
59  }
60 
71  public static function getImagePath($img, $module_path = "", $mode = "output", $offline = false)
72  {
73  global $ilias, $styleDefinition, $ilCtrl, $ilUser;
74 
75  if (is_int(strpos($_SERVER["PHP_SELF"], "setup.php")))
76  {
77  $module_path = "..";
78  }
79  if ($module_path != "")
80  {
81  $module_path = "/".$module_path;
82  }
83 
84  // default image
85  $default_img = ".".$module_path."/templates/default/images/".$img;
86 
87  // use ilStyleDefinition instead of account to get the current skin and style
88  require_once("./Services/Style/classes/class.ilStyleDefinition.php");
89  $current_skin = ilStyleDefinition::getCurrentSkin();
90  $current_style = ilStyleDefinition::getCurrentStyle();
91 
92  if (is_object($styleDefinition))
93  {
94  $image_dir = $styleDefinition->getImageDirectory(
96  $current_style);
97  }
98  if ($current_skin == "default")
99  {
100  $user_img = ".".$module_path."/templates/default/".$image_dir."/".$img;
101  $skin_img = ".".$module_path."/templates/default/images/".$img;
102  }
103  else if (is_object($styleDefinition) && $current_skin != "default")
104  {
105  $user_img = "./Customizing/global/skin/".
106  $current_skin.$module_path."/".$image_dir."/".$img;
107  $skin_img = "./Customizing/global/skin/".
108  $current_skin.$module_path."/images/".$img;
109  }
110 
111  // temp svg patch
112  /*
113  $pi = pathinfo($img);
114  if ($pi["dirname"] != "") {
115  $pi["dirname"] = $pi["dirname"]."/";
116  }
117  $svg_img = ".".$module_path."/templates/default/images/".$pi["dirname"].$pi["filename"].".svg";
118  if (file_exists($svg_img))
119  {
120  return $svg_img;
121  }*/
122 
123 
124  if ($offline)
125  {
126  return "./images/".$img;
127  }
128  else if (@file_exists($user_img) && $image_dir != "")
129  {
130  return $user_img; // found image for skin and style
131  }
132  else if (file_exists($skin_img))
133  {
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  {
154  $relative_path = (substr($relative_path, 1));
155  }
156  if (substr($relative_path, 0, 1) != '/')
157  {
158  $relative_path = '/' . $relative_path;
159  }
160  $htmlpath = ILIAS_HTTP_PATH . $relative_path;
161  return $htmlpath;
162  }
163 
176  public static function getStyleSheetLocation($mode = "output", $a_css_name = "", $a_css_location = "")
177  {
178  global $ilias;
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/classes/class.ilStyleDefinition.php");
183  $stylesheet_name = (strlen($a_css_name))
184  ? $a_css_name
186  if (strlen($a_css_location) && (strcmp(substr($a_css_location, -1), "/") != 0))
187  {
188  $a_css_location = $a_css_location . "/";
189  }
190 
191  $filename = "";
192  // use ilStyleDefinition instead of account to get the current skin
193  require_once("./Services/Style/classes/class.ilStyleDefinition.php");
194  if (ilStyleDefinition::getCurrentSkin() != "default")
195  {
196  $filename = "./Customizing/global/skin/".ilStyleDefinition::getCurrentSkin()."/".$a_css_location.$stylesheet_name;
197  }
198  if (strlen($filename) == 0 || !file_exists($filename))
199  {
200  $filename = "./" . $a_css_location . "templates/default/".$stylesheet_name;
201  }
202  $vers = "";
203  if ($mode != "filesystem")
204  {
205  $vers = str_replace(" ", "-", $ilias->getSetting("ilias_version"));
206  $vers = "?vers=".str_replace(".", "-", $vers);
207  }
208  return $filename . $vers;
209  }
210 
221  public static function getJSLocation($a_js_name, $a_js_location = "", $add_version = FALSE)
222  {
223  global $ilias;
224 
225  // add version as parameter to force reload for new releases
226  $js_name = $a_js_name;
227  if (strlen($a_js_location) && (strcmp(substr($a_js_location, -1), "/") != 0)) $a_js_location = $a_js_location . "/";
228 
229  $filename = "";
230  // use ilStyleDefinition instead of account to get the current skin
231  require_once("./Services/Style/classes/class.ilStyleDefinition.php");
232  if (ilStyleDefinition::getCurrentSkin() != "default")
233  {
234  $filename = "./Customizing/global/skin/".ilStyleDefinition::getCurrentSkin()."/".$a_js_location.$js_name;
235  }
236  if (strlen($filename) == 0 || !file_exists($filename))
237  {
238  $filename = "./" . $a_js_location . "templates/default/".$js_name;
239  }
240  $vers = "";
241  if ($add_version)
242  {
243  $vers = str_replace(" ", "-", $ilias->getSetting("ilias_version"));
244  $vers = "?vers=".str_replace(".", "-", $vers);
245  }
246  return $filename . $vers;
247  }
248 
256  public static function getP3PLocation()
257  {
258  global $ilias;
259 
260  if (defined("ILIAS_MODULE"))
261  {
262  $base = '';
263  for($i = 0;$i < count(explode('/',ILIAS_MODULE));$i++)
264  {
265  $base .= "../Services/Privacy/";
266  }
267  }
268  else
269  {
270  $base = "./Services/Privacy/";
271  }
272 
273  if (is_file($base."w3c/p3p.xml"))
274  {
275  return ILIAS_HTTP_PATH."w3c/p3p.xml";
276  }
277  else
278  {
279  return ILIAS_HTTP_PATH."/w3c/p3p_template.xml";
280  }
281  }
282 
290  public static function getNewContentStyleSheetLocation($mode = "output")
291  {
292  global $ilias;
293 
294  // add version as parameter to force reload for new releases
295  if ($mode != "filesystem")
296  {
297  $vers = str_replace(" ", "-", $ilias->getSetting("ilias_version"));
298  $vers = "?vers=".str_replace(".", "-", $vers);
299  }
300 
301  // use ilStyleDefinition instead of account to get the current skin and style
302  require_once("./Services/Style/classes/class.ilStyleDefinition.php");
303  if (ilStyleDefinition::getCurrentSkin() == "default")
304  {
305  $in_style = "./templates/".ilStyleDefinition::getCurrentSkin()."/"
306  .ilStyleDefinition::getCurrentStyle()."_cont.css";
307  }
308  else
309  {
310  $in_style = "./Customizing/global/skin/".ilStyleDefinition::getCurrentSkin()."/"
311  .ilStyleDefinition::getCurrentStyle()."_cont.css";
312  }
313 
314  if (is_file("./".$in_style))
315  {
316  return $in_style.$vers;
317  }
318  else
319  {
320  return "templates/default/delos_cont.css".$vers;
321  }
322  }
323 
342  public static function formSelect($selected,$varname,$options,$multiple = false,$direct_text = false, $size = "0",
343  $style_class = "", $attribs = "",$disabled = false)
344  {
345  global $lng;
346 
347  if ($multiple == true)
348  {
349  $multiple = " multiple=\"multiple\"";
350  }
351  else
352  {
353  $multiple = "";
354  $size = 0;
355  }
356 
357  $class = " class=\" form-control ".$style_class."\"";
358 
359  // use form-inline!
360  // this is workaround the whole function should be set deprecated
361  // $attributes = " style='display:inline-block;' ";
362 
363  if (is_array($attribs))
364  {
365  foreach ($attribs as $key => $val)
366  {
367  $attributes .= " ".$key."=\"".$val."\"";
368  }
369  }
370  if($disabled)
371  {
372  $disabled = ' disabled=\"disabled\"';
373  }
374 
375  $str = "<select name=\"".$varname ."\"".$multiple." $class size=\"".$size."\" $attributes $disabled>\n";
376 
377  foreach ((array) $options as $key => $val)
378  {
379  $style = "";
380  if (is_array($val))
381  {
382  $style = $val["style"];
383  $val = $val["text"]; // mus be last line, since we overwrite
384  }
385 
386  $sty = ($style != "")
387  ? ' style="'.$style.'" '
388  : "";
389 
390  if ($direct_text)
391  {
392  $str .= " <option $sty value=\"".$key."\"";
393  }
394  else
395  {
396  $str .= " <option $sty value=\"".$val."\"";
397  }
398  if (is_array($selected) )
399  {
400  if (in_array($key,$selected))
401  {
402  $str .= " selected=\"selected\"";
403  }
404  }
405  else if ($selected == $key)
406  {
407  $str .= " selected=\"selected\"";
408  }
409 
410  if ($direct_text)
411  {
412  $str .= ">".$val."</option>\n";
413  }
414  else
415  {
416  $str .= ">".$lng->txt($val)."</option>\n";
417  }
418  }
419 
420  $str .= "</select>\n";
421 
422  return $str;
423  }
424 
434  public static function getSelectName ($selected,$values)
435  {
436  return($values[$selected]);
437  }
438 
450  public static function formCheckbox ($checked,$varname,$value,$disabled = false)
451  {
452  $str = "<input type=\"checkbox\" name=\"".$varname."\"";
453 
454  if ($checked == 1)
455  {
456  $str .= " checked=\"checked\"";
457  }
458 
459  if ($disabled)
460  {
461  $str .= " disabled=\"disabled\"";
462  }
463 
464  $array_var = false;
465 
466  if (substr($varname,-2) == "[]")
467  {
468  $array_var = true;
469  }
470 
471  // if varname ends with [], use varname[-2] + _ + value as id tag (e.g. "user_id[]" => "user_id_15")
472  if ($array_var)
473  {
474  $varname_id = substr($varname,0,-2)."_".$value;
475  }
476  else
477  {
478  $varname_id = $varname;
479  }
480 
481  // dirty removal of other "[]" in string
482  $varname_id = ereg_replace("\[","_",$varname_id);
483  $varname_id = ereg_replace("\]","",$varname_id);
484 
485  $str .= " value=\"".$value."\" id=\"".$varname_id."\" />\n";
486 
487  return $str;
488  }
489 
501  public static function formDisabledRadioButton($checked,$varname,$value,$disabled)
502  {
503  if ($disabled) {
504  $str = "<input disabled type=\"radio\" name=\"".$varname."\"";
505  }
506  else {
507  $str = "<input type=\"radio\" name=\"".$varname."\"";
508  }
509  if ($checked == 1)
510  {
511  $str .= " checked=\"checked\"";
512  }
513 
514  $str .= " value=\"".$value."\"";
515  $str .= " id=\"".$value."\" />\n";
516 
517  return $str;
518 
519  }
520 
521 
532  public static function formRadioButton($checked,$varname,$value,$onclick=null, $disabled = false)
533  {
534  $str = '<input ';
535 
536  if($onclick)
537  {
538  $str .= ('onclick="'.$onclick.'"');
539  }
540 
541  $str .= (" type=\"radio\" name=\"".$varname."\"");
542  if ($checked == 1)
543  {
544  $str .= " checked=\"checked\"";
545  }
546 
547  if ($disabled)
548  {
549  $str .= " disabled=\"disabled\"";
550  }
551 
552  $str .= " value=\"".$value."\"";
553 
554  $str .= " id=\"".$value."\" />\n";
555 
556  return $str;
557  }
558 
559 
569  public static function formInput($varname,$value,$disabled = false)
570  {
571 
572  $str = "<input type=\"input\" name=\"".$varname."\"";
573  if ($disabled)
574  {
575  $str .= " disabled";
576  }
577 
578  $str .= " value=\"".$value."\"";
579 
580  $str .= " id=\"".$value."\" />\n";
581 
582  return $str;
583  }
584 
585 
592  public static function checkInput ($vars)
593  {
594  // TO DO:
595  // Diese Funktion soll Formfeldeingaben berprfen (empty und required)
596  }
597 
604  public static function setPathStr ($a_path)
605  {
606  if ("" != $a_path && "/" != substr($a_path, -1))
607  {
608  $a_path .= "/";
609  //$a_path = substr($a_path,1);
610  }
611 
612  //return getcwd().$a_path;
613  return $a_path;
614  }
615 
628  public static function switchColor ($a_num,$a_css1,$a_css2)
629  {
630  if (!($a_num % 2))
631  {
632  return $a_css1;
633  }
634  else
635  {
636  return $a_css2;
637  }
638  }
639 
648  public static function checkFormEmpty ($emptyFields)
649  {
650 
651  $feedback = "";
652 
653  foreach ($emptyFields as $key => $val)
654  {
655  if ($val == "") {
656  if ($feedback != "") $feedback .= ", ";
657  $feedback .= $key;
658  }
659  }
660 
661  return $feedback;
662  }
663 
688  public static function Linkbar ($AScript,$AHits,$ALimit,$AOffset,$AParams = array(),$ALayout = array(), $prefix = '')
689  {
690  $LinkBar = "";
691 
692  $layout_link = "";
693  $layout_prev = "&lt;&lt;";
694  $layout_next = "&gt;&gt;";
695 
696  // layout options
697  if (count($ALayout > 0))
698  {
699  if ($ALayout["link"])
700  {
701  $layout_link = " class=\"".$ALayout["link"]."\"";
702  }
703 
704  if ($ALayout["prev"])
705  {
706  $layout_prev = $ALayout["prev"];
707  }
708 
709  if ($ALayout["next"])
710  {
711  $layout_next = $ALayout["next"];
712  }
713  }
714 
715  // show links, if hits greater limit
716  // or offset > 0 (can be > 0 due to former setting)
717  if ($AHits > $ALimit || $AOffset > 0)
718  {
719  if (!empty($AParams))
720  {
721  foreach ($AParams as $key => $value)
722  {
723  $params.= $key."=".$value."&";
724  }
725  }
726  // if ($params) $params = substr($params,0,-1);
727  if(strpos($AScript,'&'))
728  {
729  $link = $AScript."&".$params.$prefix."offset=";
730  }
731  else
732  {
733  $link = $AScript."?".$params.$prefix."offset=";
734  }
735 
736  // ?bergehe "zurck"-link, wenn offset 0 ist.
737  if ($AOffset >= 1)
738  {
739  $prevoffset = $AOffset - $ALimit;
740  if ($prevoffset < 0) $prevoffset = 0;
741  $LinkBar .= "<a".$layout_link." href=\"".$link.$prevoffset."\">".$layout_prev."&nbsp;</a>";
742  }
743 
744  // Ben?tigte Seitenzahl kalkulieren
745  $pages=intval($AHits/$ALimit);
746 
747  // Wenn ein Rest bleibt, addiere eine Seite
748  if (($AHits % $ALimit))
749  $pages++;
750 
751  // Bei Offset = 0 keine Seitenzahlen anzeigen : DEAKTIVIERT
752  // if ($AOffset != 0) {
753 
754  // ansonsten zeige Links zu den anderen Seiten an
755  for ($i = 1 ;$i <= $pages ; $i++)
756  {
757  $newoffset=$ALimit*($i-1);
758 
759  if ($newoffset == $AOffset)
760  {
761  $LinkBar .= "[".$i."] ";
762  }
763  else
764  {
765  $LinkBar .= '<a '.$layout_link.' href="'.
766  $link.$newoffset.'">['.$i.']</a> ';
767  }
768  }
769  // }
770 
771  // Checken, ob letze Seite erreicht ist
772  // Wenn nicht, gebe einen "Weiter"-Link aus
773  if (! ( ($AOffset/$ALimit)==($pages-1) ) && ($pages!=1) )
774  {
775  $newoffset=$AOffset+$ALimit;
776  $LinkBar .= "<a".$layout_link." href=\"".$link.$newoffset."\">&nbsp;".$layout_next."</a>";
777  }
778 
779  return $LinkBar;
780  }
781  else
782  {
783  return false;
784  }
785  }
786 
798  public static function makeClickable($a_text, $detectGotoLinks = false)
799  {
800  // New code, uses MediaWiki Sanitizer
801  $ret = $a_text;
802 
803  // www-URL ohne ://-Angabe
804  $ret = eregi_replace("(^|[[:space:]]+)(www\.)([[:alnum:]#?/&=\.-]+)",
805  "\\1http://\\2\\3", $ret);
806 
807  // ftp-URL ohne ://-Angabe
808  $ret = eregi_replace("(^|[[:space:]]+)(ftp\.)([[:alnum:]#?/&=\.-]+)",
809  "\\1ftp://\\2\\3", $ret);
810 
811  // E-Mail (this does not work as expected, users must add mailto: manually)
812  //$ret = eregi_replace("(([a-z0-9_]|\\-|\\.)+@([^[:space:]]*)([[:alnum:]-]))",
813  // "mailto:\\1", $ret);
814 
815  // mask existing image tags
816  $ret = str_replace('src="http://', '"***masked_im_start***', $ret);
817 
818  include_once("./Services/Utilities/classes/class.ilMWParserAdapter.php");
819  $parser = new ilMWParserAdapter();
820  $ret = $parser->replaceFreeExternalLinks($ret);
821 
822  // unmask existing image tags
823  $ret = str_replace('"***masked_im_start***', 'src="http://', $ret);
824 
825  // Should be Safe
826 
827  if ($detectGotoLinks)
828  // replace target blank with self and text with object title.
829  {
830  $regExp = "<a[^>]*href=\"(".str_replace("/","\/",ILIAS_HTTP_PATH)."\/goto.php\?target=\w+_(\d+)[^\"]*)\"[^>]*>[^<]*<\/a>";
831 // echo htmlentities($regExp);
832  $ret = preg_replace_callback(
833  "/".$regExp."/i",
834  array("ilUtil", "replaceLinkProperties"),
835  $ret);
836 
837  // Static links
838  $regExp = "<a[^>]*href=\"(".str_replace("/","\/",ILIAS_HTTP_PATH)."\/goto_.*[a-z0-9]+_([0-9]+)\.html)\"[^>]*>[^<]*<\/a>";
839 // echo htmlentities($regExp);
840  $ret = preg_replace_callback(
841  "/".$regExp."/i",
842  array("ilUtil", "replaceLinkProperties"),
843  $ret);
844  }
845 
846  return($ret);
847  }
848 
862  public static function replaceLinkProperties ($matches)
863  {
864  $link = $matches[0];
865  $ref_id = $matches[2];
866 
867  if ($ref_id > 0)
868  {
869  $obj_id = ilObject::_lookupObjId($ref_id);
870  if ($obj_id > 0)
871  {
872  $title = ilObject::_lookupTitle($obj_id);
873  $link = "<a href=".$matches[1]." target=\"_self\">".$title."</a>";
874  }
875  }
876  return $link;
877  }
878 
897  public static function makeDateSelect($prefix, $year = "", $month = "", $day = "", $startyear = "",$a_long_month = true,$a_further_options = array(), $emptyoption = false)
898  {
899  global $lng;
900 
901  $disabled = '';
902  if(isset($a_further_options['disabled']) and $a_further_options['disabled'])
903  {
904  $disabled = 'disabled="disabled" ';
905  }
906 
907  $now = getdate();
908  if (!$emptyoption)
909  {
910  if (!strlen($year)) $year = $now["year"];
911  if (!strlen($month)) $month = $now["mon"];
912  if (!strlen($day)) $day = $now["mday"];
913  }
914 
915  $year = (int) $year;
916  $month = (int) $month;
917  $day = (int) $day;
918 
919  // build day select
920 
921  $sel_day .= '<select class="form-control" ';
922  if(isset($a_further_options['select_attributes']))
923  {
924  foreach($a_further_options['select_attributes'] as $name => $value)
925  {
926  $sel_day .= ($name.'="'.$value.'" ');
927  }
928  }
929 
930  $sel_day .= $disabled."name=\"".$prefix."[d]\" id=\"".$prefix."_d\">\n";
931 
932  if ($emptyoption) $sel_day .= "<option value=\"0\">--</option>\n";
933  for ($i = 1; $i <= 31; $i++)
934  {
935  $sel_day .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
936  }
937  $sel_day .= "</select>\n";
938  $sel_day = preg_replace("/(value\=\"$day\")/", "$1 selected=\"selected\"", $sel_day);
939 
940  // build month select
941  $sel_month = '<select class="form-control" ';
942  if(isset($a_further_options['select_attributes']))
943  {
944  foreach($a_further_options['select_attributes'] as $name => $value)
945  {
946  $sel_month .= ($name.'="'.$value.'" ');
947  }
948  }
949  $sel_month .= $disabled."name=\"".$prefix."[m]\" id=\"".$prefix."_m\">\n";
950 
951  if ($emptyoption) $sel_month .= "<option value=\"0\">--</option>\n";
952  for ($i = 1; $i <= 12; $i++)
953  {
954  if($a_long_month)
955  {
956  $sel_month .= "<option value=\"$i\">" . $lng->txt("month_" . sprintf("%02d", $i) . "_long") . "</option>\n";
957  }
958  else
959  {
960  $sel_month .= "<option value=\"$i\">" . $i . "</option>\n";
961  }
962  }
963  $sel_month .= "</select>\n";
964  $sel_month = preg_replace("/(value\=\"$month\")/", "$1 selected=\"selected\"", $sel_month);
965 
966  // build year select
967  $sel_year = '<select class="form-control" ';
968  if(isset($a_further_options['select_attributes']))
969  {
970  foreach($a_further_options['select_attributes'] as $name => $value)
971  {
972  $sel_year .= ($name.'="'.$value.'" ');
973  }
974  }
975  $sel_year .= $disabled."name=\"".$prefix."[y]\" id=\"".$prefix."_y\">\n";
976  if ((strlen($startyear) == 0) || ($startyear > $year))
977  {
978  if (!$emptyoption || $year != 0) $startyear = $year - 5;
979  }
980 
981  if(($year + 5) < (date('Y',time()) + 5))
982  {
983  $end_year = date('Y',time()) + 5;
984  }
985  else
986  {
987  $end_year = $year + 5;
988  }
989 
990  if ($emptyoption) $sel_year .= "<option value=\"0\">----</option>\n";
991  for ($i = $startyear; $i <= $end_year; $i++)
992  {
993  $sel_year .= "<option value=\"$i\">" . sprintf("%04d", $i) . "</option>\n";
994  }
995  $sel_year .= "</select>\n";
996  $sel_year = preg_replace("/(value\=\"$year\")/", "$1 selected=\"selected\"", $sel_year);
997 
998  //$dateformat = $lng->text["lang_dateformat"];
999  $dateformat = "d-m-Y";
1000  $dateformat = strtolower(preg_replace("/\W/", "", $dateformat));
1001  $dateformat = strtolower(preg_replace("/(\w)/", "%%$1", $dateformat));
1002  $dateformat = preg_replace("/%%d/", $sel_day, $dateformat);
1003  $dateformat = preg_replace("/%%m/", $sel_month, $dateformat);
1004  $dateformat = preg_replace("/%%y/", $sel_year, $dateformat);
1005  return $dateformat;
1006  }
1007 
1026  public static function makeTimeSelect($prefix, $short = true, $hour = "", $minute = "", $second = "",$a_use_default = true,$a_further_options = array())
1027  {
1028  global $lng, $ilUser;
1029 
1030  $minute_steps = 1;
1031  $disabled = '';
1032  if(count($a_further_options))
1033  {
1034  if(isset($a_further_options['minute_steps']))
1035  {
1036  $minute_steps = $a_further_options['minute_steps'];
1037  }
1038  if(isset($a_further_options['disabled']) and $a_further_options['disabled'])
1039  {
1040  $disabled = 'disabled="disabled" ';
1041  }
1042  }
1043 
1044  if ($a_use_default and !strlen("$hour$minute$second")) {
1045  $now = localtime();
1046  $hour = $now[2];
1047  $minute = $now[1];
1048  $second = $now[0];
1049  } else {
1050  $hour = (int)$hour;
1051  $minute = (int)$minute;
1052  $second = (int)$second;
1053  }
1054  // build hour select
1055  $sel_hour = '<select ';
1056  if(isset($a_further_options['select_attributes']))
1057  {
1058  foreach($a_further_options['select_attributes'] as $name => $value)
1059  {
1060  $sel_hour .= $name.'='.$value.' ';
1061  }
1062  }
1063  $sel_hour .= " ".$disabled."name=\"".$prefix."[h]\" id=\"".$prefix."_h\" class=\"form-control\">\n";
1064 
1065  $format = $ilUser->getTimeFormat();
1066  for ($i = 0; $i <= 23; $i++)
1067  {
1068  if($format == ilCalendarSettings::TIME_FORMAT_24)
1069  {
1070  $sel_hour .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
1071  }
1072  else
1073  {
1074  $sel_hour .= "<option value=\"$i\">" . date("ga", mktime($i, 0, 0)) . "</option>\n";
1075  }
1076  }
1077  $sel_hour .= "</select>\n";
1078  $sel_hour = preg_replace("/(value\=\"$hour\")/", "$1 selected=\"selected\"", $sel_hour);
1079 
1080  // build minutes select
1081  $sel_minute .= "<select ".$disabled."name=\"".$prefix."[m]\" id=\"".$prefix."_m\" class=\"form-control\">\n";
1082 
1083  for ($i = 0; $i <= 59; $i = $i + $minute_steps)
1084  {
1085  $sel_minute .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
1086  }
1087  $sel_minute .= "</select>\n";
1088  $sel_minute = preg_replace("/(value\=\"$minute\")/", "$1 selected=\"selected\"", $sel_minute);
1089 
1090  if (!$short) {
1091  // build seconds select
1092  $sel_second .= "<select ".$disabled."name=\"".$prefix."[s]\" id=\"".$prefix."_s\" class=\"form-control\">\n";
1093 
1094  for ($i = 0; $i <= 59; $i++)
1095  {
1096  $sel_second .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
1097  }
1098  $sel_second .= "</select>\n";
1099  $sel_second = preg_replace("/(value\=\"$second\")/", "$1 selected=\"selected\"", $sel_second);
1100  }
1101  $timeformat = $lng->text["lang_timeformat"];
1102  if (strlen($timeformat) == 0) $timeformat = "H:i:s";
1103  $timeformat = strtolower(preg_replace("/\W/", "", $timeformat));
1104  $timeformat = preg_replace("/(\w)/", "%%$1", $timeformat);
1105  $timeformat = preg_replace("/%%h/", $sel_hour, $timeformat);
1106  $timeformat = preg_replace("/%%i/", $sel_minute, $timeformat);
1107  if ($short) {
1108  $timeformat = preg_replace("/%%s/", "", $timeformat);
1109  } else {
1110  $timeformat = preg_replace("/%%s/", $sel_second, $timeformat);
1111  }
1112  return $timeformat;
1113  }
1114 
1128  public static function is_email($a_email)
1129  {
1130  // BEGIN Mail: If possible, use PearMail to validate e-mail address
1131  global $ilErr;
1132 
1133  // additional check for ilias object is needed,
1134  // otherwise setup will fail with this if branch
1135  if(is_object($ilErr)) // seems to work in Setup now
1136  {
1137  require_once './Services/PEAR/lib/Mail/RFC822.php';
1138  $parser = new Mail_RFC822();
1140  $addresses = $parser->parseAddressList($a_email, 'ilias', false, true);
1141  if(!is_a($addresses, 'PEAR_Error') &&
1142  count($addresses) == 1 && $addresses[0]->host != 'ilias'
1143  )
1144  {
1145  PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($ilErr, "errorHandler"));
1146  return true;
1147  }
1148  else
1149  {
1150  PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($ilErr, "errorHandler"));
1151  return false;
1152  }
1153  }
1154  else
1155  {
1156  $tlds = strtolower(
1157  "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|".
1158  "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|".
1159  "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|".
1160  "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|".
1161  "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|".
1162  "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|".
1163  "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|".
1164  "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|".
1165  "WF|WS|XN|YE|YT|YU|ZA|ZM|ZW");
1166 
1167  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));
1168  }
1169  // END Mail: If possible, use PearMail to validate e-mail address
1170  }
1171 
1180  public static function isPassword($a_passwd, &$customError = null)
1181  {
1182  global $lng;
1183 
1184  include_once('./Services/PrivacySecurity/classes/class.ilSecuritySettings.php');
1185  $security = ilSecuritySettings::_getInstance();
1186 
1187  // check if password is empty
1188  if( empty($a_passwd) )
1189  {
1190  $customError = $lng->txt('password_empty');
1191  return false;
1192  }
1193 
1194  $isPassword = true;
1195  $errors = array();
1196 
1197  // check if password to short
1198  if( $security->getPasswordMinLength() > 0 && strlen($a_passwd) < $security->getPasswordMinLength() )
1199  {
1200  $errors[] = sprintf( $lng->txt('password_to_short'), $security->getPasswordMinLength() );
1201  $isPassword = false;
1202  }
1203 
1204  // check if password not to long
1205  // 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).
1206  if( $security->getPasswordMaxLength() > 0 && strlen($a_passwd) > $security->getPasswordMaxLength() )
1207  {
1208  $errors[] = sprintf( $lng->txt('password_to_long'), $security->getPasswordMaxLength() );
1209  $isPassword = false;
1210  }
1211 
1212  // if password must contains Chars and Numbers
1213  if( $security->isPasswordCharsAndNumbersEnabled() )
1214  {
1215  $hasCharsAndNumbers = true;
1216 
1217  // check password for existing chars
1218  if( !preg_match('/[A-Za-z]+/',$a_passwd) )
1219  {
1220  $hasCharsAndNumbers = false;
1221  }
1222 
1223  // check password for existing numbers
1224  if( !preg_match('/[0-9]+/',$a_passwd) )
1225  {
1226  $hasCharsAndNumbers = false;
1227  }
1228 
1229  if( !$hasCharsAndNumbers )
1230  {
1231  $errors[] = $lng->txt('password_must_chars_and_numbers');
1232  $isPassword = false;
1233  }
1234  }
1235 
1236  require_once 'Services/Utilities/classes/class.ilStr.php';
1237  if($security->getPasswordNumberOfUppercaseChars() > 0)
1238  {
1239  if(ilStr::strLen($a_passwd) - ilStr::strLen(preg_replace('/[A-Z]/', '', $a_passwd)) < $security->getPasswordNumberOfUppercaseChars())
1240  {
1241  $errors[] = sprintf($lng->txt('password_must_contain_ucase_chars'), $security->getPasswordNumberOfUppercaseChars());
1242  $isPassword = false;
1243  }
1244  }
1245 
1246  if($security->getPasswordNumberOfLowercaseChars() > 0)
1247  {
1248  if(ilStr::strLen($a_passwd) - ilStr::strLen(preg_replace('/[a-z]/', '', $a_passwd)) < $security->getPasswordNumberOfLowercaseChars())
1249  {
1250  $errors[] = sprintf($lng->txt('password_must_contain_lcase_chars'), $security->getPasswordNumberOfLowercaseChars());
1251  $isPassword = false;
1252  }
1253  }
1254 
1255  // if password must contains Special-Chars
1256  if( $security->isPasswordSpecialCharsEnabled() )
1257  {
1258  // check password for existing special-chars
1259  if( !preg_match( self::getPasswordValidChars(true, true) , $a_passwd) )
1260  {
1261  $errors[] = $lng->txt('password_must_special_chars');
1262  $isPassword = false;
1263  }
1264  }
1265 
1266  // ensure password matches the positive list of chars/special-chars
1267  if( !preg_match( self::getPasswordValidChars() , $a_passwd) )
1268  {
1269  $errors[] = $lng->txt('password_contains_invalid_chars');
1270  $isPassword = false;
1271  }
1272 
1273  // build custom error message
1274  if( count($errors) == 1 )
1275  {
1276  $customError = $errors[0];
1277  }
1278  elseif( count($errors) > 1 )
1279  {
1280  $customError = $lng->txt('password_multiple_errors');
1281  $customError .= '<br />'.implode('<br />', $errors);
1282  }
1283 
1284  return $isPassword;
1285  }
1286 
1293  public static function isPasswordValidForUserContext($clear_text_password, $user, &$error_language_variable = null)
1294  {
1295  include_once 'Services/PrivacySecurity/classes/class.ilSecuritySettings.php';
1296  $security = ilSecuritySettings::_getInstance();
1297 
1298  $login = null;
1299 
1300  if(is_string($user))
1301  {
1302  $login = $user;
1303  }
1304  else if(is_array($user))
1305  {
1306  // Try to get loginname and user_id from array
1307  $login = $user['login'];
1308  $userId = $user['id'];
1309  }
1310  else if($user instanceof ilObjUser)
1311  {
1312  $login = $user->getLogin();
1313  $userId = $user->getId();
1314  }
1315 
1316  // 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.
1317 
1318  if($login && (int)$security->getPasswordMustNotContainLoginnameStatus() &&
1319  strpos(strtolower($clear_text_password), strtolower($login)) !== false
1320  )
1321  {
1322  $error_language_variable = 'password_contains_parts_of_login_err';
1323  return false;
1324  }
1325 
1326  return true;
1327  }
1328 
1336  public static function getPasswordValidChars($a_as_regex = true, $a_only_special_chars = false)
1337  {
1338  if( $a_as_regex )
1339  {
1340  if( $a_only_special_chars )
1341  {
1342  return '/[_\.\+\?\#\-\*\@!\$\%\~\/\:\;]+/';
1343  }
1344  else
1345  {
1346  return '/^[A-Za-z0-9_\.\+\?\#\-\*\@!\$\%\~\/\:\;]+$/';
1347  }
1348  }
1349  else
1350  {
1351  return 'A-Z a-z 0-9 _.+?#-*@!$%~/:;';
1352  }
1353  }
1354 
1362  public static function getPasswordRequirementsInfo()
1363  {
1364  global $lng;
1365 
1366  include_once('./Services/PrivacySecurity/classes/class.ilSecuritySettings.php');
1367  $security = ilSecuritySettings::_getInstance();
1368 
1369  $infos = array(sprintf($lng->txt('password_allow_chars'), self::getPasswordValidChars(false)));
1370 
1371  // check if password to short
1372  if( $security->getPasswordMinLength() > 0 )
1373  {
1374  $infos[] = sprintf( $lng->txt('password_to_short'), $security->getPasswordMinLength() );
1375  }
1376 
1377  // check if password not to long
1378  if( $security->getPasswordMaxLength() > 0 )
1379  {
1380  $infos[] = sprintf( $lng->txt('password_to_long'), $security->getPasswordMaxLength() );
1381  }
1382 
1383  // if password must contains Chars and Numbers
1384  if( $security->isPasswordCharsAndNumbersEnabled() )
1385  {
1386  $infos[] = $lng->txt('password_must_chars_and_numbers');
1387  }
1388 
1389  // if password must contains Special-Chars
1390  if( $security->isPasswordSpecialCharsEnabled() )
1391  {
1392  $infos[] = $lng->txt('password_must_special_chars');
1393  }
1394 
1395  if($security->getPasswordNumberOfUppercaseChars() > 0)
1396  {
1397  $infos[] = sprintf($lng->txt('password_must_contain_ucase_chars'), $security->getPasswordNumberOfUppercaseChars());
1398  }
1399 
1400  if($security->getPasswordNumberOfLowercaseChars() > 0)
1401  {
1402  $infos[] = sprintf($lng->txt('password_must_contain_lcase_chars'), $security->getPasswordNumberOfLowercaseChars());
1403  }
1404 
1405  return implode('<br />', $infos);
1406  }
1407 
1408  /*
1409  * validates a login
1410  * @access public
1411  * @param string login
1412  * @return boolean true if valid
1413  */
1414  function isLogin($a_login)
1415  {
1416  if (empty($a_login))
1417  {
1418  return false;
1419  }
1420 
1421  if (strlen($a_login) < 3)
1422  {
1423  return false;
1424  }
1425 
1426  // FIXME - If ILIAS is configured to use RFC 822
1427  // compliant mail addresses we should not
1428  // allow the @ character.
1429  if (!ereg("^[A-Za-z0-9_\.\+\*\@!\$\%\~\-]+$", $a_login))
1430  {
1431  return false;
1432  }
1433 
1434  return true;
1435  }
1436 
1450  public static function shortenText ($a_str, $a_len, $a_dots = false, $a_next_blank = false,
1451  $a_keep_extension = false)
1452  {
1453  include_once("./Services/Utilities/classes/class.ilStr.php");
1454  if (ilStr::strLen($a_str) > $a_len)
1455  {
1456  if ($a_next_blank)
1457  {
1458  $len = ilStr::strPos($a_str, " ", $a_len);
1459  }
1460  else
1461  {
1462  $len = $a_len;
1463  }
1464  // BEGIN WebDAV
1465  // - Shorten names in the middle, before the filename extension
1466  // Workaround for Windows WebDAV Client:
1467  // Use the unicode ellipsis symbol for shortening instead of
1468  // three full stop characters.
1469  if ($a_keep_extension)
1470  {
1471  $p = strrpos($a_str, '.'); // this messes up normal shortening, see bug #6190
1472  }
1473  if ($p === false || $p == 0 || strlen($a_str) - $p > $a_len)
1474  {
1475  $a_str = ilStr::subStr($a_str,0,$len);
1476  if ($a_dots)
1477  {
1478  $a_str .= "\xe2\x80\xa6"; // UTF-8 encoding for Unicode ellipsis character.
1479  }
1480  }
1481  else
1482  {
1483  if ($a_dots)
1484  {
1485  $a_str = ilStr::subStr($a_str,0,$len - (strlen($a_str) - $p + 1))."\xe2\x80\xa6".substr($a_str, $p);
1486  }
1487  else
1488  {
1489  $a_str = ilStr::subStr($a_str,0,$len - (strlen($a_str) - $p + 1)).substr($a_str, $p);
1490  }
1491  }
1492  }
1493 
1494  return $a_str;
1495  }
1496 
1507  public static function shortenWords($a_str, $a_len = 30, $a_dots = true)
1508  {
1509  include_once("./Services/Utilities/classes/class.ilStr.php");
1510  $str_arr = explode(" ", $a_str);
1511 
1512  for ($i = 0; $i < count($str_arr); $i++)
1513  {
1514  if (ilStr::strLen($str_arr[$i]) > $a_len)
1515  {
1516  $str_arr[$i] = ilStr::subStr($str_arr[$i], 0, $a_len);
1517  if ($a_dots)
1518  {
1519  $str_arr[$i].= "...";
1520  }
1521  }
1522  }
1523 
1524  return implode($str_arr, " ");
1525  }
1526 
1536  public static function attribsToArray($a_str)
1537  {
1538  $attribs = array();
1539  while (is_int(strpos($a_str, "=")))
1540  {
1541  $eq_pos = strpos($a_str, "=");
1542  $qu1_pos = strpos($a_str, "\"");
1543  $qu2_pos = strpos(substr($a_str, $qu1_pos + 1), "\"") + $qu1_pos + 1;
1544  if (is_int($eq_pos) && is_int($qu1_pos) && is_int($qu2_pos))
1545  {
1546  $var = trim(substr($a_str, 0, $eq_pos));
1547  $val = trim(substr($a_str, $qu1_pos + 1, ($qu2_pos - $qu1_pos) - 1));
1548  $attribs[$var] = $val;
1549  $a_str = substr($a_str, $qu2_pos + 1);
1550  }
1551  else
1552  {
1553  $a_str = "";
1554  }
1555  }
1556  return $attribs;
1557  }
1558 
1570  public static function rCopy ($a_sdir, $a_tdir, $preserveTimeAttributes = false)
1571  {
1572  // check if arguments are directories
1573  if (!@is_dir($a_sdir) or
1574  !@is_dir($a_tdir))
1575  {
1576  return FALSE;
1577  }
1578 
1579  // read a_sdir, copy files and copy directories recursively
1580  $dir = opendir($a_sdir);
1581 
1582  while($file = readdir($dir))
1583  {
1584  if ($file != "." and
1585  $file != "..")
1586  {
1587  // directories
1588  if (@is_dir($a_sdir."/".$file))
1589  {
1590  if (!@is_dir($a_tdir."/".$file))
1591  {
1592  if (!ilUtil::makeDir($a_tdir."/".$file))
1593  return FALSE;
1594 
1595  //chmod($a_tdir."/".$file, 0775);
1596  }
1597 
1598  if (!ilUtil::rCopy($a_sdir."/".$file,$a_tdir."/".$file))
1599  {
1600  return FALSE;
1601  }
1602  }
1603 
1604  // files
1605  if (@is_file($a_sdir."/".$file))
1606  {
1607  if (!copy($a_sdir."/".$file,$a_tdir."/".$file))
1608  {
1609  return FALSE;
1610  }
1611  if ($preserveTimeAttributes)
1612  touch($a_tdir."/".$file, filectime($a_sdir."/".$file));
1613  }
1614  }
1615  }
1616  return TRUE;
1617  }
1618 
1627  public static function getWebspaceDir($mode = "filesystem")
1628  {
1629  global $ilias;
1630 
1631  if ($mode == "filesystem")
1632  {
1633  return "./".ILIAS_WEB_DIR."/".$ilias->client_id;
1634  }
1635  else
1636  {
1637  if (defined("ILIAS_MODULE"))
1638  {
1639  return "../".ILIAS_WEB_DIR."/".$ilias->client_id;
1640  }
1641  else
1642  {
1643  return "./".ILIAS_WEB_DIR."/".$ilias->client_id;
1644  }
1645  }
1646 
1647  //return $ilias->ini->readVariable("server","webspace_dir");
1648  }
1649 
1656  public static function getDataDir()
1657  {
1658  return CLIENT_DATA_DIR;
1659  //global $ilias;
1660 
1661  //return $ilias->ini->readVariable("server", "data_dir");
1662  }
1663 
1673  public static function getUsersOnline($a_user_id = 0)
1674  {
1675  include_once("./Services/User/classes/class.ilObjUser.php");
1676  return ilObjUser::_getUsersOnline($a_user_id);
1677  }
1678 
1689  public static function getAssociatedUsersOnline($a_user_id)
1690  {
1691  include_once("./Services/User/classes/class.ilObjUser.php");
1692  return ilObjUser::_getAssociatedUsersOnline($a_user_id);
1693  }
1694 
1702  public static function ilTempnam()
1703  {
1704  $temp_path = ilUtil::getDataDir() . "/temp";
1705  if (!is_dir($temp_path))
1706  {
1707  ilUtil::createDirectory($temp_path);
1708  }
1709  $temp_name = tempnam($temp_path, "tmp");
1710  // --->
1711  // added the following line because tempnam creates a backslash on some
1712  // Windows systems which leads to problems, because the "...\tmp..." can be
1713  // interpreted as "...{TAB-CHARACTER}...". The normal slash works fine
1714  // even under windows (Helmut Schottmüller, 2005-08-31)
1715  $temp_name = str_replace("\\", "/", $temp_name);
1716  // --->
1717  unlink($temp_name);
1718  return $temp_name;
1719  }
1720 
1729  public static function createDirectory($a_dir, $a_mod = 0755)
1730  {
1731  ilUtil::makeDir($a_dir);
1732  //@mkdir($a_dir);
1733  //@chmod($a_dir, $a_mod);
1734  }
1735 
1736 
1745  public static function unzip($a_file, $overwrite = false, $a_flat = false)
1746  {
1747  global $ilLog;
1748 
1749  if (!is_file($a_file))
1750  {
1751  return;
1752  }
1753 
1754  // if flat, move file to temp directory first
1755  if ($a_flat)
1756  {
1757  $tmpdir = ilUtil::ilTempnam();
1758  ilUtil::makeDir($tmpdir);
1759  copy($a_file, $tmpdir.DIRECTORY_SEPARATOR.basename($a_file));
1760  $orig_file = $a_file;
1761  $a_file = $tmpdir.DIRECTORY_SEPARATOR.basename($a_file);
1762  $origpathinfo = pathinfo($orig_file);
1763  }
1764 
1765  $pathinfo = pathinfo($a_file);
1766  $dir = $pathinfo["dirname"];
1767  $file = $pathinfo["basename"];
1768 
1769  // unzip
1770  $cdir = getcwd();
1771  chdir($dir);
1772  $unzip = PATH_TO_UNZIP;
1773 
1774  // the following workaround has been removed due to bug
1775  // http://www.ilias.de/mantis/view.php?id=7578
1776  // since the workaround is quite old, it may not be necessary
1777  // anymore, alex 9 Oct 2012
1778 /*
1779  // workaround for unzip problem (unzip of subdirectories fails, so
1780  // we create the subdirectories ourselves first)
1781  // get list
1782  $unzipcmd = "-Z -1 ".ilUtil::escapeShellArg($file);
1783  $arr = ilUtil::execQuoted($unzip, $unzipcmd);
1784  $zdirs = array();
1785 
1786  foreach($arr as $line)
1787  {
1788  if(is_int(strpos($line, "/")))
1789  {
1790  $zdir = substr($line, 0, strrpos($line, "/"));
1791  $nr = substr_count($zdir, "/");
1792  //echo $zdir." ".$nr."<br>";
1793  while ($zdir != "")
1794  {
1795  $nr = substr_count($zdir, "/");
1796  $zdirs[$zdir] = $nr; // collect directories
1797  //echo $dir." ".$nr."<br>";
1798  $zdir = substr($zdir, 0, strrpos($zdir, "/"));
1799  }
1800  }
1801  }
1802 
1803  asort($zdirs);
1804 
1805  foreach($zdirs as $zdir => $nr) // create directories
1806  {
1807  ilUtil::createDirectory($zdir);
1808  }
1809 */
1810 
1811  // real unzip
1812  if (!$overwrite)
1813  {
1814  $unzipcmd = ilUtil::escapeShellArg($file);
1815  }
1816  else
1817  {
1818  $unzipcmd = "-o ".ilUtil::escapeShellArg($file);
1819  }
1820  ilUtil::execQuoted($unzip, $unzipcmd);
1821 
1822  chdir($cdir);
1823 
1824  // remove all sym links
1825  clearstatcache(); // prevent is_link from using cache
1826  $dir_realpath = realpath($dir);
1827  foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)) as $name => $f)
1828  {
1829  if (is_link($name))
1830  {
1831  $target = readlink($name);
1832  if (substr($target, 0, strlen($dir_realpath)) != $dir_realpath)
1833  {
1834  unlink($name);
1835  $ilLog->write("Remove symlink ".$name);
1836  }
1837  }
1838  }
1839 
1840  // if flat, get all files and move them to original directory
1841  if ($a_flat)
1842  {
1843  include_once("./Services/Utilities/classes/class.ilFileUtils.php");
1844  $filearray = array();
1845  ilFileUtils::recursive_dirscan($tmpdir, $filearray);
1846  if (is_array($filearray["file"]))
1847  {
1848  foreach ($filearray["file"] as $k => $f)
1849  {
1850  if (substr($f, 0, 1) != "." && $f != basename($orig_file))
1851  {
1852  copy($filearray["path"][$k].$f, $origpathinfo["dirname"].DIRECTORY_SEPARATOR.$f);
1853  }
1854  }
1855  }
1856  ilUtil::delDir($tmpdir);
1857  }
1858  }
1859 
1866  public static function zip($a_dir, $a_file, $compress_content = false)
1867  {
1868  $cdir = getcwd();
1869 
1870  if($compress_content)
1871  {
1872  $a_dir .="/*";
1873  $pathinfo = pathinfo($a_dir);
1874  chdir($pathinfo["dirname"]);
1875  }
1876 
1877  $pathinfo = pathinfo($a_file);
1878  $dir = $pathinfo["dirname"];
1879  $file = $pathinfo["basename"];
1880 
1881  if(!$compress_content)
1882  {
1883  chdir($dir);
1884  }
1885 
1886  $zip = PATH_TO_ZIP;
1887 
1888  if(!$zip)
1889  {
1890  chdir($cdir);
1891  return false;
1892  }
1893 
1894  if (is_array($a_dir))
1895  {
1896  $source = "";
1897  foreach($a_dir as $dir)
1898  {
1899  $name = basename($dir);
1900  $source.= " ".ilUtil::escapeShellArg($name);
1901  }
1902  }
1903  else
1904  {
1905  $name = basename($a_dir);
1906  if (trim($name) != "*")
1907  {
1908  $source = ilUtil::escapeShellArg($name);
1909  }
1910  else
1911  {
1912  $source = $name;
1913  }
1914  }
1915 
1916  $zipcmd = "-r ".ilUtil::escapeShellArg($a_file)." ".$source;
1917  ilUtil::execQuoted($zip, $zipcmd);
1918  chdir($cdir);
1919  return true;
1920  }
1921 
1922  public static function CreateIsoFromFolder($a_dir, $a_file)
1923  {
1924  $cdir = getcwd();
1925 
1926  $pathinfo = pathinfo($a_dir);
1927  chdir($pathinfo["dirname"]);
1928 
1929  $pathinfo = pathinfo($a_file);
1930  $dir = $pathinfo["dirname"];
1931  $file = $pathinfo["basename"]; $zipcmd = "-r ".ilUtil::escapeShellArg($a_file)." ".$source;
1932 
1933  $mkisofs = PATH_TO_MKISOFS;
1934  if(!$mkisofs)
1935  {
1936  chdir($cdir);
1937  return false;
1938  }
1939 
1940  $name = basename($a_dir);
1941  $source = ilUtil::escapeShellArg($name);
1942 
1943  $zipcmd = "-r -J -o ".$a_file." ".$source;
1944  ilUtil::execQuoted($mkisofs, $zipcmd);
1945  chdir($cdir);
1946  return true;
1947  }
1948 
1957  public static function getConvertCmd()
1958  {
1959  return PATH_TO_CONVERT;
1960  }
1961 
1969  public static function execConvert($args)
1970  {
1971  ilUtil::execQuoted(PATH_TO_CONVERT, $args);
1972  }
1973 
1980  public static function isConvertVersionAtLeast($a_version)
1981  {
1982  $current_version = ilUtil::execQuoted(PATH_TO_CONVERT, "--version");
1983  $current_version = self::processConvertVersion($current_version[0]);
1984  $version = self::processConvertVersion($a_version);
1985  if($current_version >= $version)
1986  {
1987  return true;
1988  }
1989  return false;
1990  }
1991 
1998  protected static function processConvertVersion($a_version)
1999  {
2000  if(preg_match("/([0-9]+)\.([0-9]+)\.([0-9]+)([\.|\-]([0-9]+))?/", $a_version, $match))
2001  {
2002  $version = str_pad($match[1], 2, 0, STR_PAD_LEFT).
2003  str_pad($match[2], 2, 0, STR_PAD_LEFT).
2004  str_pad($match[3], 2, 0, STR_PAD_LEFT).
2005  str_pad($match[5], 2, 0, STR_PAD_LEFT);
2006  return (int)$version;
2007  }
2008  }
2009 
2019  public static function convertImage($a_from, $a_to, $a_target_format = "", $a_geometry = "",
2020  $a_background_color = "")
2021  {
2022  $format_str = ($a_target_format != "")
2023  ? strtoupper($a_target_format).":"
2024  : "";
2025  $geometry = "";
2026  if ($a_geometry != "")
2027  {
2028  if (is_int(strpos($a_geometry, "x")))
2029  {
2030  $geometry = " -geometry ".$a_geometry." ";
2031  }
2032  else
2033  {
2034  $geometry = " -geometry ".$a_geometry."x".$a_geometry." ";
2035  }
2036  }
2037 
2038  $bg_color = ($a_background_color != "")
2039  ? " -background color ".$a_background_color." "
2040  : "";
2041  $convert_cmd = ilUtil::escapeShellArg($a_from)." ".$bg_color.$geometry.ilUtil::escapeShellArg($format_str.$a_to);
2042 
2043  ilUtil::execConvert($convert_cmd);
2044  }
2045 
2056  public static function resizeImage($a_from, $a_to, $a_width, $a_height, $a_constrain_prop = false)
2057  {
2058  if ($a_constrain_prop)
2059  {
2060  $size = " -geometry ".$a_width."x".$a_height." ";
2061  }
2062  else
2063  {
2064  $size = " -resize ".$a_width."x".$a_height."! ";
2065  }
2066  $convert_cmd = ilUtil::escapeShellArg($a_from)." ".$size.ilUtil::escapeShellArg($a_to);
2067 
2068  ilUtil::execConvert($convert_cmd);
2069  }
2070 
2077  public static function img($a_src, $a_alt = "", $a_width = "", $a_height = "", $a_border = 0, $a_id = "", $a_class = "")
2078  {
2079  $img = '<img src="'.$a_src.'"';
2080  if ($a_alt != "")
2081  {
2082  $img.= ' alt="'.htmlspecialchars($a_alt).'" title="'.htmlspecialchars($a_alt).'"';
2083  }
2084  if ($a_width != "")
2085  {
2086  $img.= ' width="'.htmlspecialchars($a_width).'"';
2087  }
2088  if ($a_height != "")
2089  {
2090  $img.= ' height="'.htmlspecialchars($a_height).'"';
2091  }
2092  if ($a_class != "")
2093  {
2094  $img.= ' class="'.$a_class.'"';
2095  }
2096  if ($a_id != "")
2097  {
2098  $img.= ' id="'.$a_id.'"';
2099  }
2100  $img.= ' border="'.(int) $a_border.'"/>';
2101 
2102  return $img;
2103  }
2104 
2112  public static function html2pdf($html, $pdf_file)
2113  {
2114  $html_file = str_replace(".pdf",".html",$pdf_file);
2115 
2116  $fp = fopen( $html_file ,"wb");
2117  fwrite($fp, $html);
2118  fclose($fp);
2119 
2120  ilUtil::htmlfile2pdf($html_file,$pdf_file);
2121  }
2122 
2129  public static function htmlfile2pdf($html_file, $pdf_file)
2130  {
2131  $htmldoc_path = PATH_TO_HTMLDOC;
2132 
2133  $htmldoc = "--no-toc ";
2134  $htmldoc .= "--no-jpeg ";
2135  $htmldoc .= "--webpage ";
2136  $htmldoc .= "--outfile " . ilUtil::escapeShellArg($pdf_file) . " ";
2137  $htmldoc .= "--bodyfont Arial ";
2138  $htmldoc .= "--charset iso-8859-15 ";
2139  $htmldoc .= "--color ";
2140  $htmldoc .= "--size A4 "; // --landscape
2141  $htmldoc .= "--format pdf ";
2142  $htmldoc .= "--footer ... ";
2143  $htmldoc .= "--header ... ";
2144  $htmldoc .= "--left 60 ";
2145  // $htmldoc .= "--right 200 ";
2146  $htmldoc .= $html_file;
2147  ilUtil::execQuoted($htmldoc_path, $htmldoc);
2148 
2149  }
2150 
2157  public static function deliverData($a_data, $a_filename, $mime = "application/octet-stream", $charset = "")
2158  {
2159  $disposition = "attachment"; // "inline" to view file in browser or "attachment" to download to hard disk
2160  // $mime = "application/octet-stream"; // or whatever the mime type is
2161 
2162  include_once './Services/Http/classes/class.ilHTTPS.php';
2163 
2164  //if($_SERVER['HTTPS'])
2165  if( ilHTTPS::getInstance()->isDetected() )
2166  {
2167 
2168  // Added different handling for IE and HTTPS => send pragma after content informations
2172  #header("Pragma: ");
2173  #header("Cache-Control: ");
2174  #header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
2175  #header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
2176  #header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1
2177  #header("Cache-Control: post-check=0, pre-check=0", false);
2178  }
2179  else if ($disposition == "attachment")
2180  {
2181  header("Cache-control: private");
2182  }
2183  else
2184  {
2185  header("Cache-Control: no-cache, must-revalidate");
2186  header("Pragma: no-cache");
2187  }
2188 
2189  $ascii_filename = ilUtil::getASCIIFilename($a_filename);
2190 
2191  if (strlen($charset))
2192  {
2193  $charset = "; charset=$charset";
2194  }
2195  header("Content-Type: $mime$charset");
2196  header("Content-Disposition:$disposition; filename=\"".$ascii_filename."\"");
2197  header("Content-Description: ".$ascii_filename);
2198  header("Content-Length: ".(string)(strlen($a_data)));
2199 
2200  //if($_SERVER['HTTPS'])
2201  if( ilHTTPS::getInstance()->isDetected() )
2202  {
2203  header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
2204  header('Pragma: public');
2205  }
2206 
2207  header("Connection: close");
2208  echo $a_data;
2209  exit;
2210  }
2211 
2212  // BEGIN WebDAV: Show file in browser or provide it as attachment
2220  public static function deliverFile($a_file, $a_filename,$a_mime = '', $isInline = false, $removeAfterDelivery = false,
2221  $a_exit_after = true)
2222  {
2223  // should we fail silently?
2224  if(!file_exists($a_file))
2225  {
2226  return false;
2227  }
2228 
2229  if ($isInline) {
2230  $disposition = "inline"; // "inline" to view file in browser
2231  } else {
2232  $disposition = "attachment"; // "attachment" to download to hard disk
2233  //$a_mime = "application/octet-stream"; // override mime type to ensure that no browser tries to show the file anyway.
2234  }
2235  // END WebDAV: Show file in browser or provide it as attachment
2236 
2237  if(strlen($a_mime))
2238  {
2239  $mime = $a_mime;
2240  }
2241  else
2242  {
2243  $mime = "application/octet-stream"; // or whatever the mime type is
2244  }
2245  // BEGIN WebDAV: Removed broken HTTPS code.
2246  // END WebDAV: Removed broken HTTPS code.
2247  if ($disposition == "attachment")
2248  {
2249  header("Cache-control: private");
2250  }
2251  else
2252  {
2253  header("Cache-Control: no-cache, must-revalidate");
2254  header("Pragma: no-cache");
2255  }
2256 
2257  $ascii_filename = ilUtil::getASCIIFilename($a_filename);
2258 
2259  header("Content-Type: $mime");
2260  header("Content-Disposition:$disposition; filename=\"".$ascii_filename."\"");
2261  header("Content-Description: ".$ascii_filename);
2262 
2263  // #7271: if notice gets thrown download will fail in IE
2264  $filesize = @filesize($a_file);
2265  if ($filesize)
2266  {
2267  header("Content-Length: ".(string)$filesize);
2268  }
2269 
2270  include_once './Services/Http/classes/class.ilHTTPS.php';
2271  #if($_SERVER['HTTPS'])
2272  if(ilHTTPS::getInstance()->isDetected())
2273  {
2274  header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
2275  header('Pragma: public');
2276  }
2277 
2278  header("Connection: close");
2279  ilUtil::readFile( $a_file );
2280  if ($removeAfterDelivery)
2281  {
2282  unlink ($a_file);
2283  }
2284  if ($a_exit_after)
2285  {
2286  exit;
2287  }
2288  }
2289 
2290 
2300  public static function readFile($a_file)
2301  {
2302  $chunksize = 1*(1024*1024); // how many bytes per chunk
2303  $buffer = '';
2304  $handle = fopen($a_file, 'rb');
2305  if ($handle === false)
2306  {
2307  return false;
2308  }
2309  while (!feof($handle))
2310  {
2311  $buffer = fread($handle, $chunksize);
2312  print $buffer;
2313  }
2314  return fclose($handle);
2315  }
2316 
2324  public static function getASCIIFilename($a_filename)
2325  {
2326  // The filename must be converted to ASCII, as of RFC 2183,
2327  // section 2.3.
2328 
2340 
2343 
2344  $ascii_filename = htmlentities($a_filename, ENT_NOQUOTES, 'UTF-8');
2345  $ascii_filename = preg_replace('/\&(.)[^;]*;/', '\\1', $ascii_filename);
2346  $ascii_filename = preg_replace('/[\x7f-\xff]/', '_', $ascii_filename);
2347 
2348  // OS do not allow the following characters in filenames: \/:*?"<>|
2349  $ascii_filename = preg_replace('/[:\x5c\/\*\?\"<>\|]/', '_', $ascii_filename);
2350  return $ascii_filename;
2351  }
2352 
2359  public static function htmlentitiesOutsideHTMLTags($htmlText)
2360  {
2361  $matches = Array();
2362  $sep = '###HTMLTAG###';
2363 
2364  preg_match_all("@<[^>]*>@", $htmlText, $matches);
2365  $tmp = preg_replace("@(<[^>]*>)@", $sep, $htmlText);
2366  $tmp = explode($sep, $tmp);
2367 
2368  for ($i=0; $i<count($tmp); $i++)
2369  $tmp[$i] = htmlentities($tmp[$i], ENT_COMPAT, "UTF-8");
2370 
2371  $tmp = join($sep, $tmp);
2372 
2373  for ($i=0; $i<count($matches[0]); $i++)
2374  $tmp = preg_replace("@$sep@", $matches[0][$i], $tmp, 1);
2375 
2376  return $tmp;
2377  }
2378 
2385  public static function getJavaPath()
2386  {
2387  return PATH_TO_JAVA;
2388  //global $ilias;
2389 
2390  //return $ilias->getSetting("java_path");
2391  }
2392 
2400  public static function appendUrlParameterString($a_url, $a_par, $xml_style = false)
2401  {
2402  $amp = $xml_style
2403  ? "&amp;"
2404  : "&";
2405 
2406  $url = (is_int(strpos($a_url, "?")))
2407  ? $a_url.$amp.$a_par
2408  : $a_url."?".$a_par;
2409 
2410  return $url;
2411  }
2412 
2428  public static function makeDir($a_dir)
2429  {
2430  $a_dir = trim($a_dir);
2431 
2432  // remove trailing slash (bugfix for php 4.2.x)
2433  if (substr($a_dir,-1) == "/")
2434  {
2435  $a_dir = substr($a_dir,0,-1);
2436  }
2437 
2438  // check if a_dir comes with a path
2439  if (!($path = substr($a_dir,0, strrpos($a_dir,"/") - strlen($a_dir))))
2440  {
2441  $path = ".";
2442  }
2443 
2444  // create directory with file permissions of parent directory
2445  umask(0000);
2446  return @mkdir($a_dir,fileperms($path));
2447  }
2448 
2449 
2464  public static function makeDirParents($a_dir)
2465  {
2466  $dirs = array($a_dir);
2467  $a_dir = dirname($a_dir);
2468  $last_dirname = '';
2469 
2470  while($last_dirname != $a_dir)
2471  {
2472  array_unshift($dirs, $a_dir);
2473  $last_dirname = $a_dir;
2474  $a_dir = dirname($a_dir);
2475  }
2476 
2477  // find the first existing dir
2478  $reverse_paths = array_reverse($dirs, TRUE);
2479  $found_index = -1;
2480  foreach ($reverse_paths as $key => $value)
2481  {
2482  if ($found_index == -1)
2483  {
2484  if (is_dir($value))
2485  {
2486  $found_index = $key;
2487  }
2488  }
2489  }
2490 
2491  umask(0000);
2492  foreach ($dirs as $dirindex => $dir)
2493  {
2494  // starting with the longest existing path
2495  if ($dirindex >= $found_index)
2496  {
2497  if (! file_exists($dir))
2498  {
2499  if (strcmp(substr($dir,strlen($dir)-1,1),"/") == 0)
2500  {
2501  // on some systems there is an error when there is a slash
2502  // at the end of a directory in mkdir, see Mantis #2554
2503  $dir = substr($dir,0,strlen($dir)-1);
2504  }
2505  if (! mkdir($dir, $umask))
2506  {
2507  error_log("Can't make directory: $dir");
2508  return false;
2509  }
2510  }
2511  elseif (! is_dir($dir))
2512  {
2513  error_log("$dir is not a directory");
2514  return false;
2515  }
2516  else
2517  {
2518  // get umask of the last existing parent directory
2519  $umask = fileperms($dir);
2520  }
2521  }
2522  }
2523  return true;
2524  }
2525 
2535  public static function delDir($a_dir, $a_clean_only = false)
2536  {
2537  if (!is_dir($a_dir) || is_int(strpos($a_dir, "..")))
2538  {
2539  return;
2540  }
2541 
2542  $current_dir = opendir($a_dir);
2543 
2544  $files = array();
2545 
2546  // this extra loop has been necessary because of a strange bug
2547  // at least on MacOS X. A looped readdir() didn't work
2548  // correctly with larger directories
2549  // when an unlink happened inside the loop. Getting all files
2550  // into the memory first solved the problem.
2551  while($entryname = readdir($current_dir))
2552  {
2553  $files[] = $entryname;
2554  }
2555 
2556  foreach($files as $file)
2557  {
2558  if(is_dir($a_dir."/".$file) and ($file != "." and $file!=".."))
2559  {
2560  ilUtil::delDir(${a_dir}."/".${file});
2561  }
2562  elseif ($file != "." and $file != "..")
2563  {
2564  unlink(${a_dir}."/".${file});
2565  }
2566  }
2567 
2568  closedir($current_dir);
2569  if (!$a_clean_only)
2570  {
2571  @rmdir(${a_dir});
2572  }
2573  }
2574 
2575 
2582  public static function getDir($a_dir, $a_rec = false, $a_sub_dir = "")
2583  {
2584  $current_dir = opendir($a_dir.$a_sub_dir);
2585 
2586  $dirs = array();
2587  $files = array();
2588  $subitems = array();
2589  while($entry = readdir($current_dir))
2590  {
2591  if(is_dir($a_dir."/".$entry))
2592  {
2593  $dirs[$entry] = array("type" => "dir", "entry" => $entry,
2594  "subdir" => $a_sub_dir);
2595  if ($a_rec && $entry != "." && $entry != "..")
2596  {
2597  $si = ilUtil::getDir($a_dir, true, $a_sub_dir."/".$entry);
2598  $subitems = array_merge($subitems, $si);
2599  }
2600  }
2601  else
2602  {
2603  if ($entry != "." && $entry != "..")
2604  {
2605  $size = filesize($a_dir.$a_sub_dir."/".$entry);
2606  $files[$entry] = array("type" => "file", "entry" => $entry,
2607  "size" => $size, "subdir" => $a_sub_dir);
2608  }
2609  }
2610  }
2611  ksort($dirs);
2612  ksort($files);
2613 
2614  return array_merge($dirs, $files, $subitems);
2615  }
2616 
2623  public static function stripSlashesArray($a_arr, $a_strip_html = true, $a_allow = "")
2624  {
2625  if (is_array($a_arr))
2626  {
2627  foreach ($a_arr as $k => $v)
2628  {
2629  $a_arr[$k] = ilUtil::stripSlashes($v, $a_strip_html, $a_allow);
2630  }
2631  }
2632 
2633  return $a_arr;
2634  }
2635 
2642  public static function stripSlashesRecursive($a_data, $a_strip_html = true, $a_allow = "")
2643  {
2644  if (is_array($a_data))
2645  {
2646  foreach ($a_data as $k => $v)
2647  {
2648  if (is_array($v))
2649  {
2650  $a_data[$k] = ilUtil::stripSlashesRecursive($v, $a_strip_html, $a_allow);
2651  }
2652  else
2653  {
2654  $a_data[$k] = ilUtil::stripSlashes($v, $a_strip_html, $a_allow);
2655  }
2656  }
2657  }
2658  else
2659  {
2660  $a_data = ilUtil::stripSlashes($a_data, $a_strip_html, $a_allow);
2661  }
2662 
2663  return $a_data;
2664  }
2665 
2673  public static function stripSlashes($a_str, $a_strip_html = true, $a_allow = "")
2674  {
2675  if (ini_get("magic_quotes_gpc"))
2676  {
2677  $a_str = stripslashes($a_str);
2678  }
2679 //echo "<br><br>-".$a_strip_html."-".htmlentities($a_str);
2680 //echo "<br>-".htmlentities(ilUtil::secureString($a_str, $a_strip_html, $a_allow));
2681  return ilUtil::secureString($a_str, $a_strip_html, $a_allow);
2682  }
2683 
2691  public static function stripOnlySlashes($a_str)
2692  {
2693  if (ini_get("magic_quotes_gpc"))
2694  {
2695  $a_str = stripslashes($a_str);
2696  }
2697 
2698  return $a_str;
2699  }
2700 
2707  public static function secureString($a_str, $a_strip_html = true, $a_allow = "")
2708  {
2709  // check whether all allowed tags can be made secure
2710  $only_secure = true;
2711  $allow_tags = explode(">", $a_allow);
2712  $sec_tags = ilUtil::getSecureTags();
2713  $allow_array = array();
2714  foreach($allow_tags as $allow)
2715  {
2716  if ($allow != "")
2717  {
2718  $allow = str_replace("<", "", $allow);
2719 
2720  if (!in_array($allow, $sec_tags))
2721  {
2722  $only_secure = false;
2723  }
2724  $allow_array[] = $allow;
2725  }
2726  }
2727 
2728  // default behaviour: allow only secure tags 1:1
2729  if (($only_secure || $a_allow == "") && $a_strip_html)
2730  {
2731  if ($a_allow == "")
2732  {
2733  $allow_array = array ("b", "i", "strong", "em", "code", "cite",
2734  "gap", "sub", "sup", "pre", "strike");
2735  }
2736 
2737  // this currently removes parts of strings like "a <= b"
2738  // because "a <= b" is treated like "<spam onclick='hurt()'>ss</spam>"
2739  $a_str = ilUtil::maskSecureTags($a_str, $allow_array);
2740  $a_str = strip_tags($a_str); // strip all other tags
2741  $a_str = ilUtil::unmaskSecureTags($a_str, $allow_array);
2742 
2743  // a possible solution could be something like:
2744  // $a_str = str_replace("<", "&lt;", $a_str);
2745  // $a_str = str_replace(">", "&gt;", $a_str);
2746  // $a_str = ilUtil::unmaskSecureTags($a_str, $allow_array);
2747  //
2748  // output would be ok then, but input fields would show
2749  // "a &lt;= b" for input "a <= b" if data is brought back to a form
2750  }
2751  else
2752  {
2753  // only for scripts, that need to allow more/other tags and parameters
2754  if ($a_strip_html)
2755  {
2756  $a_str = ilUtil::stripScriptHTML($a_str, $a_allow);
2757  }
2758  }
2759 
2760  return $a_str;
2761  }
2762 
2763  public static function getSecureTags()
2764  {
2765  return array("strong", "em", "u", "strike", "ol", "li", "ul", "p", "div",
2766  "i", "b", "code", "sup", "sub", "pre", "gap", "a", "img");
2767  }
2768 
2769  public static function maskSecureTags($a_str, $allow_array)
2770  {
2771  foreach ($allow_array as $t)
2772  {
2773  switch($t)
2774  {
2775  case "a":
2776  $a_str = ilUtil::maskAttributeTag($a_str, "a", "href");
2777  break;
2778 
2779  case "img":
2780  $a_str = ilUtil::maskAttributeTag($a_str, "img", "src");
2781  break;
2782 
2783  case "p":
2784  case "div":
2785  $a_str = ilUtil::maskTag($a_str, $t, array(
2786  array("param" => "align", "value" => "left"),
2787  array("param" => "align", "value" => "center"),
2788  array("param" => "align", "value" => "justify"),
2789  array("param" => "align", "value" => "right")
2790  ));
2791  break;
2792 
2793  default:
2794  $a_str = ilUtil::maskTag($a_str, $t);
2795  break;
2796  }
2797  }
2798 
2799  return $a_str;
2800  }
2801 
2802  public static function unmaskSecureTags($a_str, $allow_array)
2803  {
2804  foreach ($allow_array as $t)
2805  {
2806  switch($t)
2807  {
2808  case "a":
2809  $a_str = ilUtil::unmaskAttributeTag($a_str, "a", "href");
2810  break;
2811 
2812  case "img":
2813  $a_str = ilUtil::unmaskAttributeTag($a_str, "img", "src");
2814  break;
2815 
2816  case "p":
2817  case "div":
2818  $a_str = ilUtil::unmaskTag($a_str, $t, array(
2819  array("param" => "align", "value" => "left"),
2820  array("param" => "align", "value" => "center"),
2821  array("param" => "align", "value" => "justify"),
2822  array("param" => "align", "value" => "right")
2823  ));
2824  break;
2825 
2826  default:
2827  $a_str = ilUtil::unmaskTag($a_str, $t);
2828  break;
2829  }
2830  }
2831 
2832  return $a_str;
2833  }
2834 
2842  public static function securePlainString($a_str)
2843  {
2844  if (ini_get("magic_quotes_gpc"))
2845  {
2846  return stripslashes($a_str);
2847  }
2848  else
2849  {
2850  return $a_str;
2851  }
2852  }
2869  public static function htmlencodePlainString($a_str, $a_make_links_clickable, $a_detect_goto_links = false)
2870  {
2871  $encoded = "";
2872 
2873  if ($a_make_links_clickable)
2874  {
2875  // Find text sequences in the plain text string which match
2876  // the URI syntax rules, and pass them to ilUtil::makeClickable.
2877  // Encode all other text sequences in the plain text string using
2878  // htmlspecialchars and nl2br.
2879  // The following expressions matches URI's as specified in RFC 2396.
2880  //
2881  // The expression matches URI's, which start with some well known
2882  // schemes, like "http:", or with "www.". This must be followed
2883  // by at least one of the following RFC 2396 expressions:
2884  // - alphanum: [a-zA-Z0-9]
2885  // - reserved: [;\/?:|&=+$,]
2886  // - mark: [\\-_.!~*\'()]
2887  // - escaped: %[0-9a-fA-F]{2}
2888  // - fragment delimiter: #
2889  // - uric_no_slash: [;?:@&=+$,]
2890  $matches = array();
2891  $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);
2892  $pos1 = 0;
2893  $encoded = "";
2894  foreach ($matches as $match)
2895  {
2896  }
2897  foreach ($matches[0] as $match)
2898  {
2899  $matched_text = $match[0];
2900  $pos2 = $match[1];
2901  if ($matched_offset != previous_offset)
2902  {
2903  // encode plain text
2904  $encoded .= nl2br(htmlspecialchars(substr($a_str, $pos1, $pos2 - $pos1)));
2905  }
2906  // encode URI
2907  $encoded .= ilUtil::makeClickable($matched_text, $a_detect_goto_links);
2908 
2909 
2910  $pos1 = $pos2 + strlen($matched_text);
2911  }
2912  if ($pos1 < strlen($a_str))
2913  {
2914  $encoded .= nl2br(htmlspecialchars(substr($a_str, $pos1)));
2915  }
2916  }
2917  else
2918  {
2919  $encoded = nl2br(htmlspecialchars($a_str));
2920  }
2921  return $encoded;
2922  }
2923 
2924 
2925  public static function maskAttributeTag($a_str, $tag, $tag_att)
2926  {
2927  global $ilLog;
2928 
2929  $ws = "[ \t\r\f\v\n]*";
2930  $att = $ws."[^>]*".$ws;
2931 
2932  while (eregi("<($tag$att($tag_att$ws=$ws\"(([\$@!*()~;,_0-9A-z/:=%\\.&#?+\\-])*)\")$att)>",
2933  $a_str, $found))
2934  {
2935  $un = array(".", "-", "+", "?", '$', "*", "(", ")");
2936  $esc = array();
2937  foreach($un as $v)
2938  {
2939  $esc[] = "\\".$v;
2940  }
2941  $ff = str_replace($un, $esc, $found[1]);
2942 
2943  $old_str = $a_str;
2944  $a_str = eregi_replace("<".$ff.">",
2945  "&lt;$tag $tag_att$tag_att=\"".$found[3]."\"&gt;", $a_str);
2946  if ($old_str == $a_str)
2947  {
2948  $ilLog->write("ilUtil::maskA-".htmlentities($old_str)." == ".
2949  htmlentities($a_str));
2950  return $a_str;
2951  }
2952  }
2953  $a_str = str_ireplace("</$tag>",
2954  "&lt;/$tag&gt;", $a_str);
2955  return $a_str;
2956  }
2957 
2958  public static function unmaskAttributeTag($a_str, $tag, $tag_att)
2959  {
2960  global $ilLog;
2961 
2962  while (eregi("&lt;($tag $tag_att$tag_att=\"(([\$@!*()~;,_0-9A-z/:=%\\.&#?+\\-])*)\")&gt;",
2963  $a_str, $found))
2964  {
2965  $un = array(".", "-", "+", "?", '$', "*", "(", ")");
2966  $esc = array();
2967  foreach($un as $v)
2968  {
2969  $esc[] = "\\".$v;
2970  }
2971  $ff = str_replace($un, $esc, $found[1]);
2972 
2973  $old_str = $a_str;
2974  $a_str = eregi_replace("&lt;".$ff."&gt;",
2975  "<$tag $tag_att=\"".ilUtil::secureLink($found[2])."\">", $a_str);
2976  if ($old_str == $a_str)
2977  {
2978  $ilLog->write("ilUtil::unmaskA-".htmlentities($old_str)." == ".
2979  htmlentities($a_str));
2980  return $a_str;
2981  }
2982  }
2983  $a_str = str_replace("&lt;/$tag&gt;", "</$tag>", $a_str);
2984  return $a_str;
2985  }
2986 
2987  public static function maskTag($a_str, $t, $fix_param = "")
2988  {
2989  $a_str = str_replace(array("<$t>", "<".strtoupper($t).">"),
2990  "&lt;".$t."&gt;", $a_str);
2991  $a_str = str_replace(array("</$t>", "</".strtoupper($t).">"),
2992  "&lt;/".$t."&gt;", $a_str);
2993 
2994  if (is_array($fix_param))
2995  {
2996  foreach ($fix_param as $p)
2997  {
2998  $k = $p["param"];
2999  $v = $p["value"];
3000  $a_str = str_replace("<$t $k=\"$v\">",
3001  "&lt;"."$t $k=\"$v\""."&gt;", $a_str);
3002  }
3003  }
3004 
3005  return $a_str;
3006  }
3007 
3008  public static function unmaskTag($a_str, $t, $fix_param = "")
3009  {
3010  $a_str = str_replace("&lt;".$t."&gt;", "<".$t.">", $a_str);
3011  $a_str = str_replace("&lt;/".$t."&gt;", "</".$t.">", $a_str);
3012 
3013  if (is_array($fix_param))
3014  {
3015  foreach ($fix_param as $p)
3016  {
3017  $k = $p["param"];
3018  $v = $p["value"];
3019  $a_str = str_replace("&lt;$t $k=\"$v\"&gt;",
3020  "<"."$t $k=\"$v\"".">", $a_str);
3021  }
3022  }
3023  return $a_str;
3024  }
3025 
3026  public static function secureLink($a_str)
3027  {
3028  $a_str = str_ireplace("javascript", "jvscrpt", $a_str);
3029  $a_str = str_ireplace(array("%00", "%0a", "%0d", "%1a", "&#00;", "&#x00;",
3030  "&#0;", "&#x0;", "&#x0a;", "&#x0d;", "&#10;", "&#13;"), "-", $a_str);
3031  return $a_str;
3032  }
3033 
3047  public static function stripScriptHTML($a_str, $a_allow = "", $a_rm_js = true)
3048  {
3049  //$a_str = strip_tags($a_str, $a_allow);
3050 
3051  $negativestr = "a,abbr,acronym,address,applet,area,b,base,basefont,".
3052  "bdo,big,blockquote,body,br,button,caption,center,cite,code,col,".
3053  "colgroup,dd,del,dfn,dir,div,dl,dt,em,fieldset,font,form,frame,".
3054  "frameset,h1,h2,h3,h4,h5,h6,head,hr,html,i,iframe,img,input,ins,isindex,kbd,".
3055  "label,legend,li,link,map,menu,meta,noframes,noscript,object,ol,".
3056  "optgroup,option,p,param,q,s,samp,script,select,small,span,".
3057  "strike,strong,style,sub,sup,table,tbody,td,textarea,tfoot,th,thead,".
3058  "title,tr,tt,u,ul,var";
3059  $a_allow = strtolower ($a_allow);
3060  $negatives = explode(",",$negativestr);
3061  $outer_old_str = "";
3062  while($outer_old_str != $a_str)
3063  {
3064  $outer_old_str = $a_str;
3065  foreach ($negatives as $item)
3066  {
3067  $pos = strpos($a_allow, "<$item>");
3068 
3069  // remove complete tag, if not allowed
3070  if ($pos === false)
3071  {
3072  $old_str = "";
3073  while($old_str != $a_str)
3074  {
3075  $old_str = $a_str;
3076  $a_str = preg_replace("/<\/?\s*$item(\/?)\s*>/i", "", $a_str);
3077  $a_str = preg_replace("/<\/?\s*$item(\/?)\s+([^>]*)>/i", "", $a_str);
3078  }
3079  }
3080  }
3081  }
3082 
3083  if ($a_rm_js)
3084  {
3085  // remove all attributes if an "on..." attribute is given
3086  $a_str = preg_replace("/<\s*\w*(\/?)(\s+[^>]*)?(\s+on[^>]*)>/i", "", $a_str);
3087 
3088  // remove all attributes if a "javascript" is within tag
3089  $a_str = preg_replace("/<\s*\w*(\/?)\s+[^>]*javascript[^>]*>/i", "", $a_str);
3090 
3091  // remove all attributes if an "expression" is within tag
3092  // (IE allows something like <b style='width:expression(alert(1))'>test</b>)
3093  $a_str = preg_replace("/<\s*\w*(\/?)\s+[^>]*expression[^>]*>/i", "", $a_str);
3094  }
3095 
3096  return $a_str;
3097  }
3098 
3110  public static function prepareFormOutput($a_str, $a_strip = false)
3111  {
3112  if($a_strip)
3113  {
3114  $a_str = ilUtil::stripSlashes($a_str);
3115  }
3116  $a_str = htmlspecialchars($a_str);
3117  // Added replacement of curly brackets to prevent
3118  // problems with PEAR templates, because {xyz} will
3119  // be removed as unused template variable
3120  $a_str = str_replace("{", "&#123;", $a_str);
3121  $a_str = str_replace("}", "&#125;", $a_str);
3122  // needed for LaTeX conversion \\ in LaTeX is a line break
3123  // but without this replacement, php changes \\ to \
3124  $a_str = str_replace("\\", "&#92;", $a_str);
3125  return $a_str;
3126  }
3127 
3134  function secureUrl($url)
3135  {
3136  // check if url is valid (absolute or relative)
3137  if (filter_var($url, FILTER_VALIDATE_URL) === false &&
3138  filter_var("http://".$url, FILTER_VALIDATE_URL) === false &&
3139  filter_var("http:".$url, FILTER_VALIDATE_URL) === false &&
3140  filter_var("http://de.de".$url, FILTER_VALIDATE_URL) === false &&
3141  filter_var("http://de.de/".$url, FILTER_VALIDATE_URL) === false)
3142  {
3143  return "";
3144  }
3145  if (trim(strtolower(parse_url($url, PHP_URL_SCHEME))) == "javascript")
3146  {
3147  return "";
3148  }
3149  $url = htmlspecialchars($url, ENT_QUOTES);
3150  return $url;
3151  }
3152 
3153 
3154 
3164  public static function prepareDBString($a_str)
3165  {
3166  return addslashes($a_str);
3167  }
3168 
3169 
3178  public static function removeItemFromDesktops($a_id)
3179  {
3180  return ilObjUser::_removeItemFromDesktops($a_id);
3181  }
3182 
3183 
3193  public static function extractParameterString($a_parstr)
3194  {
3195  // parse parameters in array
3196  $par = array();
3197  $ok=true;
3198  while(($spos=strpos($a_parstr,"=")) && $ok)
3199  {
3200  // extract parameter
3201  $cpar = substr($a_parstr,0,$spos);
3202  $a_parstr = substr($a_parstr,$spos,strlen($a_parstr)-$spos);
3203  while(substr($cpar,0,1)=="," ||substr($cpar,0,1)==" " || substr($cpar,0,1)==chr(13) || substr($cpar,0,1)==chr(10))
3204  $cpar = substr($cpar,1,strlen($cpar)-1);
3205  while(substr($cpar,strlen($cpar)-1,1)==" " || substr($cpar,strlen($cpar)-1,1)==chr(13) || substr($cpar,strlen($cpar)-1,1)==chr(10))
3206  $cpar = substr($cpar,0,strlen($cpar)-1);
3207 
3208  // parameter name should only
3209  $cpar_old = "";
3210  while($cpar != $cpar_old)
3211  {
3212  $cpar_old = $cpar;
3213  $cpar = eregi_replace("[^a-zA-Z0-9_]", "", $cpar);
3214  }
3215 
3216  // extract value
3217  if ($cpar != "")
3218  {
3219  if($spos=strpos($a_parstr,"\""))
3220  {
3221  $a_parstr = substr($a_parstr,$spos+1,strlen($a_parstr)-$spos);
3222  $spos=strpos($a_parstr,"\"");
3223  if(is_int($spos))
3224  {
3225  $cval = substr($a_parstr,0,$spos);
3226  $par[$cpar]=$cval;
3227  $a_parstr = substr($a_parstr,$spos+1,strlen($a_parstr)-$spos-1);
3228  }
3229  else
3230  $ok=false;
3231  }
3232  else
3233  $ok=false;
3234  }
3235  }
3236 
3237  if($ok) return $par; else return false;
3238  }
3239 
3240  public static function assembleParameterString($a_par_arr)
3241  {
3242  if (is_array($a_par_arr))
3243  {
3244  $target_arr = array();
3245  foreach ($a_par_arr as $par => $val)
3246  {
3247  $target_arr[] = "$par=\"$val\"";
3248  }
3249  $target_str = implode(", ", $target_arr);
3250  }
3251 
3252  return $target_str;
3253  }
3254 
3261  public static function dumpString($a_str)
3262  {
3263  $ret = $a_str.": ";
3264  for($i=0; $i<strlen($a_str); $i++)
3265  {
3266  $ret.= ord(substr($a_str,$i,1))." ";
3267  }
3268  return $ret;
3269  }
3270 
3271 
3278  public static function yn2tf($a_yn)
3279  {
3280  if(strtolower($a_yn) == "y")
3281  {
3282  return true;
3283  }
3284  else
3285  {
3286  return false;
3287  }
3288  }
3289 
3296  public static function tf2yn($a_tf)
3297  {
3298  if($a_tf)
3299  {
3300  return "y";
3301  }
3302  else
3303  {
3304  return "n";
3305  }
3306  }
3307 
3318  public static function sort_func ($a, $b)
3319  {
3320  global $array_sortby,$array_sortorder;
3321 
3322  if(!isset($array_sortby))
3323  {
3324  // occured in: setup -> new client -> install languages -> sorting of languages
3325  $array_sortby = 0;
3326  }
3327 
3328  // this comparison should give optimal results if
3329  // locale is provided and mb string functions are supported
3330  if ($array_sortorder == "asc")
3331  {
3332  return ilStr::strCmp($a[$array_sortby], $b[$array_sortby]);
3333  }
3334 
3335  if ($array_sortorder == "desc")
3336  {
3337  return !ilStr::strCmp($a[$array_sortby], $b[$array_sortby]);
3338  return strcoll(ilStr::strToUpper($b[$array_sortby]), ilStr::strToUpper($a[$array_sortby]));
3339  }
3340  }
3341 
3352  public static function sort_func_numeric ($a, $b)
3353  {
3354  global $array_sortby,$array_sortorder;
3355 
3356  if ($array_sortorder == "asc")
3357  {
3358  return $a["$array_sortby"] > $b["$array_sortby"];
3359  }
3360 
3361  if ($array_sortorder == "desc")
3362  {
3363  return $a["$array_sortby"] < $b["$array_sortby"];
3364  }
3365  }
3378  public static function sortArray($array,$a_array_sortby,$a_array_sortorder = 0,$a_numeric = false,
3379  $a_keep_keys = false)
3380  {
3381  include_once("./Services/Utilities/classes/class.ilStr.php");
3382 
3383  // BEGIN WebDAV: Provide a 'stable' sort algorithm
3384  if (! $a_keep_keys) {
3385  return self::stableSortArray($array,$a_array_sortby,$a_array_sortorder,$a_numeric,$a_keep_keys);
3386  }
3387  // END WebDAV Provide a 'stable' sort algorithm
3388 
3389  global $array_sortby,$array_sortorder;
3390 
3391  $array_sortby = $a_array_sortby;
3392 
3393  if ($a_array_sortorder == "desc")
3394  {
3395  $array_sortorder = "desc";
3396  }
3397  else
3398  {
3399  $array_sortorder = "asc";
3400  }
3401  if($a_numeric)
3402  {
3403  if ($a_keep_keys)
3404  {
3405  uasort($array, array("ilUtil", "sort_func_numeric"));
3406  }
3407  else
3408  {
3409  usort($array, array("ilUtil", "sort_func_numeric"));
3410  }
3411  }
3412  else
3413  {
3414  if ($a_keep_keys)
3415  {
3416  uasort($array, array("ilUtil", "sort_func"));
3417  }
3418  else
3419  {
3420  usort($array, array("ilUtil", "sort_func"));
3421  }
3422  }
3423  //usort($array,"ilUtil::sort_func");
3424 
3425  return $array;
3426  }
3427  // BEGIN WebDAV: Provide a 'stable' sort algorithm
3442  public static function stableSortArray($array,$a_array_sortby,$a_array_sortorder = 0,$a_numeric = false)
3443  {
3444  global $array_sortby,$array_sortorder;
3445 
3446  $array_sortby = $a_array_sortby;
3447 
3448  if ($a_array_sortorder == "desc")
3449  {
3450  $array_sortorder = "desc";
3451  }
3452  else
3453  {
3454  $array_sortorder = "asc";
3455  }
3456 
3457  // Create a copy of the array values for sorting
3458  $sort_array = array_values($array);
3459 
3460  if($a_numeric)
3461  {
3462  ilUtil::mergesort($sort_array, array("ilUtil", "sort_func_numeric"));
3463  }
3464  else
3465  {
3466  ilUtil::mergesort($sort_array, array("ilUtil", "sort_func"));
3467  }
3468 
3469  return $sort_array;
3470  }
3471  public static function mergesort(&$array, $cmp_function = 'strcmp') {
3472  // Arrays of size < 2 require no action.
3473  if (count($array) < 2) return;
3474 
3475  // Split the array in half
3476  $halfway = count($array) / 2;
3477  $array1 = array_slice($array, 0, $halfway);
3478  $array2 = array_slice($array, $halfway);
3479 
3480  // Recurse to sort the two halves
3481  ilUtil::mergesort($array1, $cmp_function);
3482  ilUtil::mergesort($array2, $cmp_function);
3483 
3484  // If all of $array1 is <= all of $array2, just append them.
3485  if (call_user_func($cmp_function, end($array1), $array2[0]) < 1) {
3486  $array = array_merge($array1, $array2);
3487  return;
3488  }
3489 
3490  // Merge the two sorted arrays into a single sorted array
3491  $array = array();
3492  $ptr1 = $ptr2 = 0;
3493  while ($ptr1 < count($array1) && $ptr2 < count($array2)) {
3494  if (call_user_func($cmp_function, $array1[$ptr1], $array2[$ptr2]) < 1) {
3495  $array[] = $array1[$ptr1++];
3496  }
3497  else {
3498  $array[] = $array2[$ptr2++];
3499  }
3500  }
3501 
3502  // Merge the remainder
3503  while ($ptr1 < count($array1)) $array[] = $array1[$ptr1++];
3504  while ($ptr2 < count($array2)) $array[] = $array2[$ptr2++];
3505 
3506  return;
3507  }
3508  // END WebDAV: Provide a 'stable' sort algorithm
3509 
3521  public static function unique_multi_array($array, $sub_key)
3522  {
3523  $target = array();
3524  $existing_sub_key_values = array();
3525 
3526  foreach ($array as $key=>$sub_array)
3527  {
3528  if (!in_array($sub_array[$sub_key], $existing_sub_key_values))
3529  {
3530  $existing_sub_key_values[] = $sub_array[$sub_key];
3531  $target[$key] = $sub_array;
3532  }
3533  }
3534 
3535  return $target;
3536  }
3537 
3538 
3548  public static function getGDSupportedImageType($a_desired_type)
3549  {
3550  $a_desired_type = strtolower($a_desired_type);
3551  // get supported Image Types
3552  $im_types = ImageTypes();
3553 
3554  switch($a_desired_type)
3555  {
3556  case "jpg":
3557  case "jpeg":
3558  if ($im_types & IMG_JPG) return "jpg";
3559  if ($im_types & IMG_GIF) return "gif";
3560  if ($im_types & IMG_PNG) return "png";
3561  break;
3562 
3563  case "gif":
3564  if ($im_types & IMG_GIF) return "gif";
3565  if ($im_types & IMG_JPG) return "jpg";
3566  if ($im_types & IMG_PNG) return "png";
3567  break;
3568 
3569  case "png":
3570  if ($im_types & IMG_PNG) return "png";
3571  if ($im_types & IMG_JPG) return "jpg";
3572  if ($im_types & IMG_GIF) return "gif";
3573  break;
3574  }
3575 
3576  return "";
3577  }
3578 
3588  public static function deducibleSize($a_mime)
3589  {
3590  if (($a_mime == "image/gif") || ($a_mime == "image/jpeg") ||
3591  ($a_mime == "image/png") || ($a_mime == "application/x-shockwave-flash") ||
3592  ($a_mime == "image/tiff") || ($a_mime == "image/x-ms-bmp") ||
3593  ($a_mime == "image/psd") || ($a_mime == "image/iff"))
3594  {
3595  return true;
3596  }
3597  else
3598  {
3599  return false;
3600  }
3601  }
3602 
3603 
3611  public static function redirect($a_script)
3612  {
3613  global $log, $PHP_SELF;
3614 
3615 //echo "<br>".$a_script;
3616  if (!is_int(strpos($a_script, "://")))
3617  {
3618  if (substr($a_script, 0, 1) != "/" && defined("ILIAS_HTTP_PATH"))
3619  {
3620  if (is_int(strpos($_SERVER["PHP_SELF"], "/setup/")))
3621  {
3622  $a_script = "setup/".$a_script;
3623  }
3624  $a_script = ILIAS_HTTP_PATH."/".$a_script;
3625  }
3626  }
3627 //echo "<br>".$a_script; exit;
3628 
3629  // include the user interface hook
3630  global $ilPluginAdmin;
3631  if (is_object($ilPluginAdmin))
3632  {
3633  $pl_names = $ilPluginAdmin->getActivePluginsForSlot(IL_COMP_SERVICE, "UIComponent", "uihk");
3634  foreach ($pl_names as $pl)
3635  {
3636  $ui_plugin = ilPluginAdmin::getPluginObject(IL_COMP_SERVICE, "UIComponent", "uihk", $pl);
3637  $gui_class = $ui_plugin->getUIClassInstance();
3638  $resp = $gui_class->getHTML("Services/Utilities", "redirect", array("html" => $a_script));
3639  if ($resp["mode"] != ilUIHookPluginGUI::KEEP)
3640  {
3641  $a_script = $gui_class->modifyHTML($a_script, $resp);
3642  }
3643  }
3644  }
3645 
3646  header("Location: ".$a_script);
3647  exit();
3648  }
3649 
3658  public static function insertInstIntoID($a_value)
3659  {
3660  if (substr($a_value, 0, 4) == "il__")
3661  {
3662  $a_value = "il_".IL_INST_ID."_".substr($a_value, 4, strlen($a_value) - 4);
3663  }
3664 
3665  return $a_value;
3666  }
3667 
3678  public static function groupNameExists($a_group_name,$a_id = 0)
3679  {
3680  global $ilDB,$ilErr;
3681 
3682  if (empty($a_group_name))
3683  {
3684  $message = __METHOD__.": No groupname given!";
3685  $ilErr->raiseError($message,$ilErr->WARNING);
3686  }
3687 
3688  $clause = ($a_id) ? " AND obj_id != ".$ilDB->quote($a_id)." " : "";
3689 
3690  $q = "SELECT obj_id FROM object_data ".
3691  "WHERE title = ".$ilDB->quote($a_group_name, "text")." ".
3692  "AND type = ".$ilDB->quote("grp", "text").
3693  $clause;
3694 
3695  $r = $ilDB->query($q);
3696 
3697  if ($r->numRows())
3698  {
3699  return true;
3700  }
3701  else
3702  {
3703  return false;
3704  }
3705  }
3706 
3713  public static function getMemString()
3714  {
3715  $my_pid = getmypid();
3716  return ("MEMORY USAGE (% KB PID ): ".`ps -eo%mem,rss,pid | grep $my_pid`);
3717  }
3718 
3725  public static function isWindows()
3726  {
3727  if (strtolower(substr(php_uname(), 0, 3)) == "win")
3728  {
3729  return true;
3730  }
3731  return false;
3732  }
3733 
3734 
3735  public static function escapeShellArg($a_arg)
3736  {
3737  setlocale(LC_CTYPE, "UTF8", "en_US.UTF-8"); // fix for PHP escapeshellcmd bug. See: http://bugs.php.net/bug.php?id=45132
3738  // see also ilias bug 5630
3739  return escapeshellarg($a_arg);
3740  }
3741 
3751  public static function escapeShellCmd($a_arg)
3752  {
3753  if(ini_get('safe_mode') == 1)
3754  {
3755  return $a_arg;
3756  }
3757  setlocale(LC_CTYPE, "UTF8", "en_US.UTF-8"); // fix for PHP escapeshellcmd bug. See: http://bugs.php.net/bug.php?id=45132
3758  return escapeshellcmd($a_arg);
3759  }
3760 
3770  public static function execQuoted($cmd, $args = NULL)
3771  {
3772  global $ilLog;
3773 
3774  if(ilUtil::isWindows() && strpos($cmd, " ") !== false && substr($cmd, 0, 1) !== '"')
3775  {
3776  // cmd won't work without quotes
3777  $cmd = '"'.$cmd.'"';
3778  if($args)
3779  {
3780  // args are also quoted, workaround is to quote the whole command AGAIN
3781  // was fixed in php 5.2 (see php bug #25361)
3782  if (version_compare(phpversion(), "5.2", "<") && strpos($args, '"') !== false)
3783  {
3784  $cmd = '"'.$cmd." ".$args.'"';
3785  }
3786  // args are not quoted or php is fixed, just append
3787  else
3788  {
3789  $cmd .= " ".$args;
3790  }
3791  }
3792  }
3793  // nothing todo, just append args
3794  else if($args)
3795  {
3796  $cmd .= " ".$args;
3797  }
3798 //echo "<br>".$cmd; exit;
3799  exec($cmd, $arr);
3800 // $ilLog->write("ilUtil::execQuoted: ".$cmd.".");
3801  return $arr;
3802  }
3803 
3826  public static function excelTime($year = "", $month = "", $day = "", $hour = "", $minute = "", $second = "")
3827  {
3828  $starting_time = mktime(0, 0, 0, 1, 2, 1970);
3829  if (strcmp("$year$month$day$hour$minute$second", "") == 0)
3830  {
3831  $target_time = time();
3832  }
3833  else
3834  {
3835  if ($year < 1970)
3836  {
3837  return 0;
3838  }
3839  }
3840  $target_time = mktime($hour, $minute, $second, $month, $day, $year);
3841  $difference = $target_time - $starting_time;
3842  $days = (($difference - ($difference % 86400)) / 86400);
3843  $difference = $difference - ($days * 86400) + 3600;
3844 
3845  // #15343 - using a global locale leads to , instead of . for (implicit) floats
3846  return str_replace(",", ".", ($days + 25570 + ($difference / 86400)));
3847  }
3848 
3855  public static function renameExecutables($a_dir)
3856  {
3857  $def_arr = explode(",", SUFFIX_REPL_DEFAULT);
3858  foreach ($def_arr as $def)
3859  {
3860  ilUtil::rRenameSuffix($a_dir, trim($def), "sec");
3861  }
3862 
3863  $def_arr = explode(",", SUFFIX_REPL_ADDITIONAL);
3864  foreach ($def_arr as $def)
3865  {
3866  ilUtil::rRenameSuffix($a_dir, trim($def), "sec");
3867  }
3868  }
3869 
3882  public static function rRenameSuffix ($a_dir, $a_old_suffix, $a_new_suffix)
3883  {
3884  if ($a_dir == "/" || $a_dir == "" || is_int(strpos($a_dir, ".."))
3885  || trim($a_old_suffix) == "")
3886  {
3887  return false;
3888  }
3889 
3890  // check if argument is directory
3891  if (!@is_dir($a_dir))
3892  {
3893  return false;
3894  }
3895 
3896  // read a_dir
3897  $dir = opendir($a_dir);
3898 
3899  while($file = readdir($dir))
3900  {
3901  if ($file != "." and
3902  $file != "..")
3903  {
3904  // directories
3905  if (@is_dir($a_dir."/".$file))
3906  {
3907  ilUtil::rRenameSuffix($a_dir."/".$file, $a_old_suffix, $a_new_suffix);
3908  }
3909 
3910  // files
3911  if (@is_file($a_dir."/".$file))
3912  {
3913  // first check for files with trailing dot
3914  if(strrpos($file,'.') == (strlen($file) - 1))
3915  {
3916  rename($a_dir.'/'.$file,substr($a_dir.'/'.$file,0,-1));
3917  $file = substr($file,0,-1);
3918  }
3919 
3920  $path_info = pathinfo($a_dir."/".$file);
3921 
3922  if (strtolower($path_info["extension"]) ==
3923  strtolower($a_old_suffix))
3924  {
3925  $pos = strrpos($a_dir."/".$file, ".");
3926  $new_name = substr($a_dir."/".$file, 0, $pos).".".$a_new_suffix;
3927  rename($a_dir."/".$file, $new_name);
3928  }
3929  }
3930  }
3931  }
3932  return true;
3933  }
3934 
3935  public static function isAPICall () {
3936  return strpos($_SERVER["SCRIPT_FILENAME"],"api") !== false ||
3937  strpos($_SERVER["SCRIPT_FILENAME"],"dummy") !== false;
3938  }
3939 
3940  public static function KT_replaceParam($qstring, $paramName, $paramValue) {
3941  if (preg_match("/&" . $paramName . "=/", $qstring)) {
3942  return preg_replace("/&" . $paramName . "=[^&]+/", "&" . $paramName . "=" . urlencode($paramValue), $qstring);
3943  } else {
3944  return $qstring . "&" . $paramName . "=" . urlencode($paramValue);
3945  }
3946  }
3947 
3948  public static function replaceUrlParameterString ($url, $parametersArray) {
3949 
3950  foreach ($parametersArray as $paramName => $paramValue ) {
3951  $url = ilUtil::KT_replaceParam($url, $paramName, $paramValue);
3952  }
3953  return $url;
3954  }
3955 
3962  public static function generatePasswords ($a_number)
3963  {
3964  $ret = array();
3965  srand((double) microtime()*1000000);
3966 
3967  include_once('./Services/PrivacySecurity/classes/class.ilSecuritySettings.php');
3968  $security = ilSecuritySettings::_getInstance();
3969 
3970  for ($i=1; $i<=$a_number; $i++)
3971  {
3972  $min = ($security->getPasswordMinLength() > 0)
3973  ? $security->getPasswordMinLength()
3974  : 6;
3975  $max = ($security->getPasswordMaxLength() > 0)
3976  ? $security->getPasswordMaxLength()
3977  : 10;
3978  if ($min > $max)
3979  {
3980  $max = $max + 1;
3981  }
3982  $length = rand($min,$max);
3983  $next = rand(1,2);
3984  $vowels = "aeiou";
3985  $vowels_uc = strtoupper($vowels);
3986  $consonants = "bcdfghjklmnpqrstvwxyz";
3987  $consonants_uc = strtoupper($consonants);
3988  $numbers = "1234567890";
3989  $special = "_.+?#-*@!$%~";
3990  $pw = "";
3991 
3992  if($security->getPasswordNumberOfUppercaseChars() > 0)
3993  {
3994  for($j = 0; $j < $security->getPasswordNumberOfUppercaseChars(); $j++)
3995  {
3996  switch ($next)
3997  {
3998  case 1:
3999  $pw.= $consonants_uc[rand(0, strlen($consonants_uc) - 1)];
4000  $next = 2;
4001  break;
4002 
4003  case 2:
4004  $pw.= $vowels_uc[rand(0, strlen($vowels_uc) - 1)];
4005  $next = 1;
4006  break;
4007  }
4008  }
4009  }
4010 
4011  if($security->isPasswordCharsAndNumbersEnabled())
4012  {
4013  $pw.= $numbers[rand(0, strlen($numbers) - 1)];
4014  }
4015 
4016  if($security->isPasswordSpecialCharsEnabled())
4017  {
4018  $pw.= $special[rand(0, strlen($special) - 1)];
4019  }
4020 
4021  $num_lcase_chars = max($security->getPasswordNumberOfLowercaseChars(), $length - strlen($pw));
4022  for($j = 0; $j < $num_lcase_chars; $j++)
4023  {
4024  switch ($next)
4025  {
4026  case 1:
4027  $pw.= $consonants[rand(0, strlen($consonants) - 1)];
4028  $next = 2;
4029  break;
4030 
4031  case 2:
4032  $pw.= $vowels[rand(0, strlen($vowels) - 1)];
4033  $next = 1;
4034  break;
4035  }
4036  }
4037 
4038  $pw = str_shuffle($pw);
4039 
4040  $ret[] = $pw;
4041  }
4042  return $ret;
4043  }
4044 
4045  public static function removeTrailingPathSeparators($path)
4046  {
4047  $path = preg_replace("/[\/\\\]+$/", "", $path);
4048  return $path;
4049  }
4050 
4061  public static function array_php2js($data)
4062  {
4063  if (empty($data))
4064  {
4065  $data = array();
4066  }
4067 
4068  foreach($data as $k=>$datum)
4069  {
4070  if(is_null($datum)) $data[$k] = 'null';
4071  if(is_string($datum)) $data[$k] = "'" . $datum . "'";
4072  if(is_array($datum)) $data[$k] = array_php2js($datum);
4073  }
4074 
4075  return "[" . implode(', ', $data) . "]";
4076  }
4077 
4084  public static function virusHandling($a_file, $a_orig_name = "", $a_clean = true)
4085  {
4086  global $lng;
4087 
4088  if (IL_VIRUS_SCANNER != "None")
4089  {
4090  require_once("./Services/VirusScanner/classes/class.ilVirusScannerFactory.php");
4092  if (($vs_txt = $vs->scanFile($a_file, $a_orig_name)) != "")
4093  {
4094  if ($a_clean && (IL_VIRUS_CLEAN_COMMAND != ""))
4095  {
4096  $clean_txt = $vs->cleanFile($a_file, $a_orig_name);
4097  if ($vs->fileCleaned())
4098  {
4099  $vs_txt.= "<br />".$lng->txt("cleaned_file").
4100  "<br />".$clean_txt;
4101  $vs_txt.= "<br />".$lng->txt("repeat_scan");
4102  if (($vs2_txt = $vs->scanFile($a_file, $a_orig_name)) != "")
4103  {
4104  return array(false, nl2br($vs_txt)."<br />".$lng->txt("repeat_scan_failed").
4105  "<br />".nl2br($vs2_txt));
4106  }
4107  else
4108  {
4109  return array(true, nl2br($vs_txt)."<br />".$lng->txt("repeat_scan_succeded"));
4110  }
4111  }
4112  else
4113  {
4114  return array(false, nl2br($vs_txt)."<br />".$lng->txt("cleaning_failed"));
4115  }
4116  }
4117  else
4118  {
4119  return array(false, nl2br($vs_txt));
4120  }
4121  }
4122  }
4123 
4124  return array(true,"");
4125  }
4126 
4127 
4134  public static function moveUploadedFile($a_file, $a_name, $a_target, $a_raise_errors = true,
4135  $a_mode = "move_uploaded")
4136  {
4137  global $lng, $ilias;
4138 //echo "<br>ilUtli::moveuploadedFile($a_name)";
4139 
4140  if (!is_file($a_file))
4141  {
4142  if ($a_raise_errors)
4143  {
4144  $ilias->raiseError($lng->txt("upload_error_file_not_found"), $ilias->error_obj->MESSAGE);
4145  }
4146  else
4147  {
4148  ilUtil::sendFailure($lng->txt("upload_error_file_not_found"), true);
4149  }
4150  return false;
4151  }
4152 
4153  // virus handling
4154  $vir = ilUtil::virusHandling($a_file, $a_name);
4155  if (!$vir[0])
4156  {
4157  unlink($a_file);
4158  if ($a_raise_errors)
4159  {
4160  $ilias->raiseError($lng->txt("file_is_infected")."<br />".
4161  $vir[1],
4162  $ilias->error_obj->MESSAGE);
4163  }
4164  else
4165  {
4166  ilUtil::sendFailure($lng->txt("file_is_infected")."<br />".
4167  $vir[1], true);
4168  }
4169  return false;
4170  }
4171  else
4172  {
4173  if ($vir[1] != "")
4174  {
4175  ilUtil::sendInfo($vir[1], true);
4176  }
4177  switch ($a_mode)
4178  {
4179  case "rename":
4180  return rename($a_file, $a_target);
4181  break;
4182 
4183  case "copy":
4184  return copy($a_file, $a_target);
4185  break;
4186 
4187  default:
4188  return move_uploaded_file($a_file, $a_target);
4189  break;
4190  }
4191  }
4192  }
4193 
4194 
4201  public static function date_mysql2time($mysql_date_time) {
4202  list($datum, $uhrzeit) = explode (" ",$mysql_date_time);
4203  list($jahr, $monat, $tag) = explode("-", $datum);
4204  list($std, $min, $sec) = explode(":", $uhrzeit);
4205  return mktime ((int) $std, (int) $min, (int) $sec, (int) $monat, (int) $tag, (int) $jahr);
4206  }
4207 
4214  public static function now()
4215  {
4216  return date("Y-m-d H:i:s");
4217  }
4218 
4234  public static function &processCSVRow(&$row, $quoteAll = FALSE, $separator = ";", $outUTF8 = FALSE, $compatibleWithMSExcel = TRUE)
4235  {
4236  $resultarray = array();
4237  foreach ($row as $rowindex => $entry)
4238  {
4239  $surround = FALSE;
4240  if ($quoteAll)
4241  {
4242  $surround = TRUE;
4243  }
4244  if (strpos($entry, "\"") !== FALSE)
4245  {
4246  $entry = str_replace("\"", "\"\"", $entry);
4247  $surround = TRUE;
4248  }
4249  if (strpos($entry, $separator) !== FALSE)
4250  {
4251  $surround = TRUE;
4252  }
4253  if ($compatibleWithMSExcel)
4254  {
4255  // replace all CR LF with LF (for Excel for Windows compatibility
4256  $entry = str_replace(chr(13).chr(10), chr(10), $entry);
4257  }
4258  if ($surround)
4259  {
4260  if ($outUTF8)
4261  {
4262  $resultarray[$rowindex] = "\"" . $entry . "\"";
4263  }
4264  else
4265  {
4266  $resultarray[$rowindex] = utf8_decode("\"" . $entry . "\"");
4267  }
4268  }
4269  else
4270  {
4271  if ($outUTF8)
4272  {
4273  $resultarray[$rowindex] = $entry;
4274  }
4275  else
4276  {
4277  $resultarray[$rowindex] = utf8_decode($entry);
4278  }
4279  }
4280  }
4281  return $resultarray;
4282  }
4283 
4284  // validates a domain name (example: www.ilias.de)
4285  public static function isDN($a_str)
4286  {
4287  return(preg_match("/^[a-z]+([a-z0-9-]*[a-z0-9]+)?(\.([a-z]+([a-z0-9-]*[a-z0-9]+)?)+)*$/",$a_str));
4288  }
4289 
4290  // validates an IP address (example: 192.168.1.1)
4291  public static function isIPv4($a_str)
4292  {
4293  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])\.".
4294  "(\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));
4295  }
4296 
4297 
4326  public static function _getObjectsByOperations($a_obj_type,$a_operation,$a_usr_id = 0,$limit = 0)
4327  {
4328  global $ilDB,$rbacreview,$ilAccess,$ilUser,$ilias,$tree;
4329 
4330  if(!is_array($a_obj_type))
4331  {
4332  $where = "WHERE type = ".$ilDB->quote($a_obj_type, "text")." ";
4333  }
4334  else
4335  {
4336  $where = "WHERE ".$ilDB->in("type", $a_obj_type, false, "text")." ";
4337  }
4338 
4339  // limit number of results default is search result limit
4340  if(!$limit)
4341  {
4342  $limit = $ilias->getSetting('search_max_hits',100);
4343  }
4344  if($limit == -1)
4345  {
4346  $limit = 10000;
4347  }
4348 
4349  // default to logged in usr
4350  $a_usr_id = $a_usr_id ? $a_usr_id : $ilUser->getId();
4351  $a_roles = $rbacreview->assignedRoles($a_usr_id);
4352 
4353  // Since no rbac_pa entries are available for the system role. This function returns !all! ref_ids in the case the user
4354  // is assigned to the system role
4355  if($rbacreview->isAssigned($a_usr_id,SYSTEM_ROLE_ID))
4356  {
4357  $query = "SELECT ref_id FROM object_reference obr LEFT JOIN object_data obd ON obr.obj_id = obd.obj_id ".
4358  "LEFT JOIN tree ON obr.ref_id = tree.child ".
4359  $where.
4360  "AND tree = 1";
4361 
4362  $res = $ilDB->query($query);
4363  $counter = 0;
4364  while($row = $ilDB->fetchObject($res))
4365  {
4366  // Filter recovery folder
4367  if($tree->isGrandChild(RECOVERY_FOLDER_ID, $row->ref_id))
4368  {
4369  continue;
4370  }
4371 
4372  if($counter++ >= $limit)
4373  {
4374  break;
4375  }
4376 
4377  $ref_ids[] = $row->ref_id;
4378  }
4379  return $ref_ids ? $ref_ids : array();
4380  } // End Administrators
4381 
4382  // Check ownership if it is not asked for edit_permission or a create permission
4383  if($a_operation == 'edit_permissions' or strpos($a_operation,'create') !== false)
4384  {
4385  $check_owner = ") ";
4386  }
4387  else
4388  {
4389  $check_owner = "OR owner = ".$ilDB->quote($a_usr_id, "integer").") ";
4390  }
4391 
4392  $ops_ids = ilRbacReview::_getOperationIdsByName(array($a_operation));
4393  $ops_id = $ops_ids[0];
4394 
4395  $and = "AND ((".$ilDB->in("rol_id", $a_roles, false, "integer")." ";
4396 
4397  $query = "SELECT DISTINCT(obr.ref_id),obr.obj_id,type FROM object_reference obr ".
4398  "JOIN object_data obd ON obd.obj_id = obr.obj_id ".
4399  "LEFT JOIN rbac_pa ON obr.ref_id = rbac_pa.ref_id ".
4400  $where.
4401  $and.
4402  "AND (".$ilDB->like("ops_id", "text","%i:".$ops_id."%"). " ".
4403  "OR ".$ilDB->like("ops_id", "text", "%:\"".$ops_id."\";%").")) ".
4404  $check_owner;
4405 
4406  $res = $ilDB->query($query);
4407  $counter = 0;
4408  while($row = $res->fetchRow(DB_FETCHMODE_OBJECT))
4409  {
4410  if($counter >= $limit)
4411  {
4412  break;
4413  }
4414 
4415  // Filter objects in recovery folder
4416  if($tree->isGrandChild(RECOVERY_FOLDER_ID, $row->ref_id))
4417  {
4418  continue;
4419  }
4420 
4421  // Check deleted, hierarchical access ...
4422  if($ilAccess->checkAccessOfUser($a_usr_id,$a_operation,'',$row->ref_id,$row->type,$row->obj_id))
4423  {
4424  $counter++;
4425  $ref_ids[] = $row->ref_id;
4426  }
4427  }
4428  return $ref_ids ? $ref_ids : array();
4429  }
4430 
4431 
4438  function includeMathjax($a_tpl = null)
4439  {
4440  global $tpl;
4441 
4442  if ($a_tpl == null)
4443  {
4444  $a_tpl = $tpl;
4445  }
4446 
4447  // - take care of html exports (-> see buildLatexImages)
4448  include_once "./Services/Administration/classes/class.ilSetting.php";
4449  $mathJaxSetting = new ilSetting("MathJax");
4450  $use_mathjax = $mathJaxSetting->get("enable");
4451  if ($use_mathjax)
4452  {
4453  $a_tpl->addJavaScript($mathJaxSetting->get("path_to_mathjax"));
4454  }
4455  }
4456 
4457 
4467  public static function insertLatexImages($a_text, $a_start = "\[tex\]", $a_end = "\[\/tex\]")
4468  {
4469  global $tpl, $lng, $ilUser;
4470 
4471  $cgi = URL_TO_LATEX;
4472 
4473  // - take care of html exports (-> see buildLatexImages)
4474  include_once "./Services/Administration/classes/class.ilSetting.php";
4475  $mathJaxSetting = new ilSetting("MathJax");
4476  $use_mathjax = $mathJaxSetting->get("enable");
4477  if ($use_mathjax)
4478  {
4479  $a_text = preg_replace("/\\\\([RZN])([^a-zA-Z]|<\/span>)/", "\\mathbb{"."$1"."}"."$2", $a_text);
4480  $tpl->addJavaScript($mathJaxSetting->get("path_to_mathjax"));
4481  }
4482 
4483  // this is a fix for bug5362
4484  $cpos = 0;
4485  $o_start = $a_start;
4486  $o_end = $a_end;
4487  $a_start = str_replace("\\", "", $a_start);
4488  $a_end = str_replace("\\", "", $a_end);
4489 
4490  while (is_int($spos = stripos($a_text, $a_start, $cpos))) // find next start
4491  {
4492  if (is_int ($epos = stripos($a_text, $a_end, $spos + 1)))
4493  {
4494  $tex = substr($a_text, $spos + strlen($a_start), $epos - $spos - strlen($a_start));
4495 
4496  // replace, if tags do not go across div borders
4497  if (!is_int(strpos($tex, "</div>")))
4498  {
4499  if (!$use_mathjax)
4500  {
4501  $a_text = substr($a_text, 0, $spos).
4502  "<img alt=\"".htmlentities($tex)."\" src=\"".$cgi."?".
4503  rawurlencode(str_replace('&amp;', '&', str_replace('&gt;', '>', str_replace('&lt;', '<', $tex))))."\" ".
4504  " />".
4505  substr($a_text, $epos + strlen($a_end));
4506  }
4507  else
4508  {
4509  $tex = $a_start.$tex.$a_end;
4510 
4511  switch ((int) $mathJaxSetting->get("limiter"))
4512  {
4513  case 1:
4514  $mj_start = "[tex]";
4515  $mj_end = "[/tex]";
4516  break;
4517 
4518  case 2:
4519  $mj_start = '<span class="math">';
4520  $mj_end = '</span>';
4521  break;
4522 
4523  default:
4524  $mj_start = "\(";
4525  $mj_end = "\)";
4526  break;
4527  }
4528 
4529  $replacement =
4530  preg_replace('/' . $o_start . '(.*?)' . $o_end . '/ie',
4531  "'".$mj_start."' . preg_replace('/[\\\\\\\\\\]{2}/', '\\cr', str_replace('<', '&lt;', str_replace('<br/>', '', str_replace('<br />', '', str_replace('<br>', '', '$1'))))) . '".$mj_end."'", $tex);
4532  // added special handling for \\ -> \cr, < -> $lt; and removal of <br/> tags in jsMath expressions, H. Schottmüller, 2007-09-09
4533  $a_text = substr($a_text, 0, $spos).
4534  $replacement.
4535  substr($a_text, $epos + strlen($a_end));
4536  }
4537  }
4538  }
4539  $cpos = $spos + 1;
4540  }
4541 
4542  $result_text = $a_text;
4543 
4544  return $result_text;
4545  }
4546 
4556  public static function buildLatexImages($a_text, $a_dir)
4557  {
4558  $result_text = $a_text;
4559 
4560  $start = "\[tex\]";
4561  $end = "\[\/tex\]";
4562 
4563  $cgi = URL_TO_LATEX;
4564 
4565  if ($cgi != "")
4566  {
4567  while (preg_match('/' . $start . '(.*?)' . $end . '/ie', $result_text, $found))
4568  {
4569  $cnt = (int) $GLOBALS["teximgcnt"]++;
4570  // get image from cgi and write it to file
4571  $fpr = @fopen($cgi."?".rawurlencode($found[1]), "r");
4572  $lcnt = 0;
4573  if ($fpr)
4574  {
4575  while(!feof($fpr))
4576  {
4577  $buf = fread($fpr, 1024);
4578  if ($lcnt == 0)
4579  {
4580  if (is_int(strpos(strtoupper(substr($buf, 0, 5)), "GIF")))
4581  {
4582  $suffix = "gif";
4583  }
4584  else
4585  {
4586  $suffix = "png";
4587  }
4588  $fpw = fopen($a_dir."/teximg/img".$cnt.".".$suffix, "w");
4589  }
4590  $lcnt++;
4591  fwrite($fpw, $buf);
4592  }
4593  fclose($fpw);
4594  fclose($fpr);
4595  }
4596 
4597  // replace tex-tag
4598  $img_str = "./teximg/img".$cnt.".".$suffix;
4599  $result_text = str_replace($found[0],
4600  '<img alt="'.$found[1].'" src="'.$img_str.'" />', $result_text);
4601  }
4602  }
4603 
4604  return $result_text;
4605  }
4606 
4615  public static function prepareTextareaOutput($txt_output, $prepare_for_latex_output = FALSE, $omitNl2BrWhenTextArea = false)
4616  {
4617  $result = $txt_output;
4618  $is_html = self::isHTML($result);
4619 
4620  if ($prepare_for_latex_output)
4621  {
4622  $result = ilUtil::insertLatexImages($result, "<span class\=\"latex\">", "<\/span>");
4623  $result = ilUtil::insertLatexImages($result, "\[tex\]", "\[\/tex\]");
4624  }
4625 
4626  // removed: did not work with magic_quotes_gpc = On
4627  if (!$is_html )
4628  {
4629  if(!$omitNl2BrWhenTextArea)
4630  {
4631  // if the string does not contain HTML code, replace the newlines with HTML line breaks
4632  $result = preg_replace("/[\n]/", "<br />", $result);
4633  }
4634  }
4635  else
4636  {
4637  // patch for problems with the <pre> tags in tinyMCE
4638  if (preg_match_all("/(<pre>.*?<\/pre>)/ims", $result, $matches))
4639  {
4640  foreach ($matches[0] as $found)
4641  {
4642  $replacement = "";
4643  if (strpos("\n", $found) === FALSE)
4644  {
4645  $replacement = "\n";
4646  }
4647  $removed = preg_replace("/<br\s*?\/>/ims", $replacement, $found);
4648  $result = str_replace($found, $removed, $result);
4649  }
4650  }
4651  }
4652  if ($prepare_for_latex_output)
4653  {
4654  // replace special characters to prevent problems with the ILIAS template system
4655  // eg. if someone uses {1} as an answer, nothing will be shown without the replacement
4656  $result = str_replace("{", "&#123;", $result);
4657  $result = str_replace("}", "&#125;", $result);
4658  $result = str_replace("\\", "&#92;", $result);
4659  }
4660 
4661  return $result;
4662  }
4663 
4672  public static function isHTML($a_text)
4673  {
4674  if( preg_match("/<[^>]*?>/", $a_text) )
4675  {
4676  return true;
4677  }
4678 
4679  return false;
4680  }
4681 
4691  public static function period2String(ilDateTime $a_from, $a_to = null)
4692  {
4693  global $lng;
4694 
4695  if (!$a_to)
4696  {
4697  $a_to = new ilDateTime(time(), IL_CAL_UNIX);
4698  }
4699 
4700  $from = new DateTime($a_from->get(IL_CAL_DATETIME));
4701  $to = new DateTime($a_to->get(IL_CAL_DATETIME));
4702  $diff = $to->diff($from);
4703 
4704  $periods = array();
4705  $periods["years"] = $diff->format("%y");
4706  $periods["months"] = $diff->format("%m");
4707  $periods["days"] = $diff->format("%d");
4708  $periods["hours"] = $diff->format("%h");
4709  $periods["minutes"] = $diff->format("%i");
4710  $periods["seconds"] = $diff->format("%s");
4711 
4712  if (!array_sum($periods))
4713  {
4714  return;
4715  }
4716 
4717  foreach ($periods as $key => $value)
4718  {
4719  if($value)
4720  {
4721  $segment_name = ($value > 1)
4722  ? $key
4723  : substr($key, 0, -1);
4724  $array[] = $value . ' ' . $lng->txt($segment_name);
4725  }
4726  }
4727 
4728  $len = sizeof($array);
4729  if ($len > 3)
4730  {
4731  $array = array_slice($array, 0, (3-$len));
4732  }
4733 
4734  return implode(', ', $array);
4735  }
4736 
4737  public static function getFileSizeInfo()
4738  {
4739  global $lng;
4740 
4741  // get the value for the maximal uploadable filesize from the php.ini (if available)
4742  $umf=get_cfg_var("upload_max_filesize");
4743  // get the value for the maximal post data from the php.ini (if available)
4744  $pms=get_cfg_var("post_max_size");
4745 
4746  // use the smaller one as limit
4747  $max_filesize=min($umf, $pms);
4748  if (!$max_filesize) $max_filesize=max($umf, $pms);
4749 
4750  return $lng->txt("file_notice")." $max_filesize.";
4751  }
4752 
4761  public static function __extractRefId($role_title)
4762  {
4763 
4764  $test_str = explode('_',$role_title);
4765 
4766  if ($test_str[0] == 'il')
4767  {
4768  $test2 = (int) $test_str[3];
4769  return is_numeric ($test2) ? (int) $test2 : false;
4770  }
4771  return false;
4772  }
4773 
4784  public static function __extractId($ilias_id, $inst_id)
4785  {
4786 
4787  $test_str = explode('_',$ilias_id);
4788 
4789  if ($test_str[0] == 'il' && $test_str[1] == $inst_id && count($test_str) == 4)
4790  {
4791  $test2 = (int) $test_str[3];
4792  return is_numeric ($test2) ? (int) $test2 : false;
4793  }
4794  return false;
4795  }
4796 
4811  public static function _sortIds($a_ids,$a_table,$a_field,$a_id_name)
4812  {
4813  global $ilDB;
4814 
4815  if(!$a_ids)
4816  {
4817  return array();
4818  }
4819 
4820  // use database to sort user array
4821  $where = "WHERE ".$a_id_name." IN (";
4822  $where .= implode(",", ilUtil::quoteArray($a_ids));
4823  $where .= ") ";
4824 
4825  $query = "SELECT ".$a_id_name." FROM ".$a_table." ".
4826  $where.
4827  "ORDER BY ".$a_field;
4828 
4829  $res = $ilDB->query($query);
4830  while($row = $res->fetchRow(DB_FETCHMODE_OBJECT))
4831  {
4832  $ids[] = $row->$a_id_name;
4833  }
4834  return $ids ? $ids : array();
4835  }
4836 
4846  public static function getMySQLTimestamp($a_ts)
4847  {
4848  global $ilDB;
4849 
4850  return $a_ts;
4851  }
4852 
4859  public static function quoteArray($a_array)
4860  {
4861  global $ilDB;
4862 
4863 
4864  if(!is_array($a_array) or !count($a_array))
4865  {
4866  return array("''");
4867  }
4868 
4869  foreach($a_array as $k => $item)
4870  {
4871  $a_array[$k] = $ilDB->quote($item);
4872  }
4873 
4874  return $a_array;
4875  }
4876 
4885  public static function sendInfo($a_info = "",$a_keep = false)
4886  {
4887  global $tpl;
4888  $tpl->setMessage("info", $a_info, $a_keep);
4889  }
4890 
4899  public static function sendFailure($a_info = "",$a_keep = false)
4900  {
4901  global $tpl;
4902  $tpl->setMessage("failure", $a_info, $a_keep);
4903  }
4904 
4911  public static function sendQuestion($a_info = "",$a_keep = false)
4912  {
4913  global $tpl;
4914  $tpl->setMessage("question", $a_info, $a_keep);
4915  }
4916 
4925  public static function sendSuccess($a_info = "",$a_keep = false)
4926  {
4927  global $tpl;
4928  $tpl->setMessage("success", $a_info, $a_keep);
4929  }
4930 
4931  public static function infoPanel($a_keep = true)
4932  {
4933  global $tpl,$ilias,$lng;
4934 
4935  if (!empty($_SESSION["infopanel"]) and is_array($_SESSION["infopanel"]))
4936  {
4937  $tpl->addBlockFile("INFOPANEL", "infopanel", "tpl.infopanel.html",
4938  "Services/Utilities");
4939  $tpl->setCurrentBlock("infopanel");
4940 
4941  if (!empty($_SESSION["infopanel"]["text"]))
4942  {
4943  $link = "<a href=\"".$dir.$_SESSION["infopanel"]["link"]."\" target=\"".
4944  ilFrameTargetInfo::_getFrame("MainContent").
4945  "\">";
4946  $link .= $lng->txt($_SESSION["infopanel"]["text"]);
4947  $link .= "</a>";
4948  }
4949 
4950  // deactivated
4951  if (!empty($_SESSION["infopanel"]["img"]))
4952  {
4953  $link .= "<td><a href=\"".$_SESSION["infopanel"]["link"]."\" target=\"".
4954  ilFrameTargetInfo::_getFrame("MainContent").
4955  "\">";
4956  $link .= "<img src=\"".$ilias->tplPath.$ilias->account->prefs["skin"]."/images/".
4957  $_SESSION["infopanel"]["img"]."\" border=\"0\" vspace=\"0\"/>";
4958  $link .= "</a></td>";
4959  }
4960 
4961  $tpl->setVariable("INFO_ICONS",$link);
4962  $tpl->parseCurrentBlock();
4963  }
4964 
4965  //if (!$a_keep)
4966  //{
4967  ilSession::clear("infopanel");
4968  //}
4969  }
4970 
4971 
4980  public static function dirsize($directory)
4981  {
4982  $size = 0;
4983  if (!is_dir($directory))
4984  {
4985  // BEGIN DiskQuota Suppress PHP warning when attempting to determine
4986  // dirsize of non-existing directory
4987  $size = @filesize($directory);
4988  // END DiskQuota Suppress PHP warning.
4989  return ($size === false) ? -1 : $size;
4990  }
4991  if ($DIR = opendir($directory))
4992  {
4993  while (($dirfile = readdir($DIR)) !== false)
4994  {
4995  if (is_link($directory . DIRECTORY_SEPARATOR . $dirfile) || $dirfile == '.' || $dirfile == '..')
4996  continue;
4997  if (is_file($directory . DIRECTORY_SEPARATOR . $dirfile))
4998  $size += filesize($directory . DIRECTORY_SEPARATOR . $dirfile);
4999  else if (is_dir($directory . DIRECTORY_SEPARATOR . $dirfile))
5000  {
5001  // BEGIN DiskQuota: dirsize is not a global function anymore
5002  $dirSize = ilUtil::dirsize($directory . DIRECTORY_SEPARATOR . $dirfile);
5003  // END DiskQuota: dirsize is not a global function anymore
5004  if ($dirSize >= 0)
5005  $size += $dirSize;
5006  else return -1;
5007  }
5008  }
5009  closedir($DIR);
5010  }
5011  return $size;
5012  }
5013 
5014  public static function randomhash()
5015  {
5016  return md5(rand(1,9999999) + str_replace(" ", "", (string) microtime()));
5017  }
5018 
5019  public static function setCookie($a_cookie_name,$a_cookie_value = '', $a_also_set_super_global = true, $a_set_cookie_invalid = false)
5020  {
5021  /*
5022  if(!(bool)$a_set_cookie_invalid) $expire = IL_COOKIE_EXPIRE;
5023  else $expire = time() - (365*24*60*60);
5024  */
5025  // Temporary fix for feed.php
5026  if(!(bool)$a_set_cookie_invalid) $expire = 0;
5027  else $expire = time() - (365*24*60*60);
5028 
5029  // setcookie() supports 5th parameter
5030  // only for php version 5.2.0 and above
5031  if( version_compare(PHP_VERSION, '5.2.0', '>=') )
5032  {
5033  // PHP version >= 5.2.0
5034  setcookie( $a_cookie_name, $a_cookie_value, $expire,
5035  IL_COOKIE_PATH, IL_COOKIE_DOMAIN, IL_COOKIE_SECURE, IL_COOKIE_HTTPONLY
5036  );
5037  }
5038  else
5039  {
5040  // PHP version < 5.2.0
5041  setcookie( $a_cookie_name, $a_cookie_value, $expire,
5042  IL_COOKIE_PATH, IL_COOKIE_DOMAIN, IL_COOKIE_SECURE
5043  );
5044  }
5045 
5046  if((bool)$a_also_set_super_global) $_COOKIE[$a_cookie_name] = $a_cookie_value;
5047  }
5048 
5049  public static function _sanitizeFilemame($a_filename)
5050  {
5051  return strip_tags(self::stripSlashes($a_filename));
5052  }
5053 
5054  public static function _getHttpPath()
5055  {
5056  global $ilIliasIniFile;
5057 
5058  if($_SERVER['SHELL'] || php_sapi_name() == 'cli' ||
5059  // fallback for windows systems, useful in crons
5060  (class_exists("ilContext") && !ilContext::usesHTTP()))
5061  {
5062  return $ilIliasIniFile->readVariable('server', 'http_path');
5063  }
5064  else
5065  {
5066  return ILIAS_HTTP_PATH;
5067  }
5068  }
5069 
5075  public static function printBacktrace($a_limit = 0)
5076  {
5077  $bt = debug_backtrace();
5078  $cnt = 0;
5079  foreach ($bt as $t)
5080  {
5081  if ($cnt != 0 && ($a_limit == 0 || $cnt <= $a_limit))
5082  {
5083  echo "<br>".$t["file"].", ".$t["function"]." [".$t["line"]."]";
5084  }
5085  $cnt++;
5086  }
5087  echo "<br>";
5088  }
5089 
5104  public static function parseImportId($a_import_id)
5105  {
5106  $exploded = explode('_',$a_import_id);
5107 
5108  $parsed['orig'] = $a_import_id;
5109  if($exploded[0] == 'il')
5110  {
5111  $parsed['prefix'] = $exploded[0];
5112  }
5113  if(is_numeric($exploded[1]))
5114  {
5115  $parsed['inst_id'] = (int) $exploded[1];
5116  }
5117  $parsed['type'] = $exploded[2];
5118 
5119  if(is_numeric($exploded[3]))
5120  {
5121  $parsed['id'] = (int) $exploded[3];
5122  }
5123  return $parsed;
5124  }
5125 
5132  public static function unserializeSession($data)
5133  {
5134  $vars = preg_split(
5135  '/([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff^|]*)\|/',
5136  $data,
5137  -1,
5138  PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE
5139  );
5140 
5141  $result = array();
5142 
5143  for($i = 0; $vars[$i]; $i++)
5144  {
5145  $result[$vars[$i++]] = unserialize($vars[$i]);
5146  }
5147 
5148  return $result;
5149  }
5150 
5151 
5162  function rangeDownload($file) {
5163 
5164  $fp = @fopen($file, 'rb');
5165 
5166  $size = filesize($file); // File size
5167  $length = $size; // Content length
5168  $start = 0; // Start byte
5169  $end = $size - 1; // End byte
5170  // Now that we've gotten so far without errors we send the accept range header
5171  /* At the moment we only support single ranges.
5172  * Multiple ranges requires some more work to ensure it works correctly
5173  * and comply with the spesifications: http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.2
5174  *
5175  * Multirange support annouces itself with:
5176  * header('Accept-Ranges: bytes');
5177  *
5178  * Multirange content must be sent with multipart/byteranges mediatype,
5179  * (mediatype = mimetype)
5180  * as well as a boundry header to indicate the various chunks of data.
5181  */
5182  header("Accept-Ranges: 0-$length");
5183  // header('Accept-Ranges: bytes');
5184  // multipart/byteranges
5185  // http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.2
5186  if (isset($_SERVER['HTTP_RANGE'])) {
5187 
5188  $c_start = $start;
5189  $c_end = $end;
5190  // Extract the range string
5191  list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
5192  // Make sure the client hasn't sent us a multibyte range
5193  if (strpos($range, ',') !== false) {
5194 
5195  // (?) Shoud this be issued here, or should the first
5196  // range be used? Or should the header be ignored and
5197  // we output the whole content?
5198  header('HTTP/1.1 416 Requested Range Not Satisfiable');
5199  header("Content-Range: bytes $start-$end/$size");
5200  // (?) Echo some info to the client?
5201  exit;
5202  }
5203  // If the range starts with an '-' we start from the beginning
5204  // If not, we forward the file pointer
5205  // And make sure to get the end byte if spesified
5206  if ($range == '-') {
5207 
5208  // The n-number of the last bytes is requested
5209  $c_start = $size - substr($range, 1);
5210  }
5211  else {
5212 
5213  $range = explode('-', $range);
5214  $c_start = $range[0];
5215  $c_end = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size;
5216  }
5217  /* Check the range and make sure it's treated according to the specs.
5218  * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
5219  */
5220  // End bytes can not be larger than $end.
5221  $c_end = ($c_end > $end) ? $end : $c_end;
5222  // Validate the requested range and return an error if it's not correct.
5223  if ($c_start > $c_end || $c_start > $size - 1 || $c_end >= $size) {
5224 
5225  header('HTTP/1.1 416 Requested Range Not Satisfiable');
5226  header("Content-Range: bytes $start-$end/$size");
5227  // (?) Echo some info to the client?
5228  exit;
5229  }
5230  $start = $c_start;
5231  $end = $c_end;
5232  $length = $end - $start + 1; // Calculate new content length
5233  fseek($fp, $start);
5234  header('HTTP/1.1 206 Partial Content');
5235  }
5236  // Notify the client the byte range we'll be outputting
5237  header("Content-Range: bytes $start-$end/$size");
5238  header("Content-Length: $length");
5239 
5240  // Start buffered download
5241  $buffer = 1024 * 8;
5242  while(!feof($fp) && ($p = ftell($fp)) <= $end) {
5243 
5244  if ($p + $buffer > $end) {
5245 
5246  // In case we're only outputtin a chunk, make sure we don't
5247  // read past the length
5248  $buffer = $end - $p + 1;
5249  }
5250  set_time_limit(0); // Reset time limit for big files
5251  echo fread($fp, $buffer);
5252  flush(); // Free up memory. Otherwise large files will trigger PHP's memory limit.
5253  }
5254 
5255  fclose($fp);
5256 
5257  }
5258 
5259 
5260 } // END class.ilUtil
5261 
5262 
5263 ?>
< a tabindex="-1" style="border-style: none;" href="#" title="Refresh Image" onclick="document.getElementById('siimage').src = './securimage_show.php?sid=' + Math.random(); this.blur(); return false">< img src="./images/refresh.png" alt="Reload Image" height="32" width="32" onclick="this.blur()" align="bottom" border="0"/></a >< br/>< strong > Enter Code *if($_SERVER['REQUEST_METHOD']=='POST' &&@ $_POST['do']=='contact') $_SESSION['ctform']['success']
static maskTag($a_str, $t, $fix_param="")
static sendSuccess($a_info="", $a_keep=false)
Send Success Message to Screen.
static isConvertVersionAtLeast($a_version)
Compare convert version numbers.
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
$errors
static getMemString()
get current memory usage as string
$target_arr
Definition: goto.php:86
static tf2yn($a_tf)
convert true/false to "y"/"n"
ILIAS Setting Class.
static deliverData($a_data, $a_filename, $mime="application/octet-stream", $charset="")
deliver data for download via browser.
static _getIcon($a_obj_id="", $a_size="big", $a_type="", $a_offline=false)
Get icon for repository item.
print $file
static removeItemFromDesktops($a_id)
removes object from all user&#39;s desktops public
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.
$size
Definition: RandomTest.php:79
exit
Definition: login.php:54
static isDN($a_str)
static strLen($a_string)
Definition: class.ilStr.php:77
$separator
static attribsToArray($a_str)
converts a string of format var1 = "val1" var2 = "val2" ...
setErrorHandling($mode=null, $options=null)
Sets how errors generated by this object should be handled.
Definition: PEAR.php:335
static securePlainString($a_str)
Remove unsecure characters from a plain text string.
const ILIAS_MODULE
Definition: payment.php:15
const IL_CAL_DATETIME
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...
const PEAR_ERROR_CALLBACK
Definition: PEAR.php:35
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
$result
static randomhash()
static _getOperationIdsByName($operations)
get ops_id&#39;s by name.
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.
static getStyleSheetLocation($mode="output", $a_css_name="", $a_css_location="")
get full style sheet file name (path inclusive) of current user
static unserializeSession($data)
Returns the unserialized ILIAS session data.
static isPasswordValidForUserContext($clear_text_password, $user, &$error_language_variable=null)
static insertLatexImages($a_text, $a_start="\ex\, $a_end="\\tex\")
replace [text]...[/tex] tags with formula image code
if(strpos($jquery_path, './')===0) else if(strpos($jquery_path, '.')===0) $mathJaxSetting
Definition: latex.php:34
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 Linkbar($AScript, $AHits, $ALimit, $AOffset, $AParams=array(), $ALayout=array(), $prefix='')
Linkbar Diese Funktion erzeugt einen typischen Navigationsbalken mit "Previous"- und "Next"-Links und...
static strPos($a_haystack, $a_needle, $a_offset=NULL)
Definition: class.ilStr.php:32
$_COOKIE["ilClientId"]
Definition: cron.php:11
static unmaskAttributeTag($a_str, $tag, $tag_att)
static getSelectName($selected, $values)
???
static parseImportId($a_import_id)
Parse an ilias import id Typically of type il_[IL_INST_ID]_[OBJ_TYPE]_[OBJ_ID] returns array( &#39;orig&#39; ...
static _getObjectsByOperations($a_obj_type, $a_operation, $a_usr_id=0, $limit=0)
Get all objects of a specific type and check access This function is not recursive, instead it parses the serialized rbac_pa entries.
$cmd
Definition: sahs_server.php:35
static execQuoted($cmd, $args=NULL)
exec command and fix spaces on windows
static is_email($a_email)
This preg-based function checks whether an e-mail address is formally valid.
static groupNameExists($a_group_name, $a_id=0)
checks if group name already exists.
static unzip($a_file, $overwrite=false, $a_flat=false)
unzip file
static getDir($a_dir, $a_rec=false, $a_sub_dir="")
get directory
static getUsersOnline($a_user_id=0)
reads all active sessions from db and returns users that are online OR returns only one active user i...
static shortenText($a_str, $a_len, $a_dots=false, $a_next_blank=false, $a_keep_extension=false)
shorten a string to given length.
static getNewContentStyleSheetLocation($mode="output")
get full style sheet file name (path inclusive) of current user
static htmlfile2pdf($html_file, $pdf_file)
produce pdf out of html with htmldoc
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()
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()
const IL_COOKIE_PATH
Definition: index.php:6
const IL_CAL_UNIX
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)
Util class various functions, usage as namespace.
static isPassword($a_passwd, &$customError=null)
validates a password public
static sortArray($array, $a_array_sortby, $a_array_sortorder=0, $a_numeric=false, $a_keep_keys=false)
sortArray
static now()
Return current timestamp in Y-m-d H:i:s format.
static getASCIIFilename($a_filename)
convert utf8 to ascii filename
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.
const DB_FETCHMODE_OBJECT
Definition: class.ilDB.php:11
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
global $tpl
Definition: ilias.php:8
global $ilCtrl
Definition: ilias.php:18
static getCurrentMasterStyle()
get the current style
static sendInfo($a_info="", $a_keep=false)
Send Info Message to Screen.
static buildLatexImages($a_text, $a_dir)
replace [text]...[/tex] tags with formula image code //////// added additional parameters to make thi...
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)
static html2pdf($html, $pdf_file)
produce pdf out of html with htmldoc
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)
static appendUrlParameterString($a_url, $a_par, $xml_style=false)
append URL parameter string ("par1=value1&par2=value2...") to given URL string
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
static execConvert($args)
execute convert command
if(!is_array($argv)) $options
static date_mysql2time($mysql_date_time)
make time object from mysql_date_time
$GLOBALS['ct_recipient']
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 h...
static getImagePath($img, $module_path="", $mode="output", $offline=false)
get image path (for images located in a template directory)
static getJSLocation($a_js_name, $a_js_location="", $add_version=FALSE)
get full javascript file name (path inclusive) of current user
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 moveUploadedFile($a_file, $a_name, $a_target, $a_raise_errors=true, $a_mode="move_uploaded")
move uploaded file
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
static mergesort(&$array, $cmp_function='strcmp')
const PEAR_ERROR_RETURN
#+ ERROR constants
Definition: PEAR.php:31
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.
global $ilIliasIniFile
static infoPanel($a_keep=true)
Date and time handling
static getPluginObject($a_ctype, $a_cname, $a_slot_id, $a_pname)
Get Plugin Object.
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.
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.
static deliverFile($a_file, $a_filename, $a_mime='', $isInline=false, $removeAfterDelivery=false, $a_exit_after=true)
deliver file for download via browser.
static & processCSVRow(&$row, $quoteAll=FALSE, $separator=";", $outUTF8=FALSE, $compatibleWithMSExcel=TRUE)
Convertes an array for CSV usage.
get($a_format, $a_format_str='', $a_tz='')
get formatted date
static removeTrailingPathSeparators($path)
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
secureUrl($url)
Prepare secure href attribute.
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...
static array_php2js($data)
convert php arrays to javascript arrays
static replaceLinkProperties($matches)
replaces target _blank with _self and the link text with the according object title.
rangeDownload($file)
Send a file via range request, see http://mobiforge.com/design-development/content-delivery-mobile-de...
static formRadioButton($checked, $varname, $value, $onclick=null, $disabled=false)
??? public
static sendFailure($a_info="", $a_keep=false)
Send Failure Message to Screen.
$filename
Definition: buildRTE.php:89
includeMathjax($a_tpl=null)
Include Mathjax.
static makeDir($a_dir)
creates a new directory and inherits all filesystem permissions of the parent directory You may pass ...
static getInstance()
Get https instance.
static stripSlashesArray($a_arr, $a_strip_html=true, $a_allow="")
Strip slashes from array.
static htmlentitiesOutsideHTMLTags($htmlText)
Encodes HTML entities outside of HTML tags.
if(!file_exists(getcwd().'/ilias.ini.php')) if(isset( $_GET["client_id"]))
registration confirmation script for ilias
Definition: confirmReg.php:20
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)
& _getInstance()
Constructor public.
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 ilTempnam()
Create a temporary file in an ILIAS writable directory.
global $ilUser
Definition: imgupload.php:15
static strToUpper($a_string)
isLogin($a_login)
$ref_id
Definition: sahs_server.php:39
static convertImage($a_from, $a_to, $a_target_format="", $a_geometry="", $a_background_color="")
convert image
static renameExecutables($a_dir)
Rename uploaded executables for security reasons.
static escapeShellArg($a_arg)
recursive_dirscan($dir, &$arr)
Recursively scans a given directory and writes path and filename into referenced array.
global $lng
Definition: privfeed.php:40
$path
Definition: index.php:22
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
static checkInput($vars)
???
static insertInstIntoID($a_value)
inserts installation id into ILIAS id
static secureString($a_str, $a_strip_html=true, $a_allow="")
Remove unsecure tags.
static formInput($varname, $value, $disabled=false)
create html input area
static isHTML($a_text)
Checks if a given string contains HTML or not.
static getCurrentStyle()
get the current style
static htmlencodePlainString($a_str, $a_make_links_clickable, $a_detect_goto_links=false)
Encodes a plain text string into HTML for display in a browser.
static yn2tf($a_yn)
convert "y"/"n" to true/false
static checkFormEmpty($emptyFields)
??? public
static subStr($a_str, $a_start, $a_length=NULL)
Definition: class.ilStr.php:15
static redirect($a_script)
http redirect to other script
$dirs
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.
const IL_COMP_SERVICE
static isAPICall()
static formCheckbox($checked, $varname, $value, $disabled=false)
??? public
static printBacktrace($a_limit=0)
printBacktrace
static strCmp($a, $b)
Compare two strings.
static dumpString($a_str)
dumps ord values of every character of string $a_str
$r
static readFile($a_file)
there are some known problems with the original readfile method, which sometimes truncates delivered ...